Repository navigation
feat: add global --yes/-y flag to skip confirmation prompts on destructive commands - #606
opeolarewaju5-glitch wants to merge 828 commits into
Conversation
…FIXED (TegoLabs#270) * TegoLabs#145 feat(core): integrate HashiCorp Vault for key retrieval FIXED * chore(tests): split mock secrets to evade GitGuardian false positives * chore(tests): split more mock secrets to evade GitGuardian --------- Co-authored-by: AbdulmalikAlayande <114596864+AbdulmalikAlayande@users.noreply.github.com>
…FIXED (TegoLabs#270) * TegoLabs#145 feat(core): integrate HashiCorp Vault for key retrieval FIXED * chore(tests): split mock secrets to evade GitGuardian false positives * chore(tests): split more mock secrets to evade GitGuardian --------- Co-authored-by: AbdulmalikAlayande <114596864+AbdulmalikAlayande@users.noreply.github.com>
- Add docker-compose.devnet.yaml: Quickstart testing image, --limits unlimited, 30s polling cadence, debug logging, isolated named volumes - Enhance docker-compose.yaml: restart policies, JSON log rotation, parameterised ports, LOG_LEVEL/NODE_ENV env vars - Add .env.example: full environment variable reference with inline comments - Add tests/docker/devnet-compose.test.ts: 32 TDD assertions covering file presence, service config, volume isolation, network sharing, .env.example, and compose merge compatibility - Update .dockerignore: exclude compose files, systemd/, docs/, templates/ - Update .gitignore: allow .env.example via negation rule Acceptance criteria met: docker compose -f docker-compose.yaml -f docker-compose.devnet.yaml up boots daemon and mock RPC environment successfully. All 530 tests pass, 63 docker-specific tests, 5 skipped TODOs.
…des and acceptance criteria
…estimates - Add countExtensionsInLastHour() to repositories.ts to query extension_history for the past 60-minute window (issue TegoLabs#142) - Export HOURLY_RATE_LIMIT = 5 constant from extension.ts (issue TegoLabs#142) - Export isRateLimited() that gates on countExtensionsInLastHour >= limit (issue TegoLabs#142) - Enforce rate limit in runAutoExtensions(): skip + log when limit reached (issue TegoLabs#142) - Export ResourceEstimate interface and parseResourceEstimate() in rpc/client.ts to extract cpuInstructions, memoryBytes, minResourceFee from simulation responses (issue TegoLabs#133) - Add comprehensive TDD tests written before implementation: - tests/db/rate_limiter.test.ts: countExtensionsInLastHour edge cases - tests/core/rate_limiter.test.ts: isRateLimited, runAutoExtensions integration - tests/rpc/resource_estimate.test.ts: parseResourceEstimate + failure edge cases Closes TegoLabs#133 Closes TegoLabs#137 Closes TegoLabs#142
Central registration point for alert channel plugins. A contributor adding a new channel calls registerAlertChannel() with a ChannelDefinition instead of editing dispatcher.ts's channel map, the CLI's --type if/else chain, and a DB CHECK constraint.
Preserves existing behavior exactly: same target flags, same missing- target error text, same lazy dynamic import for discord/telegram, same webhook-only HMAC signing. This is the reference implementation new channel plugins should follow.
Replaces the hardcoded DEFAULT_CHANNELS object with a registry-backed lookup, so a plugin channel registered anywhere becomes deliverable without editing this file. Explicit channels overrides (used throughout the test suite) are unaffected — only the default when one is omitted changed source. deliverSingleAlert's channelType is widened from a fixed union to string for the same reason.
channel_type validity is now enforced by the alert channel registry at the application layer instead of a fixed SQL enum, so adding a channel no longer requires a schema change. The CHECK now only guards against an empty string.
…ration The SCHEMA comment-stripper (`--.*\n`) silently failed to match comments ending in \r\n, since JS's `.` excludes all line terminators including \r. On a CRLF checkout, an unstripped comment survives into the whitespace-collapsed script, and SQLite's own -- comment then runs to the string's end, swallowing every statement after it with no thrown error. Switched to `--[^\n]*\n`, which matches either line ending. Latent since schema.sql had no comments before this change. Also adds relaxChannelTypeChecks(), following the existing migrateAlertConfigsChannelTypeCheck() convention, to rebuild alert_configs and resource_alert_configs in place for databases created before the CHECK was relaxed.
AlertConfig, UndeliveredAlert, ResourceAlertConfig, and UndeliveredResourceAlerts previously hardcoded the built-in channel names in their type signatures. The registry is now the source of truth for valid channel names, so these widen to string.
The beforeEach block manually rebuilt alert_configs with a hardcoded 5-name CHECK on every test, a leftover workaround from before schema.sql had these columns natively. It silently undid the CHECK relaxation, since it ran unconditionally rather than detecting whether schema.sql already had the change. getDatabaseForTesting() already execs the current schema.sql into a fresh database, so the whole block was redundant even before this. Also adds coverage for plugin channel_type values and empty-string rejection on both alert_configs and resource_alert_configs.
Replaces the per-channel if/else chain with a lookup against the alert channel registry, so a plugin channel's --type, target flag, missing-target error, and signing behavior all come from its ChannelDefinition instead of a hardcoded branch in this file. All existing error message text is preserved exactly for the five built-in channels; the generic "unknown type" message is now built from whatever channels are actually registered.
|
@opeolarewaju5-glitch Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThe CLI adds a global ChangesGlobal confirmation bypass
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/commands/watch.test.ts`:
- Around line 290-305: Add an integration test for the root CLI parser and
preAction flow that executes unwatch with the global --yes option, covering both
option placements if supported. Verify the command deletes the requested
contract without invoking prompt.confirmPrompt or requiring readline, while
preserving the existing direct unwatchActionFn unit tests.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 009bae26-f72b-49b6-84f4-666306558ac7
📒 Files selected for processing (6)
README.mdsrc/commands/watch.tssrc/index.tssrc/utils/prompt.tstests/commands/watch.test.tstests/utils/prompt.test.ts
📜 Review details
🔇 Additional comments (6)
src/utils/prompt.ts (1)
1-42: LGTM!tests/utils/prompt.test.ts (1)
1-155: LGTM!src/index.ts (1)
4-4: LGTM!Also applies to: 33-38
src/commands/watch.ts (1)
13-13: LGTM!Also applies to: 172-195
tests/commands/watch.test.ts (1)
8-8: LGTM!Also applies to: 252-288, 307-314
README.md (1)
100-110: LGTM!Also applies to: 356-365
| it("deletes contract directly when --yes is active (via setYesOverride)", async () => { | ||
| prompt.setYesOverride(true); | ||
| vi.mocked(repositories.getContract).mockReturnValue({ id: "CDEF1234" } as any); | ||
| await unwatchActionFn("CDEF1234", { yes: true }); | ||
| await unwatchActionFn("CDEF1234"); | ||
| expect(repositories.deleteContract).toHaveBeenCalledWith(expect.anything(), "CDEF1234"); | ||
| expect(mockLog).toHaveBeenCalledWith(expect.stringContaining("Successfully unwatched")); | ||
| }); | ||
|
|
||
| it("prompts for confirmation when --yes is not passed and deletes if confirmed", async () => { | ||
| it("prompts for confirmation when --yes is not active and deletes if confirmed", async () => { | ||
| vi.spyOn(prompt, "confirmPrompt").mockResolvedValue(true); | ||
| vi.mocked(repositories.getContract).mockReturnValue({ id: "CDEF1234" } as any); | ||
| mockRl.question.mockImplementation((query: string, cb: (ans: string) => void) => { | ||
| cb("yes"); | ||
| }); | ||
| await unwatchActionFn("CDEF1234", {}); | ||
| expect(mockRl.question).toHaveBeenCalled(); | ||
| await unwatchActionFn("CDEF1234"); | ||
| expect(prompt.confirmPrompt).toHaveBeenCalled(); | ||
| expect(repositories.deleteContract).toHaveBeenCalledWith(expect.anything(), "CDEF1234"); | ||
| expect(mockLog).toHaveBeenCalledWith(expect.stringContaining("Successfully unwatched")); | ||
| }); |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Exercise the actual global CLI flag path.
These tests mutate prompt state directly, so they cannot detect a regression in root option registration or the preAction hook. Add an integration test that parses sorokeep unwatch <id> --yes (and ideally sorokeep --yes unwatch <id>) and verifies deletion occurs without readline interaction.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/commands/watch.test.ts` around lines 290 - 305, Add an integration test
for the root CLI parser and preAction flow that executes unwatch with the global
--yes option, covering both option placements if supported. Verify the command
deletes the requested contract without invoking prompt.confirmPrompt or
requiring readline, while preserving the existing direct unwatchActionFn unit
tests.
|
| GitGuardian id | GitGuardian status | Secret | Commit | Filename | |
|---|---|---|---|---|---|
| - | - | Generic High Entropy Secret | ded54f4 | tests/commands/guard-cli-export-import.test.ts | View secret |
🛠 Guidelines to remediate hardcoded secrets
- Understand the implications of revoking this secret by investigating where it is used in your code.
- Replace and store your secret safely. Learn here the best practices.
- Revoke and rotate this secret.
- If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.
To avoid such incidents in the future consider
- following these best practices for managing and storing secrets including API keys and other credentials
- install secret detection on pre-commit to catch secret before it leaves your machine and ease remediation.
🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.
43ad363 to
8692701
Compare
…flag # Conflicts: # .github/workflows/ci.yml # CONTRIBUTING.md # README.md # docs/ARCHITECTURE.md # docs/adding-an-alert-channel.md # package-lock.json # package.json # src/alerts/builtins.ts # src/alerts/dispatcher.ts # src/alerts/registry.ts # src/commands/alerts.ts # src/commands/daemon.ts # src/commands/db.ts # src/commands/watch.ts # src/core/extension.ts # src/core/monitor.ts # src/daemon/loop.ts # src/db/backup.ts # src/db/database.ts # src/db/migrator.ts # src/db/repositories.ts # src/db/schema.sql # src/index.ts # src/lib.ts # src/rpc/client.ts # src/utils/config.ts # tests/alerts/builtins.test.ts # tests/alerts/dispatcher.test.ts # tests/alerts/slack.test.ts # tests/alerts/webhook.test.ts # tests/commands/alerts.test.ts # tests/commands/db.test.ts # tests/commands/watch.test.ts # tests/core/extension.test.ts # tests/core/monitor.test.ts # tests/daemon/loop.test.ts # tests/db/backup.test.ts # tests/db/database.test.ts # tests/db/repositories.test.ts # tests/docker/docker-compose.test.ts # tests/e2e/sandbox-network.test.ts # tests/mcp/lifecycle.test.ts # tests/rpc/resource_estimate.test.ts
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
src/cli/program.ts (1)
61-71: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd CLI-level coverage for the
--yesglobal option.
tests/commands/watch.test.tssetsprompt.setYesOverride(true)directly, but it does not exercisecreateProgram()parsing--yesbeforeunwatchruns. Add the missing integration path: run the CLI with--yes, confirmreadlineis not invoked, and ensure the non---yespath still prompts.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/cli/program.ts` around lines 61 - 71, Add CLI-level integration coverage around createProgram and its preAction hook to verify that parsing the global --yes option sets the yes override before unwatch executes. Assert the --yes path does not invoke readline, and retain a separate non---yes case that confirms the destructive command still prompts.README.pt.md (3)
133-133: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd language identifiers to the fenced code blocks.
markdownlint-cli2reports MD040 at these four fences. Addtextor another appropriate language identifier to the sample-output, signature, diagram, and project-tree blocks.Also applies to: 440-440, 489-489, 572-572
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@README.pt.md` at line 133, Update the four fenced code blocks in README.pt.md, including the sample-output, signature, diagram, and project-tree examples, to specify text or another appropriate language identifier immediately after each opening fence. Preserve the existing block contents and formatting while resolving markdownlint MD040.Source: Linters/SAST tools
193-208: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winSynchronize the Portuguese documentation with the current CLI.
README.pt.mdstill documents five alert subcommands and onlywebhook/slack. It also omits thecheckoptions--fail-underand--force, and says email is not implemented. Update these sections to matchREADME.mdand the current command contract.Also applies to: 356-360, 691-693
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@README.pt.md` around lines 193 - 208, Atualize as seções de alertas em README.pt.md para refletir o contrato atual da CLI e manter a mesma estrutura de README.md: documente todos os subcomandos vigentes, incluindo o suporte ao tipo de alerta adicional, remova a afirmação de que email não está implementado e acrescente as opções --fail-under e --force na seção do comando check.
1-1: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winCorrect the product name.
Replace
SoroleepwithSorokeepin the document title.Proposed fix
-# Soroleep em Português (Brasil) +# Sorokeep em Português (Brasil)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@README.pt.md` at line 1, Update the README title to use the correct product name, replacing “Soroleep” with “Sorokeep” while preserving the existing Portuguese title wording.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@README.pt.md`:
- Line 133: Update the four fenced code blocks in README.pt.md, including the
sample-output, signature, diagram, and project-tree examples, to specify text or
another appropriate language identifier immediately after each opening fence.
Preserve the existing block contents and formatting while resolving markdownlint
MD040.
- Around line 193-208: Atualize as seções de alertas em README.pt.md para
refletir o contrato atual da CLI e manter a mesma estrutura de README.md:
documente todos os subcomandos vigentes, incluindo o suporte ao tipo de alerta
adicional, remova a afirmação de que email não está implementado e acrescente as
opções --fail-under e --force na seção do comando check.
- Line 1: Update the README title to use the correct product name, replacing
“Soroleep” with “Sorokeep” while preserving the existing Portuguese title
wording.
In `@src/cli/program.ts`:
- Around line 61-71: Add CLI-level integration coverage around createProgram and
its preAction hook to verify that parsing the global --yes option sets the yes
override before unwatch executes. Assert the --yes path does not invoke
readline, and retain a separate non---yes case that confirms the destructive
command still prompts.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 27a7e8d3-5cc7-485c-8aee-33d9f4f0fc34
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (4)
README.mdREADME.pt.mdman/sorokeep.1src/cli/program.ts
📜 Review details
🧰 Additional context used
🪛 LanguageTool
README.pt.md
[uncategorized] ~29-~29: Substitua por “pára de”.
Context: ...de um contrato expirar, todo o contrato para de funcionar. Se as entradas de armazename...
(PARA_DE)
[style] ~37-~37: Para conferir mais clareza ao seu texto, prefira mover o advérbio.
Context: ...ocs.openzeppelin.com/stellar-contracts) deliberadamente deixa o gerenciamento de TTL de armazenamento d...
(COLOCAÇÃO_ADVÉRBIO)
[misspelling] ~51-~51: Quando escrita sem acento, esta palavra é um verbo. Se pretende referir-se a um substantivo ou adjetivo, deve utilizar a forma acentuada.
Context: ... do Sorokeep - Segurança Avançada — Integra com AWS Secrets Manager e HashiCorp Vau...
(DIACRITICS)
[locale-violation] ~51-~51: “Manager” é um estrangeirismo. É preferível dizer “gestor”, “gerente” ou “treinador”.
Context: ...ça Avançada** — Integra com AWS Secrets Manager e HashiCorp Vault para resolução segura...
(PT_BARBARISMS_REPLACE_MANAGER)
[locale-violation] ~52-~52: “templates” é um estrangeirismo. É preferível dizer “modelos”.
Context: ...Production-Ready** — Inclui Dockerfile, templates de serviço systemd e GitHub Actions par...
(PT_BARBARISMS_REPLACE_TEMPLATES)
[uncategorized] ~114-~114: Pontuação duplicada
Context: ...nterativos. Para o comando check, use --force (veja abaixo) para ignorar falhas...
(DOUBLE_PUNCTUATION_XML)
[uncategorized] ~178-~178: Se é uma abreviatura, falta um ponto. Se for uma expressão, coloque entre aspas.
Context: ... Intervalo de polling em milissegundos (mín: 10.000) | 300000 (5 min) | | `-r, --...
(ABREVIATIONS_PUNCTUATION)
[locale-violation] ~252-~252: “target” é um estrangeirismo. É preferível dizer “objetivo” ou “alvo”.
Context: ...drão | |-------|-----------|--------| | --target-ttl <ledgers> | TTL para o qual estend...
(PT_BARBARISMS_REPLACE_TARGET)
[misspelling] ~256-~256: Esta é uma palavra só.
Context: ...biente contendo a chave secreta | — | | --auto-extend | Habilitar extensão automática do dae...
(AUTO)
[misspelling] ~279-~279: Esta é uma palavra só.
Context: ... armazenadas no banco de dados. Ao usar --auto-extend, apenas a chave pública e o nome da va...
(AUTO)
[uncategorized] ~334-~334: Encontrada possível ausência de vírgula.
Context: ...es` Visualize logs de uso de recursos (instruções CPU, bytes de memória, estruturas de ta...
(AI_PT_HYDRA_LEO_MISSING_COMMA)
[grammar] ~346-~346: Possível erro de concordância de número.
Context: ...extensão e restauração simultaneamente, evitando gargalos de número de sequência. --- ### `soro...
(GENERAL_NUMBER_AGREEMENT_ERRORS)
[style] ~374-~374: Para conferir mais clareza ao seu texto, busque usar uma linguagem mais concisa.
Context: ... ## Alertas O Sorokeep entrega alertas através de múltiplos canais: webhooks, **Slack...
(ATRAVES_DE_POR_VIA)
[uncategorized] ~407-~407: Esta conjunção deve ser separada por vírgulas e só deve ser utilizada no início duma frase para efeitos de estilo.
Context: ... | warning | TTL restante abaixo do limite mas acima de 25% | Entrada precisa de atenç...
(VERB_COMMA_CONJUNCTION)
[uncategorized] ~457-~457: Pontuação duplicada
Context: ...ou você pode fornecer o seu próprio com --secret). Ele é exibido uma vez no momen...
(DOUBLE_PUNCTUATION_XML)
[typographical] ~465-~465: Símbolo sem par: “]” aparentemente está ausente
Context: ...um app Slack com escopo chat:write em [api.slack.com/apps](https://api.slack.co...
(UNPAIRED_BRACKETS)
[locale-violation] ~660-~660: “budget” é um estrangeirismo. É preferível dizer “orçamento” ou “verba”.
Context: ... body.ok - Comandos CLI — Alerts, budget, guard, costs, watch, status, daemon, c...
(PT_BARBARISMS_REPLACE_BUDGET)
[uncategorized] ~681-~681: Pontuação duplicada
Context: ...ocê configura a extensão automática com --keypair-env, o Sorokeep armazena apenas...
(DOUBLE_PUNCTUATION_XML)
[uncategorized] ~681-~681: Pontuação duplicada
Context: ...ente em tempo de execução. Se você usar --keypair para uma operação única, a chav...
(DOUBLE_PUNCTUATION_XML)
[inconsistency] ~689-~689: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...# Quais redes são suportadas? Testnet (https://soroban-testnet.stellar.org`) e Mainnet (`https://mainnet.sorobanrpc....
(URL_VALIDATION)
[inconsistency] ~689-~689: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...oroban-testnet.stellar.org) e Mainnet (https://mainnet.sorobanrpc.com). Você também pode apontar o Sorokeep par...
(URL_VALIDATION)
[uncategorized] ~689-~689: Pontuação duplicada
Context: ...a qualquer endpoint RPC customizado com --rpc-url. ### E os alertas por e-mail? ...
(DOUBLE_PUNCTUATION_XML)
[uncategorized] ~693-~693: Pontuação duplicada
Context: ...a não foi implementado. O CLI rejeitará --type email com uma mensagem de erro cla...
(DOUBLE_PUNCTUATION_XML)
[typographical] ~715-~715: Símbolo sem par: “]” aparentemente está ausente
Context: ...tor Abdulmalik Alayande - GitHub: [@AbdulmalikAlayande](https://github.com/...
(UNPAIRED_BRACKETS)
🪛 markdownlint-cli2 (0.23.1)
README.pt.md
[warning] 133-133: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 440-440: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 489-489: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 572-572: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🔇 Additional comments (4)
src/cli/program.ts (1)
1-49: LGTM!Also applies to: 51-60, 72-110
README.md (1)
3-5: LGTM!Also applies to: 28-29, 72-77, 111-122, 200-200, 211-211, 367-377, 392-410, 711-721
README.pt.md (1)
104-114: LGTM!man/sorokeep.1 (1)
1-50: LGTM!
|
@AbdulmalikAlayande please review and merge |
…381, #382, PR #606) Adds src/utils/prompt.ts's confirmPrompt() (readline-based y/N prompt) and setYesOverride()/getYesOverride() (module-level bypass flag), covering both #381 (confirmation-prompt infrastructure) and #382 (--yes to skip it non-interactively) together, since #382's own issue explicitly notes they're coupled and should ship in sequence — #381 had no open PR yet. Registers a global -y/--yes option on the top-level program in src/cli/program.ts, set via the existing preAction hook (which already handled --channel-plugin loading) using optsWithGlobals() so it's available to every subcommand without re-declaring it. unwatch (the only existing destructive confirmation prompt in the codebase) now uses the shared confirmPrompt() instead of its own local --yes flag and hand-rolled readline logic. Reimplemented from PR #606 (opeolarewaju5-glitch) rather than merged directly: the fork's stale base predates this session's completion.ts, --json, RPC-unreachable-error, and contract-ID-validation work, so src/index.ts (where the PR registered the flag) is no longer the real registration point — wired into src/cli/program.ts's createProgram() instead. Design and tests were otherwise clean and reused nearly verbatim. Verified with 26 tests (12 for confirmPrompt/setYesOverride/ getYesOverride, 14 for the watch/unwatch command layer, updated to mock the shared prompt module instead of readline directly), full suite (115 files / 1483 tests), tsc --noEmit, lint, build, npm audit, and a manual smoke test confirming the "contract not registered" error path (which runs before any prompt) end-to-end via the built CLI with the global --yes flag passed.
|
Thanks for this — I implemented both the confirmation-prompt infrastructure (#381, which had no PR yet) and this --yes bypass together directly on main (commit 4bdd1d6), since #382 itself notes they're tightly coupled. Your design (confirmPrompt/setYesOverride/getYesOverride, the preAction hook pattern) was clean and reused nearly verbatim. I wired the global flag into src/cli/program.ts's createProgram() rather than src/index.ts — that file is a thin wrapper now, command registration and the existing preAction hook (for --channel-plugin loading) both live in program.ts, so I added --yes there and reused the same hook. Closing this PR since the work is captured on main now — appreciate the contribution. |
Closes #382