@warnyin/sdlc 0.1.2 → 0.2.1

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 (83) hide show
  1. package/CHANGELOG.md +66 -19
  2. package/LICENSE +21 -21
  3. package/README.md +83 -74
  4. package/bin/cli.mjs +103 -30
  5. package/bin/detect.mjs +51 -0
  6. package/bin/multiselect.mjs +147 -0
  7. package/bin/ui.mjs +78 -0
  8. package/lib/caps.mjs +45 -45
  9. package/lib/config.mjs +41 -41
  10. package/lib/delta.mjs +160 -160
  11. package/lib/frontmatter.mjs +59 -59
  12. package/lib/glob.mjs +29 -29
  13. package/lib/manifest.mjs +99 -99
  14. package/lib/observe.mjs +174 -174
  15. package/lib/settings-merge.mjs +63 -63
  16. package/lib/usage.mjs +46 -46
  17. package/lib/validate.mjs +186 -186
  18. package/package.json +42 -42
  19. package/payload/adapters/agents-md.md +8 -8
  20. package/payload/adapters/claude/agents/sdlc-architect.md +12 -12
  21. package/payload/adapters/claude/agents/sdlc-builder.md +14 -14
  22. package/payload/adapters/claude/agents/sdlc-contractor.md +13 -13
  23. package/payload/adapters/claude/agents/sdlc-evaluator.md +13 -13
  24. package/payload/adapters/claude/agents/sdlc-learner.md +16 -16
  25. package/payload/adapters/claude/agents/sdlc-ops.md +11 -11
  26. package/payload/adapters/claude/agents/sdlc-quality.md +13 -13
  27. package/payload/adapters/claude/agents/sdlc-security.md +12 -12
  28. package/payload/adapters/claude/commands/sdlc/auto.md +5 -5
  29. package/payload/adapters/claude/commands/sdlc/build.md +5 -5
  30. package/payload/adapters/claude/commands/sdlc/contract.md +5 -5
  31. package/payload/adapters/claude/commands/sdlc/converge.md +5 -5
  32. package/payload/adapters/claude/commands/sdlc/design.md +5 -5
  33. package/payload/adapters/claude/commands/sdlc/init.md +4 -4
  34. package/payload/adapters/claude/commands/sdlc/new.md +5 -5
  35. package/payload/adapters/claude/commands/sdlc/next.md +4 -4
  36. package/payload/adapters/claude/commands/sdlc/observe.md +4 -4
  37. package/payload/adapters/claude/commands/sdlc/review.md +5 -5
  38. package/payload/adapters/claude/commands/sdlc/ship.md +5 -5
  39. package/payload/adapters/claude/commands/sdlc/steer.md +4 -4
  40. package/payload/adapters/claude/commands/sdlc/verify.md +5 -5
  41. package/payload/adapters/claude/skills/contract-writing/SKILL.md +26 -26
  42. package/payload/adapters/claude/skills/delta-spec-format/SKILL.md +33 -33
  43. package/payload/adapters/claude/skills/sdlc-conventions/SKILL.md +26 -26
  44. package/payload/adapters/cline.md +8 -8
  45. package/payload/adapters/copilot.md +8 -8
  46. package/payload/adapters/cursor.mdc +7 -7
  47. package/payload/adapters/gemini.md +8 -8
  48. package/payload/adapters/windsurf.md +4 -4
  49. package/payload/hooks/_shared.mjs +154 -154
  50. package/payload/hooks/guard-writes.mjs +83 -83
  51. package/payload/hooks/inject-context.mjs +55 -55
  52. package/payload/hooks/journal.mjs +58 -58
  53. package/payload/hooks/session-summary.mjs +50 -50
  54. package/payload/hooks/validate-artifact.mjs +80 -80
  55. package/payload/playbook/README.md +30 -30
  56. package/payload/playbook/auto.md +21 -21
  57. package/payload/playbook/build.md +23 -23
  58. package/payload/playbook/context.md +26 -26
  59. package/payload/playbook/contract.md +23 -23
  60. package/payload/playbook/converge.md +19 -19
  61. package/payload/playbook/design.md +20 -20
  62. package/payload/playbook/init.md +22 -22
  63. package/payload/playbook/new.md +22 -22
  64. package/payload/playbook/next.md +12 -12
  65. package/payload/playbook/observe.md +20 -20
  66. package/payload/playbook/principles.md +28 -28
  67. package/payload/playbook/review.md +17 -17
  68. package/payload/playbook/routing.md +19 -19
  69. package/payload/playbook/rules-card.md +16 -16
  70. package/payload/playbook/ship.md +24 -24
  71. package/payload/playbook/steer.md +21 -21
  72. package/payload/playbook/verify.md +24 -24
  73. package/payload/templates/change-deep.md +29 -29
  74. package/payload/templates/change-standard.md +28 -28
  75. package/payload/templates/change-vibe.md +19 -19
  76. package/payload/templates/config.yaml +8 -8
  77. package/payload/templates/constitution.md +14 -14
  78. package/payload/templates/contract-evals.md +9 -9
  79. package/payload/templates/contract-tests.md +9 -9
  80. package/payload/templates/harness.md +33 -33
  81. package/payload/templates/spec.md +14 -14
  82. package/payload/templates/steering.md +9 -9
  83. package/scripts/validate.mjs +47 -47
