* 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>
432 lines
15 KiB
TypeScript
432 lines
15 KiB
TypeScript
/**
|
|
* Codebase Drift Detection (#2003)
|
|
*
|
|
* Detects structural drift between a committed codebase and the
|
|
* `.planning/codebase/STRUCTURE.md` map produced by `gsd-codebase-mapper`.
|
|
*
|
|
* Four categories of drift element:
|
|
* - new_dir → a newly-added file whose directory prefix does not appear
|
|
* in STRUCTURE.md
|
|
* - barrel → a newly-added barrel export at
|
|
* (packages|apps)/<name>/src/index.(ts|tsx|js|mjs|cjs)
|
|
* - migration → a newly-added migration file under one of the recognized
|
|
* migration directories (supabase, prisma, drizzle, src/migrations, …)
|
|
* - route → a newly-added route module under a `routes/` or `api/` dir
|
|
*
|
|
* Each file is counted at most once; when a file matches multiple categories
|
|
* the most specific category wins (migration > route > barrel > new_dir).
|
|
*
|
|
* Design decisions (see PR for full rubber-duck):
|
|
* - The library is pure. It takes parsed git diff output and returns a
|
|
* structured result. The CLI/workflow layer is responsible for running
|
|
* git and for spawning mappers.
|
|
* - `last_mapped_commit` is stored as YAML-style frontmatter at the top of
|
|
* each `.planning/codebase/*.md` file. This keeps the baseline attached
|
|
* to the file, survives git moves, and avoids a sidecar JSON.
|
|
* - The detector NEVER throws on malformed input — it returns a
|
|
* `{ skipped: true }` result. The phase workflow depends on this
|
|
* non-blocking guarantee.
|
|
*
|
|
* ADR-457 build-at-publish: the hand-written bin/lib/drift.cjs collapsed to
|
|
* a TypeScript source of truth. Behaviour is preserved byte-for-behaviour from
|
|
* the prior hand-written .cjs; only types are added.
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
import fs from 'node:fs';
|
|
import { platformWriteSync } from './shell-command-projection.cjs';
|
|
import { formatGsdSlash } from './runtime-slash.cjs';
|
|
|
|
// ─── Constants ───────────────────────────────────────────────────────────────
|
|
|
|
const DRIFT_CATEGORIES = Object.freeze(['new_dir', 'barrel', 'migration', 'route']);
|
|
|
|
// Category priority when a single file matches multiple rules.
|
|
// Higher index = more specific = wins.
|
|
const CATEGORY_PRIORITY: Record<string, number> = { new_dir: 0, barrel: 1, route: 2, migration: 3 };
|
|
|
|
const BARREL_RE = /^(packages|apps)\/[^/]+\/src\/index\.(ts|tsx|js|mjs|cjs)$/;
|
|
|
|
const MIGRATION_RES = [
|
|
/^supabase\/migrations\/.+\.sql$/,
|
|
/^prisma\/migrations\/.+/,
|
|
/^drizzle\/meta\/.+/,
|
|
/^drizzle\/migrations\/.+/,
|
|
/^src\/migrations\/.+\.(ts|js|sql)$/,
|
|
/^db\/migrations\/.+\.(sql|ts|js)$/,
|
|
/^migrations\/.+\.(sql|ts|js)$/,
|
|
];
|
|
|
|
const ROUTE_RES = [
|
|
/^(apps|packages)\/[^/]+\/src\/routes\/.+\.(ts|tsx|js|jsx|mjs|cjs)$/,
|
|
/^src\/routes\/.+\.(ts|tsx|js|jsx|mjs|cjs)$/,
|
|
/^src\/api\/.+\.(ts|tsx|js|jsx|mjs|cjs)$/,
|
|
/^(apps|packages)\/[^/]+\/src\/api\/.+\.(ts|tsx|js|jsx|mjs|cjs)$/,
|
|
];
|
|
|
|
// A conservative allowlist for `--paths` arguments passed to the mapper:
|
|
// repo-relative path components separated by /, containing only
|
|
// alphanumerics, dash, underscore, and dot (no `..`, no `/..`).
|
|
const SAFE_PATH_RE = /^(?!.*\.\.)(?:[A-Za-z0-9_.][A-Za-z0-9_.\-]*)(?:\/[A-Za-z0-9_.][A-Za-z0-9_.\-]*)*$/;
|
|
|
|
// ─── Classification ──────────────────────────────────────────────────────────
|
|
|
|
type DriftCategory = 'barrel' | 'migration' | 'route' | 'new_dir';
|
|
|
|
/**
|
|
* Classify a single file path into a drift category or null.
|
|
*/
|
|
function classifyFile(file: unknown): DriftCategory | null {
|
|
if (typeof file !== 'string' || !file) return null;
|
|
const norm = file.replace(/\\/g, '/');
|
|
if (MIGRATION_RES.some((r) => r.test(norm))) return 'migration';
|
|
if (ROUTE_RES.some((r) => r.test(norm))) return 'route';
|
|
if (BARREL_RE.test(norm)) return 'barrel';
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* True iff any prefix of `file` (dir1, dir1/dir2, …) appears as a substring
|
|
* of `structureMd`. Used to decide whether a file is in "mapped territory".
|
|
*
|
|
* Matching is deliberately substring-based — STRUCTURE.md is free-form
|
|
* markdown, not a structured manifest. If the map mentions `src/lib/` the
|
|
* check `structureMd.includes('src/lib')` holds.
|
|
*/
|
|
function isPathMapped(file: string, structureMd: string): boolean {
|
|
const norm = file.replace(/\\/g, '/');
|
|
const parts = norm.split('/');
|
|
// Check prefixes from longest to shortest; any hit means "mapped".
|
|
for (let i = parts.length - 1; i >= 1; i--) {
|
|
const prefix = parts.slice(0, i).join('/');
|
|
if (structureMd.includes(prefix)) return true;
|
|
}
|
|
// Finally, if even the top-level dir is mentioned, count as mapped.
|
|
if (parts.length > 0 && structureMd.includes(parts[0] + '/')) return true;
|
|
if (parts.length > 0 && structureMd.includes('`' + parts[0] + '`')) return true;
|
|
return false;
|
|
}
|
|
|
|
// ─── Types ───────────────────────────────────────────────────────────────────
|
|
|
|
interface DriftElement {
|
|
category: string;
|
|
path: string;
|
|
}
|
|
|
|
interface DetectDriftInput {
|
|
addedFiles?: unknown[];
|
|
modifiedFiles?: unknown[];
|
|
deletedFiles?: unknown[];
|
|
structureMd?: string | null;
|
|
threshold?: number;
|
|
action?: string;
|
|
runtime?: string;
|
|
}
|
|
|
|
interface DetectDriftResult {
|
|
skipped: false;
|
|
elements: DriftElement[];
|
|
actionRequired: boolean;
|
|
directive: string;
|
|
spawnMapper: boolean;
|
|
affectedPaths: string[];
|
|
threshold: number;
|
|
action: string;
|
|
message: string;
|
|
counts: {
|
|
added: number;
|
|
modified: number;
|
|
deleted: number;
|
|
};
|
|
}
|
|
|
|
interface SkippedResult {
|
|
skipped: true;
|
|
reason: string;
|
|
elements: DriftElement[];
|
|
actionRequired: false;
|
|
directive: string;
|
|
spawnMapper: false;
|
|
affectedPaths: string[];
|
|
message: string;
|
|
}
|
|
|
|
// ─── Main detection ──────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Detect codebase drift.
|
|
*/
|
|
function detectDrift(input: unknown): DetectDriftResult | SkippedResult {
|
|
try {
|
|
if (!input || typeof input !== 'object') {
|
|
return skipped('invalid-input');
|
|
}
|
|
const inp = input as DetectDriftInput;
|
|
const {
|
|
addedFiles,
|
|
modifiedFiles,
|
|
deletedFiles,
|
|
structureMd,
|
|
} = inp;
|
|
const threshold = Number.isInteger(inp.threshold) && (inp.threshold as number) >= 1
|
|
? (inp.threshold as number)
|
|
: 3;
|
|
const action = inp.action === 'auto-remap' ? 'auto-remap' : 'warn';
|
|
|
|
if (structureMd === null || structureMd === undefined) {
|
|
return skipped('missing-structure-md');
|
|
}
|
|
if (typeof structureMd !== 'string') {
|
|
return skipped('invalid-structure-md');
|
|
}
|
|
|
|
const added = Array.isArray(addedFiles) ? addedFiles.filter((x): x is string => typeof x === 'string') : [];
|
|
const modified = Array.isArray(modifiedFiles) ? modifiedFiles : [];
|
|
const deleted = Array.isArray(deletedFiles) ? deletedFiles : [];
|
|
|
|
// Build elements. One element per file, highest-priority category wins.
|
|
const elements: DriftElement[] = [];
|
|
const seen = new Map<string, string>();
|
|
|
|
for (const rawFile of added) {
|
|
const file = rawFile.replace(/\\/g, '/');
|
|
const specific = classifyFile(file);
|
|
let category: string | null = specific;
|
|
if (!category) {
|
|
if (!isPathMapped(file, structureMd)) {
|
|
category = 'new_dir';
|
|
} else {
|
|
continue; // mapped, known, ordinary file — not drift
|
|
}
|
|
}
|
|
// Dedup: if we've already counted this path at higher-or-equal priority, skip
|
|
const prior = seen.get(file);
|
|
if (prior && CATEGORY_PRIORITY[prior] >= CATEGORY_PRIORITY[category]) continue;
|
|
seen.set(file, category);
|
|
}
|
|
|
|
for (const [file, category] of seen.entries()) {
|
|
elements.push({ category, path: file });
|
|
}
|
|
|
|
// Sort for stable output.
|
|
elements.sort((a, b) =>
|
|
a.category === b.category
|
|
? a.path.localeCompare(b.path)
|
|
: a.category.localeCompare(b.category),
|
|
);
|
|
|
|
const actionRequired = elements.length >= threshold;
|
|
let directive = 'none';
|
|
let spawnMapper = false;
|
|
let affectedPaths: string[] = [];
|
|
let message = '';
|
|
|
|
if (actionRequired) {
|
|
directive = action;
|
|
affectedPaths = chooseAffectedPaths(elements.map((e) => e.path));
|
|
if (action === 'auto-remap') {
|
|
spawnMapper = true;
|
|
}
|
|
message = buildMessage(elements, affectedPaths, action, inp.runtime);
|
|
}
|
|
|
|
return {
|
|
skipped: false,
|
|
elements,
|
|
actionRequired,
|
|
directive,
|
|
spawnMapper,
|
|
affectedPaths,
|
|
threshold,
|
|
action,
|
|
message,
|
|
counts: {
|
|
added: added.length,
|
|
modified: modified.length,
|
|
deleted: deleted.length,
|
|
},
|
|
};
|
|
} catch (err) {
|
|
// Non-blocking: never throw from this function.
|
|
const errMsg = (err as Error)?.message ? (err as Error).message : String(err);
|
|
return skipped('exception:' + errMsg);
|
|
}
|
|
}
|
|
|
|
function skipped(reason: string): SkippedResult {
|
|
return {
|
|
skipped: true,
|
|
reason,
|
|
elements: [],
|
|
actionRequired: false,
|
|
directive: 'none',
|
|
spawnMapper: false,
|
|
affectedPaths: [],
|
|
message: '',
|
|
};
|
|
}
|
|
|
|
function buildMessage(elements: DriftElement[], affectedPaths: string[], action: string, runtime: string | undefined): string {
|
|
const byCat: Record<string, string[]> = {};
|
|
for (const e of elements) {
|
|
if (!byCat[e.category]) byCat[e.category] = [];
|
|
byCat[e.category].push(e.path);
|
|
}
|
|
const lines: string[] = [
|
|
`Codebase drift detected: ${elements.length} structural element(s) since last mapping.`,
|
|
'',
|
|
];
|
|
const labels: Record<string, string> = {
|
|
new_dir: 'New directories',
|
|
barrel: 'New barrel exports',
|
|
migration: 'New migrations',
|
|
route: 'New route modules',
|
|
};
|
|
for (const cat of ['new_dir', 'barrel', 'migration', 'route']) {
|
|
if (byCat[cat]) {
|
|
lines.push(`${labels[cat]}:`);
|
|
for (const p of byCat[cat]) lines.push(` - ${p}`);
|
|
}
|
|
}
|
|
lines.push('');
|
|
if (action === 'auto-remap') {
|
|
lines.push(`Auto-remap scheduled for paths: ${affectedPaths.join(', ')}`);
|
|
} else {
|
|
// drift.cts is a pure library — it must never read env/config. The
|
|
// caller (verify.cmdVerifyCodebaseDrift) resolves the runtime once and
|
|
// passes it in via input.runtime so emitted commands match the project
|
|
// the caller is targeting, not the current process directory.
|
|
const mapCmd = formatGsdSlash('map-codebase', runtime || 'claude');
|
|
lines.push(
|
|
`Run ${String(mapCmd)} --paths ${affectedPaths.join(',')} to refresh planning context.`,
|
|
);
|
|
}
|
|
return lines.join('\n');
|
|
}
|
|
|
|
// ─── Affected paths ──────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Collapse a list of drifted file paths into a sorted, deduplicated list of
|
|
* the top-level directory prefixes (depth 2 when the repo uses an
|
|
* `<apps|packages>/<name>/…` layout; depth 1 otherwise).
|
|
*/
|
|
function chooseAffectedPaths(paths: string[]): string[] {
|
|
const out = new Set<string>();
|
|
for (const raw of paths || []) {
|
|
if (typeof raw !== 'string' || !raw) continue;
|
|
const file = raw.replace(/\\/g, '/');
|
|
const parts = file.split('/');
|
|
if (parts.length === 0) continue;
|
|
const top = parts[0];
|
|
if ((top === 'apps' || top === 'packages') && parts.length >= 2) {
|
|
out.add(`${top}/${parts[1]}`);
|
|
} else {
|
|
out.add(top);
|
|
}
|
|
}
|
|
return [...out].sort();
|
|
}
|
|
|
|
/**
|
|
* Filter `paths` to only those that are safe to splice into a mapper prompt.
|
|
* Any path that is absolute, contains traversal, or includes shell
|
|
* metacharacters is dropped.
|
|
*/
|
|
function sanitizePaths(paths: unknown): string[] {
|
|
if (!Array.isArray(paths)) return [];
|
|
const out: string[] = [];
|
|
for (const p of paths) {
|
|
if (typeof p !== 'string') continue;
|
|
if (p.startsWith('/')) continue;
|
|
if (!SAFE_PATH_RE.test(p)) continue;
|
|
out.push(p);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// ─── Frontmatter helpers ─────────────────────────────────────────────────────
|
|
|
|
const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
|
|
|
|
interface FrontmatterResult {
|
|
data: Record<string, string>;
|
|
body: string;
|
|
}
|
|
|
|
function parseFrontmatter(content: unknown): FrontmatterResult {
|
|
if (typeof content !== 'string') return { data: {}, body: '' };
|
|
const m = content.match(FRONTMATTER_RE);
|
|
if (!m) return { data: {}, body: content };
|
|
const data: Record<string, string> = {};
|
|
for (const line of m[1].split(/\r?\n/)) {
|
|
const kv = line.match(/^([A-Za-z0-9_][A-Za-z0-9_-]*):\s*(.*)$/);
|
|
if (!kv) continue;
|
|
data[kv[1]] = kv[2];
|
|
}
|
|
return { data, body: content.slice(m[0].length) };
|
|
}
|
|
|
|
function serializeFrontmatter(data: Record<string, string>, body: string): string {
|
|
const keys = Object.keys(data);
|
|
if (keys.length === 0) return body;
|
|
const lines = ['---'];
|
|
for (const k of keys) lines.push(`${k}: ${data[k]}`);
|
|
lines.push('---');
|
|
return lines.join('\n') + '\n' + body;
|
|
}
|
|
|
|
/**
|
|
* Read `last_mapped_commit` from the frontmatter of a `.planning/codebase/*.md`
|
|
* file. Returns null if the file does not exist or has no frontmatter.
|
|
*/
|
|
function readMappedCommit(filePath: string): string | null {
|
|
let content: string;
|
|
try {
|
|
content = fs.readFileSync(filePath, 'utf8');
|
|
} catch {
|
|
return null;
|
|
}
|
|
const { data } = parseFrontmatter(content);
|
|
const sha = data['last_mapped_commit'];
|
|
return typeof sha === 'string' && sha.length > 0 ? sha : null;
|
|
}
|
|
|
|
/**
|
|
* Upsert `last_mapped_commit` and `last_mapped_at` into the frontmatter of
|
|
* the given file, preserving any other frontmatter keys and the body.
|
|
*/
|
|
function writeMappedCommit(filePath: string, commitSha: string, isoDate?: string): void {
|
|
// Symmetric with readMappedCommit (which returns null on missing files):
|
|
// tolerate a missing target by creating a minimal frontmatter-only file
|
|
// rather than throwing ENOENT. This matters when a mapper produces a new
|
|
// doc and the caller stamps it before any prior content existed.
|
|
let content = '';
|
|
try {
|
|
content = fs.readFileSync(filePath, 'utf8');
|
|
} catch (err) {
|
|
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
|
|
}
|
|
const { data, body } = parseFrontmatter(content);
|
|
data['last_mapped_commit'] = commitSha;
|
|
if (isoDate) data['last_mapped_at'] = isoDate;
|
|
platformWriteSync(filePath, serializeFrontmatter(data, body));
|
|
}
|
|
|
|
// ─── Exports ─────────────────────────────────────────────────────────────────
|
|
|
|
export = {
|
|
DRIFT_CATEGORIES,
|
|
classifyFile,
|
|
detectDrift,
|
|
chooseAffectedPaths,
|
|
sanitizePaths,
|
|
readMappedCommit,
|
|
writeMappedCommit,
|
|
// Exposed for the CLI layer to reuse the same parser.
|
|
parseFrontmatter,
|
|
};
|