@skathio/somi 4.1.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/icon.png +0 -0
- package/.claude-plugin/marketplace.json +8 -3
- package/.claude-plugin/plugin.json +9 -10
- package/.copilot-extension/extension.json +32 -40
- package/.copilot-extension/marketplace.json +8 -3
- package/README.md +83 -228
- package/VERSION +1 -1
- package/agents/somi-reviewer.md +21 -40
- package/agents/somi-security-reviewer.md +16 -90
- package/agents/somi-worker-high.md +11 -0
- package/agents/somi-worker-low.md +11 -0
- package/agents/somi-worker-medium.md +11 -0
- package/agents/somi.md +8 -75
- package/commands/somi-config.md +5 -14
- package/commands/somi-deliver.md +11 -0
- package/commands/somi-quality.md +10 -0
- package/commands/somi-review.md +10 -0
- package/commands/somi-status.md +11 -0
- package/commands/somi.md +10 -0
- package/hooks/hooks.json +28 -23
- package/hooks/lib/common.mjs +45 -34
- package/hooks/pre-tool/apply-tier.mjs +31 -0
- package/hooks/pre-tool/block-dangerous-bash.mjs +15 -0
- package/hooks/pre-tool/gate-dep-install.mjs +2 -2
- package/hooks/pre-tool/guard-protected-paths.mjs +9 -16
- package/hooks/pre-tool/guard-tier-config.mjs +17 -0
- package/hooks/pre-tool/reviewers-read-only.mjs +11 -0
- package/hooks/session-start/inject-digest.mjs +51 -0
- package/hooks/stop/review-due.mjs +40 -0
- package/hooks/user-prompt/capture-prompt.mjs +17 -0
- package/library/lenses/architecture.md +1 -0
- package/library/lenses/test-strategy.md +1 -0
- package/library/roles/accessibility.md +1 -0
- package/library/roles/answer.md +1 -0
- package/library/roles/atlas.md +1 -0
- package/library/roles/build.md +1 -0
- package/library/roles/debug.md +6 -0
- package/library/roles/design.md +1 -0
- package/library/roles/discover.md +1 -0
- package/library/roles/incident.md +1 -0
- package/library/roles/migrate.md +1 -0
- package/library/roles/perf.md +1 -0
- package/library/roles/plan.md +1 -0
- package/library/roles/refactor.md +1 -0
- package/library/roles/review.md +1 -0
- package/library/roles/security-review.md +1 -0
- package/library/roles/upgrade.md +1 -0
- package/library/skills/accessibility.md +16 -0
- package/library/skills/ci-infra-gotchas.md +12 -0
- package/library/skills/perf-method.md +10 -0
- package/library/skills/secure-coding.md +18 -0
- package/library/skills/testing-checklist.md +16 -0
- package/library/skills/threat-modeling.md +10 -0
- package/package.json +12 -17
- package/profiles/claude.json +21 -0
- package/profiles/copilot.json +5 -0
- package/rules/digest.md +40 -0
- package/scripts/check-links.mjs +65 -76
- package/scripts/lib/advisor.mjs +207 -0
- package/scripts/lib/check.mjs +165 -0
- package/scripts/lib/copilot-workflow.mjs +41 -0
- package/scripts/lib/doctor.mjs +91 -0
- package/scripts/lib/gates.mjs +69 -0
- package/scripts/lib/git-tree.mjs +201 -0
- package/scripts/lib/init.mjs +23 -0
- package/scripts/lib/ledger.mjs +38 -0
- package/scripts/lib/mcp-project-root.mjs +63 -67
- package/scripts/lib/migrate.mjs +73 -0
- package/scripts/lib/path-facts.mjs +2 -2
- package/scripts/lib/path-safety.mjs +6 -134
- package/scripts/lib/plan.mjs +69 -0
- package/scripts/lib/policy.mjs +103 -0
- package/scripts/lib/pr.mjs +28 -0
- package/scripts/lib/prompt.mjs +72 -0
- package/scripts/lib/quality/clones.mjs +76 -0
- package/scripts/lib/quality/css.mjs +43 -0
- package/scripts/lib/quality/gate.mjs +230 -0
- package/scripts/lib/quality/limits.mjs +73 -0
- package/scripts/lib/quality/metrics.mjs +159 -0
- package/scripts/lib/quality/parse.mjs +73 -0
- package/scripts/lib/quality/repo.mjs +69 -0
- package/scripts/lib/quality/run.mjs +38 -0
- package/scripts/lib/reviews.mjs +132 -0
- package/scripts/lib/routes.mjs +108 -0
- package/scripts/lib/setup.mjs +34 -0
- package/scripts/lib/shards.mjs +166 -0
- package/scripts/lib/signals.mjs +110 -0
- package/scripts/lib/state.mjs +42 -0
- package/scripts/lib/tiers.mjs +42 -0
- package/scripts/lib/update-notice.mjs +48 -0
- package/scripts/lib/views.mjs +62 -0
- package/scripts/lib/workflows.mjs +56 -0
- package/scripts/somi-mcp.mjs +181 -323
- package/scripts/somi.mjs +208 -0
- package/scripts/vendor/tree-sitter/LICENSE.vscode-tree-sitter-wasm +21 -0
- package/scripts/vendor/tree-sitter/LICENSE.web-tree-sitter +21 -0
- package/scripts/vendor/tree-sitter/cgmanifest.vscode-tree-sitter-wasm.json +16 -0
- package/scripts/vendor/tree-sitter/manifest.json +59 -0
- package/scripts/vendor/tree-sitter/package.json +3 -0
- package/scripts/vendor/tree-sitter/tree-sitter-css.wasm +0 -0
- package/scripts/vendor/tree-sitter/tree-sitter-javascript.wasm +0 -0
- package/scripts/vendor/tree-sitter/tree-sitter-tsx.wasm +0 -0
- package/scripts/vendor/tree-sitter/tree-sitter-typescript.wasm +0 -0
- package/scripts/vendor/tree-sitter/web-tree-sitter.js +4081 -0
- package/scripts/vendor/tree-sitter/web-tree-sitter.wasm +0 -0
- package/skills/somi-expertise/SKILL.md +6 -0
- package/workflows/deliver-stages.js +81 -0
- package/.claude/settings.json +0 -131
- package/agents/somi-architecture-reviewer.md +0 -101
- package/agents/somi-atlas.md +0 -100
- package/agents/somi-coder.md +0 -60
- package/agents/somi-designer.md +0 -36
- package/agents/somi-discovery-analyst.md +0 -57
- package/agents/somi-flow.md +0 -47
- package/agents/somi-general.md +0 -36
- package/agents/somi-impact.md +0 -95
- package/agents/somi-incident.md +0 -94
- package/agents/somi-plan-reviewer.md +0 -68
- package/agents/somi-planner.md +0 -57
- package/agents/somi-pr.md +0 -99
- package/agents/somi-refactor-designer.md +0 -81
- package/agents/somi-refactorer.md +0 -99
- package/agents/somi-sdlc-reviewer.md +0 -67
- package/agents/somi-test-strategist.md +0 -87
- package/commands/adopt.md +0 -14
- package/commands/architecture-review.md +0 -19
- package/commands/atlas.md +0 -19
- package/commands/code-loop.md +0 -19
- package/commands/code-parallel.md +0 -19
- package/commands/code.md +0 -19
- package/commands/debug.md +0 -19
- package/commands/design.md +0 -19
- package/commands/discover.md +0 -19
- package/commands/impact.md +0 -19
- package/commands/incident.md +0 -19
- package/commands/plan-loop.md +0 -19
- package/commands/plan.md +0 -19
- package/commands/pr.md +0 -19
- package/commands/refactor-design.md +0 -19
- package/commands/refactor.md +0 -19
- package/commands/release-readiness.md +0 -19
- package/commands/review-panel.md +0 -19
- package/commands/review.md +0 -19
- package/commands/security-review.md +0 -19
- package/commands/ship-loop.md +0 -19
- package/commands/ship.md +0 -19
- package/commands/test-strategy.md +0 -19
- package/commands/upgrade.md +0 -19
- package/examples/README.md +0 -19
- package/examples/code-review-example.md +0 -88
- package/examples/discovery-example.md +0 -200
- package/examples/feature-plan-example.md +0 -377
- package/examples/full-pipeline-example.md +0 -188
- package/examples/sample-consumer/.claude/settings.json +0 -29
- package/examples/sample-consumer/CLAUDE.md +0 -78
- package/examples/sample-consumer/README.md +0 -102
- package/hooks/post-tool/lint-changed-files.mjs +0 -209
- package/hooks/pre-tool/guard-cost-lowering.mjs +0 -192
- package/hooks/session-start/detect-repo-instructions.mjs +0 -287
- package/hooks/session-start/ensure-default-config.mjs +0 -113
- package/hooks/user-prompt-submit/inject-workflow-context.mjs +0 -580
- package/rules/00-priorities.md +0 -48
- package/rules/10-solid.md +0 -87
- package/rules/20-clean-code.md +0 -62
- package/rules/30-security-owasp.md +0 -83
- package/rules/40-engineering-practices.md +0 -65
- package/rules/50-collaboration.md +0 -114
- package/rules/99-overrides.md +0 -52
- package/rules/CLAUDE.md +0 -200
- package/scripts/check-session-artefacts.mjs +0 -149
- package/scripts/check-size-budget.mjs +0 -137
- package/scripts/generate-digest.mjs +0 -176
- package/scripts/lib/agent-info.mjs +0 -85
- package/scripts/lib/agent-registry.mjs +0 -92
- package/scripts/lib/cost-ceiling.mjs +0 -328
- package/scripts/lib/cost-config-edit.mjs +0 -102
- package/scripts/lib/cost-config.mjs +0 -64
- package/scripts/lib/cost-defaults.mjs +0 -53
- package/scripts/lib/cost-lowering.mjs +0 -89
- package/scripts/lib/cost-model.mjs +0 -110
- package/scripts/lib/dispatch-resolver.mjs +0 -243
- package/scripts/lib/escalation-facts.mjs +0 -146
- package/scripts/lib/escalation.mjs +0 -129
- package/scripts/lib/findings-ledger.mjs +0 -241
- package/scripts/lib/install-text.mjs +0 -97
- package/scripts/lib/loop-caps.mjs +0 -140
- package/scripts/lib/loop-diff.mjs +0 -38
- package/scripts/lib/loop-dispatch.mjs +0 -19
- package/scripts/lib/loop-engine.mjs +0 -227
- package/scripts/lib/loop-escalate.mjs +0 -49
- package/scripts/lib/loop-exit.mjs +0 -47
- package/scripts/lib/loop-notes-compact.mjs +0 -72
- package/scripts/lib/loop-notes.mjs +0 -282
- package/scripts/lib/loop-review.mjs +0 -395
- package/scripts/lib/loop-state.mjs +0 -44
- package/scripts/lib/loop-step-close.mjs +0 -75
- package/scripts/lib/loop-step-kit.mjs +0 -179
- package/scripts/lib/loop-step-review.mjs +0 -140
- package/scripts/lib/loop-step-tool.mjs +0 -89
- package/scripts/lib/loop-step.mjs +0 -303
- package/scripts/lib/run-budget.mjs +0 -28
- package/scripts/lib/run-card.mjs +0 -73
- package/scripts/lib/size-tier.mjs +0 -184
- package/scripts/lib/tier-record.mjs +0 -82
- package/scripts/size-budget-overrides.json +0 -58
- package/scripts/somi-card.mjs +0 -39
- package/scripts/somi-check.mjs +0 -237
- package/scripts/somi-config.mjs +0 -421
- package/scripts/somi-dispatch.mjs +0 -141
- package/scripts/somi-findings.mjs +0 -100
- package/scripts/somi-loop.mjs +0 -139
- package/scripts/somi-tier.mjs +0 -393
- package/scripts/validate.sh +0 -653
- package/skills/api-design/SKILL.md +0 -147
- package/skills/clean-code/SKILL.md +0 -142
- package/skills/flow-adopt/SKILL.md +0 -92
- package/skills/flow-architecture-review/SKILL.md +0 -94
- package/skills/flow-atlas/SKILL.md +0 -34
- package/skills/flow-code/SKILL.md +0 -167
- package/skills/flow-code-loop/SKILL.md +0 -263
- package/skills/flow-code-parallel/SKILL.md +0 -160
- package/skills/flow-debug/SKILL.md +0 -141
- package/skills/flow-design/SKILL.md +0 -170
- package/skills/flow-discover/SKILL.md +0 -204
- package/skills/flow-impact/SKILL.md +0 -35
- package/skills/flow-incident/SKILL.md +0 -49
- package/skills/flow-plan/SKILL.md +0 -254
- package/skills/flow-plan-loop/SKILL.md +0 -254
- package/skills/flow-pr/SKILL.md +0 -34
- package/skills/flow-refactor/SKILL.md +0 -58
- package/skills/flow-refactor-design/SKILL.md +0 -97
- package/skills/flow-release-readiness/SKILL.md +0 -82
- package/skills/flow-review/SKILL.md +0 -193
- package/skills/flow-review-panel/SKILL.md +0 -154
- package/skills/flow-security-review/SKILL.md +0 -83
- package/skills/flow-ship/SKILL.md +0 -125
- package/skills/flow-ship-loop/SKILL.md +0 -274
- package/skills/flow-somi-config/SKILL.md +0 -142
- package/skills/flow-status/SKILL.md +0 -43
- package/skills/flow-test-strategy/SKILL.md +0 -83
- package/skills/flow-upgrade/SKILL.md +0 -82
- package/skills/market-research/SKILL.md +0 -125
- package/skills/observability/SKILL.md +0 -133
- package/skills/owasp-defense/SKILL.md +0 -141
- package/skills/plan-review/SKILL.md +0 -83
- package/skills/reasoning-craft/SKILL.md +0 -213
- package/skills/requirements-engineering/SKILL.md +0 -137
- package/skills/role-coder/SKILL.md +0 -247
- package/skills/role-designer/SKILL.md +0 -172
- package/skills/role-discovery-analyst/SKILL.md +0 -288
- package/skills/role-planner/SKILL.md +0 -353
- package/skills/role-reviewer/SKILL.md +0 -218
- package/skills/rules/SKILL.md +0 -47
- package/skills/sdlc-process/SKILL.md +0 -74
- package/skills/solid-principles/SKILL.md +0 -143
- package/skills/somi-checkpoint/SKILL.md +0 -95
- package/skills/somi-dispatch/SKILL.md +0 -259
- package/skills/somi-routing/SKILL.md +0 -158
- package/skills/testing-playbook/SKILL.md +0 -133
- package/skills/threat-modeling/SKILL.md +0 -117
- package/templates/ADR.md.tmpl +0 -73
- package/templates/ATLAS.md.tmpl +0 -75
- package/templates/BRD.md.tmpl +0 -68
- package/templates/BRIEF.md.tmpl +0 -119
- package/templates/CONTEXT.md.tmpl +0 -74
- package/templates/DECISIONS.md.tmpl +0 -105
- package/templates/DESIGN.md.tmpl +0 -83
- package/templates/DIARY.md.tmpl +0 -70
- package/templates/DOD.md.tmpl +0 -90
- package/templates/FRD.md.tmpl +0 -64
- package/templates/PHASE.md.tmpl +0 -80
- package/templates/PROGRESS.md.tmpl +0 -63
- package/templates/RCA.md.tmpl +0 -53
- package/templates/RD-README.md.tmpl +0 -70
- package/templates/RESEARCH.md.tmpl +0 -96
- package/templates/REVIEW.md.tmpl +0 -82
- package/templates/SDD.md.tmpl +0 -82
- package/templates/SOMI-README.md.tmpl +0 -83
- package/templates/SPEC.md.tmpl +0 -123
- package/templates/SRS.md.tmpl +0 -85
- package/templates/TDD.md.tmpl +0 -77
- package/tests/hooks/cases/audit-log.json +0 -21
- package/tests/hooks/cases/block-dangerous-bash.json +0 -166
- package/tests/hooks/cases/block-secret-writes.json +0 -140
- package/tests/hooks/cases/detect-repo-instructions.json +0 -105
- package/tests/hooks/cases/gate-dep-install.json +0 -42
- package/tests/hooks/cases/guard-protected-paths.json +0 -222
- package/tests/hooks/cases/inject-workflow-context.json +0 -239
- package/tests/hooks/cases/lint-changed-files.json +0 -120
- package/tests/hooks/run.sh +0 -392
- package/tests/scripts/agent-model-frontmatter.sh +0 -38
- package/tests/scripts/agent-names.sh +0 -77
- package/tests/scripts/check-frontmatter.sh +0 -37
- package/tests/scripts/check-links.sh +0 -105
- package/tests/scripts/check-session-artefacts.sh +0 -60
- package/tests/scripts/check-size-budget.sh +0 -71
- package/tests/scripts/checkpoint-gate.sh +0 -131
- package/tests/scripts/convergence-runner.sh +0 -1514
- package/tests/scripts/cost-ceiling.sh +0 -255
- package/tests/scripts/cost-defaults.sh +0 -130
- package/tests/scripts/cost-hardcap.sh +0 -338
- package/tests/scripts/cost-lowering.sh +0 -261
- package/tests/scripts/cost-model.sh +0 -196
- package/tests/scripts/dispatch-guard.sh +0 -108
- package/tests/scripts/dispatch-line-gate.sh +0 -61
- package/tests/scripts/dispatch-reference-gate.sh +0 -173
- package/tests/scripts/ensure-default-config.sh +0 -162
- package/tests/scripts/escalation.sh +0 -409
- package/tests/scripts/eval-runner.sh +0 -3692
- package/tests/scripts/evals-packaging.sh +0 -224
- package/tests/scripts/fact-sheet.sh +0 -296
- package/tests/scripts/fixtures/legacy-shard-no-schema.json +0 -50
- package/tests/scripts/fixtures/mock-stdin-read-throw.cjs +0 -18
- package/tests/scripts/fixtures/size-tier-cases.json +0 -87
- package/tests/scripts/generate-digest.sh +0 -180
- package/tests/scripts/global-config.sh +0 -167
- package/tests/scripts/goldens/loop-state-breach.json +0 -1
- package/tests/scripts/goldens/loop-state-done.json +0 -1
- package/tests/scripts/goldens/somi-findings.json +0 -336
- package/tests/scripts/goldens/somi-loop.json +0 -168
- package/tests/scripts/lib/adr-shape.mjs +0 -41
- package/tests/scripts/lib/agent-registry-tests.mjs +0 -95
- package/tests/scripts/lib/brief-only-guard.mjs +0 -27
- package/tests/scripts/lib/checkpoint-gate.mjs +0 -91
- package/tests/scripts/lib/digest-marker-coupling.mjs +0 -52
- package/tests/scripts/lib/dispatch-reference-gate.mjs +0 -121
- package/tests/scripts/lib/escalation-facts-tests.mjs +0 -140
- package/tests/scripts/lib/escalation-tests.mjs +0 -154
- package/tests/scripts/lib/findings-ledger-tests.mjs +0 -118
- package/tests/scripts/lib/loop-engine-tests.mjs +0 -287
- package/tests/scripts/lib/loop-escalate-tests.mjs +0 -356
- package/tests/scripts/lib/loop-flow-gate.mjs +0 -173
- package/tests/scripts/lib/loop-notes-tests.mjs +0 -384
- package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -156
- package/tests/scripts/lib/loop-step-close-tests.mjs +0 -351
- package/tests/scripts/lib/loop-step-lenient-tests.mjs +0 -114
- package/tests/scripts/lib/loop-step-state-tests.mjs +0 -127
- package/tests/scripts/lib/loop-step-tests.mjs +0 -499
- package/tests/scripts/lib/loop-step-unwritten-tests.mjs +0 -55
- package/tests/scripts/lib/multipass-dependence.mjs +0 -192
- package/tests/scripts/lib/multipass-source-identity.mjs +0 -243
- package/tests/scripts/lib/path-facts-tests.mjs +0 -198
- package/tests/scripts/lib/path-safety-tests.mjs +0 -201
- package/tests/scripts/lib/reference-pair.mjs +0 -61
- package/tests/scripts/lib/retirement-gate.mjs +0 -172
- package/tests/scripts/lib/run-suites.mjs +0 -139
- package/tests/scripts/lib/shell-embedded-js.mjs +0 -47
- package/tests/scripts/lib/ship-loop-sizing-guard.mjs +0 -52
- package/tests/scripts/lib/site-roadmap-gate.mjs +0 -64
- package/tests/scripts/lib/size-tier-drift.mjs +0 -74
- package/tests/scripts/lib/sizing-score-tests.mjs +0 -210
- package/tests/scripts/lib/sizing-set-tests.mjs +0 -131
- package/tests/scripts/lib/somi-mcp-client.mjs +0 -102
- package/tests/scripts/lib/somi-mcp-config-tests.mjs +0 -92
- package/tests/scripts/lib/somi-mcp-loop-tests.mjs +0 -226
- package/tests/scripts/lib/somi-mcp-tests.mjs +0 -491
- package/tests/scripts/lib/somi-mcp-tier-tests.mjs +0 -64
- package/tests/scripts/lib/somi-mcp-tool-schema.mjs +0 -38
- package/tests/scripts/loop-engine.sh +0 -22
- package/tests/scripts/loop-flow-gate.sh +0 -11
- package/tests/scripts/retirement-gate.sh +0 -306
- package/tests/scripts/review-panel-seats.sh +0 -32
- package/tests/scripts/run-card.sh +0 -57
- package/tests/scripts/run-suites.sh +0 -74
- package/tests/scripts/run.sh +0 -689
- package/tests/scripts/site-roadmap-gate.sh +0 -76
- package/tests/scripts/size-tier.sh +0 -562
- package/tests/scripts/somi-agent-dispatch-contract.sh +0 -224
- package/tests/scripts/somi-config.sh +0 -286
- package/tests/scripts/somi-dispatch.sh +0 -465
- package/tests/scripts/somi-mcp.sh +0 -15
- package/tests/scripts/suite-plan.json +0 -20
package/scripts/somi-loop.mjs
DELETED
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
// somi-loop.mjs — command line of the deterministic state engine for the bounded loops: parses the arguments,
|
|
2
|
-
// calls the handler in lib/loop-engine.mjs and prints its result. No gate logic lives here.
|
|
3
|
-
//
|
|
4
|
-
// The gates live in lib/loop-engine.mjs, cap resolution (flag > env var > .somi/config.json > default) in
|
|
5
|
-
// lib/loop-caps.mjs, state in lib/loop-state.mjs, diff measurement in lib/loop-diff.mjs. Exit codes and stdout
|
|
6
|
-
// JSON shapes are frozen; callers branch on them: 0 ok, 2 max passes, 3 diff cap, 4 time budget, 5 circuit breaker
|
|
7
|
-
// (step after-review), 64 usage, 65 record-dispatch's resolver refused the agent, 70 internal error (step only).
|
|
8
|
-
//
|
|
9
|
-
// Subcommands (each prints one JSON object): run-start, init, resume, stats, pass, check-diff, review-scope,
|
|
10
|
-
// record-dispatch, record-pass, finish, and `step <open|after-code|after-review|close|status>`: the composite steps of
|
|
11
|
-
// lib/loop-step.mjs, arguments as `--flag value` (--findings and --fixed as JSON text or @<file> holding it, --reviewers comma-separated), the
|
|
12
|
-
// response on stdout as one JSON line, its `exit` as the exit code, nothing on stderr: the response carries every refusal
|
|
13
|
-
// (a bad flag included, exit 64), and an internal error (70) goes to <state dir>/step-errors.log, never to the stderr a model reads.
|
|
14
|
-
//
|
|
15
|
-
// Tested by tests/scripts/run.sh (wired into scripts/validate.sh / CI).
|
|
16
|
-
|
|
17
|
-
import fs from 'node:fs';
|
|
18
|
-
import path from 'node:path';
|
|
19
|
-
import { execFileSync } from 'node:child_process';
|
|
20
|
-
import { fileURLToPath } from 'node:url';
|
|
21
|
-
import { LoopExit, PROG, usageError } from './lib/loop-exit.mjs';
|
|
22
|
-
import { runStep } from './lib/loop-step.mjs';
|
|
23
|
-
import { base, clean, cut, stepLog } from './lib/loop-step-kit.mjs';
|
|
24
|
-
import { checkDiff, finish, init, pass, recordDispatch, recordPass, resume, reviewScope, runStart } from './lib/loop-engine.mjs';
|
|
25
|
-
|
|
26
|
-
// Unwinding with a LoopExit reaches the top-level handler, which writes its message to stderr and sets
|
|
27
|
-
// process.exitCode, letting Node exit naturally — avoids process.exit()'s risk of truncating buffered
|
|
28
|
-
// stdout/stderr writes on a pipe.
|
|
29
|
-
function die(msg) {
|
|
30
|
-
throw usageError(msg);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function requireGit() {
|
|
34
|
-
try {
|
|
35
|
-
execFileSync('git', ['--version'], { stdio: 'ignore' });
|
|
36
|
-
} catch {
|
|
37
|
-
die('requires git');
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function projectRoot() {
|
|
42
|
-
let b = process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
43
|
-
if (b.includes('${')) b = process.cwd();
|
|
44
|
-
return b;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// A handler's result: its one JSON object on stdout, its message on stderr, its code as the exit code.
|
|
48
|
-
function deliver(result, space) {
|
|
49
|
-
if (result.out !== undefined) console.log(JSON.stringify(result.out, null, space));
|
|
50
|
-
if (result.message) process.stderr.write(`${result.message}\n`);
|
|
51
|
-
process.exitCode = result.code;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// subcommand -> handler, and the JSON indent where it is not the compact default (`stats` is read by people).
|
|
55
|
-
const COMMANDS = {
|
|
56
|
-
'run-start': { handler: runStart }, init: { handler: init }, resume: { handler: resume }, stats: { handler: resume, space: 2 },
|
|
57
|
-
pass: { handler: pass }, 'check-diff': { handler: checkDiff }, 'review-scope': { handler: reviewScope },
|
|
58
|
-
'record-dispatch': { handler: recordDispatch }, 'record-pass': { handler: recordPass }, finish: { handler: finish },
|
|
59
|
-
};
|
|
60
|
-
const STEP_FLAGS = ['slug', 'loop', 'iteration', 'files', 'host', 'max-passes', 'diff-cap', 'agent', 'review-mode', 'review-scope', 'reviewers', 'verdict', 'blockers', 'majors', 'findings', 'review', 'fixed', 'status'];
|
|
61
|
-
// `--findings` and `--fixed` take JSON text, or `@<file>` naming a UTF-8 file that holds it: Windows PowerShell 5.1 strips
|
|
62
|
-
// the double quotes inside an argument it passes to node, so JSON typed on its command line never arrives intact.
|
|
63
|
-
function jsonArg(key, value) {
|
|
64
|
-
let text = value;
|
|
65
|
-
if (value.startsWith('@')) {
|
|
66
|
-
try { text = fs.readFileSync(value.slice(1), 'utf8').replace(/^\uFEFF/, ''); } catch (e) { die(`--${key}: cannot read ${cut(value.slice(1), 80)} (${e.code ?? 'error'})`); }
|
|
67
|
-
}
|
|
68
|
-
try { return JSON.parse(text); } catch { return die(`--${key} expects JSON text, or @<file> holding it (from PowerShell, which strips the quotes in an argument, write the JSON to a file and pass --${key} @<file>)`); }
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// The step's arguments from `--flag value` pairs, as runStep takes them. A flag it does not know, a repeated one or one without a value is a usage error (echoed cut and cleaned).
|
|
72
|
-
function stepArgs(argv) {
|
|
73
|
-
const args = { step: argv[0] };
|
|
74
|
-
for (let i = 1; i < argv.length; i += 2) {
|
|
75
|
-
const key = argv[i].replace(/^--/, '');
|
|
76
|
-
if (!argv[i].startsWith('--') || !STEP_FLAGS.includes(key) || argv[i + 1] === undefined) die(`unknown argument or missing value: ${cut(argv[i], 40)}`);
|
|
77
|
-
if (Object.hasOwn(args, key.replaceAll('-', '_'))) die(`repeated argument: ${cut(argv[i], 40)}`);
|
|
78
|
-
args[key.replaceAll('-', '_')] = argv[i + 1];
|
|
79
|
-
}
|
|
80
|
-
for (const k of ['findings', 'fixed']) if (args[k] !== undefined) args[k] = jsonArg(k, args[k]);
|
|
81
|
-
if (args.reviewers !== undefined) args.reviewers = args.reviewers.split(',');
|
|
82
|
-
return args;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const FLAGS = {
|
|
86
|
-
'--slug': 'slug', '--loop': 'loop', '--iteration': 'iteration', '--files': 'files', '--max-passes': 'maxPasses',
|
|
87
|
-
'--diff-cap': 'diffCap', '--severity-floor': 'severity', '--verdict': 'verdict', '--blockers': 'blockers',
|
|
88
|
-
'--majors': 'majors', '--status': 'status', '--agent': 'agent', '--host': 'host', '--max-minutes': 'maxMinutes',
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
function step(argv) {
|
|
92
|
-
const root = projectRoot();
|
|
93
|
-
const explicit = Boolean(process.env.SOMI_LOOP_STATE_DIR);
|
|
94
|
-
const stateDir = process.env.SOMI_LOOP_STATE_DIR || path.join(root, '.somi', 'somi-state', 'loop');
|
|
95
|
-
const installRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
96
|
-
let resp;
|
|
97
|
-
try {
|
|
98
|
-
resp = runStep({ root, env: process.env, stateDir, installRoot, via: 'cli', log: stepLog(root, stateDir, explicit) }, stepArgs(argv));
|
|
99
|
-
} catch (e) { // a flag the parser refuses answers like any other refusal of a step: the response on stdout
|
|
100
|
-
if (!(e instanceof LoopExit)) throw e;
|
|
101
|
-
resp = base(clean(argv[0] ?? '', 20) || null, { ok: false, exit: e.code, error: clean(e.message.replace(`${PROG}: `, ''), 300) });
|
|
102
|
-
}
|
|
103
|
-
deliver({ out: resp, code: resp.exit }, undefined);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function main() {
|
|
107
|
-
requireGit();
|
|
108
|
-
|
|
109
|
-
const cmd = process.argv[2] || '';
|
|
110
|
-
if (cmd === 'step') return step(process.argv.slice(3));
|
|
111
|
-
const args = { slug: '', loop: 'code', iteration: '', files: '', verdict: '', blockers: '0', majors: '0', status: '', agent: '', host: undefined, maxMinutes: '', force: false, maxPasses: '', diffCap: '', severity: '' };
|
|
112
|
-
for (let rest = process.argv.slice(3); rest.length > 0;) {
|
|
113
|
-
if (rest[0] === '--force') { args.force = true; rest = rest.slice(1); continue; }
|
|
114
|
-
if (!Object.hasOwn(FLAGS, rest[0])) die(`unknown argument: ${cut(rest[0], 40)}`);
|
|
115
|
-
args[FLAGS[rest[0]]] = rest[1];
|
|
116
|
-
rest = rest.slice(2);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
if (!cmd) die('usage: somi-loop.mjs <run-start|init|resume|pass|check-diff|review-scope|record-dispatch|record-pass|finish|stats> --slug <slug> …, or step <name> …');
|
|
120
|
-
if (!args.slug) die('--slug is required');
|
|
121
|
-
if (!Object.hasOwn(COMMANDS, cmd)) die(`unknown subcommand: ${cut(cmd, 40)}`);
|
|
122
|
-
|
|
123
|
-
const root = projectRoot();
|
|
124
|
-
const stateDir = process.env.SOMI_LOOP_STATE_DIR || path.join(root, '.somi', 'somi-state', 'loop');
|
|
125
|
-
const installRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
126
|
-
const { handler, space } = COMMANDS[cmd];
|
|
127
|
-
deliver(handler({ root, env: process.env, stateDir, installRoot }, args), space);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
try {
|
|
131
|
-
main();
|
|
132
|
-
} catch (e) {
|
|
133
|
-
if (e instanceof LoopExit) {
|
|
134
|
-
process.stderr.write(`${e.message}\n`);
|
|
135
|
-
process.exitCode = e.code;
|
|
136
|
-
} else {
|
|
137
|
-
throw e;
|
|
138
|
-
}
|
|
139
|
-
}
|
package/scripts/somi-tier.mjs
DELETED
|
@@ -1,393 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// somi-tier.mjs — CLI over scripts/lib/size-tier.mjs's decideTier(): how much pipeline does this
|
|
3
|
-
// request deserve, and what was decided?
|
|
4
|
-
//
|
|
5
|
-
// resolve --signals <file|-> [--override small|full] [--record <slug> [--project-dir <dir>]]
|
|
6
|
-
// Reads signals JSON (a file path, or - for stdin; at most 64 KiB; a path must be a regular
|
|
7
|
-
// file, never a symlink or FIFO), calls decideTier, applies the optional override, prints one
|
|
8
|
-
// JSON line: { tier, effective, source, floor, security_lens, failed, unknown, invalid, reasons, basis }.
|
|
9
|
-
// security_lens is true unless the request is proven free of untrusted input and of auth, crypto,
|
|
10
|
-
// secrets and PII; /code-loop then reviews with the security lens at any tier.
|
|
11
|
-
// When the input holds keys that are not signal ids, the line also carries `unrecognized` (at
|
|
12
|
-
// most 8 of those names, each cut to 40 characters and ASCII-escaped; values are never
|
|
13
|
-
// echoed) and `expected` (the exact signal ids), so a caller can correct its input. Those two
|
|
14
|
-
// fields appear only then; the decision itself is unchanged (a missing signal is read as its
|
|
15
|
-
// worst case).
|
|
16
|
-
// tier what the function computed
|
|
17
|
-
// effective the tier to run: the computed one, or the override
|
|
18
|
-
// source 'computed' | 'override' (flag) | 'env' (SOMI_SHIP_LOOP_TIER)
|
|
19
|
-
// The override may only be small or full. The --override flag wins over the environment
|
|
20
|
-
// variable; an empty variable counts as unset. Raising the tier is always allowed; lowering
|
|
21
|
-
// it is refused when the result carries floor 'full'. Invalid signals are not an error here:
|
|
22
|
-
// decideTier already read them as their worst case and lists them in `invalid`.
|
|
23
|
-
//
|
|
24
|
-
// --record <slug> also writes <project>/.somi/somi-state/tier/<slug>.json from that same
|
|
25
|
-
// result, so the recorded tier, source, floor and signals hash are the computed ones by
|
|
26
|
-
// construction: { slug, tier (the effective one), source, computed_tier, floor, security_lens, reasons,
|
|
27
|
-
// failed, basis, signals_sha256, attempt, prior, recorded_at }, and the stdout line gains
|
|
28
|
-
// `recorded` (the path relative to the project). Every attempt that computed a tier, refusals
|
|
29
|
-
// included, is first appended to tier/<slug>.attempts.jsonl (append-only, 0600, links never
|
|
30
|
-
// followed); `attempt` is its number and `prior` the { computed_tier, signals_sha256 } of
|
|
31
|
-
// the earlier ones. A re-record whose computed tier is lower than any earlier computed tier
|
|
32
|
-
// is refused (65) unless --override is given. The basis is the whole one whenever the
|
|
33
|
-
// effective tier is lower than the computed tier. The project is --project-dir or the
|
|
34
|
-
// current directory.
|
|
35
|
-
// signals_sha256 is the sha256 of the signal entries only (their value and evidence, in id
|
|
36
|
-
// order, scalars only), so key order and extra keys do not change it. Directories it creates
|
|
37
|
-
// are 0700, the file is 0600, written to a temp file and renamed; a link at .somi,
|
|
38
|
-
// somi-state or tier is refused, and a link at the final path is replaced, not followed.
|
|
39
|
-
// Residual, accepted: a same-user process that swaps a checked directory for a link between
|
|
40
|
-
// the check and the write is not defended against.
|
|
41
|
-
//
|
|
42
|
-
// approve --slug <slug> [--project-dir <dir>]
|
|
43
|
-
// Stamps approved_at and brief_sha256 (of .somi/plans/<slug>/brief.md) into the slug's record.
|
|
44
|
-
// Run once, after the human replies approve and brief.md is written. Refused (65) unless the
|
|
45
|
-
// record is tier small with a signals hash and not yet approved; 64 when the record or the
|
|
46
|
-
// brief cannot be read. `somi-loop.mjs init` accepts a brief-only item only with this stamp.
|
|
47
|
-
//
|
|
48
|
-
// Output (stdout and the state file) is pure ASCII: every non-ASCII character is \uXXXX-escaped.
|
|
49
|
-
// Error messages never echo input text raw: values are JSON-quoted and non-ASCII is escaped.
|
|
50
|
-
//
|
|
51
|
-
// Exit codes (callers branch on these — do not repurpose):
|
|
52
|
-
// 0 ok
|
|
53
|
-
// 64 usage, input or I/O error: bad flag or value, unreadable or oversize input, JSON parse
|
|
54
|
-
// error, signals that are not an object, bad slug, unusable state directory, failed write
|
|
55
|
-
// 65 refused: a downward override below a security floor (names the floor on stderr), or a
|
|
56
|
-
// re-record whose computed tier is lower than an earlier one without --override
|
|
57
|
-
// Nothing is printed to stdout on an error path. Zero-dependency: stdlib only.
|
|
58
|
-
|
|
59
|
-
import crypto from 'node:crypto';
|
|
60
|
-
import fs from 'node:fs';
|
|
61
|
-
import path from 'node:path';
|
|
62
|
-
import { decideTier, SIGNAL_IDS } from './lib/size-tier.mjs';
|
|
63
|
-
import { briefSha256, readRecord } from './lib/tier-record.mjs';
|
|
64
|
-
|
|
65
|
-
const PROG = 'somi-tier';
|
|
66
|
-
const USAGE = `usage: ${PROG}.mjs resolve --signals <file|-> [--override small|full] [--record <slug> [--project-dir <dir>]] | approve --slug <slug> [--project-dir <dir>]`;
|
|
67
|
-
|
|
68
|
-
const EXIT_USAGE = 64;
|
|
69
|
-
const EXIT_FLOOR = 65;
|
|
70
|
-
|
|
71
|
-
const MAX_INPUT_BYTES = 64 * 1024;
|
|
72
|
-
const MAX_UNRECOGNIZED = 8;
|
|
73
|
-
const MAX_NAME_CHARS = 40;
|
|
74
|
-
const OVERRIDE_TARGETS = ['small', 'full'];
|
|
75
|
-
const TIERS = ['trivial', 'small', 'full'];
|
|
76
|
-
const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
77
|
-
const ENV_OVERRIDE = 'SOMI_SHIP_LOOP_TIER';
|
|
78
|
-
const STATE_DIRS = ['.somi', 'somi-state', 'tier'];
|
|
79
|
-
const MISSING = '\u0000missing';
|
|
80
|
-
const NON_SCALAR = '\u0000non-scalar';
|
|
81
|
-
|
|
82
|
-
class ExitSignal extends Error {
|
|
83
|
-
constructor(code) {
|
|
84
|
-
super(`exit ${code}`);
|
|
85
|
-
this.code = code;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// JSON with every non-ASCII character escaped, so neither stdout nor an error line can carry
|
|
90
|
-
// bidi, line-separator or C1 characters that a terminal would act on.
|
|
91
|
-
const ascii = (x, indent) => JSON.stringify(x, null, indent)
|
|
92
|
-
.replace(/[\u007f-\uffff]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
93
|
-
const quote = (x) => ascii(String(x));
|
|
94
|
-
|
|
95
|
-
function fail(code, msg) {
|
|
96
|
-
process.stderr.write(`${PROG}: ${msg}\n`);
|
|
97
|
-
throw new ExitSignal(code);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function die(msg) {
|
|
101
|
-
fail(EXIT_USAGE, `${msg}\n${USAGE}`);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
const rank = (t) => TIERS.indexOf(t);
|
|
105
|
-
|
|
106
|
-
// flags: { '--name': { oneOf?, pattern? } } -> { '--name': value }. A flag given twice, without a
|
|
107
|
-
// value, or with an empty or out-of-list value is a usage error.
|
|
108
|
-
function parseFlags(args, flags) {
|
|
109
|
-
const out = Object.create(null);
|
|
110
|
-
for (let i = 0; i < args.length; i += 2) {
|
|
111
|
-
const flag = args[i];
|
|
112
|
-
if (!Object.hasOwn(flags, flag)) die(`unknown argument: ${quote(flag)}`);
|
|
113
|
-
const spec = flags[flag];
|
|
114
|
-
const value = args[i + 1];
|
|
115
|
-
if (value === undefined || value === '') die(`${flag} requires a non-empty value`);
|
|
116
|
-
if (flag in out) die(`${flag} given twice`);
|
|
117
|
-
if (spec.oneOf && !spec.oneOf.includes(value)) die(`${flag} must be one of: ${spec.oneOf.join(', ')}`);
|
|
118
|
-
if (spec.pattern && !spec.pattern.test(value)) die(`${flag} is not a valid ${flag.slice(2)}`);
|
|
119
|
-
out[flag] = value;
|
|
120
|
-
}
|
|
121
|
-
return out;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// Reads at most MAX_INPUT_BYTES from a regular file (opened without following links or blocking
|
|
125
|
-
// on a FIFO) or stdin.
|
|
126
|
-
function readBounded(src) {
|
|
127
|
-
let fd = 0;
|
|
128
|
-
let opened = false;
|
|
129
|
-
try {
|
|
130
|
-
if (src !== '-') {
|
|
131
|
-
fd = fs.openSync(src, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
132
|
-
opened = true;
|
|
133
|
-
if (!fs.fstatSync(fd).isFile()) fail(EXIT_USAGE, `${quote(src)} is not a regular file`);
|
|
134
|
-
}
|
|
135
|
-
const buf = Buffer.alloc(MAX_INPUT_BYTES + 1);
|
|
136
|
-
let total = 0;
|
|
137
|
-
while (total < buf.length) {
|
|
138
|
-
let n;
|
|
139
|
-
try {
|
|
140
|
-
n = fs.readSync(fd, buf, total, buf.length - total, null);
|
|
141
|
-
} catch (e) {
|
|
142
|
-
if (e.code === 'EOF') break;
|
|
143
|
-
if (e.code === 'EAGAIN') {
|
|
144
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
|
145
|
-
continue;
|
|
146
|
-
}
|
|
147
|
-
throw e;
|
|
148
|
-
}
|
|
149
|
-
if (n === 0) break;
|
|
150
|
-
total += n;
|
|
151
|
-
}
|
|
152
|
-
if (total > MAX_INPUT_BYTES) fail(EXIT_USAGE, `signals input exceeds ${MAX_INPUT_BYTES} bytes`);
|
|
153
|
-
return buf.subarray(0, total);
|
|
154
|
-
} catch (e) {
|
|
155
|
-
if (e instanceof ExitSignal) throw e;
|
|
156
|
-
return fail(EXIT_USAGE, `cannot read ${src === '-' ? 'stdin' : quote(src)}: ${e.code || 'error'}`);
|
|
157
|
-
} finally {
|
|
158
|
-
if (opened) fs.closeSync(fd);
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// -> the parsed signals object. Only JSON.parse output ever reaches decideTier.
|
|
163
|
-
function loadSignals(src) {
|
|
164
|
-
const bytes = readBounded(src);
|
|
165
|
-
let parsed;
|
|
166
|
-
try {
|
|
167
|
-
parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
168
|
-
} catch (e) {
|
|
169
|
-
// The engine's message quotes the offending input; only its position is safe to repeat.
|
|
170
|
-
const at = /position (\d+)/.exec(String(e && e.message));
|
|
171
|
-
return fail(EXIT_USAGE, `signals are not valid UTF-8 JSON${at ? ` (near position ${at[1]})` : ''}`);
|
|
172
|
-
}
|
|
173
|
-
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
174
|
-
fail(EXIT_USAGE, 'signals must be a JSON object');
|
|
175
|
-
}
|
|
176
|
-
return parsed;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
const field = (o, k) => (o !== null && typeof o === 'object' && Object.hasOwn(o, k) ? o[k] : MISSING);
|
|
180
|
-
const scalar = (x) => (x === null || ['string', 'number', 'boolean'].includes(typeof x) ? x : NON_SCALAR);
|
|
181
|
-
|
|
182
|
-
// Hash of the signal entries only, scalars only: bounded work however deeply the input nests.
|
|
183
|
-
function signalsHash(signals) {
|
|
184
|
-
const rows = SIGNAL_IDS.map((id) => {
|
|
185
|
-
const entry = field(signals, id);
|
|
186
|
-
return [id, scalar(field(entry, 'value')), scalar(field(entry, 'evidence'))];
|
|
187
|
-
});
|
|
188
|
-
return crypto.createHash('sha256').update(JSON.stringify(rows)).digest('hex');
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
function refuseBelowFloor(tier, floor, what, beforeFail) {
|
|
192
|
-
if (floor && rank(tier) < rank(floor)) {
|
|
193
|
-
beforeFail?.('refused_floor');
|
|
194
|
-
fail(EXIT_FLOOR, `${what} to ${tier} is refused: the security floor is ${floor} (the request is not proven free of security-sensitive work)`);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
// Creates the state directories under the project root, refusing any link on the way, and returns
|
|
199
|
-
// the real path of the tier directory after proving it sits inside the real project root.
|
|
200
|
-
function stateDir(projectDir) {
|
|
201
|
-
const root = fs.realpathSync(projectDir);
|
|
202
|
-
let dir = root;
|
|
203
|
-
for (const part of STATE_DIRS) {
|
|
204
|
-
dir = path.join(dir, part);
|
|
205
|
-
let st = null;
|
|
206
|
-
try {
|
|
207
|
-
st = fs.lstatSync(dir);
|
|
208
|
-
} catch (e) {
|
|
209
|
-
if (e.code !== 'ENOENT') throw e;
|
|
210
|
-
}
|
|
211
|
-
if (!st) fs.mkdirSync(dir, { mode: 0o700 });
|
|
212
|
-
else if (!st.isDirectory()) fail(EXIT_USAGE, `${path.relative(root, dir)} is not a real directory (links are not followed)`);
|
|
213
|
-
}
|
|
214
|
-
const real = fs.realpathSync(dir);
|
|
215
|
-
if (real !== path.join(root, ...STATE_DIRS)) fail(EXIT_USAGE, 'state directory escapes the project root');
|
|
216
|
-
return { root, real };
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
const MAX_ATTEMPTS = 50;
|
|
220
|
-
const MAX_LOG_BYTES = 256 * 1024;
|
|
221
|
-
const attemptsPath = (dirs, slug) => path.join(dirs.real, `${slug}.attempts.jsonl`);
|
|
222
|
-
|
|
223
|
-
// -> [{ computed_tier, signals_sha256 }] of every earlier attempt for the slug, oldest first.
|
|
224
|
-
// A log that cannot be read, is too large, or holds a malformed line fails closed.
|
|
225
|
-
function readAttempts(dirs, slug) {
|
|
226
|
-
let fd;
|
|
227
|
-
try {
|
|
228
|
-
try {
|
|
229
|
-
fd = fs.openSync(attemptsPath(dirs, slug), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
230
|
-
} catch (e) {
|
|
231
|
-
if (e.code === 'ENOENT') return [];
|
|
232
|
-
throw e;
|
|
233
|
-
}
|
|
234
|
-
const st = fs.fstatSync(fd);
|
|
235
|
-
if (!st.isFile() || st.size > MAX_LOG_BYTES) fail(EXIT_USAGE, 'the attempts log is not a regular file or is too large');
|
|
236
|
-
const rows = fs.readFileSync(fd, 'utf8').split('\n').filter(Boolean).map((line) => {
|
|
237
|
-
let row;
|
|
238
|
-
try { row = JSON.parse(line); } catch { row = null; }
|
|
239
|
-
const ok = row !== null && typeof row === 'object' && TIERS.includes(row.computed_tier)
|
|
240
|
-
&& (row.signals_sha256 === null || /^[0-9a-f]{64}$/.test(row.signals_sha256));
|
|
241
|
-
if (!ok) fail(EXIT_USAGE, 'the attempts log holds a malformed line');
|
|
242
|
-
return { computed_tier: row.computed_tier, signals_sha256: row.signals_sha256 };
|
|
243
|
-
});
|
|
244
|
-
if (rows.length >= MAX_ATTEMPTS) fail(EXIT_USAGE, `the attempts log is full (${MAX_ATTEMPTS} attempts); ask the human before sizing this work again`);
|
|
245
|
-
return rows;
|
|
246
|
-
} catch (e) {
|
|
247
|
-
if (e instanceof ExitSignal) throw e;
|
|
248
|
-
return fail(EXIT_USAGE, `cannot read the attempts log: ${e.code || 'error'}`);
|
|
249
|
-
} finally {
|
|
250
|
-
if (fd !== undefined) fs.closeSync(fd);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
// Appends one line (append-only, 0600, links never followed).
|
|
255
|
-
function appendAttempt(dirs, slug, row) {
|
|
256
|
-
let fd;
|
|
257
|
-
try {
|
|
258
|
-
fd = fs.openSync(attemptsPath(dirs, slug), fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW, 0o600);
|
|
259
|
-
if (!fs.fstatSync(fd).isFile()) fail(EXIT_USAGE, 'the attempts log is not a regular file');
|
|
260
|
-
const line = `${ascii(row)}\n`;
|
|
261
|
-
if (fs.writeSync(fd, line) !== line.length) throw Object.assign(new Error('short write'), { code: 'ESHORT' });
|
|
262
|
-
} catch (e) {
|
|
263
|
-
if (e instanceof ExitSignal) throw e;
|
|
264
|
-
fail(EXIT_USAGE, `cannot append to the attempts log: ${e.code || 'error'}`);
|
|
265
|
-
} finally {
|
|
266
|
-
if (fd !== undefined) fs.closeSync(fd);
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
function openState(projectDir) {
|
|
271
|
-
try {
|
|
272
|
-
return stateDir(projectDir);
|
|
273
|
-
} catch (e) {
|
|
274
|
-
if (e instanceof ExitSignal) throw e;
|
|
275
|
-
return fail(EXIT_USAGE, `cannot prepare the state directory: ${e.code || 'error'}`);
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
// Writes the record atomically (temp file, then rename); returns its path relative to the project.
|
|
280
|
-
function writeRecord(dirs, slug, doc) {
|
|
281
|
-
const body = `${ascii(doc, 2)}\n`;
|
|
282
|
-
const final = path.join(dirs.real, `${slug}.json`);
|
|
283
|
-
const tmp = path.join(dirs.real, `.${slug}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`);
|
|
284
|
-
try {
|
|
285
|
-
const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
286
|
-
try {
|
|
287
|
-
if (fs.writeSync(fd, body) !== body.length) throw Object.assign(new Error('short write'), { code: 'ESHORT' });
|
|
288
|
-
fs.fsyncSync(fd);
|
|
289
|
-
} finally {
|
|
290
|
-
fs.closeSync(fd);
|
|
291
|
-
}
|
|
292
|
-
fs.renameSync(tmp, final);
|
|
293
|
-
} catch (e) {
|
|
294
|
-
fs.rmSync(tmp, { force: true });
|
|
295
|
-
return fail(EXIT_USAGE, `cannot write the tier record: ${e.code || 'error'}`);
|
|
296
|
-
}
|
|
297
|
-
return path.relative(dirs.root, final);
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
function resolve(args) {
|
|
301
|
-
const f = parseFlags(args, {
|
|
302
|
-
'--signals': {}, '--override': { oneOf: OVERRIDE_TARGETS }, '--record': { pattern: SLUG }, '--project-dir': {},
|
|
303
|
-
});
|
|
304
|
-
if (!f['--signals']) die('--signals is required');
|
|
305
|
-
if (f['--project-dir'] && !f['--record']) die('--project-dir only applies with --record');
|
|
306
|
-
let requested = f['--override'];
|
|
307
|
-
let source = 'override';
|
|
308
|
-
if (!requested && process.env[ENV_OVERRIDE]) {
|
|
309
|
-
requested = process.env[ENV_OVERRIDE];
|
|
310
|
-
source = 'env';
|
|
311
|
-
if (!OVERRIDE_TARGETS.includes(requested)) die(`${ENV_OVERRIDE} must be one of: ${OVERRIDE_TARGETS.join(', ')}`);
|
|
312
|
-
}
|
|
313
|
-
const signals = loadSignals(f['--signals']);
|
|
314
|
-
const r = decideTier(signals);
|
|
315
|
-
const slug = f['--record'];
|
|
316
|
-
// The attempts log is the memory of this slug: every attempt that computed a tier is appended,
|
|
317
|
-
// refusals included, before the failure exit.
|
|
318
|
-
const dirs = slug ? openState(f['--project-dir'] || process.cwd()) : null;
|
|
319
|
-
const prior = slug ? readAttempts(dirs, slug) : [];
|
|
320
|
-
const hash = slug ? signalsHash(signals) : null;
|
|
321
|
-
const log = (outcome) => slug && appendAttempt(dirs, slug, {
|
|
322
|
-
n: prior.length + 1, at: new Date().toISOString(), computed_tier: r.tier, requested: requested || null, outcome, signals_sha256: hash,
|
|
323
|
-
});
|
|
324
|
-
let effective = r.tier;
|
|
325
|
-
if (requested) {
|
|
326
|
-
refuseBelowFloor(requested, r.floor, `overriding ${r.tier}`, log);
|
|
327
|
-
effective = requested;
|
|
328
|
-
} else {
|
|
329
|
-
source = 'computed';
|
|
330
|
-
}
|
|
331
|
-
// Re-extracting cannot talk the tier down: only a human reply (the flag) can.
|
|
332
|
-
const highest = Math.max(-1, ...prior.map((a) => rank(a.computed_tier)));
|
|
333
|
-
if (slug && !f['--override'] && rank(r.tier) < highest) {
|
|
334
|
-
log('refused_lower');
|
|
335
|
-
fail(EXIT_FLOOR, `computed tier ${r.tier} is lower than an earlier computed tier (${TIERS[highest]}) for this slug; re-extracting cannot lower the tier (a human reply with --override is required)`);
|
|
336
|
-
}
|
|
337
|
-
// An override that lowers the tier shows the whole basis, not only the security signal's.
|
|
338
|
-
const shown = requested && rank(effective) < rank(r.tier) ? decideTier(signals, { fullBasis: true }) : r;
|
|
339
|
-
const out = {
|
|
340
|
-
tier: r.tier, effective, source, floor: r.floor, security_lens: r.securityLens, failed: r.failed, unknown: r.unknown,
|
|
341
|
-
invalid: r.invalid, reasons: r.reasons, basis: shown.basis,
|
|
342
|
-
};
|
|
343
|
-
const strange = signals !== null && typeof signals === 'object' && !Array.isArray(signals) ? Object.keys(signals).filter((k) => !SIGNAL_IDS.includes(k)) : [];
|
|
344
|
-
if (strange.length > 0) {
|
|
345
|
-
out.unrecognized = strange.slice(0, MAX_UNRECOGNIZED).map((k) => k.slice(0, MAX_NAME_CHARS));
|
|
346
|
-
out.expected = [...SIGNAL_IDS];
|
|
347
|
-
}
|
|
348
|
-
if (slug) {
|
|
349
|
-
log('accepted');
|
|
350
|
-
out.recorded = writeRecord(dirs, slug, {
|
|
351
|
-
slug, tier: effective, source, computed_tier: r.tier, floor: r.floor, security_lens: r.securityLens,
|
|
352
|
-
reasons: r.reasons, failed: r.failed, basis: shown.basis, signals_sha256: hash,
|
|
353
|
-
attempt: prior.length + 1, prior, recorded_at: new Date().toISOString(),
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
console.log(ascii(out));
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
// Stamps the approval into the record: run after the human's reply and after brief.md is written.
|
|
360
|
-
// Binds the approval to the brief as it is now; a later change to the brief voids it.
|
|
361
|
-
function approve(args) {
|
|
362
|
-
const f = parseFlags(args, { '--slug': { pattern: SLUG }, '--project-dir': {} });
|
|
363
|
-
if (!f['--slug']) die('--slug is required');
|
|
364
|
-
const dirs = openState(f['--project-dir'] || process.cwd());
|
|
365
|
-
const rec = readRecord(dirs.root, f['--slug']);
|
|
366
|
-
if (!rec) fail(EXIT_USAGE, 'there is no readable tier record for this slug');
|
|
367
|
-
if (rec.tier !== 'small') fail(EXIT_FLOOR, 'only a small tier record can be approved for a brief-only run');
|
|
368
|
-
if (typeof rec.signals_sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(rec.signals_sha256)) {
|
|
369
|
-
fail(EXIT_FLOOR, 'the record has no signals hash; resolve with --record first');
|
|
370
|
-
}
|
|
371
|
-
if (rec.approved_at) fail(EXIT_FLOOR, 'the record is already approved; a new approval needs a new resolve --record');
|
|
372
|
-
const brief = briefSha256(dirs.root, f['--slug']);
|
|
373
|
-
if (!brief) fail(EXIT_USAGE, 'brief.md is missing, a link, or too large');
|
|
374
|
-
const recorded = writeRecord(dirs, f['--slug'], { ...rec, approved_at: new Date().toISOString(), brief_sha256: brief });
|
|
375
|
-
console.log(ascii({ approved: true, recorded, brief_sha256: brief }));
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
function main() {
|
|
379
|
-
const [cmd, ...rest] = process.argv.slice(2);
|
|
380
|
-
if (cmd === 'resolve') resolve(rest);
|
|
381
|
-
else if (cmd === 'approve') approve(rest);
|
|
382
|
-
else die(cmd ? `unknown subcommand: ${quote(cmd)}` : 'a subcommand is required');
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
try {
|
|
386
|
-
main();
|
|
387
|
-
} catch (e) {
|
|
388
|
-
if (e instanceof ExitSignal) {
|
|
389
|
-
process.exitCode = e.code;
|
|
390
|
-
} else {
|
|
391
|
-
throw e;
|
|
392
|
-
}
|
|
393
|
-
}
|