rungate 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Spec-change conformity — detects spec file modifications and runs conformity checks.
3
+ *
4
+ * Thin lib module called by hooks/SpecConformityTrigger.hook.ts.
5
+ * Delegates to sync-sc-status functions for SC scanning, checking, and checkbox flipping.
6
+ *
7
+ * Issue: #581
8
+ */
9
+
10
+ import {
11
+ findUncheckedSCs,
12
+ checkConformitySCs,
13
+ flipCheckboxes,
14
+ scopedKey,
15
+ } from "../scripts/sync-sc-status";
16
+
17
+ export interface SpecChangeConformityResult {
18
+ triggered: boolean;
19
+ flippedCount: number;
20
+ passing: string[];
21
+ failing: string[];
22
+ }
23
+
24
+ /**
25
+ * Check if a file path points to a spec file (specs/*.md, not nested).
26
+ */
27
+ export function isSpecFile(filePath: string): boolean {
28
+ return /(?:^|\/|\\)specs\/[^/\\]+\.md$/.test(filePath);
29
+ }
30
+
31
+ /**
32
+ * Run conformity checks against all unchecked SCs and flip passing checkboxes.
33
+ */
34
+ export function runSpecChangeConformity(projectRoot: string): SpecChangeConformityResult {
35
+ const specsDir = `${projectRoot}/specs`;
36
+ const unchecked = findUncheckedSCs(specsDir);
37
+
38
+ if (unchecked.length === 0) {
39
+ return { triggered: true, flippedCount: 0, passing: [], failing: [] };
40
+ }
41
+
42
+ const result = checkConformitySCs(unchecked, projectRoot);
43
+
44
+ // Group passing SCs by spec file for checkbox flipping
45
+ let totalFlipped = 0;
46
+ const passingIds: string[] = [];
47
+ const failingIds: string[] = [];
48
+
49
+ const bySpec = new Map<string, string[]>();
50
+ for (const key of result.passing) {
51
+ // Keys are "specFile::SC-NNN" — extract parts
52
+ const sepIdx = key.indexOf("::");
53
+ if (sepIdx === -1) continue;
54
+ const specFile = key.slice(0, sepIdx);
55
+ const scId = key.slice(sepIdx + 2);
56
+ const ids = bySpec.get(specFile) || [];
57
+ ids.push(scId);
58
+ bySpec.set(specFile, ids);
59
+ passingIds.push(scId);
60
+ }
61
+
62
+ for (const key of result.failing) {
63
+ const sepIdx = key.indexOf("::");
64
+ if (sepIdx === -1) continue;
65
+ const scId = key.slice(sepIdx + 2);
66
+ failingIds.push(scId);
67
+ }
68
+
69
+ // Flip checkboxes for passing SCs
70
+ for (const [specFile, scIds] of bySpec) {
71
+ totalFlipped += flipCheckboxes(specFile, scIds, specsDir);
72
+ }
73
+
74
+ return {
75
+ triggered: true,
76
+ flippedCount: totalFlipped,
77
+ passing: passingIds,
78
+ failing: failingIds,
79
+ };
80
+ }
@@ -0,0 +1,62 @@
1
+ import { existsSync, readdirSync } from "fs";
2
+ import { join } from "path";
3
+
4
+ /**
5
+ * The one way to ask which spec files exist (#225).
6
+ *
7
+ * `specs/` has subdirectories — `specs/bootstrap-data-flow/` holds six specs
8
+ * and 254 SCs — and until this existed, eight callers each decided for
9
+ * themselves whether to descend. Seven did not:
10
+ *
11
+ * lib/conformity.ts:354 the specMap SC conformity runs on
12
+ * lib/conformity.ts:1056 SPEC-FRONTMATTER
13
+ * lib/conformity.ts:1068 SPEC-DISCOVERY-TESTABLE
14
+ * lib/conformity.ts:1139 DRIFT-2
15
+ * lib/gap-scanner.ts:235
16
+ * scripts/sync-spec-tests.ts:98
17
+ * scripts/sync-spec-tests.ts:309
18
+ *
19
+ * All seven were the same line — `readdirSync(specsDir).filter(f =>
20
+ * f.endsWith(".md"))` — and the eighth, `lib/conformity.ts:558`, hand-rolled
21
+ * a one-level descent inline.
22
+ *
23
+ * DRIFT-2 is why this is a shared function and not seven edits. Its stated job
24
+ * is "every testable spec is referenced by at least one test", and because it
25
+ * collected flat it had never looked at five specs that no test references,
26
+ * while reporting 20 pass / 0 fail. A detector narrower than what it detects,
27
+ * guarding the one thing it cannot see
28
+ * (.claude/rules/checks-must-be-able-to-fail.md). Seven separate fixes would
29
+ * leave the eighth caller free to reintroduce it; one function means the next
30
+ * caller cannot get it wrong without going out of its way.
31
+ *
32
+ * Returns paths relative to `specsDir`, so `join(specsDir, p)` reads the file
33
+ * and `specs/${p}` names it in a finding — the shape every caller already
34
+ * used for the flat case.
35
+ */
36
+ export function collectSpecFiles(specsDir: string): string[] {
37
+ if (!existsSync(specsDir)) return [];
38
+ const out: string[] = [];
39
+ const walk = (dir: string, prefix: string) => {
40
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
41
+ if (entry.isDirectory()) {
42
+ walk(join(dir, entry.name), prefix ? `${prefix}/${entry.name}` : entry.name);
43
+ continue;
44
+ }
45
+ if (!entry.name.endsWith(".md")) continue;
46
+ // INDEX.md is a split spec's table of contents and carries no
47
+ // frontmatter, so collecting it would make SPEC-FRONTMATTER fail on a
48
+ // file that is correct as it is. `lib/conformity.ts:562` already
49
+ // excluded it for that reason; this is that exclusion, kept.
50
+ //
51
+ // SPEC-TEMPLATE.md is deliberately NOT excluded. It is `testable:
52
+ // false`, so every testable-spec check already filters it out, and the
53
+ // flat collectors did include it — dropping it here would quietly
54
+ // narrow SPEC-FRONTMATTER's coverage, which is the opposite of what
55
+ // this change is for.
56
+ if (entry.name === "INDEX.md") continue;
57
+ out.push(prefix ? `${prefix}/${entry.name}` : entry.name);
58
+ }
59
+ };
60
+ walk(specsDir, "");
61
+ return out.sort();
62
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Spec Registry — governs-field discovery for spec files.
3
+ *
4
+ * SC-505: exports [getGoverningSpecs, getGovernedFiles, getUngoverned]
5
+ * SC-506: contains [governs, frontmatter, specs/, invertedIndex]
6
+ *
7
+ * Three consumers already parse governs-field independently (scanner.ts,
8
+ * conformity.ts, spec-validators.ts). This module centralizes the contract
9
+ * so doc-hygiene, scaffold, and gate enforcement share one source of truth.
10
+ *
11
+ * Issue: #24
12
+ */
13
+
14
+ import { existsSync, readFileSync, readdirSync } from 'fs';
15
+ import { join } from 'path';
16
+
17
+ export interface SpecEntry {
18
+ /** Filename relative to specs/ (e.g. "GATE-CONTRACTS-SPEC.md" or "sub/SUB-SPEC.md") */
19
+ file: string;
20
+ /** Parsed governs field from frontmatter */
21
+ governs: string;
22
+ /** Full path to the spec file */
23
+ path: string;
24
+ }
25
+
26
+ /**
27
+ * Parse frontmatter from a markdown file's content.
28
+ * Returns key-value pairs from YAML-style frontmatter block.
29
+ */
30
+ function parseFrontmatter(content: string): Record<string, string> | null {
31
+ const match = content.match(/^---\n([\s\S]*?)\n---/);
32
+ if (!match) return null;
33
+ const fields: Record<string, string> = {};
34
+ for (const line of match[1].split('\n')) {
35
+ const kv = line.match(/^(\w[\w-]*):\s*(.+)$/);
36
+ if (kv) fields[kv[1]] = kv[2].trim();
37
+ }
38
+ return fields;
39
+ }
40
+
41
+ /**
42
+ * Check if a governs field value is valid (non-empty, not TODO).
43
+ */
44
+ function isValidGoverns(governs: string | undefined): governs is string {
45
+ if (!governs) return false;
46
+ const trimmed = governs.trim();
47
+ return trimmed.length > 0 && !trimmed.includes('TODO');
48
+ }
49
+
50
+ /**
51
+ * Scan a single directory for spec files and extract governs frontmatter.
52
+ */
53
+ function scanSpecDir(dir: string, prefix: string = ''): { governed: SpecEntry[]; ungoverned: string[] } {
54
+ const governed: SpecEntry[] = [];
55
+ const ungoverned: string[] = [];
56
+
57
+ if (!existsSync(dir)) return { governed, ungoverned };
58
+
59
+ const entries = readdirSync(dir, { withFileTypes: true });
60
+
61
+ for (const entry of entries) {
62
+ if (entry.isDirectory()) {
63
+ // Recurse into subdirectories
64
+ const subResult = scanSpecDir(join(dir, entry.name), prefix ? `${prefix}/${entry.name}` : entry.name);
65
+ governed.push(...subResult.governed);
66
+ ungoverned.push(...subResult.ungoverned);
67
+ continue;
68
+ }
69
+
70
+ if (!entry.name.endsWith('.md')) continue;
71
+ if (entry.name === 'SPEC-TEMPLATE.md') continue;
72
+ if (entry.name === 'INDEX.md') continue;
73
+
74
+ const filePath = join(dir, entry.name);
75
+ const content = readFileSync(filePath, 'utf-8');
76
+ const fm = parseFrontmatter(content);
77
+ const relFile = prefix ? `${prefix}/${entry.name}` : entry.name;
78
+
79
+ if (fm && isValidGoverns(fm.governs)) {
80
+ governed.push({
81
+ file: relFile,
82
+ governs: fm.governs,
83
+ path: filePath,
84
+ });
85
+ } else {
86
+ ungoverned.push(relFile);
87
+ }
88
+ }
89
+
90
+ return { governed, ungoverned };
91
+ }
92
+
93
+ /**
94
+ * Get all specs that have a valid governs field in their frontmatter.
95
+ *
96
+ * Scans specs/ directory (and subdirectories) under the given root.
97
+ * Returns an array of SpecEntry objects with file, governs, and path.
98
+ */
99
+ export function getGoverningSpecs(root: string): SpecEntry[] {
100
+ const specsDir = join(root, 'specs');
101
+ return scanSpecDir(specsDir).governed;
102
+ }
103
+
104
+ /**
105
+ * Build an invertedIndex mapping governs text to spec file names.
106
+ *
107
+ * Used by doc-hygiene to look up which spec governs a given area.
108
+ * Each governs value maps to an array of spec filenames that claim it.
109
+ */
110
+ export function getGovernedFiles(root: string): Record<string, string[]> {
111
+ const specs = getGoverningSpecs(root);
112
+ const invertedIndex: Record<string, string[]> = {};
113
+
114
+ for (const spec of specs) {
115
+ if (!invertedIndex[spec.governs]) {
116
+ invertedIndex[spec.governs] = [];
117
+ }
118
+ invertedIndex[spec.governs].push(spec.file);
119
+ }
120
+
121
+ return invertedIndex;
122
+ }
123
+
124
+ /**
125
+ * Get spec files that lack a valid governs field.
126
+ *
127
+ * Returns filenames (relative to specs/) that have no governs
128
+ * or have TODO as their governs value.
129
+ */
130
+ export function getUngoverned(root: string): string[] {
131
+ const specsDir = join(root, 'specs');
132
+ return scanSpecDir(specsDir).ungoverned;
133
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * spec-updater — patches governing spec decision tables on PROVEN verdict.
3
+ * Reads governingSpec.path from GoalRecord, finds D-NNN rows,
4
+ * replaces ACCEPTED status with SHIPPED + issue number.
5
+ * Project-agnostic: never hardcodes any specific spec filename.
6
+ */
7
+ import { readFileSync, writeFileSync, existsSync } from "fs";
8
+
9
+ export interface SpecUpdateInput {
10
+ goalRecord: {
11
+ governingSpec?: { path: string; detectedFrom?: string };
12
+ };
13
+ issueNumber: number;
14
+ decisionIds: string[];
15
+ }
16
+
17
+ export interface SpecUpdateResult {
18
+ updated: boolean;
19
+ skipped: boolean;
20
+ specPath?: string;
21
+ rowsUpdated: number;
22
+ reason?: string;
23
+ }
24
+
25
+ /**
26
+ * Extract D-NNN decision IDs from arbitrary text (issue body, GoalRecord fields, etc.)
27
+ */
28
+ export function extractDecisionIds(text: string): string[] {
29
+ const matches = text.match(/D-\d{3}/g);
30
+ if (!matches) return [];
31
+ return [...new Set(matches)];
32
+ }
33
+
34
+ /**
35
+ * Update the governing spec's decision table rows from ACCEPTED to SHIPPED.
36
+ * Skips gracefully when governingSpec is absent, path is empty, or file not found.
37
+ */
38
+ export async function updateSpecStatus(input: SpecUpdateInput): Promise<SpecUpdateResult> {
39
+ const { goalRecord, issueNumber, decisionIds } = input;
40
+
41
+ // Guard: no governing spec
42
+ if (!goalRecord.governingSpec?.path) {
43
+ return { updated: false, skipped: true, rowsUpdated: 0, reason: "no governing spec in GoalRecord" };
44
+ }
45
+
46
+ const specPath = goalRecord.governingSpec.path;
47
+
48
+ // Guard: empty path
49
+ if (!specPath.trim()) {
50
+ return { updated: false, skipped: true, specPath, rowsUpdated: 0, reason: "governing spec path is empty" };
51
+ }
52
+
53
+ // Guard: file not found
54
+ if (!existsSync(specPath)) {
55
+ return { updated: false, skipped: true, specPath, rowsUpdated: 0, reason: `spec file not found at ${specPath}` };
56
+ }
57
+
58
+ // Guard: no decision IDs to update
59
+ if (!decisionIds.length) {
60
+ return { updated: false, skipped: true, specPath, rowsUpdated: 0, reason: "no decision IDs to update" };
61
+ }
62
+
63
+ let content = readFileSync(specPath, "utf-8");
64
+ let rowsUpdated = 0;
65
+
66
+ for (const dId of decisionIds) {
67
+ // Match a table row containing the decision ID and an ACCEPTED status cell.
68
+ // Handles both 3-column (| ID | Decision | Status |) and
69
+ // 4-column (| ID | Decision | Priority | Status |) formats.
70
+ // The ACCEPTED cell may have trailing text like "(Wave 7, #386)".
71
+ const pattern = new RegExp(
72
+ `^(\\|\\s*${escapeRegExp(dId)}\\s*\\|.+\\|)\\s*ACCEPTED(?:\\s*\\([^)]*\\))?\\s*\\|`,
73
+ "m"
74
+ );
75
+
76
+ if (pattern.test(content)) {
77
+ content = content.replace(pattern, `$1 **SHIPPED** (#${issueNumber}) |`);
78
+ rowsUpdated++;
79
+ }
80
+ }
81
+
82
+ if (rowsUpdated > 0) {
83
+ writeFileSync(specPath, content);
84
+ }
85
+
86
+ return {
87
+ updated: rowsUpdated > 0,
88
+ skipped: false,
89
+ specPath,
90
+ rowsUpdated,
91
+ };
92
+ }
93
+
94
+ function escapeRegExp(str: string): string {
95
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
96
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Stale cleanup utilities — extracted from StaleTTLCleanup.hook.ts
3
+ *
4
+ * Deep module: recursive file finder and TTL cleanup logic.
5
+ * The hook file is a thin trigger that delegates here.
6
+ *
7
+ * Issue: #544, #469 (archive-then-purge)
8
+ */
9
+
10
+ import { readdirSync, readFileSync, statSync, unlinkSync, existsSync, rmdirSync, renameSync, mkdirSync } from 'fs';
11
+ import { join, dirname } from 'path';
12
+
13
+ /**
14
+ * Recursively find files by name under a directory.
15
+ */
16
+ function findFiles(dir: string, name: string): string[] {
17
+ const results: string[] = [];
18
+ try {
19
+ const entries = readdirSync(dir, { withFileTypes: true });
20
+ for (const entry of entries) {
21
+ const fullPath = join(dir, entry.name);
22
+ if (entry.isDirectory()) {
23
+ results.push(...findFiles(fullPath, name));
24
+ } else if (entry.name === name) {
25
+ results.push(fullPath);
26
+ }
27
+ }
28
+ } catch {}
29
+ return results;
30
+ }
31
+
32
+ export interface CleanupResult {
33
+ deleted: number;
34
+ logs: string[];
35
+ }
36
+
37
+ export interface ArchiveResult {
38
+ archived: number;
39
+ purged: number;
40
+ skipped: number;
41
+ logs: string[];
42
+ }
43
+
44
+ /**
45
+ * Archive and purge work directories.
46
+ *
47
+ * Archive phase: Move directories to .archive/ after archiveTtlMs (default 4h)
48
+ * Purge phase: Delete archived directories after purgeTtlMs (default 30d)
49
+ * Migration: Move old _archived-* directories into .archive/
50
+ */
51
+ export function archiveAndPurge(
52
+ workDir: string,
53
+ archiveTtlMs: number,
54
+ purgeTtlMs: number,
55
+ ): ArchiveResult {
56
+ const now = Date.now();
57
+ let archived = 0;
58
+ let purged = 0;
59
+ let skipped = 0;
60
+ const logs: string[] = [];
61
+
62
+ const archiveDir = join(workDir, '.archive');
63
+ const sevenDaysMs = 7 * 24 * 60 * 60 * 1000;
64
+
65
+ // Create .archive/ if it doesn't exist
66
+ if (!existsSync(archiveDir)) {
67
+ try {
68
+ mkdirSync(archiveDir, { recursive: true });
69
+ } catch {}
70
+ }
71
+
72
+ // Migration: Move old _archived-* directories into .archive/
73
+ try {
74
+ for (const entry of readdirSync(workDir, { withFileTypes: true })) {
75
+ if (!entry.isDirectory()) continue;
76
+ if (entry.name.startsWith('_archived-')) {
77
+ try {
78
+ const srcPath = join(workDir, entry.name);
79
+ const destPath = join(archiveDir, entry.name);
80
+ renameSync(srcPath, destPath);
81
+ logs.push(`MIGRATED ${entry.name} to .archive/`);
82
+ } catch {}
83
+ }
84
+ }
85
+ } catch {}
86
+
87
+ // Archive phase: scan top-level directories
88
+ try {
89
+ for (const entry of readdirSync(workDir, { withFileTypes: true })) {
90
+ if (!entry.isDirectory()) continue;
91
+
92
+ // Skip hidden directories (except .archive itself)
93
+ if (entry.name.startsWith('.')) continue;
94
+
95
+ const dirPath = join(workDir, entry.name);
96
+ const workflowStatePath = join(dirPath, 'workflow-state.json');
97
+
98
+ try {
99
+ let shouldArchive = false;
100
+ let reason = '';
101
+
102
+ if (existsSync(workflowStatePath)) {
103
+ const data = JSON.parse(readFileSync(workflowStatePath, 'utf-8'));
104
+ const phase = data.phase || '';
105
+ const isActivePhase = ['BUILD', 'VERIFY', 'SCOPE'].includes(phase);
106
+ const ageMs = now - statSync(workflowStatePath).mtimeMs;
107
+
108
+ if (isActivePhase && ageMs < sevenDaysMs) {
109
+ // Active work, skip
110
+ skipped++;
111
+ continue;
112
+ } else if (isActivePhase && ageMs >= sevenDaysMs) {
113
+ // Hard TTL exceeded
114
+ shouldArchive = true;
115
+ reason = `phase=${phase} age=${Math.floor(ageMs / 86400000)}d (7-day hard TTL)`;
116
+ } else if (ageMs > archiveTtlMs) {
117
+ // Non-active phase, exceeded archive TTL
118
+ shouldArchive = true;
119
+ reason = `phase=${phase} age=${Math.floor(ageMs / 60000)}m`;
120
+ }
121
+ } else {
122
+ // Orphaned directory (no workflow-state.json).
123
+ //
124
+ // Age-checked like every other branch here (#132). This used to
125
+ // archive on sight, which made "has not written workflow-state.json
126
+ // YET" indistinguishable from "never will" — so a run that writes
127
+ // any other artifact first could have its directory renamed out
128
+ // from under it while still live. That happened to a real run
129
+ // holding its own PRD, and it is why compliance grades turn up in
130
+ // .archive: a mid-run move splits one run's artifacts across two
131
+ // paths with nothing recording that they belong together.
132
+ //
133
+ // mtime of the directory, since there is no state file to read.
134
+ const ageMs = now - statSync(dirPath).mtimeMs;
135
+ if (ageMs > archiveTtlMs) {
136
+ shouldArchive = true;
137
+ reason = `orphaned (no workflow-state.json) age=${Math.floor(ageMs / 60000)}m`;
138
+ } else {
139
+ skipped++;
140
+ continue;
141
+ }
142
+ }
143
+
144
+ if (shouldArchive) {
145
+ const destPath = join(archiveDir, entry.name);
146
+ renameSync(dirPath, destPath);
147
+ archived++;
148
+ logs.push(`ARCHIVED ${entry.name} reason=${reason}`);
149
+ }
150
+ } catch {}
151
+ }
152
+ } catch {}
153
+
154
+ // Purge phase: delete old archived directories
155
+ if (existsSync(archiveDir)) {
156
+ try {
157
+ for (const entry of readdirSync(archiveDir, { withFileTypes: true })) {
158
+ if (!entry.isDirectory()) continue;
159
+
160
+ const archivedPath = join(archiveDir, entry.name);
161
+ try {
162
+ const ageMs = now - statSync(archivedPath).mtimeMs;
163
+ if (ageMs > purgeTtlMs) {
164
+ rmdirSync(archivedPath, { recursive: true });
165
+ purged++;
166
+ logs.push(`PURGED ${entry.name} age=${Math.floor(ageMs / 86400000)}d`);
167
+ }
168
+ } catch {}
169
+ }
170
+ } catch {}
171
+ }
172
+
173
+ // Clean empty directories in .archive/
174
+ if (existsSync(archiveDir)) {
175
+ try {
176
+ for (const entry of readdirSync(archiveDir, { withFileTypes: true })) {
177
+ if (!entry.isDirectory()) continue;
178
+ try {
179
+ const archEntryPath = join(archiveDir, entry.name);
180
+ if (readdirSync(archEntryPath).length === 0) {
181
+ rmdirSync(archEntryPath);
182
+ }
183
+ } catch {}
184
+ }
185
+ } catch {}
186
+ }
187
+
188
+ return { archived, purged, skipped, logs };
189
+ }
190
+
191
+ /**
192
+ * Clean stale .ship-active files and archive work directories.
193
+ * Returns count of deleted files and log messages.
194
+ */
195
+ export function cleanStaleFiles(
196
+ workDir: string,
197
+ fourHoursMs: number,
198
+ sevenDaysMs: number,
199
+ ): CleanupResult {
200
+ const now = Date.now();
201
+ let deleted = 0;
202
+ const logs: string[] = [];
203
+
204
+ // Clean .ship-active > 4h old
205
+ for (const f of findFiles(workDir, '.ship-active')) {
206
+ try {
207
+ const ageMs = now - statSync(f).mtimeMs;
208
+ if (ageMs > fourHoursMs) {
209
+ logs.push(`DELETED .ship-active age=${Math.floor(ageMs / 60000)}m path=${f}`);
210
+ unlinkSync(f);
211
+ deleted++;
212
+ }
213
+ } catch {}
214
+ }
215
+
216
+ // Archive and purge work directories
217
+ const thirtyDaysMs = 30 * 24 * 60 * 60 * 1000;
218
+ const archiveResult = archiveAndPurge(workDir, fourHoursMs, thirtyDaysMs);
219
+
220
+ // Merge logs
221
+ logs.push(...archiveResult.logs);
222
+
223
+ return { deleted, logs };
224
+ }
@@ -0,0 +1,36 @@
1
+ import { readFileSync, existsSync } from "fs";
2
+ import { join } from "path";
3
+
4
+ interface Phase {
5
+ name: string;
6
+ scs: Array<{ id: string; done: boolean }>;
7
+ note?: string;
8
+ }
9
+
10
+ interface ScanResult {
11
+ scanned: number;
12
+ staleIssues: number[];
13
+ }
14
+
15
+ export function findStaleIssues(projectRoot: string): ScanResult {
16
+ const statePath = join(projectRoot, "project-state.json");
17
+ if (!existsSync(statePath)) return { scanned: 0, staleIssues: [] };
18
+
19
+ const state = JSON.parse(readFileSync(statePath, "utf-8"));
20
+ const phases: Phase[] = state.phases || [];
21
+ const issuePattern = /#(\d+)/g;
22
+ const staleIssues: number[] = [];
23
+
24
+ for (const phase of phases) {
25
+ if (phase.scs.length === 0) continue;
26
+ const allDone = phase.scs.every((sc) => sc.done);
27
+ if (!allDone) continue;
28
+
29
+ let match;
30
+ while ((match = issuePattern.exec(phase.name)) !== null) {
31
+ staleIssues.push(parseInt(match[1], 10));
32
+ }
33
+ }
34
+
35
+ return { scanned: phases.length, staleIssues: [...new Set(staleIssues)] };
36
+ }