@dzhechkov/harness-core 0.3.111 → 0.3.113

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.
@@ -0,0 +1,249 @@
1
+ /**
2
+ * MR rake analyzer (feature mr-rake-analyzer, ADR-001).
3
+ *
4
+ * Mines a project's review corpus for RECURRING mistakes ("rakes") and closes them into self-learning.
5
+ * The parse/normalize/detect/render functions are PURE + deterministic (sorted, no clock/random) so the
6
+ * same corpus yields a byte-identical report; the load/scan helpers do disk I/O with TOP-LEVEL node:fs
7
+ * imports (harness-core is ESM — a lazy require() is undefined at runtime; the R1 footgun).
8
+ *
9
+ * Signature is DETERMINISTIC (ADR-001 §1): a rule table of known rake classes, with an unmatched finding
10
+ * falling to a normalized-text bucket so novel recurrences still cluster. LLM classification is an optional
11
+ * amplifier, never in this core.
12
+ *
13
+ * SAFETY PROPERTY (ADR-001 §3, load-bearing): a finding whose signature appears in fewer than
14
+ * `thresholds.candidate` DISTINCT sources is a one-off — it is NEVER a rake and never reaches teach/critic.
15
+ */
16
+ import { existsSync, readFileSync, readdirSync, statSync, realpathSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ const SEVERITY_RANK = { blocker: 4, high: 3, medium: 2, low: 1, unknown: 0 };
19
+ export const DEFAULT_RAKE_THRESHOLDS = { candidate: 2, confirmed: 3 };
20
+ /**
21
+ * Known rake classes (extensible, data-only). Seeded from the classes that actually recur in this repo's
22
+ * QE reports — that IS the dogfood. First match in order wins; unmatched → normalized-text bucket.
23
+ */
24
+ export const RAKE_SIGNATURES = [
25
+ { id: 'esm-require-footgun', label: 'ESM lazy require() undefined at runtime', patterns: [/require\(['"]node:/, /\besm\b.*require/i, /lazy require/i] },
26
+ { id: 'untested-adr-property', label: 'ADR-named safety property left untested', patterns: [/load-bearing.*(untested|not\s+tested|no\s+test)/i, /adr.*names.*(property|test)/i, /safety property.*test/i] },
27
+ { id: 'claim-check-fp', label: 'claim-check false positive / untagged count', patterns: [/claim-check.*(false positive|\bfp\b)/i, /untagged.*(count|claim)/i, /metric term/i] },
28
+ // "traversal" alone over-matches (AST/tree traversal); require a filesystem-scope token to CO-OCCUR
29
+ // (or a literal `../`) — cross-model QE caught the over-match.
30
+ { id: 'path-traversal', label: 'path not constrained to the repo (traversal)', patterns: [/\.\.\//, /(?=.*travers)(?=.*(repo|root|\bpath\b|director|\/etc\/))/i, /escapes.{0,12}repo/i] },
31
+ { id: 'silent-drop-or-inject', label: 'silent drop / silent injection (no report)', patterns: [/silent(ly)?\s+(drop|inject|discard|dropped)/i, /no silent (injection|caps|drop)/i] },
32
+ { id: 'swallow-generic-exception', label: 'generic except/catch swallows real bugs', patterns: [/except\s+Exception/i, /catch.*swallow/i, /generic (exception|catch)/i] },
33
+ { id: 'determinism-hole', label: 'non-deterministic output (unsorted/clock/random)', patterns: [/non-determinis/i, /determinism hole/i, /unsorted|not sorted/i] },
34
+ { id: 'cross-model-self-qe', label: 'coder self-QE instead of cross-model', patterns: [/self-qe/i, /coder.*(review|qe).*(itself|self)/i, /cross-model/i] },
35
+ { id: 'malformed-input-bypass', label: 'malformed input bypasses validation', patterns: [/array.*(pass|bypass)/i, /malformed.*(bypass|pass|manifest)/i, /typeof.*object/i] },
36
+ ];
37
+ // Deep-freeze so an external caller can't inject a `/g`-flag regex whose `.test()` mutates lastIndex and
38
+ // makes signatureOf non-deterministic (cross-model QE). None of the patterns above use `g`/`y`.
39
+ for (const s of RAKE_SIGNATURES) {
40
+ Object.freeze(s.patterns);
41
+ Object.freeze(s);
42
+ }
43
+ Object.freeze(RAKE_SIGNATURES);
44
+ const byStr = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
45
+ const uniqSorted = (xs) => [...new Set(xs)].sort(byStr);
46
+ const maxSeverity = (a, b) => (SEVERITY_RANK[a] >= SEVERITY_RANK[b] ? a : b);
47
+ const STOPWORDS = new Set(['the', 'a', 'an', 'and', 'or', 'to', 'of', 'in', 'on', 'is', 'it', 'that', 'this', 'for', 'with', 'as', 'at', 'by', 'be', 'not', 'no', 'its', 'when', 'if', 'was', 'are', 'но', 'и', 'в', 'на', 'что', 'это', 'не', 'из', 'за', 'для']);
48
+ /** Normalize a finding's text to a stable clustering key: lowercase, strip sites/numbers/punct, top significant words. */
49
+ export function normalizeText(text) {
50
+ const cleaned = text
51
+ .toLowerCase()
52
+ .replace(/[\w./-]+:\d+/g, ' ') // drop file:line
53
+ .replace(/`[^`]*`/g, ' ') // drop code literals
54
+ .replace(/[^a-zа-я\s]/gi, ' '); // drop digits/punct
55
+ const words = cleaned.split(/\s+/).filter((w) => w.length >= 4 && !STOPWORDS.has(w));
56
+ return uniqSorted(words).slice(0, 6).join(' ');
57
+ }
58
+ const SEV_MAP = {
59
+ blocker: 'blocker', critical: 'blocker', crit: 'blocker',
60
+ high: 'high', hi: 'high',
61
+ medium: 'medium', med: 'medium',
62
+ low: 'low', nit: 'low',
63
+ };
64
+ const toSeverity = (raw) => SEV_MAP[raw.trim().toLowerCase()] ?? 'unknown';
65
+ const SITE_RE = /([\w./-]+\.(?:ts|js|tsx|jsx|py|go|md|json|yml|yaml):\d+)/;
66
+ /** The signature of a finding: first matching rule, else the normalized-text bucket. */
67
+ export function signatureOf(finding) {
68
+ for (const s of RAKE_SIGNATURES) {
69
+ if (s.patterns.some((p) => p.test(finding.text)))
70
+ return { id: s.id, label: s.label };
71
+ }
72
+ const key = normalizeText(finding.text);
73
+ if (key !== '')
74
+ return { id: `text:${key}`, label: key };
75
+ // No significant words (code-only / very short). Key on the LITERAL text so two DIFFERENT such findings
76
+ // never merge into a false "unclassified ×N" rake (cross-model QE) — but two IDENTICAL ones still cluster.
77
+ const literal = finding.text.toLowerCase().replace(/\s+/g, ' ').trim().slice(0, 80);
78
+ return { id: `literal:${literal}`, label: literal === '' ? 'unclassified finding' : literal };
79
+ }
80
+ /**
81
+ * Parse one markdown artifact into findings. Handles (a) severity table rows `| … | High | <text> | … |`,
82
+ * (b) inline markers `[High]` / `**High —**` / `Sev — <text>`. Deterministic; unknown formats yield nothing.
83
+ */
84
+ export function extractFindings(markdown, source) {
85
+ const out = [];
86
+ const push = (severity, text) => {
87
+ const t = text.replace(/\s+/g, ' ').trim();
88
+ if (t.length < 8)
89
+ return; // too short to be a finding
90
+ const site = SITE_RE.exec(t)?.[1];
91
+ out.push(site ? { source, severity, text: t, site } : { source, severity, text: t });
92
+ };
93
+ for (const line of markdown.split('\n')) {
94
+ // (a) table row: | ... | <sev> | <finding> | ...
95
+ const cells = line.includes('|') ? line.split('|').map((c) => c.trim()) : null;
96
+ if (cells && cells.length >= 4) {
97
+ const sevCell = cells.find((c) => SEV_MAP[c.toLowerCase()] !== undefined);
98
+ if (sevCell) {
99
+ const sevIdx = cells.indexOf(sevCell);
100
+ const finding = cells.slice(sevIdx + 1).find((c) => c.length >= 8 && !/^-+$/.test(c));
101
+ if (finding) {
102
+ push(toSeverity(sevCell), finding);
103
+ continue;
104
+ }
105
+ }
106
+ }
107
+ // (b) inline `[High] text` / `**High —** text` / `- High: text`. The bracketed form `[High] text`
108
+ // needs no separator (the brackets delimit); the bare form `High: text` requires one so prose like
109
+ // "high latency" doesn't register (cross-model QE: a missing separator silently dropped findings).
110
+ const bracketed = /^[\s\-*>]*\**\[(blocker|critical|high|medium|med|low)\]\**\s*[—:\-]?\s*(.+)$/i.exec(line);
111
+ const bare = /^[\s\-*>]*\**(blocker|critical|high|medium|med|low)\**\s*[—:]\s*(.+)$/i.exec(line);
112
+ const m = bracketed ?? bare;
113
+ if (m && m[1] && m[2])
114
+ push(toSeverity(m[1]), m[2]);
115
+ }
116
+ return out;
117
+ }
118
+ /**
119
+ * Detect rakes: group findings by signature, count DISTINCT sources, keep only groups at/above the candidate
120
+ * threshold (a below-threshold group is a one-off, NEVER a rake — the load-bearing anti-noise property).
121
+ * PURE + deterministic (ADR-001 §1): rakes sorted by (count desc, severity desc, signature asc).
122
+ */
123
+ export function detectRakes(findings, thresholds = DEFAULT_RAKE_THRESHOLDS) {
124
+ const groups = new Map();
125
+ for (const f of findings) {
126
+ const sig = signatureOf(f);
127
+ const g = groups.get(sig.id);
128
+ if (g)
129
+ g.findings.push(f);
130
+ else
131
+ groups.set(sig.id, { label: sig.label, findings: [f] });
132
+ }
133
+ const rakes = [];
134
+ let oneOffs = 0;
135
+ for (const [signature, g] of groups) {
136
+ const sources = uniqSorted(g.findings.map((f) => f.source));
137
+ const count = sources.length;
138
+ if (count < thresholds.candidate) {
139
+ oneOffs++;
140
+ continue;
141
+ }
142
+ const severity = g.findings.reduce((m, f) => maxSeverity(m, f.severity), 'unknown');
143
+ const examples = [...g.findings]
144
+ .sort((a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] || byStr(a.source, b.source))
145
+ .slice(0, 3);
146
+ rakes.push({ signature, label: g.label, sources, count, severity, examples, status: count >= thresholds.confirmed ? 'confirmed' : 'candidate' });
147
+ }
148
+ rakes.sort((a, b) => b.count - a.count || SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] || byStr(a.signature, b.signature));
149
+ return { rakes, totalFindings: findings.length, oneOffs };
150
+ }
151
+ /** Human render of the rake report. Deterministic. */
152
+ export function renderRakeReport(report) {
153
+ if (report.rakes.length === 0) {
154
+ return `mr-rakes: no recurring rakes (${report.totalFindings} finding(s), ${report.oneOffs} one-off signature(s) below threshold).`;
155
+ }
156
+ const lines = [`mr-rakes: ${report.rakes.length} rake(s) from ${report.totalFindings} finding(s) (${report.oneOffs} one-off(s) dropped):`, ''];
157
+ for (const r of report.rakes) {
158
+ lines.push(` [${r.status}] ${r.severity.toUpperCase()} ×${r.count} — ${r.label} (${r.signature})`);
159
+ lines.push(` sources: ${r.sources.join(', ')}`);
160
+ }
161
+ return lines.join('\n');
162
+ }
163
+ /** The teachable rule text for a rake (fed to `dz teach`). Deterministic. */
164
+ export function rakeAsLesson(rake) {
165
+ return `Project rake (recurred in ${rake.count} reviews): ${rake.label}. First seen: ${rake.examples[0]?.site ?? rake.sources[0]}. Watch for this class before it ships again.`;
166
+ }
167
+ /** Severity → teach reward. Higher-severity rakes are higher-signal lessons. */
168
+ export function rakeReward(rake) {
169
+ return { blocker: 0.95, high: 0.9, medium: 0.8, low: 0.7, unknown: 0.7 }[rake.severity];
170
+ }
171
+ /** Render the CONFIRMED rakes as a project-critic SKILL.md section (sink B). Deterministic; confirmed only. */
172
+ export function renderCriticSection(report) {
173
+ const confirmed = report.rakes.filter((r) => r.status === 'confirmed');
174
+ const lines = [
175
+ '## Recurring mistakes (auto-mined by `dz mr-rakes`)',
176
+ '',
177
+ confirmed.length === 0
178
+ ? '_No confirmed recurring rakes yet._'
179
+ : 'These classes of mistake have recurred across this project\'s reviews. Flag them before they ship again:',
180
+ '',
181
+ ];
182
+ for (const r of confirmed) {
183
+ lines.push(`- **${r.label}** (${r.severity}, ×${r.count}) — e.g. ${r.examples[0]?.site ?? r.sources[0]}.`);
184
+ }
185
+ return lines.join('\n');
186
+ }
187
+ // ── Thin I/O (top-level fs; never throws) ────────────────────────────────────────────────────────────
188
+ /** Find review artifacts: each `features/<slug>/08_qe_report.md` plus any `REVIEW`-named markdown. Sorted. */
189
+ export function findReviewArtifacts(repoRoot) {
190
+ if (typeof repoRoot !== 'string' || repoRoot === '')
191
+ return []; // fail-open on bad runtime input (cross-model QE)
192
+ const candidates = [];
193
+ const featuresDir = join(repoRoot, 'features');
194
+ try {
195
+ if (existsSync(featuresDir)) {
196
+ for (const slug of readdirSync(featuresDir)) {
197
+ const qe = join(featuresDir, slug, '08_qe_report.md');
198
+ if (existsSync(qe))
199
+ candidates.push(`features/${slug}/08_qe_report.md`);
200
+ }
201
+ }
202
+ }
203
+ catch { /* ignore */ }
204
+ // Shallow scan of the repo root for REVIEW-named markdown (mr-review outputs land there).
205
+ try {
206
+ for (const entry of readdirSync(repoRoot)) {
207
+ if (/REVIEW.*\.md$/i.test(entry)) {
208
+ try {
209
+ if (statSync(join(repoRoot, entry)).isFile())
210
+ candidates.push(entry);
211
+ }
212
+ catch { /* ignore */ }
213
+ }
214
+ }
215
+ }
216
+ catch { /* ignore */ }
217
+ // Dedupe by PHYSICAL identity (realpath), not path string — two paths (e.g. a symlinked feature dir)
218
+ // pointing at ONE file must count as ONE source, else a single review fakes a rake (cross-model QE:
219
+ // the real load-bearing breach). Keep the first (sorted) relative path per physical file.
220
+ const seenReal = new Set();
221
+ const out = [];
222
+ for (const rel of uniqSorted(candidates)) {
223
+ let real;
224
+ try {
225
+ real = realpathSync(join(repoRoot, rel));
226
+ }
227
+ catch {
228
+ real = join(repoRoot, rel);
229
+ }
230
+ if (seenReal.has(real))
231
+ continue;
232
+ seenReal.add(real);
233
+ out.push(rel);
234
+ }
235
+ return out;
236
+ }
237
+ /** Analyze the whole repo corpus. Impure wrapper: find artifacts → extract → detect. Never throws. */
238
+ export function analyzeCorpus(repoRoot, thresholds = DEFAULT_RAKE_THRESHOLDS) {
239
+ const findings = [];
240
+ for (const rel of findReviewArtifacts(repoRoot)) {
241
+ try {
242
+ const md = readFileSync(join(repoRoot, rel), 'utf8');
243
+ findings.push(...extractFindings(md, rel));
244
+ }
245
+ catch { /* skip unreadable artifact */ }
246
+ }
247
+ return detectRakes(findings, thresholds);
248
+ }
249
+ //# sourceMappingURL=rake-analyzer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rake-analyzer.js","sourceRoot":"","sources":["../src/rake-analyzer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,MAAM,aAAa,GAA6B,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;AAoBvG,MAAM,CAAC,MAAM,uBAAuB,GAAmB,EAAE,SAAS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AC,GAAG,CAAC,IAAI,CAAC,CAAC;QACnB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,sGAAsG;AACtG,MAAM,UAAU,aAAa,CAAC,QAAgB,EAAE,aAA6B,uBAAuB;IAClG,MAAM,QAAQ,GAAc,EAAE,CAAC;IAC/B,KAAK,MAAM,GAAG,IAAI,mBAAmB,CAAC,QAAQ,CAAC,EAAE,CAAC;QAChD,IAAI,CAAC;YACH,MAAM,EAAE,GAAG,YAAY,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;YACrD,QAAQ,CAAC,IAAI,CAAC,GAAG,eAAe,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC;QAC7C,CAAC;QAAC,MAAM,CAAC,CAAC,8BAA8B,CAAC,CAAC;IAC5C,CAAC;IACD,OAAO,WAAW,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;AAC3C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dzhechkov/harness-core",
3
- "version": "0.3.111",
3
+ "version": "0.3.113",
4
4
  "description": "Shared harness logic - skill loading, additive apply, and the init/sync/verify/doctor operations.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,10 +33,10 @@
33
33
  "@dzhechkov/adapter-agents-md": "0.1.1",
34
34
  "@dzhechkov/adapter-copilot": "0.1.1",
35
35
  "@dzhechkov/adapter-gemini": "0.1.1",
36
+ "@dzhechkov/adapter-windsurf": "0.1.1",
36
37
  "@dzhechkov/core": "0.2.14",
37
- "@dzhechkov/adapter-cursor": "0.1.1",
38
38
  "@dzhechkov/memory": "0.2.9",
39
- "@dzhechkov/adapter-windsurf": "0.1.1"
39
+ "@dzhechkov/adapter-cursor": "0.1.1"
40
40
  },
41
41
  "peerDependenciesMeta": {
42
42
  "@ruvector/rvf": {
package/src/index.ts CHANGED
@@ -264,3 +264,5 @@ export type {
264
264
  } from './usage.js';
265
265
  export * from './safla-delta.js';
266
266
  export * from './architecture.js';
267
+ export * from './project-skills.js';
268
+ export * from './rake-analyzer.js';
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Polymorphic feature-adr (feature polymorphic-feature-adr, ADR-001).
3
+ *
4
+ * A COMMITTED per-project manifest (`architecture/project-skills.json`) declares the project-specific
5
+ * skills feature-adr should fold into its pipeline — so a generic pipeline becomes project-aware WITHOUT
6
+ * editing pipeline code (the Copilot `Orchestrates:` anti-pattern) and WITHOUT the skill self-declaring
7
+ * where it attaches (orchestration is the parent's job). Hybrid model: a CLOSED core-role enum with a
8
+ * fixed role→stage map, plus an open `extra` list. Guidance injection only in this release; `extra-phase`
9
+ * is accepted but skipped (fail-open, forward-compatible).
10
+ *
11
+ * The build/plan/render functions are PURE + deterministic (sorted, no clock/random) so the same manifest
12
+ * yields byte-identical plans; the load/resolve helpers do the disk I/O with TOP-LEVEL node:fs imports
13
+ * (harness-core is ESM — a lazy require() is undefined at runtime; the R1 footgun).
14
+ *
15
+ * SAFETY PROPERTY (ADR-001 Decision 3, load-bearing): with NO manifest the plan is empty and
16
+ * `guidanceForStage` returns '' — so `prompt + guidanceForStage(...)` is byte-identical to today. Every
17
+ * injection that DOES happen is named in the report (no silent injection).
18
+ */
19
+
20
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
21
+ import { join, resolve, isAbsolute, sep } from 'node:path';
22
+
23
+ /** The injectable pipeline stages a project skill can target. */
24
+ export type Stage = 'design' | 'code' | 'qe';
25
+
26
+ /** The CLOSED core-role enum (each has a fixed stage mapping). */
27
+ export type CoreRole = 'product-vision' | 'critic' | 'brand' | 'impl-bar';
28
+
29
+ export const CORE_ROLES: readonly CoreRole[] = ['product-vision', 'critic', 'brand', 'impl-bar'];
30
+
31
+ /** Fixed role→stage map (FR-3). product-vision informs design + QE; impl-bar the code; critic the QE; brand the code. */
32
+ export const ROLE_STAGES: Readonly<Record<CoreRole, readonly Stage[]>> = {
33
+ 'product-vision': ['design', 'qe'],
34
+ 'impl-bar': ['code'],
35
+ 'critic': ['qe'],
36
+ 'brand': ['code'],
37
+ };
38
+
39
+ /** Default doc for the product-vision role when the manifest omits it (the R1 seam). */
40
+ export const PRODUCT_VISION_DEFAULT = 'architecture/vision.md';
41
+
42
+ export interface ExtraSkill {
43
+ readonly skill: string; // repo-relative path to a doc / SKILL.md
44
+ readonly phase: Stage;
45
+ readonly as: 'guidance' | 'extra-phase';
46
+ readonly position?: 'before' | 'after'; // extra-phase only (deferred)
47
+ }
48
+
49
+ export interface ProjectSkillManifest {
50
+ readonly version: number;
51
+ readonly roles?: Partial<Record<CoreRole, string>>;
52
+ readonly extra?: readonly ExtraSkill[];
53
+ }
54
+
55
+ /** A validated manifest + the entries that were dropped (fail-open, NFR-2). */
56
+ export interface ValidatedManifest {
57
+ readonly manifest: ProjectSkillManifest | null;
58
+ readonly errors: readonly string[];
59
+ }
60
+
61
+ /** A source path resolved to its on-disk content, tagged with what it fills. */
62
+ export interface ResolvedItem {
63
+ readonly source: string; // repo-relative path
64
+ readonly role: CoreRole | 'extra';
65
+ readonly stages: readonly Stage[]; // stages this item feeds
66
+ readonly content: string;
67
+ }
68
+
69
+ /** One concrete guidance injection for one stage. */
70
+ export interface Injection {
71
+ readonly stage: Stage;
72
+ readonly source: string;
73
+ readonly role: CoreRole | 'extra';
74
+ readonly content: string;
75
+ }
76
+
77
+ export interface InjectionPlan {
78
+ readonly injections: readonly Injection[];
79
+ readonly skipped: readonly { readonly entry: string; readonly reason: string }[];
80
+ }
81
+
82
+ const byStr = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
83
+ const isStage = (s: unknown): s is Stage => s === 'design' || s === 'code' || s === 'qe';
84
+
85
+ const realOrNull = (p: string): string | null => { try { return realpathSync(p); } catch { return null; } };
86
+ const isContained = (root: string, abs: string): boolean => abs === root || abs.startsWith(root + sep);
87
+
88
+ /**
89
+ * Resolve a manifest-declared path to a SAFE absolute path inside repoRoot, or null if it escapes
90
+ * (absolute path, `../` traversal, or a symlink pointing outside). The manifest is committed, but a
91
+ * hostile/careless entry must never make the pipeline read `/etc/passwd` (cross-model QE High finding).
92
+ */
93
+ function safeResolve(repoRoot: string, relPath: string): string | null {
94
+ if (isAbsolute(relPath)) return null;
95
+ const abs = resolve(repoRoot, relPath);
96
+ if (!isContained(repoRoot, abs)) return null; // lexical `../` escape
97
+ if (existsSync(abs)) { // symlink-aware escape (only checkable when it exists)
98
+ const real = realOrNull(abs);
99
+ const rootReal = realOrNull(repoRoot) ?? repoRoot;
100
+ if (real !== null && !isContained(rootReal, real)) return null;
101
+ }
102
+ return abs;
103
+ }
104
+
105
+ /**
106
+ * Validate a parsed manifest object. FAIL-OPEN (NFR-2): a bad top-level shape → null + errors; a bad
107
+ * entry (unknown role key, missing fields, bad stage) is DROPPED with a reason, the rest survive. A
108
+ * config typo must never brick a run.
109
+ */
110
+ export function validateManifest(raw: unknown): ValidatedManifest {
111
+ const errors: string[] = [];
112
+ // An ARRAY is `typeof 'object'` but is NOT a valid manifest — reject it, else `[]` would sanitize to an
113
+ // empty manifest and silently activate the product-vision default (cross-model QE High finding).
114
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
115
+ return { manifest: null, errors: ['manifest must be a JSON object'] };
116
+ }
117
+ const obj = raw as Record<string, unknown>;
118
+
119
+ const roles: Partial<Record<CoreRole, string>> = {};
120
+ if (obj.roles !== undefined) {
121
+ if (obj.roles === null || typeof obj.roles !== 'object') {
122
+ errors.push('roles: not an object — ignored');
123
+ } else {
124
+ for (const [key, val] of Object.entries(obj.roles as Record<string, unknown>)) {
125
+ if (!CORE_ROLES.includes(key as CoreRole)) { errors.push(`roles.${key}: unknown role — skipped`); continue; }
126
+ if (typeof val !== 'string' || val.trim() === '') { errors.push(`roles.${key}: path must be a non-empty string — skipped`); continue; }
127
+ roles[key as CoreRole] = val;
128
+ }
129
+ }
130
+ }
131
+
132
+ const extra: ExtraSkill[] = [];
133
+ if (obj.extra !== undefined) {
134
+ if (!Array.isArray(obj.extra)) {
135
+ errors.push('extra: not an array — ignored');
136
+ } else {
137
+ obj.extra.forEach((e, i) => {
138
+ if (e === null || typeof e !== 'object') { errors.push(`extra[${i}]: not an object — skipped`); return; }
139
+ const ent = e as Record<string, unknown>;
140
+ if (typeof ent.skill !== 'string' || ent.skill.trim() === '') { errors.push(`extra[${i}].skill: missing path — skipped`); return; }
141
+ if (!isStage(ent.phase)) { errors.push(`extra[${i}].phase: must be design|code|qe — skipped`); return; }
142
+ if (ent.as !== 'guidance' && ent.as !== 'extra-phase') { errors.push(`extra[${i}].as: must be guidance|extra-phase — skipped`); return; }
143
+ if (ent.as === 'extra-phase') { errors.push(`extra[${i}] (${String(ent.skill)}): extra-phase is not supported yet (guidance-only release) — skipped`); return; }
144
+ const item: ExtraSkill = { skill: ent.skill, phase: ent.phase, as: 'guidance' };
145
+ extra.push(item);
146
+ });
147
+ }
148
+ }
149
+
150
+ return { manifest: { version: typeof obj.version === 'number' ? obj.version : 1, roles, extra }, errors };
151
+ }
152
+
153
+ /**
154
+ * Resolve each manifest entry to its on-disk content. Impure I/O (top-level fs; never throws). A missing
155
+ * file is DROPPED with a reason (fail-open). product-vision defaults to `architecture/vision.md` (FR-4)
156
+ * when the role is unset and the default exists.
157
+ */
158
+ export function resolveInjections(
159
+ repoRoot: string,
160
+ manifest: ProjectSkillManifest,
161
+ ): { resolved: ResolvedItem[]; skipped: { entry: string; reason: string }[] } {
162
+ const resolved: ResolvedItem[] = [];
163
+ const skipped: { entry: string; reason: string }[] = [];
164
+
165
+ // Read a manifest path SAFELY (contained in repoRoot). Returns {content} or a skip reason.
166
+ const read = (relPath: string): { content: string } | { reason: string } => {
167
+ const abs = safeResolve(repoRoot, relPath);
168
+ if (abs === null) return { reason: 'path escapes the repo — rejected' };
169
+ try {
170
+ return existsSync(abs) ? { content: readFileSync(abs, 'utf8') } : { reason: 'file not found' };
171
+ } catch { return { reason: 'unreadable' }; }
172
+ };
173
+
174
+ // Core roles (incl. the product-vision default).
175
+ for (const role of CORE_ROLES) {
176
+ const explicit = manifest.roles?.[role];
177
+ const path = explicit ?? (role === 'product-vision' ? PRODUCT_VISION_DEFAULT : undefined);
178
+ if (path === undefined) continue; // role not configured, no default
179
+ const r = read(path);
180
+ if (!('content' in r)) { skipped.push({ entry: `${role} → ${path}`, reason: r.reason }); continue; }
181
+ resolved.push({ source: path, role, stages: ROLE_STAGES[role], content: r.content });
182
+ }
183
+
184
+ // Extra guidance entries.
185
+ for (const e of manifest.extra ?? []) {
186
+ const r = read(e.skill);
187
+ if (!('content' in r)) { skipped.push({ entry: `extra → ${e.skill}`, reason: r.reason }); continue; }
188
+ resolved.push({ source: e.skill, role: 'extra', stages: [e.phase], content: r.content });
189
+ }
190
+
191
+ return { resolved, skipped };
192
+ }
193
+
194
+ /**
195
+ * Build the injection plan. PURE + deterministic: one Injection per (item, stage), sorted by
196
+ * (stage, source). The same resolved set always yields a byte-identical plan (ADR-001 §1).
197
+ */
198
+ export function buildInjectionPlan(
199
+ resolved: readonly ResolvedItem[],
200
+ skipped: readonly { entry: string; reason: string }[] = [],
201
+ ): InjectionPlan {
202
+ const injections: Injection[] = [];
203
+ for (const item of resolved) {
204
+ for (const stage of item.stages) {
205
+ injections.push({ stage, source: item.source, role: item.role, content: item.content });
206
+ }
207
+ }
208
+ injections.sort((a, b) => byStr(a.stage, b.stage) || byStr(a.source, b.source) || byStr(String(a.role), String(b.role)));
209
+ const skippedSorted = [...skipped].sort((a, b) => byStr(a.entry, b.entry));
210
+ return { injections, skipped: skippedSorted };
211
+ }
212
+
213
+ /**
214
+ * The guidance suffix for one stage — a concat of every injection targeting it, each with a provenance
215
+ * header. Returns '' when nothing targets the stage, so `prompt + guidanceForStage(...)` is byte-identical
216
+ * to the bare prompt on a no-manifest run (FR-7, load-bearing).
217
+ */
218
+ export function guidanceForStage(plan: InjectionPlan, stage: Stage): string {
219
+ const items = plan.injections.filter((i) => i.stage === stage);
220
+ if (items.length === 0) return '';
221
+ const blocks = items.map((i) => {
222
+ const tag = i.role === 'extra' ? `project skill ${i.source}` : `project ${i.role} (${i.source})`;
223
+ return `\n\n### Project-specific guidance — ${tag} (apply to this ${stage} step; injected via architecture/project-skills.json):\n${i.content.trim()}`;
224
+ });
225
+ return blocks.join('');
226
+ }
227
+
228
+ /** Human "who injected what" report (FR-6 — no silent injection). Deterministic. */
229
+ export function renderInjectionReport(plan: InjectionPlan): string {
230
+ if (plan.injections.length === 0 && plan.skipped.length === 0) {
231
+ return 'project-skills: no manifest / nothing injected (generic run).';
232
+ }
233
+ const lines: string[] = ['project-skills injections:'];
234
+ if (plan.injections.length === 0) lines.push(' (none applied)');
235
+ for (const i of plan.injections) {
236
+ const who = i.role === 'extra' ? `extra ${i.source}` : `${i.role} (${i.source})`;
237
+ lines.push(` • ${i.stage} ← ${who}`);
238
+ }
239
+ if (plan.skipped.length > 0) {
240
+ lines.push(' skipped:');
241
+ for (const s of plan.skipped) lines.push(` ⚠ ${s.entry} — ${s.reason}`);
242
+ }
243
+ return lines.join('\n');
244
+ }
245
+
246
+ /**
247
+ * Load + validate the project manifest (`architecture/project-skills.json`). Impure; returns null when
248
+ * absent OR unparseable OR top-level-invalid (fail-open) — a null means "generic run" (FR-7). Entry-level
249
+ * problems are kept on the returned manifest's implicit skip path (via validateManifest at resolve time).
250
+ */
251
+ export function loadProjectSkills(repoRoot: string): ProjectSkillManifest | null {
252
+ try {
253
+ const p = join(repoRoot, 'architecture', 'project-skills.json');
254
+ if (!existsSync(p)) return null;
255
+ const parsed = JSON.parse(readFileSync(p, 'utf8')) as unknown;
256
+ return validateManifest(parsed).manifest;
257
+ } catch {
258
+ return null;
259
+ }
260
+ }
261
+
262
+ /**
263
+ * One-shot convenience for the pipeline: load → validate → resolve → plan. Returns an EMPTY plan when
264
+ * there is no manifest file (FR-7 byte-identical). Validation problems (unknown role / bad entry) AND
265
+ * missing-file skips both surface in `plan.skipped` so the report hides nothing (FR-6). Impure.
266
+ */
267
+ export function planProjectSkills(repoRoot: string): InjectionPlan {
268
+ let parsed: unknown;
269
+ try {
270
+ const p = join(repoRoot, 'architecture', 'project-skills.json');
271
+ if (!existsSync(p)) return { injections: [], skipped: [] }; // no manifest file → generic run
272
+ parsed = JSON.parse(readFileSync(p, 'utf8'));
273
+ } catch (e) {
274
+ return { injections: [], skipped: [{ entry: 'architecture/project-skills.json', reason: 'unreadable/invalid JSON' }] };
275
+ }
276
+ const { manifest, errors } = validateManifest(parsed);
277
+ const validationSkips = errors.map((reason) => ({ entry: 'manifest', reason }));
278
+ if (manifest === null) return { injections: [], skipped: validationSkips };
279
+ const { resolved, skipped } = resolveInjections(repoRoot, manifest);
280
+ return buildInjectionPlan(resolved, [...skipped, ...validationSkips]);
281
+ }