mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 01:46:55 +02:00
* refactor(resolvers): split review.ts into MECE resolver modules (pure move) Move every function from scripts/resolvers/review.ts, unchanged, into: - review-dashboard.ts: review dashboard, plan-file review report - plan-gates.ts: approval check, exit-plan-mode gate, plan-file discovery, plan-completion audit/gate (ship + review), plan verification exec - spec-review.ts: both spec review loops, benefits-from, anti-shortcut clause - outside-voice-steps.ts: Codex second opinion, adversarial step, Codex plan review, Codex doc review, disabled-outside record - review-scope.ts: scope drift, cross-review dedup, shared-code reuse review.ts is deleted; index.ts imports the new modules. gen-skill-docs output is byte-identical for every host (--host all). Test imports and source-path references are re-pointed; the two source-text report/gate tests in gen-skill-docs.test.ts become behavioral renders across every consuming skill and host. All 46 touchfile entries that named review.ts now name all five modules, guarded by a recorded selection golden. * test(browse): black-box auth matrix for every server route and both surfaces Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token, root token, scoped token and the SSE cookie for all 33 routes, plus unmatched paths and wrong methods. Denials assert today's exact status, body and content type; allowed credentials assert the handler was reached. Written against the unchanged if-chain server so the W3 route-table refactor must keep it green. * refactor(shard-engine): move scripts/test-strict-output.ts to scripts/lib/shard-engine.ts The shared shard engine grows from the existing strict-output module (runShardChild, killProcessGroup, signal forwarding, strict classifier). scripts/test-strict-output.ts stays as a re-export so existing importers, mock.module paths and the strict-output/run-shard-child tests are unchanged. The engine inherits the global touchfile entry; the free runner's CLI-routing fixture copies the new module. * refactor(resolvers): decompose the three >150-line review resolvers (output-neutral) Split generateAdversarialStep, generateCodexPlanReview and generatePlanCompletionAuditInner into per-section helpers whose template literals are copied verbatim, so every function in the new modules is at or under 150 lines. gen-skill-docs output is byte-identical for every host (--host all, compared against96764e80with a fixed --link-root). * refactor(resolvers): one outside-voice failure policy (deliberate prose unification) outsideVoiceFailurePolicy(ctx, opts) in outside-voice.ts now renders the auth / timeout / empty-response bullets for all four call sites that hand-typed them (Codex second opinion, adversarial step, Codex plan review, design outside voices). Options are explicit per site (timeoutMinutes, onTimeout, stderrOnEmpty, fallback, escape) with no defaults. Deliberate generated-prose changes (every host): - office-hours: 'Fall back to <native> subagent.' becomes 'Fall back to the <native> subagent below.' - plan-devex-review: the plain 'Auth failure (stderr contains ...)' bullets become the canonical bold bullets; auth also triggers on 'API key'; 'auth failed' becomes 'authentication failed'. - review/ship adversarial: 'exceeded 9 minutes and was terminated' becomes 'timed out after 9 minutes and was terminated'; the timeout is still MISSING COVERAGE. - design outside voices: unchanged. Adds ratchet (d) (test/outside-voice-failure-policy.test.ts) with a reasoned allowlist for /codex's own CLI errors, the MISSING COVERAGE retention test, refreshed codex/factory ship goldens, and outside-voice.ts in every touchfile entry of review.ts and design.ts (selection golden extended). * test(pty): fake PTY session driver with an injectable clock through the runner launch seam The three plan-skill runners take an optional PtyDriver (launch, now, monotonic, sleep); omitted, they use the real launcher and clocks exactly as before. test/helpers/pty/fake-session.ts feeds scripted frames through that seam, and claude-pty-runner.runners.unit.test.ts runs observation, counting and floor for success, deadline timeout, permission prompt and plan-ready outcomes with no CLI or real timers. These cases must stay green unchanged through the W4 split and the runPtySession extraction. Touchfiles: every entry that lists claude-pty-runner.ts or pty-screen.ts now also lists test/helpers/pty/**. * refactor(shard-engine): run both lanes on the shared engine; lane policy injected Engine (scripts/lib/shard-engine.ts) gains the W2 primitives: per-shard tmp/Chromium sandbox + async cleanup backstop, log-path allocation and full-stream log capture, one duration-seed reader/writer with a lane predicate, LanePolicy (seed predicate + zero-execution verdict), strictShardStatus, and the shared CLI flag loop. runShardChild takes an optional companion (signal/settle) and waits a bounded 250ms to reap a wall-killed child. Free lane stops spawning shards itself: runFreeShard uses runShardChild with trackShardBrowser as the companion (win32 path unchanged: no process group, no negative-pid kill). Its sync state-dir removal stays lane policy. Paid lane uses the sandbox, log, seed, verdict and flag primitives; the hollow-shard guard applies PAID_LANE_POLICY. Lane outcomes are unchanged (free keeps >= 0 seeds and file-count zero-exec rule; paid keeps > 0 seeds, warning under selection and passed-empty under EVALS_ALL). paid-free-boundary's closure assertion now names the engine module, where the strict classifier lives. * test(shard-engine): engine unit tests, fixture-corpus equivalence, per-lane CLI parity - test/shard-engine.test.ts: failing/unhandled/module-load output fails both lanes, per-lane zero-execution and seed rules, whole-group kill on a wall timeout (both lanes), mocked-win32 path with no negative-pid kill, companion settle order, log capture, sandbox isolation, flag loop. - test/shard-engine-equivalence.test.ts + test/fixtures/shard-equivalence: seven outcome fixtures plus one real shard, run through both lanes and compared with classifications recorded from the base runners (96764e80). - test/shard-cli-parity.test.ts + test/fixtures/shard-cli-parity: flag set, defaults, validation errors and the Unknown argument error per lane match the base runners. * refactor(shard-engine): decompose runFreeShard and runPaidShard to <= 150 lines Output-neutral extraction under the fixture-corpus equivalence and runner tests: captureFreeStream, explainFreeVerdict and logFreeRecovery (free); paidShardCommand, settleShardSpool, settleBootstrapRetention and printLogTail (paid). The bootstrap scope-creation block that bootstrap-retention.test.ts evaluates stays verbatim. * refactor(pty): split claude-pty-runner.ts into test/helpers/pty/* behind a barrel Pure move: every line of the former 5,047-line runner lands verbatim in one module (four private helpers gain `export` for cross-module use): binary, screen (absorbs test/helpers/pty-screen.ts, which now re-exports it), launch, session (PtyDriver), judge, classify, auq, plan-native, boundaries, runners/{observation,counting,floor}. claude-pty-runner.ts re-exports the original public surface by name; pty/ modules import siblings directly. Tests that read the runner's source text: - rewritten as behavioral: the unit test's model-pin tripwire (fake CLI argv: fallback chain, --model before extraArgs, hermetic --strict-mcp-config), pty-skill-seeding-wiring (runners through the fake driver; launcher through a fake CLI reporting CLAUDE_CONFIG_DIR). The "three wrappers forward model" grep is replaced by the runners' fake-driver launch assertions. - pty-screen-session / pty-screen-supervision: stop copying runner source; they mock.module the real pty/screen.ts (and the fixture cleanup) instead. - re-pointed to the owning module (they execute a sliced runner body with injected boundaries; no seam exists for those boundaries yet): eng-seeded-completion-ai, plan-floor-permission, plan-create-prepublication, plan-count-completion; hermetic-wiring's source guard now reads pty/launch.ts and scans every pty/ module for raw process.env spreads. - plan-count-timeout and pty-output-wake mock the viewport at pty/screen.ts. * test(ratchet-c): enforcing module/function size ratchet and moved-code touchfile coverage Ratchet (c) ships enforcing: test/helpers/module-size.ts counts file and top-level function lengths by brace matching over masked source (strings, comments, regex literals and template text masked; ${} expressions kept), covering function declarations, arrow functions assigned to consts and route-table handler properties, with no parser dependency. Its self-test uses template literals and code-fence braces copied from scripts/resolvers/review.ts and design.ts. test/fixtures/module-size-ratchet.json binds scripts/lib/shard-engine.ts (<= 800 lines, <= 150 per function) and records the residual runner sizes (free 2352, paid 1921) as non-growth caps; allowlist entries are keyed on file plus matched text and need a reason. Failure output lists file:line, the rule, Fix: and the allowlist path. touchfiles.test.ts gains the moved-code superset check over test/fixtures/touchfile-move-goldens/ (W2 golden recorded at96764e80: test-strict-output.ts and test-paid-shards.ts global, test-free-shards.ts none). * refactor(browse): declared route table replaces the buildFetchHandler if-chain The ~1,300-line if-chain in buildFetchHandler becomes a route table: each entry declares method, path, auth kind and surfaces, and one auth gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer, scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token required; extension-origin: 403 Forbidden). Unmatched requests take the declared fallthrough (root-bearer check, then plain-text 404). Handlers move to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files, inspector}.ts and receive a RouteContext with auth checks as functions instead of closing over factory locals. Dispatch order is unchanged: tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a literal in server.ts. Behavior-preserving: the black-box auth matrix from the previous commit passes unchanged. /memory and /inspector/events are declared root-bearer because the blanket check always ran before their SSE-cookie branch. Source-text route tests are rewritten as behavioral tests through buildFetchHandler or a route's real handler with a stub RouteContext (browse/test/route-test-harness.ts). Checks with no runtime seam are re-pointed to the route modules: Surface type, /inspector/events SSE helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import, and the ngrok config lookup and startTunnel wiring that stay in server.ts. * test(browse): stubbed-handler auth matrix and route inventory for the route table Every ROUTES entry runs through the real dispatcher and gate with stub handlers on each declared surface and six credentials; denials assert the exact status and body each auth kind returned at96764e8, admitted credentials assert the handler ran (with the gate's TokenInfo for scoped routes). Also pins the reviewed route inventory (method, path, auth kind, surfaces), that every entry declares auth and surfaces, that the table's tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the unmatched fallthrough, and that the root token is rejected on every tunnel route through buildFetchHandler. * test(browse): ratchet (b) keeps route dispatch inside the route table Scans browse/src/server.ts and browse/src/routes/*.ts for pathname comparisons; only the table matcher and the tunnel-surface filter are allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file plus line text). Also checks every entry declares auth and surfaces and that gstack registers no beforeRoute overlay itself. Self-tests plant a violation and assert the file:line, Fix: and allowlist path in the message, that a shifted line stays allowlisted, and that a reasonless entry is rejected. * test: touchfile superset check for modules moved out of browse/src/server.ts Records the paid evals selected by touching browse/src/server.ts at96764e80(17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects a superset. The test reads every golden in test/fixtures/moved-module-selection/ so other moved-code goldens can sit beside it. * test(shard-engine): give non-timeout corpus fixtures CI headroom; keep the POSIX golden off the Windows lane Only the wall-timeout fixture keeps a 3s wall; the rest get 60s so a loaded host cannot turn a pass into a timeout. Base and branch runners still agree on every classification under the new walls. The Windows exclusion entry moves the free runner's ratchet (c) residual cap to 2356 lines. * refactor(pty): one runPtySession loop drives observation, counting and floor test/helpers/pty/session.ts owns launch -> start -> (poll -> tick)* -> timeout and the failure contract the three runners each hand-rolled: the run's own error wins over capture and close errors, close always runs, owned fixture cleanup runs last (also when launch fails). Each runner now supplies a PtySessionPlan: its boot/command step, poll cadence (2s observation/floor sleep; counting's output wake + 250ms coalesce), tick policy (permission handling, native identity, terminal rules stay per runner because they differ) and capture hooks. The runner bodies are decomposed into top-level steps so no function exceeds 150 lines; behavior is unchanged and the fake-driver cases from the first W4 commit pass unmodified. The counting capture step and the native completion-summary predicate are now named functions (countingCapture, isNativeCompletionSummary), so plan-create-prepublication and plan-count-completion call them directly instead of executing sliced source. The two harnesses that still execute a sliced runner body with injected boundaries (eng-seeded-completion-ai, plan-floor-permission) pass the PtyDriver seam instead of overriding Date/Bun.sleep. * test(ratchet-c): register route modules, review resolver modules and server.ts residual cap * refactor(pty): decompose launchClaudePty and engNumberedFindingAUQ under 150 lines launchClaudePty (349 lines) becomes launch preparation (args, hermetic child env, owned state roots), recorder creation, spawn, the trust-dialog watcher, close, and the session handle over one PtyProcess state object. The failure order is unchanged: abort the viewport, dispose any recorders created so far, dispose the viewport, rethrow. The --model / --strict-mcp-config ordering and seedSkills wiring stay pinned by the behavioral fake-CLI tests. engNumberedFindingAUQ (345 lines) keeps its guards and dispatch; each self-contained issue family (declared cache, library retry hooks, cache owner, injected singleton, shared writers, injected export) moves verbatim into its own function. Every pty/ module is now <= 800 lines and every top-level function <= 150 lines. * test(pty): split claude-pty-runner.unit.test.ts along the pty/ module seams The 188 unit tests move verbatim into claude-pty-runner.{screen,classify, auq,launch,plan-native,boundaries}.unit.test.ts (test names unchanged; each file imports only what it uses from the barrel). The five files that no longer read a SKILL.md template join the test-of-test ratchet baseline with a reason. * test(touchfiles): moved PTY modules keep their paid-eval selection test/fixtures/touchfile-selection/w4-pty.json records, at96764e8, the paid evals selected by touching test/helpers/claude-pty-runner.ts (20) and test/helpers/pty-screen.ts (20). touchfiles.test.ts now asserts every .ts file under test/helpers/pty/ (and pty/screen.ts for both sources) selects a superset, reading every golden in that directory so later moves can add one; a planted-violation case pins the report and its Fix line. * fix(browse): unexchanged pair setup keys no longer authenticate bearer requests validateToken accepted a gsk_setup_ key as a bearer on /command, /batch and /file (found while building the W3 auth matrix). A setup key now only authenticates the /connect exchange. * W1: one state-root owner (lib/state-root.ts + bin/gstack-state-root.sh), gstack-paths --explain and fail-stop, parity tests * W1: guarded migration of every executable state-root site; uninstall deletes only ~/.gstack Bins, careful/freeze hooks, setup, upgrade migrations, browse/src, design, ios-qa daemon, lib and scripts resolve the state root through bin/gstack-state-root.sh (bash) or lib/state-root.ts (TS). Bins source the twin and stop with a reinstall message when it is missing; hooks source it and never spawn gstack-paths. browse/src/config.ts and lib/cso/state.ts delegate to resolveStateRoot. Analytics writers and readers move together so the usage log stays one file. gstack-uninstall deletes state only at ~/.gstack, refuses (exit 2) when it resolves to /, $HOME or an ancestor, the checkout or the git root, and leaves any other resolved root in place with the removal command. Fixtures that copy single bins now copy the twin. * W1: privacy keys and trust-policy deny tiers merge across state roots; gstack-config reporting; test hermeticity readConfigKey / gstack_read_config_key return the most restrictive telemetry, memorable_recall, codex_reviews and update_check across the resolved root and ~/.gstack; other keys read the resolved root only. gstack-config set reports an overriding root with the exact override command, list shows the winning root and a root-variable disagreement line. gstack-gbrain-repo-policy get merges deny/read-only tiers. gstack-egress reads through readConfigKey. test-setup.ts strips inherited GSTACK_STATE_ROOT/GSTACK_STATE_DIR and redirects the legacy root. * W1: shared hook logging helper (hosts/claude/hooks/hook-log.ts) One hook-errors.log writer: root from resolveStateRoot, 0600 on every append, opt-in rate limit used only by memorable-user-prompt. The five hooks route through it. * W1: docs/state-root.md and README troubleshooting pointer Precedence table, a real --explain example, the move-your-state recipe, merged privacy keys, the uninstall rule, the resolver-failure fix, and the plugin-mode note (evidence gate: no official plugin distribution). * W1b: template and resolver prose resolve state through guarded gstack-paths; ratchet (a) Every gstack-paths eval in templates and resolvers carries the fail-stop guard; executable ~/.gstack paths in bash blocks (context recovery preamble, eureka log, analytics, project artifacts, upgrade snooze, setup-gbrain lock, retro snapshots, ship consent marker) use $GSTACK_STATE_ROOT, and the writer prose that pairs with them points at the printed PROJECT_DIR / RETRO_FILE. ship drops export GSTACK_STATE_ROOT. SKILL.md regenerated (claude + codex), ship goldens re-pinned, parity and context-budget caps raised to the measured sizes with notes. test/state-root-ratchet.test.ts enforces the rule with a reasoned allowlist; W1 touchfile entries plus a superset golden. * refactor: apply W1 state-root edits in W2/W3/W5-owned files; one moved-code touchfile golden for all workstreams * test: fold the moved-code touchfile golden into touchfiles.test.ts; fix integration fixture closure and caps * v1.91.11.0: CHANGELOG, TODOS, docs and conventions for the refactor wave * test: re-measure plan-ceo/design-consultation caps and ship goldens after the guarded plan-discovery and spec-review blocks; add the state-root twin to the workflow-boundaries fixture * fix(windows): migrations resolve their directory with either path separator; state-root parity compares under the HOME Git Bash actually sees * fix(review,ship): state plan-check timing after smoke expiry and test_stub Skip semantics (review workflow judge clarity) * test(qa-eval): webhook fix eval asks for the fix loop's post-repair probes; eight-scenario coverage stays in the report-only case and the harness recheck * test(qa-eval): re-pin the webhook prompt contract to the fix-loop stage; R29 coverage omissions stay bound by the report-only case * fix(review,ship): plan checks publish a checkpoint before each probe; only the smoke expiry stop is skipped * fix(qa): carry #2999's checkpoint receipt link, report-template line and full-revision placeholder (identical hunks) * test(qa-callers): disable git auto maintenance in the caller fixture Git 2.47+ runs auto maintenance detached after commit; on the CI runner's git 2.55 it rewrote .git/objects fan-out directories while the write observer was running, which surfaced as unauthorized mutations. Same gc.auto=0 / maintenance.auto=false guard the shared-libs fixture already uses. * test(plan-mode-no-op): require prose evidence for the prose-fallback members so a spinner-frame judge verdict cannot end the run as asked * test(ship-docsync): carry #2999's seeded-attempt docsync harness (identical files) The doc-sync fault cases replayed attempt 1 before reaching their gate and ran out of their 285s budget. The fixture now seeds attempt 1 and the parent starts at the gate under test. Taken byte-identical from origin/capy/audit-fix-wave (fb526898,e6ac813d,6ce10ff7,d0c53577,77cce3be). Local: stale-before, recovery and late-result 6/6 PASS (97-164s); the whole file 12/12 PASS.
391 lines
27 KiB
TypeScript
391 lines
27 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||
import { spawnSync } from 'node:child_process';
|
||
import { tmpdir } from 'node:os';
|
||
import { join, resolve } from 'node:path';
|
||
import { ALL_HOST_CONFIGS } from '../hosts';
|
||
import { generateAdversarialStep } from '../scripts/resolvers/outside-voice-steps';
|
||
import { generatePlanCompletionGateShip } from '../scripts/resolvers/plan-gates';
|
||
import { generateReviewDashboard } from '../scripts/resolvers/review-dashboard';
|
||
import { HOST_PATHS } from '../scripts/resolvers/types';
|
||
|
||
const read = (file: string) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8');
|
||
const compact = (text: string) => text.replace(/\s+/g, ' ');
|
||
const entry = read('ship/SKILL.md.tmpl');
|
||
const start = entry.indexOf('### Ship control flow');
|
||
const end = entry.indexOf('{{SECTION_INDEX:ship}}');
|
||
const controller = entry.slice(start, end);
|
||
const review = compact(read('ship/sections/review-army.md.tmpl'));
|
||
const adversarial = compact(generateAdversarialStep({ host: 'claude', skillName: 'ship', tmplPath: '', paths: HOST_PATHS.claude }));
|
||
const gate = compact(entry.slice(entry.indexOf('## Step 16:'), entry.indexOf('## Step 17:')));
|
||
|
||
describe('ship source controller', () => {
|
||
test('documentation freshness covers selected code paths as well as release metadata', () => {
|
||
const docs = compact(read('ship/sections/documentation.md.tmpl'));
|
||
expect(docs).toContain('hashes of the selected release paths, generated outputs and docs/templates');
|
||
const freshness = gate.slice(gate.indexOf('### 3.'), gate.indexOf('### 4.'));
|
||
expect(freshness).toContain('selected release paths, generated outputs and docs/templates');
|
||
expect(freshness).toContain("A prior invocation's audit or risk decision never qualifies");
|
||
expect(freshness).toContain('the same approved scope and exact content');
|
||
});
|
||
|
||
test('changed documentation inputs permit only the remaining bounded re-audit', () => {
|
||
const docs = compact(read('ship/sections/documentation.md.tmpl'));
|
||
const recovery = docs.slice(docs.indexOf('## Blocked recovery'));
|
||
expect(recovery).toContain('If an attempt remains and either the audited inputs changed');
|
||
expect(recovery).toContain('a concrete launch/input/permission correction or reviewed patch repair is available');
|
||
expect(docs).toContain('an initial audit plus ONE repair/re-audit');
|
||
expect(docs).toContain('never a third attempt, even after Step 16 changes');
|
||
const freshness = gate.slice(gate.indexOf('### 3.'), gate.indexOf('### 4.'));
|
||
expect(freshness).toContain('**An attempt remains, with changed inputs or an available repair:**');
|
||
expect(freshness).toContain('**Otherwise:** STOP unless the user accepts');
|
||
expect(freshness).not.toContain('**No attempt remains or no repair is available:**');
|
||
});
|
||
|
||
test('repairs use one ordered work list without a return stack', () => {
|
||
const text = compact(controller);
|
||
expect(compact(entry)).toContain('**Next steps:** one ordered work list, with the current step marked');
|
||
expect(text).toContain('Expand a repair into individual steps and insert them before the still-pending work');
|
||
expect(text).toContain('This replaces the current item, whose actual result stays in the record');
|
||
expect(text).toContain('Add its destination only if not already the next pending step');
|
||
expect(text).toContain('The saved list takes precedence over ordinary next-step sentences inside a repair');
|
||
expect(text).toContain('5 → 6 → 7 → 8 → 9 → 10 → 11 → 11.5');
|
||
expect(text).not.toContain('finish the inner repair, then resume the unfinished outer range');
|
||
expect(text).toContain('Keep the same attempt counts throughout the invocation');
|
||
expect(text).toContain('initial-plus-ONE limit never resets');
|
||
});
|
||
|
||
test('the roadmap and recovery groups define ownership and zero-edit eligibility', () => {
|
||
const text = compact(entry);
|
||
expect(text).toContain('integrate (1–3) → test and review (4–11.5) → prepare the release (12–15) → verify frozen content (16) → push and publish (17–21)');
|
||
expect(text).toContain('children return evidence, not permission to proceed');
|
||
expect(review).toContain('**No edits in this pass:** Resolve the required-probe gate below');
|
||
expect(review).toContain('Only after it clears may you continue to Step 10');
|
||
expect(review).toContain('With completed checklist and dispatched reviewers, failed/unavailable required probes block continuation');
|
||
expect(review).toContain('This cannot waive missing reviewer output, recurring fixes or independent test/security gates');
|
||
expect(review).toContain('Undispatched gated/unsupported specialists do not block independently');
|
||
expect(text).toContain('Reuse it only for that same scope; a repair never resets approvals or expands them');
|
||
expect(text).not.toContain('eligible zero-edit pass');
|
||
expect(text).not.toContain('the same waiver');
|
||
expect(text).not.toContain("the controller's detour");
|
||
});
|
||
|
||
test('distribution discovery is a shortlist, not a manifest-only artifact decision', () => {
|
||
const distribution = compact(entry.slice(entry.indexOf('## Step 2:'), entry.indexOf('## Step 3:')));
|
||
expect(distribution).toContain('List candidate distribution paths');
|
||
expect(distribution).toContain("Also inspect matching untracked files from Step 1's status");
|
||
expect(distribution).toContain('a new `package.json` or `Cargo.toml` alone does not establish a publishable artifact');
|
||
expect(distribution).toContain('inspect existing manifests for newly declared binaries or package exports');
|
||
expect(distribution).toContain('New artifact without a pipeline');
|
||
expect(distribution).toContain('AskUserQuestion');
|
||
expect(distribution).toContain('Do not publish a release during `/ship`');
|
||
});
|
||
|
||
test('queue qualification exhaustively distinguishes online, git fallback and unusable output', () => {
|
||
const version = compact(entry.slice(entry.indexOf('## Step 12:'), entry.indexOf('{{SECTION:changelog}}')));
|
||
const qualify = version.indexOf('**Qualify first:**');
|
||
const usable = version.indexOf('**Usable candidate:**');
|
||
const missing = version.indexOf('**No usable candidate:**');
|
||
expect(qualify).toBeGreaterThan(0);
|
||
expect(usable).toBeGreaterThan(qualify);
|
||
expect(missing).toBeGreaterThan(usable);
|
||
expect(version).toContain('require successful utility output and a nonempty valid version');
|
||
expect(version).toContain('`offline:false` qualifies; `offline:true` qualifies only with `fallback:"git"`');
|
||
expect(version).toContain('Offline output without that fallback, failure, malformed output or an empty version is unusable, even if it contains a version-looking string');
|
||
expect(version).toContain('FRESH sets `NEW_VERSION=CANDIDATE_VERSION`');
|
||
expect(version).toContain('Only approval changes the existing version');
|
||
expect(version).toContain('a sibling holding `>= NEW_VERSION` requires a choice: advance past it, or stop this attempt and sync');
|
||
expect(version.slice(missing)).toContain('FRESH uses local `BUMP_LEVEL` arithmetic; ALREADY_BUMPED keeps `currentVersion`');
|
||
});
|
||
|
||
test.each(['home', 'override', 'plugin'])('the actual nudge shell honors %s roots, repeat suppression and enabled tuning', mode => {
|
||
const root = mkdtempSync(join(tmpdir(), 'gstack-ship-nudge-'));
|
||
try {
|
||
const home = join(root, 'home');
|
||
const state = mode === 'home' ? join(home, '.gstack') : join(root, 'state root');
|
||
mkdirSync(home, { recursive: true });
|
||
const nudge = entry.slice(entry.indexOf('## Step 21:'), entry.indexOf('## Section self-check'));
|
||
const block = nudge.match(/```bash\n([\s\S]*?)\n```/);
|
||
expect(block).not.toBeNull();
|
||
const script = block![1].replaceAll('~/.claude/skills/gstack', JSON.stringify(resolve(import.meta.dir, '..')));
|
||
const run = () => spawnSync('bash', ['-c', script], {
|
||
cwd: root,
|
||
env: {
|
||
PATH: process.env.PATH,
|
||
HOME: home,
|
||
TMPDIR: join(root, 'tmp'),
|
||
...(mode === 'override' ? { GSTACK_HOME: state } : {}),
|
||
...(mode === 'plugin' ? { CLAUDE_PLUGIN_ROOT: join(root, 'gstack'), CLAUDE_PLUGIN_DATA: state } : {}),
|
||
},
|
||
encoding: 'utf8',
|
||
timeout: 10_000,
|
||
});
|
||
const marker = join(state, '.plan-tune-nudge-shown');
|
||
const first = run();
|
||
expect(first.status).toBe(0);
|
||
expect(first.stdout).toContain('Run /plan-tune to opt in');
|
||
expect(existsSync(marker)).toBe(true);
|
||
if (mode !== 'home') expect(existsSync(join(home, '.gstack', '.plan-tune-nudge-shown'))).toBe(false);
|
||
const repeated = run();
|
||
expect(repeated.status).toBe(0);
|
||
expect(repeated.stdout).toBe('');
|
||
rmSync(marker);
|
||
writeFileSync(join(state, 'config.yaml'), 'question_tuning: true\n');
|
||
const enabled = run();
|
||
expect(enabled.status).toBe(0);
|
||
expect(enabled.stdout).toBe('');
|
||
expect(existsSync(marker)).toBe(false);
|
||
} finally {
|
||
rmSync(root, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test('nested repairs resume the unfinished outer range before its destination', () => {
|
||
const text = compact(controller);
|
||
expect(text).toContain('Expand a repair into individual steps and insert them before the still-pending work');
|
||
expect(text).toContain('For another repair, repeat rule 2 without discarding pending work');
|
||
expect(text).toContain('Step 11 fixes insert `9 → 10 → 11` before 11.5');
|
||
expect(text).toContain('A further Step 9 fix affecting 6–8 makes the list `5 → 6 → 7 → 8 → 9 → 10 → 11 → 11.5`');
|
||
expect(text).toContain('The unchanged release steps follow');
|
||
expect(text).not.toContain('Enter Step 9 before REVIEW_START capture and full review');
|
||
});
|
||
|
||
test('shared foreground dispatch stays mandatory at all three owned dispatch sites', () => {
|
||
const coverage = read('ship/sections/test-coverage.md.tmpl');
|
||
const shared = coverage.indexOf('### Shared subagent dispatch');
|
||
expect(shared).toBeGreaterThan(0);
|
||
expect(shared).toBeLessThan(coverage.indexOf('Dispatch the audit through Agent'));
|
||
const contract = compact(coverage.slice(shared, coverage.indexOf('Dispatch the audit through Agent')));
|
||
expect(contract).toContain('use the Agent tool with `run_in_background: false`');
|
||
expect(contract).toContain('Omitting the flag runs the subagent in the background');
|
||
expect(contract).toContain('keeping a fresh context');
|
||
expect(contract).toContain('Do not invoke the target as a Skill or run it inline instead');
|
||
expect(contract).toContain("only under that section's documented fallback, after a failed subagent has stopped");
|
||
for (const section of ['test-coverage', 'plan-completion', 'greptile']) {
|
||
const text = read(`ship/sections/${section}.md.tmpl`);
|
||
expect(text).toContain('shared foreground-dispatch rule');
|
||
expect(text).toContain('run_in_background: false');
|
||
expect(text).not.toContain('{{FOREGROUND_DISPATCH_NOTE}}');
|
||
}
|
||
expect(entry).not.toContain('### Shared subagent dispatch');
|
||
for (const section of ['plan-completion', 'greptile']) {
|
||
expect(read(`ship/sections/${section}.md.tmpl`)).toContain("Step 7's shared foreground-dispatch rule");
|
||
}
|
||
});
|
||
|
||
test('ship dashboard displays actual historical records without a repeated sample panel', () => {
|
||
const ctx = { host: 'claude' as const, skillName: 'ship', tmplPath: '', paths: HOST_PATHS.claude };
|
||
const ship = generateReviewDashboard(ctx);
|
||
expect(ship).toContain('REVIEW READINESS DASHBOARD');
|
||
expect(ship).toContain('| Review | Runs | Last run | Status | Required |');
|
||
expect(ship).toContain('Use one row for each entry in step 1');
|
||
expect(ship).toContain('Only Eng Review is marked required');
|
||
expect(ship).toContain('{actual status and reason}');
|
||
expect(ship).toContain('VERDICT: {CLEARED or NOT CLEARED} — {reason}');
|
||
expect(ship).not.toContain('+====================================================================+');
|
||
const review = generateReviewDashboard({ ...ctx, skillName: 'review' });
|
||
expect(review).toContain('+====================================================================+');
|
||
});
|
||
|
||
test('coverage fallback settles the child and still applies the coverage gate', () => {
|
||
const text = compact(read('ship/sections/test-coverage.md.tmpl'));
|
||
const fallback = text.slice(text.indexOf('**Audit failure:**'), text.indexOf('{{TEST_COVERAGE_GATE_SHIP}}'));
|
||
expect(fallback).toContain('confirm it stopped before running the same audit inline');
|
||
expect(fallback).toContain('does not pass or bypass the coverage gate');
|
||
expect(fallback).toContain('including its undetermined-percentage and test-only rules');
|
||
expect(text).not.toContain('partial results are better than none');
|
||
});
|
||
|
||
test('no-plan gate skips only the audit and retains verification and the remaining section', () => {
|
||
const text = generatePlanCompletionGateShip({ host: 'claude', skillName: 'ship', tmplPath: '', paths: HOST_PATHS.claude });
|
||
const noPlan = compact(text.slice(text.indexOf('**No plan file found:**')));
|
||
expect(noPlan).toContain('Skip only the plan completion audit');
|
||
expect(noPlan).toContain('Continue with Step 8.1, Scope Drift and Prior Learnings');
|
||
expect(noPlan).toContain('Step 9 QA still runs');
|
||
expect(noPlan).not.toContain('Skip entirely');
|
||
});
|
||
|
||
test('binding separates record selection, three snapshots and probe outcomes', () => {
|
||
const text = compact(entry.slice(entry.indexOf('## Step 11.5:'), entry.indexOf('## Step 12:')));
|
||
const steps = ['1. **Select', '2. **Compare', '3. **Preserve', '4. **Save'];
|
||
const positions = steps.map(step => text.indexOf(step));
|
||
expect(positions.every(position => position >= 0)).toBe(true);
|
||
expect(positions).toEqual([...positions].sort((a,b) => a-b));
|
||
expect(text).toContain('All three snapshots must match');
|
||
expect(text).toContain('does not mean the failed or unrun probes passed');
|
||
expect(text).not.toContain('equal snapshots do not pass waived probes');
|
||
});
|
||
|
||
test('late classification and docs freshness are ordered decisions, not metadata assumptions', () => {
|
||
const text = compact(entry.slice(entry.indexOf('## Step 16:'), entry.indexOf('## Step 17:')));
|
||
expect(text).toContain('**Behavior, tests or build inputs changed:**');
|
||
expect(text).toContain('**Only authored docs or release metadata changed:**');
|
||
expect(text).toContain('**No changes, or the docs-only checks still support the plan:**');
|
||
expect(text).toContain('accepted audit matches all inputs | Continue to stage 4');
|
||
expect(text).toContain("Use Blocked recovery with the existing count");
|
||
expect(text).toContain('Use this example only after confirming that every allowed edit is release metadata');
|
||
expect(text).not.toContain('Every listed change below is metadata:');
|
||
});
|
||
|
||
test('one early controller owns detours without replacing local gates', () => {
|
||
expect(start).toBeGreaterThan(entry.indexOf('# Ship:'));
|
||
expect(start).toBeLessThan(end);
|
||
expect(end).toBeLessThan(entry.indexOf('{{BASE_BRANCH_DETECT}}'));
|
||
expect(entry.match(/### Ship control flow/g)).toHaveLength(1);
|
||
const text = compact(controller);
|
||
expect(text).toContain('You, the **parent** running /ship, own advancement');
|
||
expect(text).toContain('Follow the saved work list');
|
||
expect(text).toContain('STOP and AskUserQuestion gates still apply during repairs');
|
||
expect(text).toContain('The saved list takes precedence over ordinary next-step sentences inside a repair. A range never adds unlisted steps');
|
||
expect(text).toContain('Keep the same attempt counts throughout the invocation');
|
||
expect(text).toContain('A range ending at Step 14 does not enter Step 14.5');
|
||
expect(text).toContain('its initial-plus-ONE limit never resets');
|
||
expect(text).not.toContain('| At step |');
|
||
expect(entry.match(/Ship control flow/g)).toHaveLength(1);
|
||
expect(review).toContain('Every repeat starts before the checklist read and captures a fresh REVIEW_START');
|
||
});
|
||
|
||
test('distribution and bootstrap detours end at their exact forward resume', () => {
|
||
const merge = compact(entry.slice(entry.indexOf('## Step 3:'), entry.indexOf('{{SECTION:tests}}')));
|
||
expect(merge).toContain('repeat Step 2 on the merged content, including its decisions, then continue to Step 4');
|
||
expect(merge).toContain('Otherwise continue to Step 4 directly');
|
||
const tests = compact(read('ship/sections/tests.md.tmpl'));
|
||
expect(tests).toContain('A runs Step 4 with this new bootstrap choice, then returns here to run the tests');
|
||
expect(tests).toContain('A) Add tests (recommended)');
|
||
expect(tests).toContain('declining bootstrap alone is not that approval');
|
||
});
|
||
|
||
test('missing dispatched output outranks the cycle cap, fixes and zero-edit continuation', () => {
|
||
const decisions = review.slice(review.indexOf('### Decide whether to repeat Step 9'));
|
||
const names = ['1. **Dispatched reviewer output missing:**', '2. **Third fixing cycle reached (`CYCLES >= 3`):**', '3. **Fixes applied below the cap:**', '4. **No edits in this pass:**'];
|
||
const positions = names.map(name => decisions.indexOf(name));
|
||
expect(positions.every(position => position >= 0)).toBe(true);
|
||
expect(positions).toEqual([...positions].sort((a, b) => a - b));
|
||
const missing = decisions.slice(positions[0], positions[1]);
|
||
expect(missing).toContain('STOP and name each failed specialist or Red Team');
|
||
expect(missing).toContain('Retain queued fixes and restore coverage');
|
||
expect(missing).toContain('If this pass made edits, resume at the next decision; otherwise run a fresh complete Step 9');
|
||
expect(missing).toContain('A successful peer or a QA exception cannot replace missing dispatched coverage');
|
||
const cap = decisions.slice(positions[1], positions[2]);
|
||
expect(cap).toContain('STOP');
|
||
expect(cap).toContain('`converged:false`; do not run a fourth fixing cycle');
|
||
const fixes = decisions.slice(positions[2], positions[3]);
|
||
expect(fixes).toContain('Insert Step 5, affected Steps 6–8 and all of Step 9 before the pending Step 10 in the work list');
|
||
expect(fixes).toContain('Tests must pass or retain approval for the same verified pre-existing failures and scope');
|
||
expect(fixes).toContain('Keep CYCLES and scoped approvals across this repeat');
|
||
expect(decisions.slice(positions[3])).toContain('Only after it clears may you continue to Step 10');
|
||
expect(review).toContain('Undispatched host-unsupported/gated specialists do not block');
|
||
expect(review).toContain('Failed, blocked, inconclusive or not-run required probes mean false, never clean');
|
||
expect(review).toContain('This cannot waive missing reviewer output, recurring fixes or independent test/security gates');
|
||
});
|
||
|
||
test('comment fixes resume triage and preserve settled approvals and replies', () => {
|
||
const section = compact(read('ship/sections/greptile.md.tmpl'));
|
||
expect(section).toContain('If fixes were approved, save their approvals and comment references');
|
||
expect(section).toContain("Run Step 9's full review/fix loop, then return here");
|
||
expect(review).toContain('Finish the complete review and QA before applying any fix in Step 9.4');
|
||
expect(section).toContain('Finish the saved replies without asking again about completed fixes, and classify new comments');
|
||
expect(section).toContain('With no queued fixes, continue to Step 11');
|
||
expect(section).toContain('This optional triage does not block ship');
|
||
expect(section).toContain('unknown or missing status is unavailable');
|
||
expect(section).not.toContain('return to Step 9');
|
||
});
|
||
|
||
test('native recovery has one corrected attempt and cannot borrow outside completion', () => {
|
||
const finish = adversarial.slice(adversarial.indexOf('### Finish the adversarial phase'));
|
||
const recovery = finish.slice(finish.indexOf('1. **Required native'), finish.indexOf('2. **Fixes queued'));
|
||
expect(recovery).toContain('STOP and confirm the native task stopped');
|
||
expect(recovery).toContain('Outside-provider output cannot replace this pass');
|
||
expect(recovery).toContain('One recovery retry is allowed only after a concrete prerequisite correction and restored access');
|
||
expect(recovery).toContain('count it in the invocation record before launch');
|
||
expect(recovery).toContain('Capture a fresh PASS_START and persist the new attempt separately');
|
||
expect(recovery).toContain('Without that correction, or if the recovery fails, ask for repair and remain blocked');
|
||
const queued = finish.slice(finish.indexOf('2. **Fixes queued'), finish.indexOf('3. **Native complete'));
|
||
expect(queued).toContain('Keep the findings and their approvals');
|
||
expect(queued).toContain('Insert Steps 9, 10 and 11 before the pending Step 11.5 in the work list. Step 9 completes full review before fixes');
|
||
expect(queued).toContain('any further repair inserts its checks ahead of the remaining items');
|
||
expect(queued).toContain('not recovery retries');
|
||
expect(finish.slice(finish.indexOf('3. **Native complete'))).toContain('then continue to Step 11.5');
|
||
});
|
||
|
||
test.each(ALL_HOST_CONFIGS.map(({ name }) => name))('%s cannot skip Step 11.5 or change standalone review control flow', host => {
|
||
const ctx = { host, skillName: 'ship', tmplPath: '', paths: HOST_PATHS[host] };
|
||
const ship = generateAdversarialStep(ctx);
|
||
const finish = compact(ship.slice(ship.indexOf('### Finish the adversarial phase')));
|
||
expect(finish).toContain('Apply these decisions in order before leaving Step 11');
|
||
expect(finish).toContain('Required native review incomplete');
|
||
expect(finish).toContain('Outside-provider output cannot replace this pass');
|
||
expect(finish).toContain('Fixes queued after native completion');
|
||
expect(finish).toContain('Native complete with no queued fixes');
|
||
expect(finish).toContain('Step 11.5');
|
||
expect(finish).not.toContain('proceed to Step 12');
|
||
expect(finish).not.toContain('return to Step 9');
|
||
const review = generateAdversarialStep({ ...ctx, skillName: 'review' });
|
||
expect(review).not.toContain('Ship control flow');
|
||
expect(review).not.toContain('Step 11.5');
|
||
expect(review).toContain('Return all findings and structured-review decisions to Step 5');
|
||
expect(review).toContain('do not start an inner repair loop');
|
||
});
|
||
|
||
test('Step 11.5 verifies original record identity before any release write', () => {
|
||
const bindingStart = entry.indexOf('## Step 11.5:');
|
||
expect(bindingStart).toBeGreaterThan(entry.indexOf('{{SECTION:adversarial}}'));
|
||
expect(bindingStart).toBeLessThan(entry.indexOf('## Step 12:'));
|
||
const binding = compact(entry.slice(bindingStart, entry.indexOf('## Step 12:')));
|
||
for (const field of ['saved handle, original token and source', 'skill:"review"', 'via:"ship"', 'skill:"adversarial-review"',
|
||
'review_binding.state', 'verified', 'review_binding.start_wtree', 'review_binding.end_wtree']) expect(binding).toContain(field);
|
||
expect(binding).toContain('Never attach new tokens to old work');
|
||
expect(binding).toContain('Keep Step 9.4\'s incomplete flags');
|
||
expect(binding).toContain('does not mean the failed or unrun probes passed');
|
||
expect(binding).toContain('insert `9 → 10 → 11 → 11.5` before Step 12. Bind the new records at 11.5');
|
||
});
|
||
|
||
test('late build and behavior changes complete bounded ranges before docs', () => {
|
||
const build = gate.slice(gate.indexOf('### 1.'), gate.indexOf('### 2.'));
|
||
expect(build).toContain('A missing prerequisite or failed build stops shipping');
|
||
expect(build).toContain('Repair the prerequisite or build, then repeat stage 1');
|
||
expect(build).toContain('After it passes, continue to stage 2; treat any content repair as a behavioral change there');
|
||
const behavior = gate.slice(gate.indexOf('1. **Behavior'), gate.indexOf('2. **Only authored'));
|
||
expect(behavior).toContain('Insert `5–11.5 → 12–14 → 16` before the pending Step 17');
|
||
expect(behavior).toContain('before the pending Step 17, then stop this step. This repair excludes Step 14.5');
|
||
expect(behavior).toContain('rebuild and compare again before stage 3 decides documentation freshness');
|
||
const plan = gate.slice(gate.indexOf('2. **Only authored'), gate.indexOf('3. **No changes'));
|
||
expect(plan).toContain("run Step 8's audit and decision gates only, then return to Step 16 stage 1");
|
||
expect(plan).toContain("Never edit the child's counts yourself");
|
||
});
|
||
|
||
test('docs freshness has bounded re-audit and exact-content exception routes', () => {
|
||
const docs = gate.slice(gate.indexOf('### 3.'), gate.indexOf('### 4.'));
|
||
expect(docs).toContain("Use Blocked recovery with the existing count");
|
||
expect(docs).toContain('**An attempt remains, with changed inputs or an available repair:** insert `14.5 → 15 → 16` before Step 17');
|
||
expect(docs).toContain('restart Step 16 stage 1 to regenerate and compare again');
|
||
expect(docs).toContain('STOP unless the user accepts the specific named documentation risk and all unwaivable gates clear');
|
||
expect(docs).toContain('Never run a third audit');
|
||
expect(docs).toContain('Unchanged approved content goes to stage 4; repaired content goes to stage 1');
|
||
expect(docs).toContain('retain `Documentation: blocked`');
|
||
expect(docs).toContain('Missing, stale or blocked | Use recovery below. Never silently refresh hashes');
|
||
});
|
||
|
||
test('tests, absent test approval and new writes reopen final verification', () => {
|
||
const tests = gate.slice(gate.indexOf('### 4.'), gate.indexOf('### 5.'));
|
||
expect(tests).toContain("**New, changed or unwaived test failure:** STOP publication. Run Steps 5–15, starting with Step 5's triage, then return to Step 16 stage 1");
|
||
expect(tests).toContain('This recovery also applies if a failure appears while reporting in stage 5');
|
||
expect(tests).toContain('run Steps 5–15, including the no-tests decision, then return to Step 16 stage 1');
|
||
expect(tests).toContain('it does not authorize a third attempt');
|
||
expect(gate).toContain('If content changes during or after verification, restart at stage 1 and complete all five stages before Step 17');
|
||
expect(gate).toContain('Content-preserving commits keep valid evidence');
|
||
});
|
||
|
||
test('push failure kinds and publication races have distinct resumes', () => {
|
||
const push = compact(entry.slice(entry.indexOf('## Step 17:'), entry.indexOf('## Step 18:')));
|
||
expect(push).toContain('**If the push fails, STOP.** No Step 19 or publication claim');
|
||
expect(push).toContain("fetch and inspect the remote, then merge under Step 3's conflict rules");
|
||
expect(push).toContain('Run Steps 5–16 before returning to Step 17. Never rewrite history');
|
||
expect(push).toContain('repeat Step 16 even if content is unchanged before returning to Step 17');
|
||
expect(push).toContain('Never bypass failed guards');
|
||
const publication = compact(read('ship/sections/pr-body.md.tmpl'));
|
||
expect(publication).toContain("If the open PR/MR or title changed, repeat Step 18's identity/title preparation");
|
||
expect(publication).toContain('then return here for a new lookup, fresh body and both redaction scans before publishing');
|
||
});
|
||
});
|