package/lib/manifest.mjs CHANGED
@@ -1,99 +1,99 @@
1
- // Manifest + prune guards (ported from the battle-tested warnyin-agents
2
- // installer). The manifest records sha256 of every payload-owned file so
3
- // `update` can distinguish ours-unmodified (refresh), ours-modified-by-user
4
- // (keep + warn), and stale (prune with guards).
5
-
6
- import fs from 'node:fs';
7
- import path from 'node:path';
8
-
9
- export const PRUNE_BLAST_CAP = 50;
10
-
11
- // Payload-owned roots — prune may only ever touch paths under these.
12
- const PRUNABLE_PREFIXES = [
13
- 'sdlc/.playbook/',
14
- 'sdlc/.hooks/',
15
- '.claude/commands/sdlc/',
16
- ];
17
- const AGENT_ALLOW_RE = /^\.claude\/agents\/sdlc-[^/]+\.md$/;
18
- const SKILL_ALLOW_RE = /^\.claude\/skills\/(delta-spec-format|contract-writing|sdlc-conventions)\/[^/]+$/;
19
- const ADAPTER_ALLOW = new Set([
20
- '.cursor/rules/sdlc.mdc',
21
- '.windsurf/rules/sdlc.md',
22
- ]);
23
-
24
- export function parseManifest(text) {
25
- const map = new Map();
26
- for (const line of (text ?? '').split(/\r?\n/)) {
27
- if (!line.trim() || line.startsWith('#')) continue;
28
- const m = line.match(/^([a-f0-9]{64})\s{2}(.+)$/);
29
- if (!m) continue;
30
- map.set(m[2], m[1]);
31
- }
32
- return map;
33
- }
34
-
35
- export function renderManifest(map) {
36
- const lines = ['# @warnyin/sdlc manifest — sha256 path (posix, relative to project root)'];
37
- for (const [p, hash] of [...map.entries()].sort()) lines.push(`${hash} ${p}`);
38
- return lines.join('\n') + '\n';
39
- }
40
-
41
- // Guard 1: structural path safety (manifest is data — never trust it blindly).
42
- export function isSafeRelPath(relPosix) {
43
- if (typeof relPosix !== 'string' || relPosix === '') return false;
44
- if (relPosix.includes('\\') || relPosix.startsWith('/') || /^[A-Za-z]:/.test(relPosix)) return false;
45
- if (/[\u0000-\u001f]/.test(relPosix)) return false;
46
- const segments = relPosix.split('/');
47
- return segments.every((s) => s !== '' && s !== '.' && s !== '..');
48
- }
49
-
50
- // Guard 2: scope — only payload-owned locations are ever prunable.
51
- export function isPrunablePath(relPosix) {
52
- if (!isSafeRelPath(relPosix)) return false;
53
- if (PRUNABLE_PREFIXES.some((p) => relPosix.startsWith(p))) return true;
54
- if (AGENT_ALLOW_RE.test(relPosix)) return true;
55
- if (SKILL_ALLOW_RE.test(relPosix)) return true;
56
- if (ADAPTER_ALLOW.has(relPosix)) return true;
57
- return false;
58
- }
59
-
60
- // Stale = in the old manifest but absent from the new payload set.
61
- // Every candidate must pass path + scope guards; the caller additionally
62
- // checks hash-match-on-disk and realpath containment before deleting.
63
- export function computeStale(oldManifest, newPaths) {
64
- const stale = [];
65
- const rejected = [];
66
- for (const [relPath, hash] of oldManifest.entries()) {
67
- if (newPaths.has(relPath)) continue;
68
- if (!isPrunablePath(relPath)) {
69
- rejected.push({ path: relPath, reason: 'outside prunable scope' });
70
- continue;
71
- }
72
- stale.push({ path: relPath, hash });
73
- }
74
- return { stale, rejected, overCap: stale.length > PRUNE_BLAST_CAP };
75
- }
76
-
77
- export function containedIn(rootAbs, targetAbs) {
78
- const rel = path.relative(rootAbs, targetAbs);
79
- return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
80
- }
81
-
82
- // Guard: no path segment between root and target may be a symlink. Without
83
- // this, a symlinked ancestor inside a prunable prefix redirects the delete to
84
- // whatever real file it points at (arbitrary-deletion class — the manifest is
85
- // untrusted, user-writable input).
86
- export function hasSymlinkSegment(rootAbs, targetAbs) {
87
- const rel = path.relative(rootAbs, targetAbs);
88
- if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return true; // suspicious → treat as unsafe
89
- let cur = rootAbs;
90
- for (const seg of rel.split(path.sep)) {
91
- cur = path.join(cur, seg);
92
- try {
93
- if (fs.lstatSync(cur).isSymbolicLink()) return true;
94
- } catch {
95
- return false; // component missing — nothing to follow
96
- }
97
- }
98
- return false;
99
- }
1
+ // Manifest + prune guards (ported from the battle-tested warnyin-agents
2
+ // installer). The manifest records sha256 of every payload-owned file so
3
+ // `update` can distinguish ours-unmodified (refresh), ours-modified-by-user
4
+ // (keep + warn), and stale (prune with guards).
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ export const PRUNE_BLAST_CAP = 50;
10
+
11
+ // Payload-owned roots — prune may only ever touch paths under these.
12
+ const PRUNABLE_PREFIXES = [
13
+ 'sdlc/.playbook/',
14
+ 'sdlc/.hooks/',
15
+ '.claude/commands/sdlc/',
16
+ ];
17
+ const AGENT_ALLOW_RE = /^\.claude\/agents\/sdlc-[^/]+\.md$/;
18
+ const SKILL_ALLOW_RE = /^\.claude\/skills\/(delta-spec-format|contract-writing|sdlc-conventions)\/[^/]+$/;
19
+ const ADAPTER_ALLOW = new Set([
20
+ '.cursor/rules/sdlc.mdc',
21
+ '.windsurf/rules/sdlc.md',
22
+ ]);
23
+
24
+ export function parseManifest(text) {
25
+ const map = new Map();
26
+ for (const line of (text ?? '').split(/\r?\n/)) {
27
+ if (!line.trim() || line.startsWith('#')) continue;
28
+ const m = line.match(/^([a-f0-9]{64})\s{2}(.+)$/);
29
+ if (!m) continue;
30
+ map.set(m[2], m[1]);
31
+ }
32
+ return map;
33
+ }
34
+
35
+ export function renderManifest(map) {
36
+ const lines = ['# @warnyin/sdlc manifest — sha256 path (posix, relative to project root)'];
37
+ for (const [p, hash] of [...map.entries()].sort()) lines.push(`${hash} ${p}`);
38
+ return lines.join('\n') + '\n';
39
+ }
40
+
41
+ // Guard 1: structural path safety (manifest is data — never trust it blindly).
42
+ export function isSafeRelPath(relPosix) {
43
+ if (typeof relPosix !== 'string' || relPosix === '') return false;
44
+ if (relPosix.includes('\\') || relPosix.startsWith('/') || /^[A-Za-z]:/.test(relPosix)) return false;
45
+ if (/[\u0000-\u001f]/.test(relPosix)) return false;
46
+ const segments = relPosix.split('/');
47
+ return segments.every((s) => s !== '' && s !== '.' && s !== '..');
48
+ }
49
+
50
+ // Guard 2: scope — only payload-owned locations are ever prunable.
51
+ export function isPrunablePath(relPosix) {
52
+ if (!isSafeRelPath(relPosix)) return false;
53
+ if (PRUNABLE_PREFIXES.some((p) => relPosix.startsWith(p))) return true;
54
+ if (AGENT_ALLOW_RE.test(relPosix)) return true;
55
+ if (SKILL_ALLOW_RE.test(relPosix)) return true;
56
+ if (ADAPTER_ALLOW.has(relPosix)) return true;
57
+ return false;
58
+ }
59
+
60
+ // Stale = in the old manifest but absent from the new payload set.
61
+ // Every candidate must pass path + scope guards; the caller additionally
62
+ // checks hash-match-on-disk and realpath containment before deleting.
63
+ export function computeStale(oldManifest, newPaths) {
64
+ const stale = [];
65
+ const rejected = [];
66
+ for (const [relPath, hash] of oldManifest.entries()) {
67
+ if (newPaths.has(relPath)) continue;
68
+ if (!isPrunablePath(relPath)) {
69
+ rejected.push({ path: relPath, reason: 'outside prunable scope' });
70
+ continue;
71
+ }
72
+ stale.push({ path: relPath, hash });
73
+ }
74
+ return { stale, rejected, overCap: stale.length > PRUNE_BLAST_CAP };
75
+ }
76
+
77
+ export function containedIn(rootAbs, targetAbs) {
78
+ const rel = path.relative(rootAbs, targetAbs);
79
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
80
+ }
81
+
82
+ // Guard: no path segment between root and target may be a symlink. Without
83
+ // this, a symlinked ancestor inside a prunable prefix redirects the delete to
84
+ // whatever real file it points at (arbitrary-deletion class — the manifest is
85
+ // untrusted, user-writable input).
86
+ export function hasSymlinkSegment(rootAbs, targetAbs) {
87
+ const rel = path.relative(rootAbs, targetAbs);
88
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return true; // suspicious → treat as unsafe
89
+ let cur = rootAbs;
90
+ for (const seg of rel.split(path.sep)) {
91
+ cur = path.join(cur, seg);
92
+ try {
93
+ if (fs.lstatSync(cur).isSymbolicLink()) return true;
94
+ } catch {
95
+ return false; // component missing — nothing to follow
96
+ }
97
+ }
98
+ return false;
99
+ }
package/lib/observe.mjs CHANGED
@@ -1,174 +1,174 @@
1
- // Observability aggregation — reads journals + context files, computes the
2
- // numbers /sdlc:observe reports. Pure given an sdlc root; no LLM involved.
3
-
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import { parseFrontmatter } from './frontmatter.mjs';
7
- import { CAPS, countEffectiveLines } from './caps.mjs';
8
-
9
- function readJournal(dir) {
10
- const p = path.join(dir, 'journal.ndjson');
11
- if (!fs.existsSync(p)) return [];
12
- return fs.readFileSync(p, 'utf8').split('\n').filter(Boolean).map((l) => {
13
- try { return JSON.parse(l); } catch { return null; }
14
- }).filter(Boolean);
15
- }
16
-
17
- function summarizeChange(dir, id, archived) {
18
- const events = readJournal(dir);
19
- const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
20
- let costUsd = 0;
21
- let costKnown = false;
22
- let sessions = 0;
23
- const verify = { rounds: 0, firstPass: null };
24
- let guards = 0;
25
- let compacts = 0;
26
-
27
- for (const e of events) {
28
- if (e.event === 'session') {
29
- sessions++;
30
- for (const k of Object.keys(tokens)) tokens[k] += e.totals?.[k] ?? 0;
31
- if (typeof e.costUsd === 'number') { costUsd += e.costUsd; costKnown = true; }
32
- } else if (e.event === 'verify') {
33
- verify.rounds++;
34
- if (verify.firstPass === null) verify.firstPass = e.result === 'pass';
35
- } else if (e.event === 'guard') guards++;
36
- else if (e.event === 'compact') compacts++;
37
- }
38
-
39
- const first = events[0]?.ts ? Date.parse(events[0].ts) : null;
40
- const shipEvent = events.find((e) => e.event === 'ship');
41
- const shippedAt = shipEvent?.ts ? Date.parse(shipEvent.ts) : null;
42
- const leadTimeMs = first != null && shippedAt != null ? shippedAt - first : null;
43
-
44
- let tier = null;
45
- let status = null;
46
- const changePath = path.join(dir, 'change.md');
47
- if (fs.existsSync(changePath)) {
48
- const { data } = parseFrontmatter(fs.readFileSync(changePath, 'utf8'));
49
- tier = data.tier ?? null;
50
- status = data.status ?? null;
51
- }
52
-
53
- return {
54
- id, archived, tier, status, sessions, tokens,
55
- costUsd: costKnown ? Number(costUsd.toFixed(4)) : null,
56
- verify, guards, compacts, leadTimeMs,
57
- digest: archived ? fs.existsSync(path.join(dir, 'digest.md')) : null,
58
- };
59
- }
60
-
61
- export function buildReport(sdlcRoot) {
62
- const changes = [];
63
-
64
- const changesDir = path.join(sdlcRoot, 'changes');
65
- if (fs.existsSync(changesDir)) {
66
- for (const d of fs.readdirSync(changesDir, { withFileTypes: true })) {
67
- if (!d.isDirectory() || d.name === 'archive') continue;
68
- changes.push(summarizeChange(path.join(changesDir, d.name), d.name, false));
69
- }
70
- const archiveDir = path.join(changesDir, 'archive');
71
- if (fs.existsSync(archiveDir)) {
72
- for (const d of fs.readdirSync(archiveDir, { withFileTypes: true })) {
73
- if (!d.isDirectory()) continue;
74
- changes.push(summarizeChange(path.join(archiveDir, d.name), d.name, true));
75
- }
76
- }
77
- }
78
-
79
- // Residency: constitution + always-steering effective lines vs budget.
80
- let alwaysLines = 0;
81
- const constitutionPath = path.join(sdlcRoot, 'context', 'constitution.md');
82
- if (fs.existsSync(constitutionPath)) {
83
- alwaysLines += countEffectiveLines(fs.readFileSync(constitutionPath, 'utf8'));
84
- }
85
- const steering = [];
86
- const pointerHits = new Map();
87
- for (const c of changes) {
88
- const dir = c.archived
89
- ? path.join(sdlcRoot, 'changes', 'archive', c.id)
90
- : path.join(sdlcRoot, 'changes', c.id);
91
- for (const e of readJournal(dir)) {
92
- if (e.event === 'pointer' && e.steering) {
93
- pointerHits.set(e.steering, (pointerHits.get(e.steering) ?? 0) + 1);
94
- }
95
- }
96
- }
97
- // Global journal (events with no active change) counts too.
98
- for (const e of readJournal(path.join(sdlcRoot, '.state'))) {
99
- if (e.event === 'pointer' && e.steering) {
100
- pointerHits.set(e.steering, (pointerHits.get(e.steering) ?? 0) + 1);
101
- }
102
- }
103
-
104
- const steeringDir = path.join(sdlcRoot, 'context', 'steering');
105
- if (fs.existsSync(steeringDir)) {
106
- for (const f of fs.readdirSync(steeringDir).filter((n) => n.endsWith('.md')).sort()) {
107
- const raw = fs.readFileSync(path.join(steeringDir, f), 'utf8');
108
- const { data } = parseFrontmatter(raw);
109
- const inclusion = data.inclusion ?? 'manual';
110
- if (inclusion === 'always') alwaysLines += countEffectiveLines(raw);
111
- steering.push({ file: f, inclusion, pointerHits: pointerHits.get(f) ?? 0 });
112
- }
113
- }
114
-
115
- // Flags — plain strings the playbook can surface with suggested fixes.
116
- const flags = [];
117
- if (alwaysLines > CAPS.alwaysBudget) {
118
- flags.push(`residency: always-loaded is ${alwaysLines}/${CAPS.alwaysBudget} lines — distill via /sdlc:steer`);
119
- }
120
- const shipped = changes.filter((c) => c.archived);
121
- for (const s of steering.filter((s) => s.inclusion === 'paths' && s.pointerHits === 0)) {
122
- if (shipped.length >= 2) {
123
- flags.push(`steering/${s.file}: zero pointer hits across ${shipped.length} shipped changes — demote or delete`);
124
- }
125
- }
126
- for (const c of changes) {
127
- if (c.compacts > 0) flags.push(`${c.id}: ${c.compacts} compact event(s) — context overflowed, find the resident artifact`);
128
- if (c.verify.rounds > 3) flags.push(`${c.id}: ${c.verify.rounds} verify rounds — contract or routing needs attention`);
129
- }
130
- for (const c of shipped.filter((c) => c.digest === false)) {
131
- flags.push(`${c.id}: archived without digest.md — ship playbook step 4 was skipped`);
132
- }
133
-
134
- const firstPassRuns = changes.filter((c) => c.verify.firstPass !== null);
135
- const summary = {
136
- active: changes.filter((c) => !c.archived).length,
137
- shipped: shipped.length,
138
- firstPassRate: firstPassRuns.length
139
- ? Number((firstPassRuns.filter((c) => c.verify.firstPass).length / firstPassRuns.length).toFixed(2))
140
- : null,
141
- };
142
-
143
- return {
144
- summary,
145
- changes,
146
- residency: { alwaysLines, budget: CAPS.alwaysBudget },
147
- steering,
148
- flags,
149
- };
150
- }
151
-
152
- const fmtK = (n) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M`
153
- : n >= 1_000 ? `${(n / 1_000).toFixed(1)}k` : String(n));
154
-
155
- export function renderReport(report) {
156
- const lines = [];
157
- const { summary, residency } = report;
158
- lines.push(`changes: ${summary.active} active · ${summary.shipped} shipped`
159
- + (summary.firstPassRate != null ? ` · first-pass ${(summary.firstPassRate * 100).toFixed(0)}%` : ''));
160
- lines.push(`residency: ${residency.alwaysLines}/${residency.budget} always-loaded lines`);
161
- for (const c of report.changes) {
162
- const t = c.tokens;
163
- const lead = c.leadTimeMs != null ? ` · lead ${(c.leadTimeMs / 3_600_000).toFixed(1)}h` : '';
164
- lines.push(` ${c.archived ? '✓' : '·'} ${c.id} [${c.tier ?? '?'}]`
165
- + ` ${fmtK(t.input)}in/${fmtK(t.output)}out`
166
- + (c.costUsd != null ? ` $${c.costUsd}` : '')
167
- + ` · verify×${c.verify.rounds}${lead}`);
168
- }
169
- for (const s of report.steering) {
170
- lines.push(` steering/${s.file} [${s.inclusion}] hits:${s.pointerHits}`);
171
- }
172
- for (const f of report.flags) lines.push(` ⚠ ${f}`);
173
- return lines.join('\n');
174
- }
1
+ // Observability aggregation — reads journals + context files, computes the
2
+ // numbers /sdlc:observe reports. Pure given an sdlc root; no LLM involved.
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { parseFrontmatter } from './frontmatter.mjs';
7
+ import { CAPS, countEffectiveLines } from './caps.mjs';
8
+
9
+ function readJournal(dir) {
10
+ const p = path.join(dir, 'journal.ndjson');
11
+ if (!fs.existsSync(p)) return [];
12
+ return fs.readFileSync(p, 'utf8').split('\n').filter(Boolean).map((l) => {
13
+ try { return JSON.parse(l); } catch { return null; }
14
+ }).filter(Boolean);
15
+ }
16
+
17
+ function summarizeChange(dir, id, archived) {
18
+ const events = readJournal(dir);
19
+ const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
20
+ let costUsd = 0;
21
+ let costKnown = false;
22
+ let sessions = 0;
23
+ const verify = { rounds: 0, firstPass: null };
24
+ let guards = 0;
25
+ let compacts = 0;
26
+
27
+ for (const e of events) {
28
+ if (e.event === 'session') {
29
+ sessions++;
30
+ for (const k of Object.keys(tokens)) tokens[k] += e.totals?.[k] ?? 0;
31
+ if (typeof e.costUsd === 'number') { costUsd += e.costUsd; costKnown = true; }
32
+ } else if (e.event === 'verify') {
33
+ verify.rounds++;
34
+ if (verify.firstPass === null) verify.firstPass = e.result === 'pass';
35
+ } else if (e.event === 'guard') guards++;
36
+ else if (e.event === 'compact') compacts++;
37
+ }
38
+
39
+ const first = events[0]?.ts ? Date.parse(events[0].ts) : null;
40
+ const shipEvent = events.find((e) => e.event === 'ship');
41
+ const shippedAt = shipEvent?.ts ? Date.parse(shipEvent.ts) : null;
42
+ const leadTimeMs = first != null && shippedAt != null ? shippedAt - first : null;
43
+
44
+ let tier = null;
45
+ let status = null;
46
+ const changePath = path.join(dir, 'change.md');
47
+ if (fs.existsSync(changePath)) {
48
+ const { data } = parseFrontmatter(fs.readFileSync(changePath, 'utf8'));
49
+ tier = data.tier ?? null;
50
+ status = data.status ?? null;
51
+ }
52
+
53
+ return {
54
+ id, archived, tier, status, sessions, tokens,
55
+ costUsd: costKnown ? Number(costUsd.toFixed(4)) : null,
56
+ verify, guards, compacts, leadTimeMs,
57
+ digest: archived ? fs.existsSync(path.join(dir, 'digest.md')) : null,
58
+ };
59
+ }
60
+
61
+ export function buildReport(sdlcRoot) {
62
+ const changes = [];
63
+
64
+ const changesDir = path.join(sdlcRoot, 'changes');
65
+ if (fs.existsSync(changesDir)) {
66
+ for (const d of fs.readdirSync(changesDir, { withFileTypes: true })) {
67
+ if (!d.isDirectory() || d.name === 'archive') continue;
68
+ changes.push(summarizeChange(path.join(changesDir, d.name), d.name, false));
69
+ }
70
+ const archiveDir = path.join(changesDir, 'archive');
71
+ if (fs.existsSync(archiveDir)) {
72
+ for (const d of fs.readdirSync(archiveDir, { withFileTypes: true })) {
73
+ if (!d.isDirectory()) continue;
74
+ changes.push(summarizeChange(path.join(archiveDir, d.name), d.name, true));
75
+ }
76
+ }
77
+ }
78
+
79
+ // Residency: constitution + always-steering effective lines vs budget.
80
+ let alwaysLines = 0;
81
+ const constitutionPath = path.join(sdlcRoot, 'context', 'constitution.md');
82
+ if (fs.existsSync(constitutionPath)) {
83
+ alwaysLines += countEffectiveLines(fs.readFileSync(constitutionPath, 'utf8'));
84
+ }
85
+ const steering = [];
86
+ const pointerHits = new Map();
87
+ for (const c of changes) {
88
+ const dir = c.archived
89
+ ? path.join(sdlcRoot, 'changes', 'archive', c.id)
90
+ : path.join(sdlcRoot, 'changes', c.id);
91
+ for (const e of readJournal(dir)) {
92
+ if (e.event === 'pointer' && e.steering) {
93
+ pointerHits.set(e.steering, (pointerHits.get(e.steering) ?? 0) + 1);
94
+ }
95
+ }
96
+ }
97
+ // Global journal (events with no active change) counts too.
98
+ for (const e of readJournal(path.join(sdlcRoot, '.state'))) {
99
+ if (e.event === 'pointer' && e.steering) {
100
+ pointerHits.set(e.steering, (pointerHits.get(e.steering) ?? 0) + 1);
101
+ }
102
+ }
103
+
104
+ const steeringDir = path.join(sdlcRoot, 'context', 'steering');
105
+ if (fs.existsSync(steeringDir)) {
106
+ for (const f of fs.readdirSync(steeringDir).filter((n) => n.endsWith('.md')).sort()) {
107
+ const raw = fs.readFileSync(path.join(steeringDir, f), 'utf8');
108
+ const { data } = parseFrontmatter(raw);
109
+ const inclusion = data.inclusion ?? 'manual';
110
+ if (inclusion === 'always') alwaysLines += countEffectiveLines(raw);
111
+ steering.push({ file: f, inclusion, pointerHits: pointerHits.get(f) ?? 0 });
112
+ }
113
+ }
114
+
115
+ // Flags — plain strings the playbook can surface with suggested fixes.
116
+ const flags = [];
117
+ if (alwaysLines > CAPS.alwaysBudget) {
118
+ flags.push(`residency: always-loaded is ${alwaysLines}/${CAPS.alwaysBudget} lines — distill via /sdlc:steer`);
119
+ }
120
+ const shipped = changes.filter((c) => c.archived);
121
+ for (const s of steering.filter((s) => s.inclusion === 'paths' && s.pointerHits === 0)) {
122
+ if (shipped.length >= 2) {
123
+ flags.push(`steering/${s.file}: zero pointer hits across ${shipped.length} shipped changes — demote or delete`);
124
+ }
125
+ }
126
+ for (const c of changes) {
127
+ if (c.compacts > 0) flags.push(`${c.id}: ${c.compacts} compact event(s) — context overflowed, find the resident artifact`);
128
+ if (c.verify.rounds > 3) flags.push(`${c.id}: ${c.verify.rounds} verify rounds — contract or routing needs attention`);
129
+ }
130
+ for (const c of shipped.filter((c) => c.digest === false)) {
131
+ flags.push(`${c.id}: archived without digest.md — ship playbook step 4 was skipped`);
132
+ }
133
+
134
+ const firstPassRuns = changes.filter((c) => c.verify.firstPass !== null);
135
+ const summary = {
136
+ active: changes.filter((c) => !c.archived).length,
137
+ shipped: shipped.length,
138
+ firstPassRate: firstPassRuns.length
139
+ ? Number((firstPassRuns.filter((c) => c.verify.firstPass).length / firstPassRuns.length).toFixed(2))
140
+ : null,
141
+ };
142
+
143
+ return {
144
+ summary,
145
+ changes,
146
+ residency: { alwaysLines, budget: CAPS.alwaysBudget },
147
+ steering,
148
+ flags,
149
+ };
150
+ }
151
+
152
+ const fmtK = (n) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M`
153
+ : n >= 1_000 ? `${(n / 1_000).toFixed(1)}k` : String(n));
154
+
155
+ export function renderReport(report) {
156
+ const lines = [];
157
+ const { summary, residency } = report;
158
+ lines.push(`changes: ${summary.active} active · ${summary.shipped} shipped`
159
+ + (summary.firstPassRate != null ? ` · first-pass ${(summary.firstPassRate * 100).toFixed(0)}%` : ''));
160
+ lines.push(`residency: ${residency.alwaysLines}/${residency.budget} always-loaded lines`);
161
+ for (const c of report.changes) {
162
+ const t = c.tokens;
163
+ const lead = c.leadTimeMs != null ? ` · lead ${(c.leadTimeMs / 3_600_000).toFixed(1)}h` : '';
164
+ lines.push(` ${c.archived ? '✓' : '·'} ${c.id} [${c.tier ?? '?'}]`
165
+ + ` ${fmtK(t.input)}in/${fmtK(t.output)}out`
166
+ + (c.costUsd != null ? ` $${c.costUsd}` : '')
167
+ + ` · verify×${c.verify.rounds}${lead}`);
168
+ }
169
+ for (const s of report.steering) {
170
+ lines.push(` steering/${s.file} [${s.inclusion}] hits:${s.pointerHits}`);
171
+ }
172
+ for (const f of report.flags) lines.push(` ⚠ ${f}`);
173
+ return lines.join('\n');
174
+ }