* 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>
736 lines
22 KiB
TypeScript
736 lines
22 KiB
TypeScript
/**
|
|
* lib/intel.cts -- Intel storage and query operations for GSD.
|
|
*
|
|
* Provides a persistent, queryable intelligence system for project metadata.
|
|
* Intel files live in .planning/intel/ and store structured data about
|
|
* the project's files, APIs, dependencies, architecture, and tech stack.
|
|
*
|
|
* All public functions gate on intel.enabled config (no-op when false).
|
|
*
|
|
* ADR-457 build-at-publish: the hand-written bin/lib/intel.cjs collapsed
|
|
* to a TypeScript source of truth. Behaviour is preserved byte-for-behaviour
|
|
* from the prior hand-written .cjs; only types are added.
|
|
*/
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import crypto from 'node:crypto';
|
|
import { platformWriteSync, platformReadSync, platformEnsureDir } from './shell-command-projection.cjs';
|
|
|
|
// ─── Constants ───────────────────────────────────────────────────────────────
|
|
|
|
const INTEL_DIR = '.planning/intel';
|
|
|
|
const INTEL_FILES: Record<string, string> = {
|
|
files: 'file-roles.json',
|
|
apis: 'api-map.json',
|
|
deps: 'dependency-graph.json',
|
|
arch: 'arch-decisions.json',
|
|
stack: 'stack.json',
|
|
};
|
|
|
|
// ─── Internal helpers ────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Ensure the intel directory exists under the given planning dir.
|
|
*/
|
|
function ensureIntelDir(planningDir: string): string {
|
|
const intelPath = path.join(planningDir, 'intel');
|
|
platformEnsureDir(intelPath);
|
|
return intelPath;
|
|
}
|
|
|
|
/**
|
|
* Check whether intel is enabled in the project config.
|
|
* Reads config.json directly via fs. Returns false by default
|
|
* (when no config, no intel key, or on error).
|
|
*/
|
|
function isIntelEnabled(planningDir: string): boolean {
|
|
try {
|
|
const configPath = path.join(planningDir, 'config.json');
|
|
const raw = platformReadSync(configPath);
|
|
if (raw === null) return false;
|
|
const config: unknown = JSON.parse(raw);
|
|
if (
|
|
config &&
|
|
typeof config === 'object' &&
|
|
'intel' in config &&
|
|
config.intel &&
|
|
typeof config.intel === 'object' &&
|
|
'enabled' in config.intel &&
|
|
(config.intel as Record<string, unknown>).enabled === true
|
|
) return true;
|
|
return false;
|
|
} catch (_e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
interface DisabledResponse {
|
|
disabled: true;
|
|
message: string;
|
|
}
|
|
|
|
/**
|
|
* Return the standard disabled response object.
|
|
*/
|
|
function disabledResponse(): DisabledResponse {
|
|
return { disabled: true, message: 'Intel system disabled. Set intel.enabled=true in config.json to activate.' };
|
|
}
|
|
|
|
/**
|
|
* Resolve full path to an intel file.
|
|
*/
|
|
function intelFilePath(planningDir: string, filename: string): string {
|
|
return path.join(planningDir, 'intel', filename);
|
|
}
|
|
|
|
interface IntelData {
|
|
_meta?: {
|
|
updated_at?: string;
|
|
version?: number;
|
|
[key: string]: unknown;
|
|
};
|
|
entries?: Record<string, unknown>;
|
|
[key: string]: unknown;
|
|
}
|
|
|
|
/**
|
|
* Safely read and parse a JSON intel file.
|
|
* Returns null if file doesn't exist or can't be parsed.
|
|
*/
|
|
function safeReadJson(filePath: string): IntelData | null {
|
|
try {
|
|
const raw = platformReadSync(filePath);
|
|
if (raw === null) return null;
|
|
return JSON.parse(raw) as IntelData;
|
|
} catch (_e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Compute SHA-256 hash of a file's contents.
|
|
* Returns null if the file doesn't exist.
|
|
*/
|
|
function hashFile(filePath: string): string | null {
|
|
try {
|
|
const content = platformReadSync(filePath);
|
|
if (content === null) return null;
|
|
return crypto.createHash('sha256').update(content).digest('hex');
|
|
} catch (_e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
interface SearchMatch {
|
|
key: string;
|
|
value: unknown;
|
|
}
|
|
|
|
/**
|
|
* Search for a term (case-insensitive) in a JSON object's keys and string values.
|
|
* Returns an array of matching entries.
|
|
*/
|
|
function searchJsonEntries(data: IntelData, term: string): SearchMatch[] {
|
|
if (!data || typeof data !== 'object') return [];
|
|
|
|
const entries = data.entries || data;
|
|
if (!entries || typeof entries !== 'object') return [];
|
|
|
|
const lowerTerm = term.toLowerCase();
|
|
const matches: SearchMatch[] = [];
|
|
|
|
for (const [key, value] of Object.entries(entries)) {
|
|
if (key === '_meta') continue;
|
|
|
|
// Check key match
|
|
if (key.toLowerCase().includes(lowerTerm)) {
|
|
matches.push({ key, value });
|
|
continue;
|
|
}
|
|
|
|
// Check string value match (recursive for objects)
|
|
if (matchesInValue(value, lowerTerm)) {
|
|
matches.push({ key, value });
|
|
}
|
|
}
|
|
|
|
return matches;
|
|
}
|
|
|
|
/**
|
|
* Recursively check if a term appears in any string value.
|
|
*/
|
|
function matchesInValue(value: unknown, lowerTerm: string): boolean {
|
|
if (typeof value === 'string') {
|
|
return value.toLowerCase().includes(lowerTerm);
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return value.some(v => matchesInValue(v, lowerTerm));
|
|
}
|
|
if (value && typeof value === 'object') {
|
|
return Object.values(value).some(v => matchesInValue(v, lowerTerm));
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Search for a term in arch.md text content.
|
|
* Returns matching lines.
|
|
*/
|
|
function searchArchMd(filePath: string, term: string): string[] {
|
|
try {
|
|
const content = platformReadSync(filePath);
|
|
if (content === null) return [];
|
|
const lowerTerm = term.toLowerCase();
|
|
const lines = content.split(/\r?\n/);
|
|
return lines.filter(line => line.toLowerCase().includes(lowerTerm));
|
|
} catch (_e) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
// ─── Public API ──────────────────────────────────────────────────────────────
|
|
|
|
interface IntelQueryResult {
|
|
matches: Array<{ source: string; entries: SearchMatch[] }>;
|
|
term: string;
|
|
total: number;
|
|
}
|
|
|
|
/**
|
|
* Query intel files for a search term.
|
|
* Searches across all JSON intel files (keys and values) and arch.md (text lines).
|
|
*/
|
|
function intelQuery(term: string, planningDir: string): IntelQueryResult | DisabledResponse {
|
|
if (!isIntelEnabled(planningDir)) return disabledResponse();
|
|
|
|
const matches: Array<{ source: string; entries: SearchMatch[] }> = [];
|
|
let total = 0;
|
|
|
|
// Search all JSON intel files
|
|
for (const [_key, filename] of Object.entries(INTEL_FILES)) {
|
|
const filePath = intelFilePath(planningDir, filename);
|
|
const data = safeReadJson(filePath);
|
|
if (!data) continue;
|
|
|
|
const found = searchJsonEntries(data, term);
|
|
if (found.length > 0) {
|
|
matches.push({ source: filename, entries: found });
|
|
total += found.length;
|
|
}
|
|
}
|
|
|
|
return { matches, term, total };
|
|
}
|
|
|
|
interface IntelStatusFileEntry {
|
|
exists: boolean;
|
|
updated_at: string | null;
|
|
stale: boolean;
|
|
}
|
|
|
|
interface IntelStatusResult {
|
|
files: Record<string, IntelStatusFileEntry>;
|
|
overall_stale: boolean;
|
|
}
|
|
|
|
/**
|
|
* Report status and staleness of each intel file.
|
|
* A file is considered stale if its updated_at is older than 24 hours.
|
|
*/
|
|
function intelStatus(planningDir: string): IntelStatusResult | DisabledResponse {
|
|
if (!isIntelEnabled(planningDir)) return disabledResponse();
|
|
|
|
const STALE_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
const now = Date.now();
|
|
const files: Record<string, IntelStatusFileEntry> = {};
|
|
let overallStale = false;
|
|
|
|
for (const [_key, filename] of Object.entries(INTEL_FILES)) {
|
|
const filePath = intelFilePath(planningDir, filename);
|
|
const exists = fs.existsSync(filePath);
|
|
|
|
if (!exists) {
|
|
files[filename] = { exists: false, updated_at: null, stale: true };
|
|
overallStale = true;
|
|
continue;
|
|
}
|
|
|
|
let updatedAt: string | null = null;
|
|
|
|
// All intel files are JSON — read _meta.updated_at
|
|
const data = safeReadJson(filePath);
|
|
if (data && data._meta && data._meta.updated_at) {
|
|
updatedAt = data._meta.updated_at;
|
|
}
|
|
|
|
let stale = true;
|
|
if (updatedAt) {
|
|
const age = now - new Date(updatedAt).getTime();
|
|
stale = age > STALE_MS;
|
|
}
|
|
|
|
if (stale) overallStale = true;
|
|
files[filename] = { exists: true, updated_at: updatedAt, stale };
|
|
}
|
|
|
|
return { files, overall_stale: overallStale };
|
|
}
|
|
|
|
interface IntelDiffResult {
|
|
changed: string[];
|
|
added: string[];
|
|
removed: string[];
|
|
}
|
|
|
|
/**
|
|
* Show changes since the last full refresh by comparing file hashes.
|
|
*/
|
|
function intelDiff(planningDir: string): IntelDiffResult | { no_baseline: true } | DisabledResponse {
|
|
if (!isIntelEnabled(planningDir)) return disabledResponse();
|
|
|
|
const snapshotPath = intelFilePath(planningDir, '.last-refresh.json');
|
|
const snapshot = safeReadJson(snapshotPath);
|
|
|
|
if (!snapshot) {
|
|
return { no_baseline: true };
|
|
}
|
|
|
|
const prevHashes = (snapshot.hashes as Record<string, string> | undefined) || {};
|
|
const changed: string[] = [];
|
|
const added: string[] = [];
|
|
const removed: string[] = [];
|
|
|
|
// Check current files against snapshot
|
|
for (const [_key, filename] of Object.entries(INTEL_FILES)) {
|
|
const filePath = intelFilePath(planningDir, filename);
|
|
const currentHash = hashFile(filePath);
|
|
|
|
if (currentHash && !prevHashes[filename]) {
|
|
added.push(filename);
|
|
} else if (currentHash && prevHashes[filename] && currentHash !== prevHashes[filename]) {
|
|
changed.push(filename);
|
|
} else if (!currentHash && prevHashes[filename]) {
|
|
removed.push(filename);
|
|
}
|
|
}
|
|
|
|
return { changed, added, removed };
|
|
}
|
|
|
|
/**
|
|
* Stub for triggering an intel update.
|
|
* The actual update is performed by the intel-updater agent (PLAN-02).
|
|
*/
|
|
function intelUpdate(planningDir: string): { action: string; message: string } | DisabledResponse {
|
|
if (!isIntelEnabled(planningDir)) return disabledResponse();
|
|
|
|
return {
|
|
action: 'spawn_agent',
|
|
message: 'Run gsd-tools intel update or spawn gsd-intel-updater agent for full refresh',
|
|
};
|
|
}
|
|
|
|
interface SaveRefreshResult {
|
|
saved: boolean;
|
|
timestamp: string;
|
|
files: number;
|
|
}
|
|
|
|
/**
|
|
* Save a refresh snapshot with hashes of all current intel files.
|
|
* Called by the intel-updater agent after completing a refresh.
|
|
*/
|
|
function saveRefreshSnapshot(planningDir: string): SaveRefreshResult {
|
|
const intelPath = ensureIntelDir(planningDir);
|
|
const hashes: Record<string, string> = {};
|
|
let fileCount = 0;
|
|
|
|
for (const [_key, filename] of Object.entries(INTEL_FILES)) {
|
|
const filePath = path.join(intelPath, filename);
|
|
const hash = hashFile(filePath);
|
|
if (hash) {
|
|
hashes[filename] = hash;
|
|
fileCount++;
|
|
}
|
|
}
|
|
|
|
const timestamp = new Date().toISOString();
|
|
const snapshotPath = path.join(intelPath, '.last-refresh.json');
|
|
platformWriteSync(snapshotPath, JSON.stringify({
|
|
hashes,
|
|
timestamp,
|
|
version: 1,
|
|
}, null, 2));
|
|
|
|
return { saved: true, timestamp, files: fileCount };
|
|
}
|
|
|
|
// ─── CLI Subcommands ─────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Thin wrapper around saveRefreshSnapshot for CLI dispatch.
|
|
* Writes .last-refresh.json with accurate timestamps and hashes.
|
|
*/
|
|
function intelSnapshot(planningDir: string): SaveRefreshResult | DisabledResponse {
|
|
if (!isIntelEnabled(planningDir)) return disabledResponse();
|
|
return saveRefreshSnapshot(planningDir);
|
|
}
|
|
|
|
interface IntelValidateResult {
|
|
valid: boolean;
|
|
errors: string[];
|
|
warnings: string[];
|
|
}
|
|
|
|
/**
|
|
* Validate all intel files for correctness and freshness.
|
|
*/
|
|
function intelValidate(planningDir: string): IntelValidateResult | DisabledResponse {
|
|
if (!isIntelEnabled(planningDir)) return disabledResponse();
|
|
|
|
const errors: string[] = [];
|
|
const warnings: string[] = [];
|
|
const STALE_MS = 24 * 60 * 60 * 1000;
|
|
const now = Date.now();
|
|
|
|
for (const [key, filename] of Object.entries(INTEL_FILES)) {
|
|
const filePath = intelFilePath(planningDir, filename);
|
|
|
|
// Check existence
|
|
if (!fs.existsSync(filePath)) {
|
|
errors.push(`${filename}: file does not exist`);
|
|
continue;
|
|
}
|
|
|
|
// All intel files are JSON — validate _meta and entries structure
|
|
|
|
// Parse JSON
|
|
const raw = platformReadSync(filePath);
|
|
if (raw === null) {
|
|
errors.push(`${filename}: file missing`);
|
|
continue;
|
|
}
|
|
let data: IntelData;
|
|
try {
|
|
data = JSON.parse(raw) as IntelData;
|
|
} catch (e) {
|
|
errors.push(`${filename}: invalid JSON — ${(e as Error).message}`);
|
|
continue;
|
|
}
|
|
|
|
// Check _meta.updated_at recency
|
|
if (data._meta && data._meta.updated_at) {
|
|
const age = now - new Date(data._meta.updated_at).getTime();
|
|
if (age > STALE_MS) {
|
|
warnings.push(`${filename}: _meta.updated_at is ${Math.round(age / 3600000)} hours old (>24 hr)`);
|
|
}
|
|
} else {
|
|
warnings.push(`${filename}: missing _meta.updated_at`);
|
|
}
|
|
|
|
// Validate entries are objects with expected fields
|
|
if (data.entries && typeof data.entries === 'object') {
|
|
// files.json: check exports are actual symbol names (no spaces)
|
|
if (key === 'files') {
|
|
for (const [entryPath, entry] of Object.entries(data.entries)) {
|
|
const entryObj = entry as Record<string, unknown>;
|
|
if (entryObj.exports && Array.isArray(entryObj.exports)) {
|
|
for (const exp of entryObj.exports as unknown[]) {
|
|
if (typeof exp === 'string' && exp.includes(' ')) {
|
|
warnings.push(`${filename}: "${entryPath}" export "${exp}" looks like a description (contains space)`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Spot-check first 5 file paths exist on disk
|
|
const entryPaths = Object.keys(data.entries).slice(0, 5);
|
|
for (const ep of entryPaths) {
|
|
if (!fs.existsSync(ep)) {
|
|
warnings.push(`${filename}: entry path "${ep}" does not exist on disk`);
|
|
}
|
|
}
|
|
}
|
|
|
|
// deps.json: check entries have version, type, used_by
|
|
if (key === 'deps') {
|
|
for (const [depName, entry] of Object.entries(data.entries)) {
|
|
const entryObj = entry as Record<string, unknown>;
|
|
const missing: string[] = [];
|
|
if (!entryObj.version) missing.push('version');
|
|
if (!entryObj.type) missing.push('type');
|
|
if (!entryObj.used_by) missing.push('used_by');
|
|
if (missing.length > 0) {
|
|
warnings.push(`${filename}: "${depName}" missing fields: ${missing.join(', ')}`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return { valid: errors.length === 0, errors, warnings };
|
|
}
|
|
|
|
interface IntelApiSurfaceResult {
|
|
written: string;
|
|
symbolCount: number;
|
|
stale: boolean;
|
|
}
|
|
|
|
/**
|
|
* Render .planning/intel/api-map.json into a human-readable API-SURFACE.md.
|
|
* Always writes the file — even when api-map.json is absent or empty, the
|
|
* surface will contain an explicit "incomplete" banner so consumers never
|
|
* mistake silence for "nothing exists".
|
|
*/
|
|
function intelApiSurface(planningDir: string): IntelApiSurfaceResult | DisabledResponse {
|
|
if (!isIntelEnabled(planningDir)) return disabledResponse();
|
|
|
|
const intelPath = ensureIntelDir(planningDir);
|
|
const apiMapPath = path.join(intelPath, INTEL_FILES.apis);
|
|
const outputPath = path.join(intelPath, 'API-SURFACE.md');
|
|
|
|
const data = safeReadJson(apiMapPath);
|
|
const entries = (data && data.entries && typeof data.entries === 'object')
|
|
? Object.entries(data.entries)
|
|
: [];
|
|
const symbolCount = entries.length;
|
|
|
|
// Staleness: reuse the _meta.updated_at field if present
|
|
const STALE_MS = 24 * 60 * 60 * 1000;
|
|
let stale = true;
|
|
if (data && data._meta && data._meta.updated_at) {
|
|
const age = Date.now() - new Date(data._meta.updated_at).getTime();
|
|
stale = age > STALE_MS;
|
|
}
|
|
|
|
const lines: string[] = [];
|
|
lines.push('# API Surface');
|
|
lines.push('');
|
|
lines.push('> Generated from `.planning/intel/api-map.json`. Do not edit by hand.');
|
|
lines.push('');
|
|
|
|
if (symbolCount === 0) {
|
|
lines.push('> **Incomplete:** api-map.json has no entries (intel extraction is regex/JS-only or not yet populated).');
|
|
lines.push('> Treat absence here as "unknown", not "does not exist".');
|
|
lines.push('');
|
|
} else {
|
|
if (stale) {
|
|
lines.push('> **Warning:** api-map.json is stale (>24 hours old). Data below may be out of date.');
|
|
lines.push('');
|
|
}
|
|
|
|
for (const [symbol, info] of entries) {
|
|
lines.push(`## \`${symbol}\``);
|
|
lines.push('');
|
|
if (info && typeof info === 'object') {
|
|
for (const [field, val] of Object.entries(info as Record<string, unknown>)) {
|
|
const display = Array.isArray(val) ? val.join(', ') : String(val);
|
|
lines.push(`- **${field}:** ${display}`);
|
|
}
|
|
}
|
|
lines.push('');
|
|
}
|
|
}
|
|
|
|
platformWriteSync(outputPath, lines.join('\n'));
|
|
|
|
return { written: outputPath, symbolCount, stale };
|
|
}
|
|
|
|
interface IntelPatchMetaResult {
|
|
patched: boolean;
|
|
file?: string;
|
|
timestamp?: string;
|
|
error?: string;
|
|
}
|
|
|
|
/**
|
|
* Patch _meta.updated_at in a JSON intel file to the current timestamp.
|
|
* Reads the file, updates _meta.updated_at, increments version, writes back.
|
|
*
|
|
* NOTE: Does not gate on isIntelEnabled — operates on arbitrary file paths
|
|
* for use by agents patching individual files outside the intel store.
|
|
*/
|
|
function intelPatchMeta(filePath: string): IntelPatchMetaResult {
|
|
try {
|
|
const content = platformReadSync(filePath);
|
|
if (content === null) {
|
|
return { patched: false, error: `File not found: ${filePath}` };
|
|
}
|
|
let data: IntelData;
|
|
try {
|
|
data = JSON.parse(content) as IntelData;
|
|
} catch (e) {
|
|
return { patched: false, error: `Invalid JSON: ${(e as Error).message}` };
|
|
}
|
|
|
|
if (!data._meta) {
|
|
data._meta = {};
|
|
}
|
|
|
|
const timestamp = new Date().toISOString();
|
|
data._meta.updated_at = timestamp;
|
|
data._meta.version = (data._meta.version || 0) + 1;
|
|
|
|
platformWriteSync(filePath, JSON.stringify(data, null, 2) + '\n');
|
|
|
|
return { patched: true, file: filePath, timestamp };
|
|
} catch (e) {
|
|
return { patched: false, error: (e as Error).message };
|
|
}
|
|
}
|
|
|
|
interface IntelExtractExportsResult {
|
|
file: string;
|
|
exports: string[];
|
|
method: string;
|
|
}
|
|
|
|
/**
|
|
* Extract exports from a JS/CJS file by parsing module.exports or exports.X patterns.
|
|
*
|
|
* NOTE: Does not gate on isIntelEnabled — operates on arbitrary source files
|
|
* for use by agents building intel data from project files.
|
|
*/
|
|
function intelExtractExports(filePath: string): IntelExtractExportsResult {
|
|
const content = platformReadSync(filePath);
|
|
if (content === null) {
|
|
return { file: filePath, exports: [], method: 'none' };
|
|
}
|
|
const exports = new Set<string>();
|
|
let method = 'none';
|
|
|
|
// Try module.exports = { ... } pattern (handle multi-line)
|
|
// Find the LAST module.exports assignment (the actual one, not references in code)
|
|
const allMatches = [...content.matchAll(/module\.exports\s*=\s*\{/g)];
|
|
if (allMatches.length > 0) {
|
|
const lastMatch = allMatches[allMatches.length - 1];
|
|
const startIdx = lastMatch.index + lastMatch[0].length;
|
|
// Find matching closing brace by counting braces
|
|
let depth = 1;
|
|
let endIdx = startIdx;
|
|
while (endIdx < content.length && depth > 0) {
|
|
if (content[endIdx] === '{') depth++;
|
|
else if (content[endIdx] === '}') depth--;
|
|
if (depth > 0) endIdx++;
|
|
}
|
|
const block = content.substring(startIdx, endIdx);
|
|
method = 'module.exports';
|
|
// Extract key names from lines like " keyName," or " keyName: value,"
|
|
const lines = block.split('\n');
|
|
for (const line of lines) {
|
|
const trimmed = line.trim();
|
|
// Skip comments and empty lines
|
|
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('*')) continue;
|
|
// Match identifier at start of line (before comma, colon, end of line)
|
|
const keyMatch = trimmed.match(/^(\w+)\s*[,}:]/) || trimmed.match(/^(\w+)$/);
|
|
if (keyMatch) {
|
|
exports.add(keyMatch[1]);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Also try individual exports.X = patterns (only at start of line, not inside strings/regex)
|
|
const individualPattern = /^exports\.(\w+)\s*=/gm;
|
|
let im: RegExpExecArray | null;
|
|
while ((im = individualPattern.exec(content)) !== null) {
|
|
if (!exports.has(im[1])) {
|
|
exports.add(im[1]);
|
|
if (method === 'none') method = 'exports.X';
|
|
}
|
|
}
|
|
|
|
const hadCjs = exports.size > 0;
|
|
|
|
// ESM patterns
|
|
const esmExports = new Set<string>();
|
|
|
|
// export default function X / export default class X
|
|
const defaultNamedPattern = /^export\s+default\s+(?:function|class)\s+(\w+)/gm;
|
|
let em: RegExpExecArray | null;
|
|
while ((em = defaultNamedPattern.exec(content)) !== null) {
|
|
esmExports.add(em[1]);
|
|
}
|
|
|
|
// export default (without named function/class)
|
|
const defaultAnonPattern = /^export\s+default\s+(?!function\s|class\s)/gm;
|
|
if (defaultAnonPattern.test(content) && esmExports.size === 0) {
|
|
esmExports.add('default');
|
|
}
|
|
|
|
// export function X( / export async function X(
|
|
const exportFnPattern = /^export\s+(?:async\s+)?function\s+(\w+)\s*\(/gm;
|
|
while ((em = exportFnPattern.exec(content)) !== null) {
|
|
esmExports.add(em[1]);
|
|
}
|
|
|
|
// export const X = / export let X = / export var X =
|
|
const exportVarPattern = /^export\s+(?:const|let|var)\s+(\w+)\s*=/gm;
|
|
while ((em = exportVarPattern.exec(content)) !== null) {
|
|
esmExports.add(em[1]);
|
|
}
|
|
|
|
// export class X
|
|
const exportClassPattern = /^export\s+class\s+(\w+)/gm;
|
|
while ((em = exportClassPattern.exec(content)) !== null) {
|
|
esmExports.add(em[1]);
|
|
}
|
|
|
|
// export { X, Y, Z } — strip "as alias" parts
|
|
const exportBlockPattern = /^export\s*\{([^}]+)\}/gm;
|
|
while ((em = exportBlockPattern.exec(content)) !== null) {
|
|
const items = em[1].split(',');
|
|
for (const item of items) {
|
|
const trimmed = item.trim();
|
|
if (!trimmed) continue;
|
|
// "foo as bar" -> extract "foo"
|
|
const name = trimmed.split(/\s+as\s+/)[0].trim();
|
|
if (name) esmExports.add(name);
|
|
}
|
|
}
|
|
|
|
// Merge ESM exports into the result
|
|
for (const e of esmExports) {
|
|
exports.add(e);
|
|
}
|
|
|
|
// Determine method
|
|
const hadEsm = esmExports.size > 0;
|
|
if (hadCjs && hadEsm) {
|
|
method = 'mixed';
|
|
} else if (hadEsm && !hadCjs) {
|
|
method = 'esm';
|
|
}
|
|
|
|
return { file: filePath, exports: [...exports], method };
|
|
}
|
|
|
|
// ─── Exports ─────────────────────────────────────────────────────────────────
|
|
|
|
export = {
|
|
// Public API
|
|
intelQuery,
|
|
intelUpdate,
|
|
intelStatus,
|
|
intelDiff,
|
|
saveRefreshSnapshot,
|
|
|
|
// CLI subcommands
|
|
intelSnapshot,
|
|
intelValidate,
|
|
intelExtractExports,
|
|
intelPatchMeta,
|
|
intelApiSurface,
|
|
|
|
// Utilities
|
|
ensureIntelDir,
|
|
isIntelEnabled,
|
|
|
|
// Constants
|
|
INTEL_FILES,
|
|
INTEL_DIR,
|
|
};
|