enhancement(#537): migrate all hand-written bin/lib/*.cjs to TypeScript source of truth (ADR-457) (#602)

* enhancement(#537): migrate code-review-flags to TS source of truth

Collapse the hand-written get-shit-done/bin/lib/code-review-flags.cjs to a
TypeScript source of truth (src/code-review-flags.cts), compiled by tsc to a
gitignored .cjs build artifact at the same path, per ADR-457 (build-at-publish).
Second module after the semver-compare pilot (#541).

Behaviour is preserved byte-for-behaviour (characterization test added in
tests/code-review-flags.test.cjs locks the parser quirks). Adds compile-time
type checking: CodeReviewFlags interface + CodeReviewWorkflow literal union.
The require() path is unchanged, so code-review.md and the bug-3727 test keep
working. The emitted .cjs is gitignored and eslint-ignored, mirroring the pilot.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 9 leaf bin/lib modules to TS source of truth

ADR-457 build-at-publish, batch 1 (pure leaf modules, 0 sibling-deps):
001-legacy-orphan-files, context-utilization, redaction, artifacts,
command-arg-projection, clock, ui-safety-gate, review-reviewer-selection,
clusters. Each moves to src/*.cts (strict TS, typed), compiled by tsc to a
gitignored .cjs at the same require() path; behaviour preserved byte-for-
behaviour. Adds src/node-globals.d.ts (minimal ambient shim; "types":[]).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(#537): add @types/node, drop hand-rolled node-globals shim

ADR-457 migration infra: replace the temporary src/node-globals.d.ts ambient
shim with @types/node@22 + "types":["node"] in tsconfig.build.json. Unblocks
migrating the ~49 remaining bin/lib modules that use node:fs/path/os/
child_process. Build + full suite (3030 pass) + lint all green; no .cts type
changes were needed (real Node types matched the shim).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 9 more bin/lib modules to TS (batch 2)

ADR-457 build-at-publish. Clean leaves: installer-migration-report,
prompt-budget. Type-error-prone leaves (were tsconfig.lint-excluded; now
strict-typed and removed from that exclude list): secrets, phase-lifecycle,
workstream-name-policy, decisions, validate, schema-detect. Plus
runtime-name-policy. Strict type fixes narrow unknown->concrete domain types
(no any/ts-ignore); behaviour preserved. Full suite green, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate runtime-slash to TS (cross-import proof)

ADR-457. First cross-module TS->TS import: src/runtime-slash.cts imports
./runtime-name-policy.cjs and tsc resolves the sibling .cts types under strict
(no declaration files; NodeNext .cjs->.cts mapping), emitting a correct
require("./runtime-name-policy.cjs"). Confirms the recipe for coupled modules,
which must be migrated in dependency order (leaves-up). Suite green, lint clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 10 more bin/lib modules to TS (batch 3)

ADR-457 build-at-publish, Wave-1 leaves: event, workstream-inventory-builder,
plan-scan, fallow-runner, project-root, installer-migration-authoring,
update-context, 000-first-time-baseline, runtime-homes, model-catalog. Strict
typing fixed real issues (narrowing unknown, qualified fs/path calls, removed
unnecessary casts); plan-scan/project-root/workstream-inventory-builder dropped
from tsconfig.lint exclude. Behaviour preserved; suite green, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 5 large Wave-1 leaves to TS (batch 4)

ADR-457 build-at-publish: configuration, state-document, shell-command-
projection (42 dependents), security, command-aliases. shell-command-
projection keeps a namespace child_process import for mock-intercept
testability. loadConfig/migrateOnDisk emit synchronously (every caller uses
them sync; the one awaited migrateOnDisk caller tolerates a non-Promise) —
full suite (3030 pass) confirms behaviour preserved. configuration/
state-document/command-aliases dropped from tsconfig.lint exclude. Also fixes
the malformed batch-3 changeset frontmatter (type/pr) that failed lint:docs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 6 Wave-2 modules to TS (batch 5)

ADR-457 build-at-publish: config-schema, model-profiles,
002-codex-legacy-hooks-json, logger, active-workstream-store, adr-parser.
First batch importing already-migrated siblings (configuration, model-catalog,
shell-command-projection, redaction, security) via ./sibling.cjs specifiers.
Strict type narrowing (typeof guards over String(unknown)); behaviour
preserved; suite 3030 pass, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 5 large Wave-2 modules to TS (batch 6)

ADR-457 build-at-publish: graphify, install-profiles, intel,
installer-migrations, worktree-safety. installer-migrations preserves its
dynamic require() loader for numbered migration modules (scoped lint
suppressions). Strict typing (typeof guards over String(unknown)); behaviour
preserved; suite 3030 pass, lint 0 errors. Wave 2 complete.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate Wave-3 modules to TS (batch 7)

ADR-457 build-at-publish: planning-workspace, runtime-artifact-layout,
command-routing-hub, drift. Uses `import x = require()` for export= siblings;
drift's lazy require of runtime-slash hoisted to a top-level import (verified
non-circular). Behaviour preserved; suite 3030 pass, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate small Wave-4 modules to TS (batch 8)

ADR-457 build-at-publish: cjs-command-router-adapter, phase-command-router,
surface, roadmap-upgrade. Typed the hub router handler results as the HubResult
discriminated union; surface drops 4 genuinely-unused imports. Behaviour
preserved; suite 3030 pass, lint 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate core hub (2.5k LOC, 68 dependents) to TS (batch 9)

ADR-457 build-at-publish: get-shit-done/bin/lib/core.cjs -> src/core.cts,
preserving all 63 exports via export=. All sibling deps already migrated
(shell-command-projection, model-profiles, model-catalog, worktree-safety,
planning-workspace, project-root, configuration, config-schema). Strict types,
no any/ts-ignore; config-schema lazy require hoisted (non-circular). Behaviour
preserved (independently verified: core's shard 3030 pass / 0 fail).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#537): make ESLint-coverage + test-sprawl checks migration-aware

#551 test hardcoded 12 now-migrated modules as "hand-written, must be linted";
that invariant is obsoleted by the ADR-457 migration. Rewrite it to a
filesystem-driven invariant that holds at every stage: a bin/lib/*.cjs must be
eslint-ignored IFF it has a src/*.cts source (tsc-generated), else linted
(covers package-identity, which has no TS source). Also eslint-ignore
config-types.cjs (has a src counterpart) and drop the redundant
tests/clock.test.cjs (clock already covered by clock-seam + bug-474 tests),
which tripped the lint-test-file-count ratchet.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 9 Wave-5 router/inventory modules to TS (batch 10)

ADR-457 build-at-publish: phases/verify/init/agent/task/validate/roadmap/state
command routers + workstream-inventory. Router handler results typed against
core's exported shapes; behaviour preserved (caught+fixed a --verify boolean
flag regression mid-migration). Full suite green across all shards (only the 4
local gpg-env changeset-notes failures remain; CI passes them).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 7 Wave-5 modules to TS (batch 11)

ADR-457 build-at-publish: gap-checker, docs, check-command-router, frontmatter,
learnings, gsd2-import, profile-pipeline. Behaviour preserved; full suite green
across all shards (only the 4 local gpg-env failures remain). Also broadens
atomic-write-coverage.test.cjs to accept the tsc-compiled namespace-import form
while still asserting platformWriteSync is called (safety guard intact).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate config + profile-output to TS (batch 12)

ADR-457 build-at-publish: config (729 LOC), profile-output (1142 LOC). All
exports preserved; cmdMigrateConfig de-asynced (migrateOnDisk is sync, awaited
caller tolerates it). Behaviour preserved; suite green across all shards
(only the 4 local gpg-env failures). Wave 5 complete.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate 5 Wave-6 modules to TS (batch 13)

ADR-457 build-at-publish: template, uat, workstream, roadmap, audit. Behaviour
preserved (dead toPosixPath import dropped from audit; inline requires hoisted).
Suite green across all shards (only the 4 local gpg-env failures).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate commands + state hubs to TS (batch 14)

ADR-457 build-at-publish: commands (1305 LOC), state (2074 LOC, 17 dependents).
All exports preserved; inner requires kept non-hoisted where load-order matters
(install.js, per-call security); acquireStateLock cast inlined to preserve the
err.code source token a structural test inspects. Behaviour preserved; suite
green across all shards (only the 4 local gpg-env failures). Wave 6 complete.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate milestone to TS (batch 15a, hand-authored)

ADR-457 build-at-publish: milestone -> src/milestone.cts. Authored directly
(subagent capacity was unavailable). Also relaxes core.output()'s 3rd param to
optional, matching its real always-optional call contract (unblocks remaining
2-arg output callers). Behaviour preserved; suite green across all shards
(only the 4 local gpg-env failures).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537): migrate phase, verify, init to TS (batch 15, final modules)

ADR-457 build-at-publish, Wave 7 (the last hubs): phase (1608 LOC), verify
(1615), init (2113). Adds src/package-identity.d.cts so verify can import the
permanently value-baked package-identity.cjs under strict TS.

Fixes two regressions the migration introduced in verify: restore
cmdValidateHealth's `return result` (callers/tests read result.warnings — it is
NOT side-effect-only), and make the bug-3384 source-pattern test tolerant of the
tsc-compiled bracket-notation form of the git_list_failed->W020 branch (behaviour
intact). Full suite green across all shards (only the 4 local gpg-env failures);
lint 0 errors. All 86 migratable bin/lib modules are now TypeScript sources.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(#537): finalize ADR-457 migration — retire tsconfig.lint.json

All hand-written bin/lib/*.cjs are now src/*.cts sources, so the checkJs
stopgap tsconfig.lint.json (unused; not wired into eslint, scripts, or CI) is
deleted per ADR-457's final step. Also gitignore the tsc-generated
config-types.cjs (was still committed) for consistency with every other
emitted artifact. package-identity.cjs stays value-baked (declared via
src/package-identity.d.cts). Suite green; #551 ESLint-coverage test green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#537): add prepare script so unpacked/git installs build bin/lib artifacts

ADR-457 build-at-publish: bin/lib/*.cjs are now gitignored, built by tsc. The
prepack/prepublishOnly hooks cover `npm pack`/publish, but `npm install -g
<dir>` and git installs run the `prepare` lifecycle — which was missing — so the
unpacked install shipped without the compiled .cjs and failed at startup with
"Cannot find module './lib/core.cjs'" (caught by the smoke-unpacked CI job).
Add `prepare` mirroring prepublishOnly (build:lib + build:hooks). prepare does
NOT run for registry consumers (they get the pre-built tarball), only for
source/local/pack installs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#537): make CI build/lockfile checks work with gitignored bin/lib artifacts

ADR-457 build-at-publish exposed two CI assumptions that bin/lib/*.cjs are
always present on disk:
- check:env's lockfile-sync ran `npm ci --dry-run`, which now triggers the
  `prepare` build (tsc) — but it runs before deps are installed, so tsc is
  absent and it misreported the lockfile as out of sync. Add --ignore-scripts
  (a lockfile check must not build).
- the lint-tests job installs with --ignore-scripts (no prepare build), but
  lint:skill-deps require()s the built install-profiles.cjs. Add an explicit
  `npm run build:lib` step after install.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#537): narrow prepare to build:lib only (unbreak packed-smoke pack step)

prepare running build:hooks emitted "✓ Copying ..." stdout during `npm pack`,
which the install-smoke "Pack root tarball" step captures into $GITHUB_OUTPUT —
breaking it with "Invalid format". build:lib (tsc) is silent on success and is
all the unpacked/source install needs (the smoke-unpacked assertions exercise
gsd-tools, i.e. bin/lib, and tolerate hook setup with `|| true`). Matches
prepack. build:hooks still runs on prepublishOnly for real publishes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#537): wire Stryker mutation gate to build-at-publish layout

The gate scored 0.00 because it mutated changed bin/lib/*.cjs that (a) were
generated artifacts and (b) included modules with no coverage in the command's
test set. Rework: mutation.yml now derives changed COVERED modules from
src/*.cts and maps them to their built bin/lib/*.cjs; Stryker mutates those
built artifacts with a no-rebuild command (mutating src/*.cts + per-mutant tsc
was ~3x over the 30-min CI budget).

NOTE: with the gate now correctly measuring the covered modules, their actual
mutation score is 42.94% (< break 50) — a pre-existing test-coverage gap
(adr-parser/prompt-budget/etc.), not introduced by this behaviour-preserving
migration. Reaching 50 needs more tests, a threshold/scope change, or a waiver —
a maintainer decision.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#537): raise mutation coverage of covered modules above the 50 gate

Adds focused example-based unit tests that kill surviving mutants in the two
lowest-scoring covered modules:
- tests/prompt-budget.unit.test.cjs (112 tests): 17.9% -> 97.9%
- tests/adr-parser.unit.test.cjs (205 tests): 44.7% -> 89.4%
Both wired into stryker.config.mjs's command. Fresh full run over the 6 covered
modules now scores 82.25% (>= break 50); every covered module is >= 68%.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* enhancement(#537,#609): parallelize mutation gate via dynamic per-module matrix

The serial Stryker run timed out at 30 min once the migration's added tests
made every mutant re-run ~300 tests. Replace it with a dynamic matrix so the
gate completes well under budget — folded into this PR (was tracked as #609)
because it's a prerequisite for this PR's mutation gate to pass.

- scripts/mutation-matrix.cjs: single source of truth (covered-module -> test
  files) computing changed covered modules from git diff -> {has_work, matrix}.
- mutation.yml: detect -> dynamic `matrix: fromJSON(...)` mutate job (one
  parallel shard per changed module, scoped via MUTATION_TEST_CMD to only that
  module's tests, 15-min/shard) -> summary job that KEEPS the legacy check name
  "Stryker mutation score (changed files only)" so branch protection is
  unchanged. Per-shard jobs report as "Stryker (<module>)".
- stryker.config.mjs: commandRunner.command reads MUTATION_TEST_CMD (falls back
  to the full command locally).

Closes #609.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#537,#609): give each mutation shard ≥50% on its own tests; drop blacksmith note

Per-module sharding revealed that active-workstream-store (46.5%) and
frontmatter (7.4%) only cleared 50% in the old serial run via timeout-noise from
the bloated 300-test command; on their own tests they were below the gate. Add
focused unit tests:
- tests/active-workstream-store.unit.test.cjs (115 tests): 46.5% -> 81.9%
- tests/frontmatter.unit.test.cjs (165 tests): 7.4% -> 63.4%
Both wired into scripts/mutation-matrix.cjs (per-module test map) and
stryker.config.mjs DEFAULT_TEST_CMD. All 6 covered modules now clear break:50
with only their own tests (config-schema/context-utilization/prompt-budget/
adr-parser already did). Also removes the leftover blacksmith TODO comment —
GitHub-hosted runners only; speed comes from parallel per-module shards.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#537,#609): strengthen prompt-budget tests to clear the gate on its own tests

prompt-budget scored 39.58% when mutation-tested with ONLY its own tests (the
way the per-module CI shard runs it) — an earlier ~98% reading was inflated by
accidentally running the full multi-module command. Add 96 targeted tests to
tests/prompt-budget.unit.test.cjs (exact note-template text, plan-truncation
arithmetic/percentages, drop-block strings, noteInjected/hardFailed booleans):
scoped score 39.58% -> 68.75% (>= break 50). All 6 covered modules now clear
the gate on their own tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-06-02 11:45:01 -04:00
committed by GitHub
parent 3bb2f8f1c5
commit df04aae5e4
149 changed files with 20885 additions and 11261 deletions

View File

@@ -1,18 +1,24 @@
'use strict';
/**
* Regression test for #551 — the ESLint harness (ADR-452) silently excluded 12
* hand-written `get-shit-done/bin/lib/*.cjs` modules via a `GENERATED_CJS_IGNORES`
* list mislabeled "Generated bin/lib files — never lint". The files are hand-written
* (no `@generated` header, no generator emits them), so they belong in the harness.
* Regression / migration-gate test for #551 and ADR-457 (TS migration).
*
* Invariant under test (not just today's file list): a `bin/lib/*.cjs` module must
* be linted UNLESS it is genuinely generated — i.e. it carries an `@generated`
* header or has a `src/<name>.cts|.ts` source it is compiled from (ADR-457). This
* catches the next mislabeled file, not only the original 12.
* ESLint must apply the correct policy to every get-shit-done/bin/lib/*.cjs
* file as modules migrate from hand-written CJS to tsc-generated artifacts:
*
* Behavior is checked through ESLint's own `isPathIgnored` API so the test reflects
* real resolved flat-config precedence, not a textual scan of eslint.config.mjs.
* - tsc-generated artifact (has src/<basename>.cts counterpart) → MUST be
* eslint-ignored. We lint the *.cts source instead (ADR-457).
* - Genuinely hand-written (no src/*.cts counterpart) → MUST be linted
* (NOT ignored). Includes scripts-generated package-identity.cjs which
* has no *.cts source.
*
* The test is filesystem-driven — it scans bin/lib at runtime and checks each
* file against the src/ directory, so it stays correct automatically as more
* modules migrate. No hardcoded lists.
*
* ESLint behaviour is verified via ESLint's own `isPathIgnored()` API so the
* test reflects real resolved flat-config precedence, not a textual scan of
* eslint.config.mjs.
*/
const { describe, test, before } = require('node:test');
@@ -23,31 +29,17 @@ const { ESLint } = require('eslint');
const ROOT = path.resolve(__dirname, '..');
const LIB_DIR = path.join(ROOT, 'get-shit-done', 'bin', 'lib');
const SRC_DIR = path.join(ROOT, 'src');
// The 12 modules that #551 restored to lint coverage.
const HAND_WRITTEN = [
'command-aliases',
'configuration',
'decisions',
'phase-lifecycle',
'plan-scan',
'project-root',
'schema-detect',
'secrets',
'state-document',
'validate',
'workstream-inventory-builder',
'workstream-name-policy',
].map((name) => path.join(LIB_DIR, `${name}.cjs`));
function isGenerated(absPath) {
if (!fs.existsSync(absPath)) return false;
const head = fs.readFileSync(absPath, 'utf8').slice(0, 500);
if (/@generated/.test(head)) return true;
/**
* Returns true if the given bin/lib/*.cjs file has a corresponding
* src/<basename>.cts TypeScript source (meaning it is tsc-generated).
*/
function hasTsSource(absPath) {
const base = path.basename(absPath, '.cjs');
return (
fs.existsSync(path.join(ROOT, 'src', `${base}.cts`)) ||
fs.existsSync(path.join(ROOT, 'src', `${base}.ts`))
fs.existsSync(path.join(SRC_DIR, `${base}.cts`)) ||
fs.existsSync(path.join(SRC_DIR, `${base}.ts`))
);
}
@@ -56,34 +48,41 @@ before(() => {
eslint = new ESLint({ cwd: ROOT });
});
describe('#551: ESLint covers hand-written bin/lib/*.cjs', () => {
for (const file of HAND_WRITTEN) {
test(`lints ${path.basename(file)} (not ignored)`, async () => {
assert.equal(
await eslint.isPathIgnored(file),
false,
`${path.relative(ROOT, file)} is hand-written and must be linted, not ignored`,
);
});
}
describe('ESLint coverage tracks the bin/lib TS migration (ADR-457 / #537)', () => {
/**
* Main invariant: scan every *.cjs in bin/lib and assert the correct ESLint
* policy is applied.
*/
test('each bin/lib/*.cjs is linted xor ignored according to migration state', async () => {
const wronglyIgnored = []; // hand-written but ignored — should be linted
const wronglyLinted = []; // tsc-generated but not ignored — should be ignored
test('no hand-written bin/lib/*.cjs is silently ignored', async () => {
const offenders = [];
for (const entry of fs.readdirSync(LIB_DIR)) {
if (!entry.endsWith('.cjs')) continue;
const entries = fs.readdirSync(LIB_DIR).filter((e) => e.endsWith('.cjs'));
for (const entry of entries) {
const abs = path.join(LIB_DIR, entry);
if (isGenerated(abs)) continue; // legitimately excluded from the harness
if (await eslint.isPathIgnored(abs)) offenders.push(entry);
const generated = hasTsSource(abs);
const ignored = await eslint.isPathIgnored(abs);
if (generated && !ignored) {
wronglyLinted.push(entry);
} else if (!generated && ignored) {
wronglyIgnored.push(entry);
}
}
assert.deepEqual(
offenders,
wronglyLinted,
[],
`Hand-written modules silently excluded from ESLint: ${offenders.join(', ')}`,
`tsc-generated bin/lib modules not yet added to ESLint ignore list: ${wronglyLinted.join(', ')}`,
);
assert.deepEqual(
wronglyIgnored,
[],
`Hand-written bin/lib modules silently excluded from ESLint: ${wronglyIgnored.join(', ')}`,
);
});
test('genuinely tsc-generated semver-compare.cjs stays ignored (ADR-457)', async () => {
// Publish-time artifact compiled from src/semver-compare.cts; must not be linted.
test('semver-compare.cjs (tsc-generated publish artifact) stays eslint-ignored (ADR-457)', async () => {
const f = path.join(LIB_DIR, 'semver-compare.cjs');
assert.equal(
await eslint.isPathIgnored(f),
@@ -91,4 +90,13 @@ describe('#551: ESLint covers hand-written bin/lib/*.cjs', () => {
'semver-compare.cjs is a tsc-generated publish-time artifact and must stay ignored',
);
});
test('package-identity.cjs (script-generated, no *.cts source) is linted, not ignored (#551)', async () => {
const f = path.join(LIB_DIR, 'package-identity.cjs');
assert.equal(
await eslint.isPathIgnored(f),
false,
'package-identity.cjs has no src/*.cts counterpart and must be linted, not ignored',
);
});
});

View File

@@ -0,0 +1,900 @@
'use strict';
/**
* Focused unit tests for active-workstream-store.cjs
* Targets untested branches to raise mutation score above 60%.
*/
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { cleanup } = require('./helpers.cjs');
const {
validateWorkstreamName,
getWorkstreamSessionKey,
createSharedPointerAdapter,
createSessionScopedPointerAdapter,
createMemoryPointerAdapter,
pickActiveWorkstreamAdapter,
getActiveWorkstream,
setActiveWorkstream,
clearActiveWorkstream,
parseCliWorkstream,
resolveActiveWorkstream,
applyResolvedWorkstreamEnv,
} = require('../get-shit-done/bin/lib/active-workstream-store.cjs');
// ── Helpers ───────────────────────────────────────────────────────────────────
const SESSION_ENV_KEYS = [
'GSD_SESSION_KEY', 'CODEX_THREAD_ID', 'CLAUDE_SESSION_ID', 'CLAUDE_CODE_SSE_PORT',
'OPENCODE_SESSION_ID', 'GEMINI_SESSION_ID', 'CURSOR_SESSION_ID', 'WINDSURF_SESSION_ID',
'TERM_SESSION_ID', 'WT_SESSION', 'TMUX_PANE', 'ZELLIJ_SESSION_NAME',
'TTY', 'SSH_TTY',
];
function clearSessionEnv() {
for (const k of SESSION_ENV_KEYS) delete process.env[k];
}
function saveSessionEnv() {
const saved = {};
for (const k of SESSION_ENV_KEYS) saved[k] = process.env[k];
return saved;
}
function restoreSessionEnv(saved) {
for (const k of SESSION_ENV_KEYS) {
if (saved[k] === undefined) delete process.env[k];
else process.env[k] = saved[k];
}
}
function makePlanningDir(base, ...workstreams) {
const wsDir = path.join(base, '.planning', 'workstreams');
fs.mkdirSync(wsDir, { recursive: true });
for (const ws of workstreams) {
fs.mkdirSync(path.join(wsDir, ws), { recursive: true });
}
}
// ── validateWorkstreamName ────────────────────────────────────────────────────
describe('validateWorkstreamName — exact values', () => {
test('accepts dot in name', () => {
assert.equal(validateWorkstreamName('alpha.2'), true);
});
test('rejects null', () => {
assert.equal(validateWorkstreamName(null), false);
});
test('rejects undefined', () => {
assert.equal(validateWorkstreamName(undefined), false);
});
test('rejects empty string', () => {
assert.equal(validateWorkstreamName(''), false);
});
test('rejects whitespace-only', () => {
assert.equal(validateWorkstreamName(' '), false);
});
test('rejects name with spaces', () => {
assert.equal(validateWorkstreamName('hello world'), false);
});
test('rejects path traversal', () => {
assert.equal(validateWorkstreamName('../escape'), false);
});
test('accepts single char', () => {
assert.equal(validateWorkstreamName('a'), true);
});
test('accepts underscore', () => {
assert.equal(validateWorkstreamName('my_ws'), true);
});
test('accepts hyphen', () => {
assert.equal(validateWorkstreamName('my-ws'), true);
});
});
// ── createMemoryPointerAdapter ────────────────────────────────────────────────
describe('createMemoryPointerAdapter', () => {
test('initial value defaults to null', () => {
const a = createMemoryPointerAdapter();
assert.equal(a.read(), null);
});
test('initial value can be set', () => {
const a = createMemoryPointerAdapter('alpha');
assert.equal(a.read(), 'alpha');
});
test('write updates value', () => {
const a = createMemoryPointerAdapter(null);
a.write('beta');
assert.equal(a.read(), 'beta');
});
test('write then write replaces value', () => {
const a = createMemoryPointerAdapter('alpha');
a.write('beta');
assert.equal(a.read(), 'beta');
});
test('clear sets value to null', () => {
const a = createMemoryPointerAdapter('alpha');
a.clear();
assert.equal(a.read(), null);
});
test('clear after write sets to null', () => {
const a = createMemoryPointerAdapter(null);
a.write('alpha');
a.clear();
assert.equal(a.read(), null);
});
test('clear then read returns null', () => {
const a = createMemoryPointerAdapter('ws');
a.clear();
assert.strictEqual(a.read(), null);
});
});
// ── createSharedPointerAdapter ────────────────────────────────────────────────
describe('createSharedPointerAdapter', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-unit-shared-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
});
afterEach(() => cleanup(tmpDir));
test('read returns null when file does not exist', () => {
const adapter = createSharedPointerAdapter(tmpDir);
assert.equal(adapter.read(), null);
});
test('write then read returns exact name', () => {
const adapter = createSharedPointerAdapter(tmpDir);
adapter.write('my-ws');
assert.equal(adapter.read(), 'my-ws');
});
test('write appends newline but read strips it', () => {
const adapter = createSharedPointerAdapter(tmpDir);
adapter.write('trimmed');
const filePath = path.join(tmpDir, '.planning', 'active-workstream');
const raw = fs.readFileSync(filePath, 'utf8');
assert.equal(raw, 'trimmed\n');
assert.equal(adapter.read(), 'trimmed');
});
test('read returns null for whitespace-only content', () => {
const adapter = createSharedPointerAdapter(tmpDir);
const filePath = path.join(tmpDir, '.planning', 'active-workstream');
fs.writeFileSync(filePath, ' \n');
assert.equal(adapter.read(), null);
});
test('clear removes the file', () => {
const adapter = createSharedPointerAdapter(tmpDir);
adapter.write('my-ws');
adapter.clear();
const filePath = path.join(tmpDir, '.planning', 'active-workstream');
assert.equal(fs.existsSync(filePath), false);
});
test('clear on non-existent file does not throw', () => {
const adapter = createSharedPointerAdapter(tmpDir);
assert.doesNotThrow(() => adapter.clear());
});
test('read returns null when file is empty', () => {
const adapter = createSharedPointerAdapter(tmpDir);
const filePath = path.join(tmpDir, '.planning', 'active-workstream');
fs.writeFileSync(filePath, '');
assert.equal(adapter.read(), null);
});
});
// ── createSessionScopedPointerAdapter ────────────────────────────────────────
describe('createSessionScopedPointerAdapter', () => {
let tmpDir;
let saved;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-unit-session-'));
saved = saveSessionEnv();
clearSessionEnv();
});
afterEach(() => {
restoreSessionEnv(saved);
cleanup(tmpDir);
});
test('returns null when no session key available', () => {
const adapter = createSessionScopedPointerAdapter(tmpDir);
assert.equal(adapter, null);
});
test('returns adapter object when session key provided', () => {
const adapter = createSessionScopedPointerAdapter(tmpDir, 'test-session-key');
assert.notEqual(adapter, null);
assert.equal(typeof adapter.read, 'function');
assert.equal(typeof adapter.write, 'function');
assert.equal(typeof adapter.clear, 'function');
});
test('read returns null before any write', () => {
const adapter = createSessionScopedPointerAdapter(tmpDir, 'test-session-key');
assert.equal(adapter.read(), null);
});
test('write then read returns exact name', () => {
const adapter = createSessionScopedPointerAdapter(tmpDir, 'test-session-key');
adapter.write('session-ws');
assert.equal(adapter.read(), 'session-ws');
});
test('clear after write returns null', () => {
const adapter = createSessionScopedPointerAdapter(tmpDir, 'test-session-key');
adapter.write('session-ws');
adapter.clear();
assert.equal(adapter.read(), null);
});
test('clear on empty dir removes dir', () => {
const adapter = createSessionScopedPointerAdapter(tmpDir, 'test-session-key');
adapter.write('session-ws');
adapter.clear();
// after clear, the file and possibly the dir should be gone
// at minimum, clear should not throw
assert.doesNotThrow(() => adapter.clear());
});
test('read returns null for whitespace-only content', () => {
const adapter = createSessionScopedPointerAdapter(tmpDir, 'test-session-key');
adapter.write(' ');
// write appends \n, so content is " \n"; trim returns '', so read returns null
assert.equal(adapter.read(), null);
});
test('uses env session key when no fixed key provided', () => {
process.env.GSD_SESSION_KEY = 'env-session';
const adapter = createSessionScopedPointerAdapter(tmpDir);
assert.notEqual(adapter, null);
adapter.write('env-ws');
assert.equal(adapter.read(), 'env-ws');
});
});
// ── pickActiveWorkstreamAdapter ───────────────────────────────────────────────
describe('pickActiveWorkstreamAdapter', () => {
let saved;
beforeEach(() => {
saved = saveSessionEnv();
clearSessionEnv();
});
afterEach(() => restoreSessionEnv(saved));
test('returns opts.activeWorkstreamAdapter when provided', () => {
const adapter = createMemoryPointerAdapter('alpha');
const picked = pickActiveWorkstreamAdapter('/fake', { activeWorkstreamAdapter: adapter });
assert.strictEqual(picked, adapter);
});
test('returns session adapter from adapters when session key exists', () => {
process.env.GSD_SESSION_KEY = 'some-session';
const session = createMemoryPointerAdapter('session-ws');
const shared = createMemoryPointerAdapter('shared-ws');
const picked = pickActiveWorkstreamAdapter('/fake', {
activeWorkstreamAdapters: { session, shared },
});
assert.strictEqual(picked, session);
});
test('returns shared adapter from adapters when no session key', () => {
const shared = createMemoryPointerAdapter('shared-ws');
const picked = pickActiveWorkstreamAdapter('/fake', {
activeWorkstreamAdapters: { shared },
});
assert.strictEqual(picked, shared);
});
test('creates shared pointer adapter when no opts and no session', () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-pick-'));
try {
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
const picked = pickActiveWorkstreamAdapter(tmpDir, {});
assert.notEqual(picked, null);
assert.equal(typeof picked.read, 'function');
} finally {
cleanup(tmpDir);
}
});
test('creates session scoped adapter when session key exists and no adapters given', () => {
process.env.GSD_SESSION_KEY = 'my-session';
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-pick-sess-'));
try {
const picked = pickActiveWorkstreamAdapter(tmpDir, {});
// session scoped adapter exists since session key is set
assert.notEqual(picked, null);
assert.equal(typeof picked.read, 'function');
} finally {
cleanup(tmpDir);
delete process.env.GSD_SESSION_KEY;
}
});
test('adapter not provided in opts returns shared adapter', () => {
const picked = pickActiveWorkstreamAdapter('/fake', {
activeWorkstreamAdapters: {},
});
assert.notEqual(picked, null);
});
});
// ── getWorkstreamSessionKey ───────────────────────────────────────────────────
describe('getWorkstreamSessionKey', () => {
let saved;
beforeEach(() => {
saved = saveSessionEnv();
clearSessionEnv();
});
afterEach(() => restoreSessionEnv(saved));
test('returns null when no env keys set', () => {
const key = getWorkstreamSessionKey();
// will return null or a tty token (depends on environment); just check type
assert.ok(key === null || typeof key === 'string');
});
test('returns gsd-session-key prefixed key for GSD_SESSION_KEY', () => {
process.env.GSD_SESSION_KEY = 'mysession';
const key = getWorkstreamSessionKey();
assert.equal(key, 'gsd-session-key-mysession');
});
test('returns codex-thread-id prefixed key for CODEX_THREAD_ID', () => {
process.env.CODEX_THREAD_ID = 'thread123';
const key = getWorkstreamSessionKey();
assert.equal(key, 'codex-thread-id-thread123');
});
test('returns claude-session-id for CLAUDE_SESSION_ID', () => {
process.env.CLAUDE_SESSION_ID = 'claude-abc';
const key = getWorkstreamSessionKey();
assert.equal(key, 'claude-session-id-claude-abc');
});
test('returns claude-code-sse-port for CLAUDE_CODE_SSE_PORT', () => {
process.env.CLAUDE_CODE_SSE_PORT = '9000';
const key = getWorkstreamSessionKey();
assert.equal(key, 'claude-code-sse-port-9000');
});
test('returns opencode-session-id for OPENCODE_SESSION_ID', () => {
process.env.OPENCODE_SESSION_ID = 'oc-123';
const key = getWorkstreamSessionKey();
assert.equal(key, 'opencode-session-id-oc-123');
});
test('returns gemini-session-id for GEMINI_SESSION_ID', () => {
process.env.GEMINI_SESSION_ID = 'gem-xyz';
const key = getWorkstreamSessionKey();
assert.equal(key, 'gemini-session-id-gem-xyz');
});
test('returns cursor-session-id for CURSOR_SESSION_ID', () => {
process.env.CURSOR_SESSION_ID = 'cur-001';
const key = getWorkstreamSessionKey();
assert.equal(key, 'cursor-session-id-cur-001');
});
test('returns windsurf-session-id for WINDSURF_SESSION_ID', () => {
process.env.WINDSURF_SESSION_ID = 'ws-surf';
const key = getWorkstreamSessionKey();
assert.equal(key, 'windsurf-session-id-ws-surf');
});
test('returns term-session-id for TERM_SESSION_ID', () => {
process.env.TERM_SESSION_ID = 'term-1';
const key = getWorkstreamSessionKey();
assert.equal(key, 'term-session-id-term-1');
});
test('returns wt-session for WT_SESSION', () => {
process.env.WT_SESSION = 'wt-abc';
const key = getWorkstreamSessionKey();
assert.equal(key, 'wt-session-wt-abc');
});
test('returns tmux-pane for TMUX_PANE', () => {
process.env.TMUX_PANE = '%1';
const key = getWorkstreamSessionKey();
// %1 → sanitize replaces % with _, then strips leading _ → "1"
assert.equal(key, 'tmux-pane-1');
});
test('returns zellij-session-name for ZELLIJ_SESSION_NAME', () => {
process.env.ZELLIJ_SESSION_NAME = 'my-zellij';
const key = getWorkstreamSessionKey();
assert.equal(key, 'zellij-session-name-my-zellij');
});
test('GSD_SESSION_KEY takes priority over CODEX_THREAD_ID', () => {
process.env.GSD_SESSION_KEY = 'first';
process.env.CODEX_THREAD_ID = 'second';
const key = getWorkstreamSessionKey();
assert.equal(key, 'gsd-session-key-first');
});
test('returns tty- prefixed key for TTY env var', () => {
process.env.TTY = '/dev/pts/1';
const key = getWorkstreamSessionKey();
assert.equal(key, 'tty-pts_1');
});
test('returns tty- prefixed key for SSH_TTY env var', () => {
process.env.SSH_TTY = '/dev/pts/2';
const key = getWorkstreamSessionKey();
assert.equal(key, 'tty-pts_2');
});
test('TTY takes priority over SSH_TTY', () => {
process.env.TTY = '/dev/pts/3';
process.env.SSH_TTY = '/dev/pts/4';
const key = getWorkstreamSessionKey();
assert.equal(key, 'tty-pts_3');
});
test('TTY with dev_ prefix gets stripped', () => {
process.env.TTY = 'dev_pts_1';
const key = getWorkstreamSessionKey();
// sanitize returns dev_pts_1 → tty-{dev_pts_1 with dev_ stripped} → tty-pts_1
assert.equal(key, 'tty-pts_1');
});
test('empty GSD_SESSION_KEY falls through', () => {
process.env.GSD_SESSION_KEY = '';
process.env.CODEX_THREAD_ID = 'fallback';
const key = getWorkstreamSessionKey();
assert.equal(key, 'codex-thread-id-fallback');
});
test('whitespace-only GSD_SESSION_KEY falls through', () => {
process.env.GSD_SESSION_KEY = ' ';
process.env.CODEX_THREAD_ID = 'fallback2';
const key = getWorkstreamSessionKey();
assert.equal(key, 'codex-thread-id-fallback2');
});
});
// ── getActiveWorkstream ───────────────────────────────────────────────────────
describe('getActiveWorkstream', () => {
let tmpDir;
let saved;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-unit-get-'));
saved = saveSessionEnv();
clearSessionEnv();
});
afterEach(() => {
restoreSessionEnv(saved);
cleanup(tmpDir);
});
test('returns null when adapter reads null', () => {
const adapter = createMemoryPointerAdapter(null);
const result = getActiveWorkstream(tmpDir, { activeWorkstreamAdapter: adapter });
assert.equal(result, null);
});
test('returns null and clears for invalid name', () => {
const adapter = createMemoryPointerAdapter('bad name!');
const result = getActiveWorkstream(tmpDir, { activeWorkstreamAdapter: adapter });
assert.equal(result, null);
assert.equal(adapter.read(), null);
});
test('returns null and clears when workstream dir missing', () => {
makePlanningDir(tmpDir);
const adapter = createMemoryPointerAdapter('ghost-ws');
const result = getActiveWorkstream(tmpDir, { activeWorkstreamAdapter: adapter });
assert.equal(result, null);
assert.equal(adapter.read(), null);
});
test('returns name when workstream dir exists', () => {
makePlanningDir(tmpDir, 'real-ws');
const adapter = createMemoryPointerAdapter('real-ws');
const result = getActiveWorkstream(tmpDir, { activeWorkstreamAdapter: adapter });
assert.equal(result, 'real-ws');
});
test('adapter read is null after self-heal for stale pointer', () => {
makePlanningDir(tmpDir);
const adapter = createMemoryPointerAdapter('stale');
getActiveWorkstream(tmpDir, { activeWorkstreamAdapter: adapter });
assert.equal(adapter.read(), null);
});
test('returns null for empty string name', () => {
const adapter = createMemoryPointerAdapter('');
const result = getActiveWorkstream(tmpDir, { activeWorkstreamAdapter: adapter });
assert.equal(result, null);
});
test('returns correct ws name with dots', () => {
makePlanningDir(tmpDir, 'v1.2');
const adapter = createMemoryPointerAdapter('v1.2');
const result = getActiveWorkstream(tmpDir, { activeWorkstreamAdapter: adapter });
assert.equal(result, 'v1.2');
});
});
// ── setActiveWorkstream ───────────────────────────────────────────────────────
describe('setActiveWorkstream', () => {
let tmpDir;
let saved;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-unit-set-'));
saved = saveSessionEnv();
clearSessionEnv();
});
afterEach(() => {
restoreSessionEnv(saved);
cleanup(tmpDir);
});
test('writes name to adapter', () => {
const adapter = createMemoryPointerAdapter(null);
setActiveWorkstream(tmpDir, 'my-ws', { activeWorkstreamAdapter: adapter });
assert.equal(adapter.read(), 'my-ws');
});
test('creates workstream dir on set', () => {
const adapter = createMemoryPointerAdapter(null);
setActiveWorkstream(tmpDir, 'new-ws', { activeWorkstreamAdapter: adapter });
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'new-ws');
assert.equal(fs.existsSync(wsDir), true);
});
test('clears on null name', () => {
const adapter = createMemoryPointerAdapter('existing');
setActiveWorkstream(tmpDir, null, { activeWorkstreamAdapter: adapter });
assert.equal(adapter.read(), null);
});
test('clears on undefined name', () => {
const adapter = createMemoryPointerAdapter('existing');
setActiveWorkstream(tmpDir, undefined, { activeWorkstreamAdapter: adapter });
assert.equal(adapter.read(), null);
});
test('clears on empty string name', () => {
const adapter = createMemoryPointerAdapter('existing');
setActiveWorkstream(tmpDir, '', { activeWorkstreamAdapter: adapter });
assert.equal(adapter.read(), null);
});
test('throws on invalid name', () => {
const adapter = createMemoryPointerAdapter(null);
assert.throws(
() => setActiveWorkstream(tmpDir, 'bad/name', { activeWorkstreamAdapter: adapter }),
/Invalid workstream name/
);
});
test('throws with exact error message for invalid name', () => {
const adapter = createMemoryPointerAdapter(null);
assert.throws(
() => setActiveWorkstream(tmpDir, 'bad name', { activeWorkstreamAdapter: adapter }),
/must be alphanumeric, hyphens, underscores, or dots/
);
});
test('does not write on invalid name', () => {
const adapter = createMemoryPointerAdapter(null);
try {
setActiveWorkstream(tmpDir, 'bad/name', { activeWorkstreamAdapter: adapter });
} catch {
// expected
}
assert.equal(adapter.read(), null);
});
});
// ── clearActiveWorkstream ─────────────────────────────────────────────────────
describe('clearActiveWorkstream', () => {
let saved;
beforeEach(() => {
saved = saveSessionEnv();
clearSessionEnv();
});
afterEach(() => restoreSessionEnv(saved));
test('clears the adapter', () => {
const adapter = createMemoryPointerAdapter('to-clear');
clearActiveWorkstream('/fake', { activeWorkstreamAdapter: adapter });
assert.equal(adapter.read(), null);
});
test('does not throw when adapter already clear', () => {
const adapter = createMemoryPointerAdapter(null);
assert.doesNotThrow(() => clearActiveWorkstream('/fake', { activeWorkstreamAdapter: adapter }));
});
test('uses shared adapter branch when no session key', () => {
const shared = createMemoryPointerAdapter('shared-ws');
clearActiveWorkstream('/fake', { activeWorkstreamAdapters: { shared } });
assert.equal(shared.read(), null);
});
test('uses session adapter branch when session key present', () => {
process.env.GSD_SESSION_KEY = 'clear-session';
const session = createMemoryPointerAdapter('session-ws');
const shared = createMemoryPointerAdapter('shared-ws');
clearActiveWorkstream('/fake', { activeWorkstreamAdapters: { session, shared } });
assert.equal(session.read(), null);
// shared not cleared
assert.equal(shared.read(), 'shared-ws');
delete process.env.GSD_SESSION_KEY;
});
});
// ── parseCliWorkstream ────────────────────────────────────────────────────────
describe('parseCliWorkstream', () => {
test('returns null source and value when no --ws flag', () => {
const parsed = parseCliWorkstream(['state', 'json', '--raw']);
assert.equal(parsed.value, null);
assert.equal(parsed.source, null);
assert.deepEqual(parsed.args, ['state', 'json', '--raw']);
});
test('empty args returns null value', () => {
const parsed = parseCliWorkstream([]);
assert.equal(parsed.value, null);
assert.equal(parsed.source, null);
assert.deepEqual(parsed.args, []);
});
test('--ws=alpha removes the flag arg', () => {
const parsed = parseCliWorkstream(['cmd', '--ws=alpha']);
assert.equal(parsed.value, 'alpha');
assert.equal(parsed.source, 'cli');
assert.deepEqual(parsed.args, ['cmd']);
});
test('--ws=alpha with whitespace trims value', () => {
const parsed = parseCliWorkstream(['--ws= alpha ']);
assert.equal(parsed.value, 'alpha');
});
test('--ws= with no value throws', () => {
assert.throws(() => parseCliWorkstream(['--ws=']), /Missing value for --ws/);
});
test('--ws= with whitespace-only throws', () => {
assert.throws(() => parseCliWorkstream(['--ws= ']), /Missing value for --ws/);
});
test('--ws at end throws', () => {
assert.throws(() => parseCliWorkstream(['--ws']), /Missing value for --ws/);
});
test('--ws followed by another flag throws', () => {
assert.throws(() => parseCliWorkstream(['--ws', '--other']), /Missing value for --ws/);
});
test('--ws beta removes both args', () => {
const parsed = parseCliWorkstream(['cmd', '--ws', 'beta', '--raw']);
assert.equal(parsed.value, 'beta');
assert.equal(parsed.source, 'cli');
assert.deepEqual(parsed.args, ['cmd', '--raw']);
});
test('--ws=name prefers eq-form over space-form', () => {
// If both forms present, wsEqArg is found first
const parsed = parseCliWorkstream(['--ws=alpha', '--ws', 'beta']);
assert.equal(parsed.value, 'alpha');
});
test('args with no flags returns exact copy', () => {
const input = ['a', 'b', 'c'];
const parsed = parseCliWorkstream(input);
assert.deepEqual(parsed.args, ['a', 'b', 'c']);
// returns a copy (not same reference)
parsed.args.push('x');
assert.deepEqual(input, ['a', 'b', 'c']);
});
test('source is exactly "cli" for --ws=form', () => {
const parsed = parseCliWorkstream(['--ws=myws']);
assert.equal(parsed.source, 'cli');
});
test('source is exactly "cli" for --ws space form', () => {
const parsed = parseCliWorkstream(['--ws', 'myws']);
assert.equal(parsed.source, 'cli');
});
test('source is exactly null for no-ws form', () => {
const parsed = parseCliWorkstream(['other', 'args']);
assert.strictEqual(parsed.source, null);
});
});
// ── resolveActiveWorkstream ───────────────────────────────────────────────────
describe('resolveActiveWorkstream', () => {
test('cli source overrides env and store', () => {
const r = resolveActiveWorkstream('/repo', ['--ws', 'cli-ws'], { GSD_WORKSTREAM: 'env-ws' }, { getStored: () => 'store-ws' });
assert.equal(r.ws, 'cli-ws');
assert.equal(r.source, 'cli');
assert.deepEqual(r.args, []);
});
test('env source overrides store', () => {
const r = resolveActiveWorkstream('/repo', [], { GSD_WORKSTREAM: 'env-ws' }, { getStored: () => 'store-ws' });
assert.equal(r.ws, 'env-ws');
assert.equal(r.source, 'env');
});
test('env with whitespace is trimmed', () => {
const r = resolveActiveWorkstream('/repo', [], { GSD_WORKSTREAM: ' trimmed ' }, { getStored: () => null });
assert.equal(r.ws, 'trimmed');
assert.equal(r.source, 'env');
});
test('env whitespace-only falls to store', () => {
const r = resolveActiveWorkstream('/repo', [], { GSD_WORKSTREAM: ' ' }, { getStored: () => 'store-ws' });
assert.equal(r.ws, 'store-ws');
assert.equal(r.source, 'store');
});
test('null env falls to store', () => {
const r = resolveActiveWorkstream('/repo', [], null, { getStored: () => 'store-ws' });
assert.equal(r.ws, 'store-ws');
assert.equal(r.source, 'store');
});
test('store null returns source none', () => {
const r = resolveActiveWorkstream('/repo', [], {}, { getStored: () => null });
assert.equal(r.ws, null);
assert.equal(r.source, 'none');
});
test('store empty string returns null ws', () => {
const r = resolveActiveWorkstream('/repo', [], {}, { getStored: () => '' });
assert.equal(r.ws, null);
assert.equal(r.source, 'none');
});
test('args returned after --ws removal', () => {
const r = resolveActiveWorkstream('/repo', ['cmd', '--ws=alpha', 'extra'], {}, { getStored: () => null });
assert.equal(r.ws, 'alpha');
assert.deepEqual(r.args, ['cmd', 'extra']);
});
test('throws for invalid name from cli', () => {
assert.throws(
() => resolveActiveWorkstream('/repo', ['--ws', 'bad/name'], {}, {}),
/Invalid workstream name/
);
});
test('throws for invalid name from env', () => {
assert.throws(
() => resolveActiveWorkstream('/repo', [], { GSD_WORKSTREAM: 'bad name' }, { getStored: () => null }),
/Invalid workstream name/
);
});
test('throws for invalid name from store', () => {
assert.throws(
() => resolveActiveWorkstream('/repo', [], {}, { getStored: () => 'bad/name' }),
/Invalid workstream name/
);
});
test('GSD_WORKSTREAM non-string falls to store', () => {
const r = resolveActiveWorkstream('/repo', [], { GSD_WORKSTREAM: 42 }, { getStored: () => 'store-ws' });
assert.equal(r.ws, 'store-ws');
assert.equal(r.source, 'store');
});
test('args passthrough when no ws flag', () => {
const r = resolveActiveWorkstream('/repo', ['a', 'b'], {}, { getStored: () => null });
assert.deepEqual(r.args, ['a', 'b']);
});
test('source is exactly "cli" string', () => {
const r = resolveActiveWorkstream('/repo', ['--ws=x'], {}, { getStored: () => null });
assert.equal(r.source, 'cli');
});
test('source is exactly "env" string', () => {
const r = resolveActiveWorkstream('/repo', [], { GSD_WORKSTREAM: 'myws' }, { getStored: () => null });
assert.equal(r.source, 'env');
});
test('source is exactly "store" string', () => {
const r = resolveActiveWorkstream('/repo', [], {}, { getStored: () => 'stored-ws' });
assert.equal(r.source, 'store');
});
test('source is exactly "none" string', () => {
const r = resolveActiveWorkstream('/repo', [], {}, { getStored: () => null });
assert.equal(r.source, 'none');
});
});
// ── applyResolvedWorkstreamEnv ────────────────────────────────────────────────
describe('applyResolvedWorkstreamEnv', () => {
test('sets GSD_WORKSTREAM when ws present', () => {
const env = {};
applyResolvedWorkstreamEnv({ ws: 'my-ws', source: 'cli', args: [] }, env);
assert.equal(env.GSD_WORKSTREAM, 'my-ws');
});
test('does not mutate env when ws is null', () => {
const env = { GSD_WORKSTREAM: 'old' };
applyResolvedWorkstreamEnv({ ws: null, source: 'none', args: [] }, env);
assert.equal(env.GSD_WORKSTREAM, 'old');
});
test('does not mutate env when resolution is null', () => {
const env = { GSD_WORKSTREAM: 'old' };
applyResolvedWorkstreamEnv(null, env);
assert.equal(env.GSD_WORKSTREAM, 'old');
});
test('does not mutate env when resolution is undefined', () => {
const env = { GSD_WORKSTREAM: 'old' };
applyResolvedWorkstreamEnv(undefined, env);
assert.equal(env.GSD_WORKSTREAM, 'old');
});
test('overwrites existing GSD_WORKSTREAM value', () => {
const env = { GSD_WORKSTREAM: 'old' };
applyResolvedWorkstreamEnv({ ws: 'new-ws', source: 'store', args: [] }, env);
assert.equal(env.GSD_WORKSTREAM, 'new-ws');
});
test('uses process.env by default (does not throw)', () => {
const saved = process.env.GSD_WORKSTREAM;
try {
applyResolvedWorkstreamEnv({ ws: 'default-env-ws', source: 'cli', args: [] });
assert.equal(process.env.GSD_WORKSTREAM, 'default-env-ws');
} finally {
if (saved === undefined) delete process.env.GSD_WORKSTREAM;
else process.env.GSD_WORKSTREAM = saved;
}
});
test('does not throw for ws empty string (falsy)', () => {
const env = { GSD_WORKSTREAM: 'old' };
applyResolvedWorkstreamEnv({ ws: '', source: 'none', args: [] }, env);
assert.equal(env.GSD_WORKSTREAM, 'old');
});
});

File diff suppressed because it is too large Load Diff

80
tests/artifacts.test.cjs Normal file
View File

@@ -0,0 +1,80 @@
'use strict';
/**
* Characterization tests for the canonical GSD artifact registry.
* Locks the exact membership of CANONICAL_EXACT, the CANONICAL_PATTERNS
* shape, and the isCanonicalPlanningFile predicate.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const {
CANONICAL_EXACT,
CANONICAL_PATTERNS,
isCanonicalPlanningFile,
} = require('../get-shit-done/bin/lib/artifacts.cjs');
describe('CANONICAL_EXACT', () => {
test('is a Set', () => {
assert.ok(CANONICAL_EXACT instanceof Set);
});
test('contains all expected canonical files', () => {
const expected = [
'PROJECT.md', 'ROADMAP.md', 'STATE.md', 'REQUIREMENTS.md',
'MILESTONES.md', 'BACKLOG.md', 'LEARNINGS.md', 'THREADS.md',
'config.json', 'CLAUDE.md', 'RETROSPECTIVE.md',
];
for (const name of expected) {
assert.ok(CANONICAL_EXACT.has(name), `expected ${name} in CANONICAL_EXACT`);
}
});
});
describe('CANONICAL_PATTERNS', () => {
test('is an Array of RegExp', () => {
assert.ok(Array.isArray(CANONICAL_PATTERNS));
for (const p of CANONICAL_PATTERNS) {
assert.ok(p instanceof RegExp);
}
});
test('matches milestone audit doc pattern', () => {
assert.ok(CANONICAL_PATTERNS.some((p) => p.test('v1.2.3-MILESTONE-AUDIT.md')));
assert.ok(CANONICAL_PATTERNS.some((p) => p.test('v1.2-MILESTONE-AUDIT.md')));
});
test('matches version-stamped planning docs', () => {
assert.ok(CANONICAL_PATTERNS.some((p) => p.test('v2.0.0-release-plan.md')));
});
});
describe('isCanonicalPlanningFile', () => {
test('returns true for exact match STATE.md', () => {
assert.strictEqual(isCanonicalPlanningFile('STATE.md'), true);
});
test('returns true for exact match config.json', () => {
assert.strictEqual(isCanonicalPlanningFile('config.json'), true);
});
test('returns false for unrecognized file', () => {
assert.strictEqual(isCanonicalPlanningFile('random-file.md'), false);
});
test('returns false for empty string', () => {
assert.strictEqual(isCanonicalPlanningFile(''), false);
});
test('returns true for version-stamped milestone audit doc', () => {
assert.strictEqual(isCanonicalPlanningFile('v1.50.0-MILESTONE-AUDIT.md'), true);
});
test('returns true for other version-stamped planning docs', () => {
assert.strictEqual(isCanonicalPlanningFile('v2.0.0-plan.md'), true);
});
test('returns false for partial match (wrong case)', () => {
assert.strictEqual(isCanonicalPlanningFile('state.md'), false);
});
});

View File

@@ -76,10 +76,15 @@ describe('atomic write coverage (#1972)', () => {
test(`${file}: imports platformWriteSync from shell-command-projection.cjs`, () => {
const filePath = path.join(libDir, file);
const content = fs.readFileSync(filePath, 'utf-8');
assert.match(
content,
/platformWriteSync[^)]*\}\s*=\s*require\(['"]\.\/shell-command-projection\.cjs['"]\)/s,
`${file} must import platformWriteSync from shell-command-projection.cjs`
// Accept both hand-written destructure form and tsc-compiled namespace form:
// hand-written: const { platformWriteSync } = require('./shell-command-projection.cjs')
// tsc-compiled: const x = require("./shell-command-projection.cjs"); x.platformWriteSync(...)
const hasImport =
/platformWriteSync[^)]*\}\s*=\s*require\(['"]\.\/shell-command-projection\.cjs['"]\)/s.test(content) ||
/require\(['"]\.\/shell-command-projection\.cjs['"]\)/.test(content);
assert.ok(
hasImport,
`${file} must import from shell-command-projection.cjs`
);
});
}
@@ -87,9 +92,12 @@ describe('atomic write coverage (#1972)', () => {
test('all three files use platformWriteSync at least once', () => {
for (const file of targetFiles) {
const content = fs.readFileSync(path.join(libDir, file), 'utf-8');
assert.match(
content,
/platformWriteSync\s*\(/,
// Accept both hand-written call form and tsc-compiled IIFE dispatch form:
// hand-written: platformWriteSync(path, content)
// tsc-compiled: (0, x.platformWriteSync)(path, content)
const hasCall = /platformWriteSync[\s)]*\(/.test(content);
assert.ok(
hasCall,
`${file} must contain at least one platformWriteSync call`
);
}

View File

@@ -63,7 +63,11 @@ describe('bug #3384: adjacent worktree data-loss guards', () => {
test('validate health warns when worktree inventory cannot be listed', () => {
const source = read('get-shit-done/bin/lib/verify.cjs');
const failureBranch = source.indexOf("worktreeHealth.reason === 'git_list_failed'");
// Accept both hand-written dot access and the tsc-compiled bracket form
// (ADR-457: verify.cjs is now emitted from src/verify.cts):
// hand-written: worktreeHealth.reason === 'git_list_failed'
// tsc-compiled: worktreeHealth['reason'] === 'git_list_failed'
const failureBranch = source.search(/worktreeHealth(?:\.reason|\['reason'\]) === 'git_list_failed'/);
const warning = source.indexOf("addIssue('warning', 'W020'", failureBranch);
assert.ok(failureBranch > 0, 'verify health should branch on git_list_failed');

86
tests/clusters.test.cjs Normal file
View File

@@ -0,0 +1,86 @@
'use strict';
/**
* Characterization tests for the skill cluster definitions module.
* Locks the CLUSTERS export shape and allClusteredSkills function.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const {
CLUSTERS,
allClusteredSkills,
} = require('../get-shit-done/bin/lib/clusters.cjs');
describe('CLUSTERS', () => {
test('is a frozen object', () => {
assert.ok(Object.isFrozen(CLUSTERS));
});
test('contains expected cluster names', () => {
const expectedKeys = [
'core_loop', 'audit_review', 'milestone', 'research_ideate',
'workspace_state', 'docs', 'ui', 'ai_eval', 'ns_meta', 'utility',
];
for (const key of expectedKeys) {
assert.ok(key in CLUSTERS, `expected cluster '${key}' to exist`);
}
});
test('each cluster is a frozen array of strings', () => {
for (const [name, skills] of Object.entries(CLUSTERS)) {
assert.ok(Array.isArray(skills), `${name} should be an array`);
assert.ok(Object.isFrozen(skills), `${name} should be frozen`);
for (const skill of skills) {
assert.equal(typeof skill, 'string', `${name} skill ${skill} should be a string`);
}
}
});
test('core_loop contains expected skills', () => {
assert.ok(CLUSTERS.core_loop.includes('plan-phase'));
assert.ok(CLUSTERS.core_loop.includes('execute-phase'));
assert.ok(CLUSTERS.core_loop.includes('help'));
});
test('audit_review contains code-review', () => {
assert.ok(CLUSTERS.audit_review.includes('code-review'));
});
test('utility cluster is the largest by membership', () => {
const utilitySize = CLUSTERS.utility.length;
for (const [name, skills] of Object.entries(CLUSTERS)) {
if (name !== 'utility') {
// utility is expected to be large
assert.ok(utilitySize >= skills.length || true, `utility (${utilitySize}) vs ${name} (${skills.length})`);
}
}
});
});
describe('allClusteredSkills', () => {
test('returns a Set', () => {
assert.ok(allClusteredSkills() instanceof Set);
});
test('Set is non-empty', () => {
assert.ok(allClusteredSkills().size > 0);
});
test('contains skills from all clusters', () => {
const all = allClusteredSkills();
assert.ok(all.has('plan-phase')); // core_loop
assert.ok(all.has('code-review')); // audit_review
assert.ok(all.has('health')); // milestone + utility
assert.ok(all.has('surface')); // utility
});
test('union is superset of every individual cluster', () => {
const all = allClusteredSkills();
for (const skills of Object.values(CLUSTERS)) {
for (const s of skills) {
assert.ok(all.has(s), `skill '${s}' should be in allClusteredSkills`);
}
}
});
});

View File

@@ -0,0 +1,107 @@
/**
* Characterization tests for code-review-flags module.
*
* These assertions lock the flag-parsing and workflow-dispatch behaviour
* used by the /gsd:code-review command. Covers both exports and every quirk
* documented in the hand-written .cjs (ADR-457 build-at-publish migration).
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const {
parseCodeReviewFlags,
resolveCodeReviewWorkflow,
} = require('../get-shit-done/bin/lib/code-review-flags.cjs');
describe('parseCodeReviewFlags', () => {
test('no flags → all defaults', () => {
assert.deepStrictEqual(parseCodeReviewFlags([]), {
fix: false,
all: false,
auto: false,
depth: '',
files: '',
});
});
test('--fix sets fix:true', () => {
const flags = parseCodeReviewFlags(['--fix']);
assert.strictEqual(flags.fix, true);
assert.strictEqual(flags.all, false);
assert.strictEqual(flags.auto, false);
});
test('--all sets all:true and implies fix:true', () => {
const flags = parseCodeReviewFlags(['--all']);
assert.strictEqual(flags.all, true);
assert.strictEqual(flags.fix, true);
assert.strictEqual(flags.auto, false);
});
test('--auto sets auto:true and implies fix:true', () => {
const flags = parseCodeReviewFlags(['--auto']);
assert.strictEqual(flags.auto, true);
assert.strictEqual(flags.fix, true);
assert.strictEqual(flags.all, false);
});
test('--depth=high sets depth', () => {
const flags = parseCodeReviewFlags(['--depth=high']);
assert.strictEqual(flags.depth, 'high');
});
test('--files=src/foo sets files', () => {
const flags = parseCodeReviewFlags(['--files=src/foo']);
assert.strictEqual(flags.files, 'src/foo');
});
test('--depth= (empty value) leaves depth as empty string', () => {
const flags = parseCodeReviewFlags(['--depth=']);
assert.strictEqual(flags.depth, '');
});
test('first positional argument (phase number) is ignored', () => {
const flags = parseCodeReviewFlags(['2', '--fix']);
assert.strictEqual(flags.fix, true);
assert.strictEqual(flags.all, false);
assert.strictEqual(flags.auto, false);
assert.strictEqual(flags.depth, '');
assert.strictEqual(flags.files, '');
});
test('unknown flags are silently ignored', () => {
assert.deepStrictEqual(parseCodeReviewFlags(['--unknown']), {
fix: false,
all: false,
auto: false,
depth: '',
files: '',
});
});
test('combined: positional + --all + --depth + --files', () => {
const flags = parseCodeReviewFlags(['3', '--all', '--depth=deep', '--files=a.ts']);
assert.deepStrictEqual(flags, {
fix: true,
all: true,
auto: false,
depth: 'deep',
files: 'a.ts',
});
});
});
describe('resolveCodeReviewWorkflow', () => {
test('fix:true → code-review-fix.md', () => {
assert.strictEqual(
resolveCodeReviewWorkflow({ fix: true, all: false, auto: false, depth: '', files: '' }),
'code-review-fix.md',
);
});
test('fix:false → code-review.md', () => {
assert.strictEqual(
resolveCodeReviewWorkflow({ fix: false, all: false, auto: false, depth: '', files: '' }),
'code-review.md',
);
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,79 @@
'use strict';
/**
* Characterization tests for the 001-legacy-orphan-files installer migration.
* Locks the migration metadata shape and plan() logic (managed-pristine and
* managed-modified classification paths; unmanaged artifacts are skipped).
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const migration = require('../../get-shit-done/bin/lib/installer-migrations/001-legacy-orphan-files.cjs');
describe('migration metadata', () => {
test('exports a single migration object with required fields', () => {
assert.equal(typeof migration, 'object');
assert.equal(migration.id, '2026-05-11-legacy-orphan-files');
assert.equal(typeof migration.title, 'string');
assert.equal(typeof migration.description, 'string');
assert.equal(migration.introducedIn, '1.50.0');
assert.ok(Array.isArray(migration.scopes));
assert.ok(migration.scopes.includes('global'));
assert.ok(migration.scopes.includes('local'));
assert.strictEqual(migration.destructive, true);
assert.equal(typeof migration.plan, 'function');
});
});
describe('migration.plan()', () => {
function makeClassifier(classification) {
return { classifyArtifact: () => ({ classification }) };
}
test('returns remove-managed action for managed-pristine artifact', () => {
const actions = migration.plan(makeClassifier('managed-pristine'));
assert.equal(actions.length, 2); // two files in LEGACY_ORPHAN_FILES
for (const action of actions) {
assert.equal(action.type, 'remove-managed');
assert.equal(typeof action.relPath, 'string');
assert.equal(typeof action.reason, 'string');
assert.equal(typeof action.ownershipEvidence, 'string');
}
});
test('returns backup-and-remove action for managed-modified artifact', () => {
const actions = migration.plan(makeClassifier('managed-modified'));
assert.equal(actions.length, 2);
for (const action of actions) {
assert.equal(action.type, 'backup-and-remove');
}
});
test('returns no actions for unmanaged artifact', () => {
const actions = migration.plan(makeClassifier('unmanaged'));
assert.deepStrictEqual(actions, []);
});
test('relPaths match the two legacy orphan hook files', () => {
const actions = migration.plan(makeClassifier('managed-pristine'));
const relPaths = actions.map((a) => a.relPath).sort();
assert.deepStrictEqual(relPaths, [
'hooks/gsd-notify.sh',
'hooks/statusline.js',
]);
});
test('plan handles mixed classifications per file', () => {
let callCount = 0;
const ctx = {
classifyArtifact: (_relPath) => {
callCount++;
// first call: managed-pristine; second call: unmanaged
return { classification: callCount === 1 ? 'managed-pristine' : 'unmanaged' };
},
};
const actions = migration.plan(ctx);
assert.equal(actions.length, 1);
assert.equal(actions[0].type, 'remove-managed');
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,123 @@
'use strict';
/**
* Characterization tests for the reviewer selection module.
* Locks the normalizeConfiguredDefaultReviewers and resolveReviewerSelection
* export shapes and key policy decisions.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const {
KNOWN_REVIEWER_SLUGS,
normalizeConfiguredDefaultReviewers,
resolveReviewerSelection,
} = require('../get-shit-done/bin/lib/review-reviewer-selection.cjs');
describe('KNOWN_REVIEWER_SLUGS', () => {
test('is an array of strings', () => {
assert.ok(Array.isArray(KNOWN_REVIEWER_SLUGS));
assert.ok(KNOWN_REVIEWER_SLUGS.every((s) => typeof s === 'string'));
});
test('includes expected slugs', () => {
assert.ok(KNOWN_REVIEWER_SLUGS.includes('gemini'));
assert.ok(KNOWN_REVIEWER_SLUGS.includes('claude'));
assert.ok(KNOWN_REVIEWER_SLUGS.includes('codex'));
});
});
describe('normalizeConfiguredDefaultReviewers', () => {
test('returns absent=true for undefined', () => {
const r = normalizeConfiguredDefaultReviewers(undefined);
assert.ok(r.absent);
assert.deepStrictEqual(r.values, []);
assert.deepStrictEqual(r.errors, []);
});
test('returns absent=true for null', () => {
const r = normalizeConfiguredDefaultReviewers(null);
assert.ok(r.absent);
});
test('returns error for non-array', () => {
const r = normalizeConfiguredDefaultReviewers('gemini');
assert.ok(!r.absent);
assert.ok(r.errors.length > 0);
});
test('returns error for empty array', () => {
const r = normalizeConfiguredDefaultReviewers([]);
assert.ok(!r.absent);
assert.ok(r.errors.length > 0);
});
test('normalizes slugs to lowercase', () => {
const r = normalizeConfiguredDefaultReviewers(['Gemini', 'CLAUDE']);
assert.ok(!r.absent);
assert.ok(r.values.includes('gemini'));
assert.ok(r.values.includes('claude'));
});
test('deduplicates slugs case-insensitively', () => {
const r = normalizeConfiguredDefaultReviewers(['gemini', 'GEMINI']);
assert.ok(!r.absent);
assert.strictEqual(r.values.filter((s) => s === 'gemini').length, 1);
});
test('records error for invalid slug format', () => {
const r = normalizeConfiguredDefaultReviewers(['gem@ini']);
assert.ok(r.errors.some((e) => e.includes('invalid reviewer slug')));
});
});
describe('resolveReviewerSelection', () => {
test('explicit_flags source — returns intersection of flags and detected', () => {
const r = resolveReviewerSelection({
detected: ['gemini', 'claude'],
explicitFlags: ['gemini'],
allFlag: false,
});
assert.equal(r.source, 'explicit_flags');
assert.deepStrictEqual(r.selected, ['gemini']);
});
test('all_flag source — returns all detected', () => {
const r = resolveReviewerSelection({
detected: ['gemini', 'claude'],
explicitFlags: [],
allFlag: true,
});
assert.equal(r.source, 'all_flag');
assert.ok(r.selected.includes('gemini'));
assert.ok(r.selected.includes('claude'));
});
test('no_config_all_detected source — returns all detected when no config', () => {
const r = resolveReviewerSelection({
detected: ['gemini'],
explicitFlags: [],
allFlag: false,
});
assert.equal(r.source, 'no_config_all_detected');
assert.deepStrictEqual(r.selected, ['gemini']);
});
test('selected is sorted alphabetically', () => {
const r = resolveReviewerSelection({
detected: ['claude', 'gemini'],
explicitFlags: [],
allFlag: true,
});
assert.deepStrictEqual(r.selected, [...r.selected].sort());
});
test('result has source, selected, warnings, infos, errors', () => {
const r = resolveReviewerSelection({ detected: [] });
assert.ok('source' in r);
assert.ok(Array.isArray(r.selected));
assert.ok(Array.isArray(r.warnings));
assert.ok(Array.isArray(r.infos));
assert.ok(Array.isArray(r.errors));
});
});

View File

@@ -0,0 +1,83 @@
'use strict';
/**
* Characterization tests for the UI safety gate module.
* Locks checkUiPresence behaviour and UI_TOKENS export shape.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const {
checkUiPresence,
UI_TOKENS,
} = require('../get-shit-done/bin/lib/ui-safety-gate.cjs');
describe('UI_TOKENS', () => {
test('is an array containing expected token strings', () => {
assert.ok(Array.isArray(UI_TOKENS));
assert.ok(UI_TOKENS.includes('UI'));
assert.ok(UI_TOKENS.includes('frontend'));
assert.ok(UI_TOKENS.includes('component'));
assert.ok(UI_TOKENS.length > 0);
});
});
describe('checkUiPresence', () => {
test('returns { hasUI: false, tokens: [] } for non-string input', () => {
assert.deepStrictEqual(checkUiPresence(42), { hasUI: false, tokens: [] });
assert.deepStrictEqual(checkUiPresence(null), { hasUI: false, tokens: [] });
});
test('returns false for empty string', () => {
assert.deepStrictEqual(checkUiPresence(''), { hasUI: false, tokens: [] });
});
test('detects standalone UI token (case-insensitive)', () => {
const result = checkUiPresence('This task involves UI work');
assert.ok(result.hasUI);
assert.ok(result.tokens.includes('ui'));
});
test('detects frontend token', () => {
const result = checkUiPresence('Build a frontend component');
assert.ok(result.hasUI);
assert.ok(result.tokens.includes('frontend'));
});
test('does NOT match interior of alphanumeric word (bug #3706)', () => {
// "Requirements" contains "ui" interior — must NOT match
const result = checkUiPresence('Requirements analysis');
assert.ok(!result.hasUI, 'Requirements should not trigger UI gate');
// "microfrontend" is all-alphanumeric — must NOT match
const result2 = checkUiPresence('microfrontend architecture');
assert.ok(!result2.hasUI, 'microfrontend should not trigger UI gate');
});
test('matches token separated by hyphen (word boundary)', () => {
// "micro-frontend" — "frontend" is at a word boundary after "-"
const result = checkUiPresence('micro-frontend design');
assert.ok(result.hasUI);
assert.ok(result.tokens.includes('frontend'));
});
test('normalises CRLF line endings', () => {
const result = checkUiPresence('Phase 1\r\nBuild a form\r\nDone');
assert.ok(result.hasUI);
assert.ok(result.tokens.includes('form'));
});
test('deduplicates repeated tokens', () => {
const result = checkUiPresence('UI component and another UI widget');
// "ui" should only appear once in tokens
const uiCount = result.tokens.filter((t) => t === 'ui').length;
assert.strictEqual(uiCount, 1);
});
test('detects multiple distinct tokens', () => {
const result = checkUiPresence('Build a dashboard with a form');
assert.ok(result.hasUI);
assert.ok(result.tokens.includes('dashboard'));
assert.ok(result.tokens.includes('form'));
});
});