@bluenyang/reins 0.1.0-rc.1 → 0.1.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.
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { isAbsolute, join, relative, sep } from 'node:path';
3
3
  import { harnessDir, readYaml } from '../lib/harness.js';
4
4
  import { loadSchemas, validateFile } from '../lib/schema.js';
5
5
  import { compound } from './gate.js';
@@ -85,7 +85,7 @@ function approvalChain(root, intent, ticket) {
85
85
  });
86
86
  else if (!list(p.data['tickets']).includes(ticket))
87
87
  out.push({
88
- reason: 'C2',
88
+ reason: 'P2',
89
89
  verdict: 'STOP',
90
90
  path: p.path,
91
91
  message: `ticket ${ticket} is not in the plan's tickets:`,
@@ -187,14 +187,33 @@ export function ticketStart(root, id) {
187
187
  /** What a raw evidence text says: the command line (`$ cmd`) and the exit code (`exit N`). */
188
188
  export function readEvidence(root, evidence) {
189
189
  const tokens = evidence.split(/\s+/).filter(Boolean);
190
- const files = tokens.length > 0 && tokens.every((t) => existsSync(join(root, t)));
191
- const pieces = files
192
- ? tokens.map((t) => ({ source: t, text: readFileSync(join(root, t), 'utf8') }))
193
- : [{ source: 'inline', text: evidence }];
190
+ // an absolute path inside the repository reads like a relative one; outside it is refused
191
+ const inside = (t) => {
192
+ const rel = relative(root, t);
193
+ return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
194
+ };
195
+ const outside = tokens.filter((t) => isAbsolute(t) && !inside(t));
196
+ const resolve = (t) => (isAbsolute(t) ? t : join(root, t));
197
+ const files = tokens.length > 0 && tokens.every((t) => existsSync(resolve(t)));
198
+ const pieces = outside.length > 0
199
+ ? outside.map((t) => ({ source: t, text: '', outside: true }))
200
+ : files
201
+ ? tokens.map((t) => ({
202
+ source: isAbsolute(t) ? relative(root, t) : t,
203
+ text: readFileSync(resolve(t), 'utf8'),
204
+ }))
205
+ : [{ source: 'inline', text: evidence }];
194
206
  return pieces.map((p) => {
207
+ const empty = !p.outside &&
208
+ p.text
209
+ .split(/\r?\n/)
210
+ .filter((l) => !l.startsWith('$ ') && !/^exit[: =]?\s*-?\d+\s*$/i.test(l))
211
+ .join('')
212
+ .trim() === '';
195
213
  const code = /^exit[: =]?\s*(-?\d+)\s*$/im.exec(p.text)?.[1];
196
214
  return {
197
215
  ...p,
216
+ empty,
198
217
  cmd: /^\$ (.+)$/m.exec(p.text)?.[1]?.trim(),
199
218
  exit: code === undefined ? undefined : Number(code),
200
219
  };
@@ -202,7 +221,17 @@ export function readEvidence(root, evidence) {
202
221
  }
203
222
  /** T3 — at a gate or test verdict: the latest verification of a ticket must be a real pass. */
204
223
  export function verdictCheck(root, id) {
205
- const verifies = busFor(root, id).filter((b) => b.request?.['kind'] === 'verify');
224
+ const bus = busFor(root, id);
225
+ const unreadable = bus.flatMap((b) => b.broken);
226
+ if (unreadable.length > 0)
227
+ return unreadable.map((u) => ({
228
+ reason: 'F2',
229
+ verdict: 'STOP',
230
+ path: u.path,
231
+ message: `bus file is not valid YAML: ${u.message}`,
232
+ resume: 'quote values containing ": " or " #" in double quotes, then re-run the check',
233
+ }));
234
+ const verifies = bus.filter((b) => b.request?.['kind'] === 'verify');
206
235
  if (verifies.length === 0)
207
236
  return [
208
237
  {
@@ -214,6 +243,27 @@ export function verdictCheck(root, id) {
214
243
  ];
215
244
  const findings = [];
216
245
  const last = verifies.at(-1);
246
+ const dir = harnessDir(root);
247
+ const schemas = dir ? loadSchemas(dir) : undefined;
248
+ const bad = [];
249
+ for (const [kind, name] of [
250
+ ['request', 'bus-request'],
251
+ ['response', 'bus-response'],
252
+ ]) {
253
+ const v = schemas?.get(name);
254
+ const rel = `.loctx/bus/${last.id}.${kind}.yaml`;
255
+ if (v && last[kind])
256
+ for (const i of validateFile(v, join(root, rel), true))
257
+ bad.push({
258
+ reason: 'F2',
259
+ verdict: 'STOP',
260
+ path: rel,
261
+ message: `${name}: ${i.message}`,
262
+ resume: 'fix the bus file against its schema, then re-run the check',
263
+ });
264
+ }
265
+ if (bad.length > 0)
266
+ return bad;
217
267
  if (!last.response)
218
268
  return [
219
269
  {
@@ -261,6 +311,24 @@ export function verdictCheck(root, id) {
261
311
  else
262
312
  for (const e of readEvidence(root, ev)) {
263
313
  const at2 = e.source === 'inline' ? at : `${at} → ${e.source}`;
314
+ if (e.outside) {
315
+ findings.push({
316
+ reason: 'D5',
317
+ verdict: 'STOP',
318
+ path: at2,
319
+ message: 'evidence path outside the repository',
320
+ resume: 'copy the gate output under .loctx/reports/ and cite that path',
321
+ });
322
+ continue;
323
+ }
324
+ if (e.empty)
325
+ findings.push({
326
+ reason: 'D4',
327
+ verdict: 'WARN',
328
+ path: at2,
329
+ message: 'gate output is empty',
330
+ resume: 'check that the gate produced output; attach it unabridged',
331
+ });
264
332
  if (e.exit === undefined)
265
333
  findings.push({
266
334
  reason: 'D4',
@@ -356,7 +424,7 @@ export function rcClose(root, release) {
356
424
  for (const o of open)
357
425
  if (o.data['intent'] === id && !planned.includes(str(o.data['id'])))
358
426
  findings.push({
359
- reason: 'C2',
427
+ reason: 'P2',
360
428
  verdict: 'STOP',
361
429
  path: o.path,
362
430
  message: `ticket ${str(o.data['id'])} is not in the plan of intent ${id}`,
@@ -18,6 +18,11 @@ function headingOf(block) {
18
18
  function outside(text) {
19
19
  return text.replace(BLOCK_RE, '');
20
20
  }
21
+ /** The project already has this block's `## <heading>` outside any managed block (applyBlocks leaves such a block out). */
22
+ export function hasOwnSection(text, block) {
23
+ const h = headingOf(block);
24
+ return h !== null && new RegExp(`^## ${h}\\s*$`, 'm').test(outside(text));
25
+ }
21
26
  /**
22
27
  * Put the upstream blocks into an AGENTS.md. Existing blocks are replaced in place; an overridden block is
23
28
  * left alone; a block whose heading the project already has outside any block is skipped (migrate replaces it).
@@ -41,7 +46,7 @@ export function applyBlocks(text, upstream) {
41
46
  continue;
42
47
  }
43
48
  const h = headingOf(b);
44
- if (h && new RegExp(`^## ${h}\\s*$`, 'm').test(outside(res.text))) {
49
+ if (hasOwnSection(res.text, b)) {
45
50
  res.skipped.push({
46
51
  name: b.name,
47
52
  why: `the project already has a "## ${h}" section — \`reins migrate\` replaces it`,
@@ -1,4 +1,4 @@
1
- import { execFileSync } from 'node:child_process';
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
2
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  export function generation(root) {
@@ -103,3 +103,93 @@ export function discoverGates(root) {
103
103
  }
104
104
  return res;
105
105
  }
106
+ /** Vendor of a model ID by prefix, in order: gpt, gemini, cursor-, else claude (spec S-2). */
107
+ export function vendorOf(model) {
108
+ if (model.startsWith('gpt'))
109
+ return 'openai';
110
+ if (model.startsWith('gemini'))
111
+ return 'google';
112
+ if (model.startsWith('cursor-'))
113
+ return 'cursor';
114
+ return 'claude';
115
+ }
116
+ /** Model IDs seen working in this environment. */
117
+ export const CONFIRMED_MODELS = new Set(['claude-opus-5-5', 'claude-fable-5-1']);
118
+ /** Runs `<cli> models` without a shell, stdin closed, 10 s limit. Nothing else is ever run. */
119
+ export const spawnModels = (cli, args) => {
120
+ if (process.env['REINS_NO_VENDOR_SPAWN'])
121
+ throw new Error(`refusing to spawn ${cli} under test`);
122
+ const r = spawnSync(cli, args, {
123
+ stdio: ['ignore', 'pipe', 'ignore'],
124
+ timeout: 10_000,
125
+ encoding: 'utf8',
126
+ });
127
+ const code = r.error?.code;
128
+ return {
129
+ status: r.status,
130
+ stdout: r.stdout ?? '',
131
+ timedOut: code === 'ETIMEDOUT',
132
+ error: r.error?.message,
133
+ };
134
+ };
135
+ const LISTERS = { google: 'agy', cursor: 'cursor-agent' };
136
+ // eslint-disable-next-line no-control-regex
137
+ const ANSI = /\u001b\[[0-9;?]*[A-Za-z]/g;
138
+ function parseModels(cli, out) {
139
+ const ids = [];
140
+ for (const line of out.replace(ANSI, '').split(/\r?\n/)) {
141
+ if (cli === 'agy') {
142
+ if (line.includes('\t'))
143
+ ids.push(line.split('\t')[0].trim());
144
+ }
145
+ else {
146
+ const m = /^(\S+) - .+$/.exec(line);
147
+ if (m)
148
+ ids.push(m[1]);
149
+ }
150
+ }
151
+ return ids.filter(Boolean);
152
+ }
153
+ /** `<cli> models` → model IDs, or the reason it could not be read. */
154
+ export function listModels(vendor, run = spawnModels) {
155
+ const cli = LISTERS[vendor];
156
+ const r = run(cli, ['models']);
157
+ if (r.timedOut)
158
+ return { failed: 'timed out after 10 s' };
159
+ if (r.error)
160
+ return { failed: r.error };
161
+ if (r.status !== 0)
162
+ return { failed: `exit ${r.status}` };
163
+ const ids = parseModels(cli, r.stdout);
164
+ return ids.length ? { ids } : { failed: 'no model IDs in output' };
165
+ }
166
+ export function newModelCache(o = {}) {
167
+ return {
168
+ run: o.run ?? spawnModels,
169
+ onPath: o.onPath ?? (process.env['REINS_NO_VENDOR_SPAWN'] ? () => false : onPath),
170
+ warn: o.warn ?? ((m) => void process.stderr.write(`warning: ${m}\n`)),
171
+ lists: new Map(),
172
+ };
173
+ }
174
+ /**
175
+ * Checks a binding against the vendor CLI's model list (spec S-3). Returns the fields to record,
176
+ * or null when the vendor has no list command or its CLI is absent. Never blocks, never changes the model.
177
+ */
178
+ export function checkBinding(model, vendor, cache) {
179
+ if (vendor !== 'google' && vendor !== 'cursor')
180
+ return null;
181
+ const cli = LISTERS[vendor];
182
+ if (!cache.onPath(cli))
183
+ return null;
184
+ let res = cache.lists.get(cli);
185
+ if (!res) {
186
+ res = listModels(vendor, cache.run);
187
+ cache.lists.set(cli, res);
188
+ }
189
+ if ('failed' in res)
190
+ return { unverified: true, note: `${cli} models failed: ${res.failed}` };
191
+ if (res.ids.includes(model))
192
+ return {};
193
+ cache.warn(`${model} is not in \`${cli} models\` — recorded as unverified`);
194
+ return { unverified: true, note: `not in ${cli} models` };
195
+ }
@@ -1,9 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
- import { join } from 'node:path';
4
2
  import { parse, stringify } from 'yaml';
5
- import { listFiles } from './fsx.js';
6
- import { redLines } from './harness.js';
3
+ import { workTreeReader } from './reader.js';
7
4
  import { splitFrontmatter } from './skills.js';
8
5
  /**
9
6
  * Vendor files generated from `.agents/harness/` (design §6). Round one generates Claude Code only:
@@ -11,8 +8,8 @@ import { splitFrontmatter } from './skills.js';
11
8
  */
12
9
  export const MANIFEST = '.agents/harness/generated.yaml';
13
10
  export const sha = (s) => createHash('sha256').update(s).digest('hex').slice(0, 16);
14
- function readRole(path) {
15
- const { data, body } = splitFrontmatter(readFileSync(path, 'utf8'));
11
+ function readRole(text) {
12
+ const { data, body } = splitFrontmatter(text);
16
13
  const d = data ?? {};
17
14
  return {
18
15
  role: String(d['role']),
@@ -65,8 +62,8 @@ export function claudeAgent(r, b, version) {
65
62
  ].join('\n');
66
63
  }
67
64
  /** C4 patterns → Claude Code deny rules. A pattern that would also hide an allowed template (`.env.*` vs `.env.example`) is narrowed. */
68
- export function denyRules(harness) {
69
- const c4 = redLines(harness).find((r) => r.id === 'C4');
65
+ export function denyRules(lines) {
66
+ const c4 = lines.find((r) => r.id === 'C4');
70
67
  const globs = new Set();
71
68
  for (const p of c4?.patterns ?? []) {
72
69
  if (p === '.env.*')
@@ -87,59 +84,59 @@ export function denyRules(harness) {
87
84
  for (const t of ['Read', 'Edit'])
88
85
  rules.push(`${t}(${g.startsWith('**/') ? g : `**/${g}`})`);
89
86
  // A1 force push and C5 hook bypass: the user runs these explicitly, never an agent
90
- rules.push('Bash(git push --force *)', 'Bash(git push -f *)', 'Bash(git push --force-with-lease *)', 'Bash(git commit --no-verify *)', 'Bash(git push --no-verify *)');
87
+ rules.push('Bash(git push --force *)', 'Bash(git push -f *)', 'Bash(git push --force-with-lease *)', 'Bash(git commit --no-verify *)', 'Bash(git commit -n *)', 'Bash(git push --no-verify *)');
91
88
  return rules;
92
89
  }
93
90
  /** Everything the generator owns, computed from the installed harness. Pure. */
94
- export function generateVendorFiles(root) {
95
- const harness = join(root, '.agents', 'harness');
96
- const bindingsPath = join(harness, 'bindings.yaml');
97
- const version = existsSync(join(harness, 'VERSION'))
98
- ? readFileSync(join(harness, 'VERSION'), 'utf8').trim()
99
- : '?';
91
+ export function generateVendorFiles(root, rd = workTreeReader(root)) {
92
+ const harness = '.agents/harness';
93
+ const version = rd.read(`${harness}/VERSION`)?.trim() ?? '?';
100
94
  const out = { writes: [], skipped: [] };
101
- if (!existsSync(harness))
95
+ if (rd.list(harness).length === 0)
102
96
  return out;
103
- const bindings = existsSync(bindingsPath)
104
- ? (parse(readFileSync(bindingsPath, 'utf8')).roles ??
105
- {})
97
+ const bindingsText = rd.read(`${harness}/bindings.yaml`);
98
+ const bindings = bindingsText
99
+ ? (parse(bindingsText).roles ?? {})
106
100
  : {};
107
- const rolesDir = join(harness, 'roles');
108
- if (existsSync(rolesDir))
109
- for (const f of readdirSync(rolesDir)
110
- .filter((x) => x.endsWith('.md'))
111
- .toSorted()) {
112
- const r = readRole(join(rolesDir, f));
113
- const b = bindings[r.role];
114
- if (!b)
115
- continue;
116
- if (b.vendor !== 'claude') {
117
- out.skipped.push(`${r.role} → ${b.vendor} ${b.model}`);
118
- continue;
119
- }
120
- out.writes.push({
121
- path: `.claude/agents/reins-${r.role}.md`,
122
- content: claudeAgent(r, b, version),
123
- why: `role ${r.role}`,
124
- });
101
+ const rolesDir = `${harness}/roles`;
102
+ for (const p of rd
103
+ .list(rolesDir)
104
+ .filter((x) => /^[^/]+\.md$/.test(x.slice(rolesDir.length + 1)))
105
+ .toSorted()) {
106
+ const r = readRole(rd.read(p) ?? '');
107
+ const b = bindings[r.role];
108
+ if (!b)
109
+ continue;
110
+ if (b.vendor !== 'claude') {
111
+ out.skipped.push(`${r.role} → ${b.vendor} ${b.model}`);
112
+ continue;
125
113
  }
114
+ out.writes.push({
115
+ path: `.claude/agents/reins-${r.role}.md`,
116
+ content: claudeAgent(r, b, version),
117
+ why: `role ${r.role}`,
118
+ });
119
+ }
126
120
  // skills: Codex, Gemini and Cursor read .agents/skills/ directly; Claude Code reads a byte-identical copy
127
- const skills = join(root, '.agents', 'skills');
128
- if (existsSync(skills))
129
- for (const name of readdirSync(skills).toSorted()) {
130
- if (!existsSync(join(skills, name, 'SKILL.md')))
131
- continue;
132
- for (const f of listFiles(join(skills, name)))
133
- out.writes.push({
134
- path: `.claude/skills/${name}/${f}`,
135
- content: readFileSync(join(skills, name, f), 'utf8'),
136
- why: `skill ${name}`,
137
- });
138
- }
139
- if (existsSync(join(harness, 'policy')))
121
+ const skills = '.agents/skills';
122
+ const names = [
123
+ ...new Set(rd.list(skills).map((p) => p.slice(skills.length + 1).split('/')[0] ?? '')),
124
+ ].toSorted();
125
+ for (const name of names) {
126
+ if (rd.read(`${skills}/${name}/SKILL.md`) === undefined)
127
+ continue;
128
+ for (const p of rd.list(`${skills}/${name}`).toSorted())
129
+ out.writes.push({
130
+ path: `.claude/skills/${p.slice(skills.length + 1)}`,
131
+ content: rd.read(p) ?? '',
132
+ why: `skill ${name}`,
133
+ });
134
+ }
135
+ const redText = rd.read(`${harness}/policy/common-red-lines.yaml`);
136
+ if (rd.list(`${harness}/policy`).length > 0 && redText !== undefined)
140
137
  out.writes.push({
141
138
  path: '.claude/settings.json',
142
- content: `${JSON.stringify({ $schema: 'https://json.schemastore.org/claude-code-settings.json', permissions: { deny: denyRules(harness) } }, null, 2)}\n`,
139
+ content: `${JSON.stringify({ $schema: 'https://json.schemastore.org/claude-code-settings.json', permissions: { deny: denyRules(parse(redText).rules) } }, null, 2)}\n`,
143
140
  why: 'C4 secrets, A1 force push, C5 hook bypass',
144
141
  });
145
142
  return out;
@@ -10,8 +10,19 @@ export function stagedFiles(cwd) {
10
10
  const out = git(['diff', '--cached', '--name-only', '--diff-filter=ACMR'], cwd);
11
11
  return out ? out.split('\n') : [];
12
12
  }
13
+ /** The checked-out branch; on a repository without commits `rev-parse` fails, so ask for the symbolic ref instead. */
13
14
  export function currentBranch(cwd) {
14
- return git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd);
15
+ try {
16
+ return git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd);
17
+ }
18
+ catch {
19
+ try {
20
+ return git(['symbolic-ref', '--short', 'HEAD'], cwd);
21
+ }
22
+ catch {
23
+ return '';
24
+ }
25
+ }
15
26
  }
16
27
  export function isAncestor(ancestor, descendant, cwd) {
17
28
  try {
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { parse } from 'yaml';
4
+ import { workTreeReader } from './reader.js';
4
5
  /**
5
6
  * Where the harness sources live: an installed project has `.agents/harness/`;
6
7
  * this repository (the upstream) keeps them at `harness/`.
@@ -12,6 +13,13 @@ export function harnessDir(root) {
12
13
  }
13
14
  return null;
14
15
  }
16
+ /** Like `harnessDir`, but repository-relative and read through a `Reader` (the index, for pre-commit). */
17
+ export function harnessRel(rd) {
18
+ for (const d of ['.agents/harness', 'harness'])
19
+ if (rd.list(`${d}/policy`).length > 0)
20
+ return d;
21
+ return null;
22
+ }
15
23
  export function readYaml(path) {
16
24
  return parse(readFileSync(path, 'utf8'));
17
25
  }
@@ -22,11 +30,14 @@ export function stops(dir) {
22
30
  return readYaml(join(dir, 'policy', 'stops.yaml')).stops;
23
31
  }
24
32
  /** Secret patterns from red line C4, or null when there is no harness to read. */
25
- export function secretPolicy(root) {
26
- const dir = harnessDir(root);
27
- if (!dir)
33
+ export function secretPolicy(root, rd = workTreeReader(root)) {
34
+ const rel = harnessRel(rd);
35
+ if (!rel)
36
+ return null;
37
+ const text = rd.read(`${rel}/policy/common-red-lines.yaml`);
38
+ if (text === undefined)
28
39
  return null;
29
- const c4 = redLines(dir).find((r) => r.id === 'C4');
40
+ const c4 = parse(text).rules.find((r) => r.id === 'C4');
30
41
  if (!c4?.patterns)
31
42
  return null;
32
43
  return { patterns: c4.patterns, allowed: c4.allowed ?? [] };
@@ -111,9 +111,12 @@ export function readMetrics(root) {
111
111
  }
112
112
  return { records, broken };
113
113
  }
114
+ /** Stop ids renamed in harness 0.1.1: old records carry the red-line-looking C1 and C2. */
115
+ const LEGACY_IDS = { C1: 'P1', C2: 'P2' };
114
116
  /**
115
117
  * Counts blocking reason ids by kind. An id found in stops.yaml counts as that stop's kind
116
- * (so C1 and C2 are knowledge stops); otherwise an id in common-red-lines.yaml is a redline;
118
+ * (so P1 and P2 are knowledge stops; old C1 and C2 read as P1 and P2); otherwise an id in
119
+ * common-red-lines.yaml is a redline;
117
120
  * an id in neither is not counted and stays in `reasons` only. Each distinct id counts once.
118
121
  */
119
122
  export function classify(reasons, harness) {
@@ -129,7 +132,7 @@ export function classify(reasons, harness) {
129
132
  catch {
130
133
  return out;
131
134
  }
132
- for (const id of new Set(reasons)) {
135
+ for (const id of new Set(reasons.map((r) => LEGACY_IDS[r] ?? r))) {
133
136
  const k = kinds.get(id);
134
137
  if (k)
135
138
  out[k]++;
@@ -0,0 +1,47 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ export function workTreeReader(root) {
5
+ const walk = (rel, out) => {
6
+ const abs = join(root, rel);
7
+ if (!existsSync(abs))
8
+ return out;
9
+ for (const e of readdirSync(abs)) {
10
+ const r = `${rel}/${e}`;
11
+ if (statSync(join(root, r)).isDirectory())
12
+ walk(r, out);
13
+ else
14
+ out.push(r);
15
+ }
16
+ return out;
17
+ };
18
+ return {
19
+ read: (rel) => {
20
+ const abs = join(root, rel);
21
+ return existsSync(abs) && statSync(abs).isFile() ? readFileSync(abs, 'utf8') : undefined;
22
+ },
23
+ list: (relDir) => walk(relDir.replace(/\/$/, ''), []),
24
+ };
25
+ }
26
+ /** Reads with `git show :<path>`; a path that is not in the index is absent. Only the paths asked for are read. */
27
+ export function indexReader(root) {
28
+ const run = (args) => {
29
+ try {
30
+ return execFileSync('git', args, {
31
+ cwd: root,
32
+ encoding: 'utf8',
33
+ maxBuffer: 64 * 1024 * 1024,
34
+ stdio: ['ignore', 'pipe', 'ignore'],
35
+ });
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ };
41
+ return {
42
+ read: (rel) => run(['show', `:${rel}`]),
43
+ list: (relDir) => (run(['ls-files', '-z', '--', `${relDir.replace(/\/$/, '')}/`]) ?? '')
44
+ .split('\0')
45
+ .filter(Boolean),
46
+ };
47
+ }
@@ -3,6 +3,27 @@ import { basename, join } from 'node:path';
3
3
  import { Ajv2020 } from 'ajv/dist/2020.js';
4
4
  import { parse } from 'yaml';
5
5
  import { splitFrontmatter } from './skills.js';
6
+ /** The same, read through a `Reader` from a repository-relative harness directory. */
7
+ export function loadSchemasFrom(rd, harnessRel) {
8
+ const dir = `${harnessRel}/schemas`;
9
+ const ajv = new Ajv2020({ allErrors: true, strict: false });
10
+ const ids = new Map();
11
+ for (const p of rd
12
+ .list(dir)
13
+ .filter((x) => /^[^/]+\.schema\.json$/.test(x.slice(dir.length + 1)))) {
14
+ const schema = JSON.parse(rd.read(p) ?? '{}');
15
+ ajv.addSchema(schema);
16
+ if (schema.$id)
17
+ ids.set(p.slice(dir.length + 1).replace(/\.schema\.json$/, ''), schema.$id);
18
+ }
19
+ const out = new Map();
20
+ for (const [name, id] of ids) {
21
+ const v = ajv.getSchema(id);
22
+ if (v)
23
+ out.set(name, v);
24
+ }
25
+ return out;
26
+ }
6
27
  /** Loads every `*.schema.json` in the harness and compiles them by file name (`intent`, `bus-request`, …). */
7
28
  export function loadSchemas(harness) {
8
29
  const dir = join(harness, 'schemas');
@@ -30,8 +51,8 @@ function errors(v, path) {
30
51
  }));
31
52
  }
32
53
  /** Validates a Markdown file's YAML frontmatter, or a whole YAML file when `whole` is set. */
33
- export function validateFile(v, path, whole = false) {
34
- const text = readFileSync(path, 'utf8');
54
+ export function validateFile(v, path, whole = false, content) {
55
+ const text = content ?? readFileSync(path, 'utf8');
35
56
  let data;
36
57
  let error;
37
58
  if (whole) {
@@ -16,10 +16,10 @@ export function splitFrontmatter(text) {
16
16
  return { data: null, body: m[2] ?? '', error: e.message.split('\n')[0] };
17
17
  }
18
18
  }
19
- export function validateSkillFile(path) {
19
+ export function validateSkillFile(path, content) {
20
20
  const issues = [];
21
21
  const dir = basename(join(path, '..'));
22
- const text = readFileSync(path, 'utf8');
22
+ const text = content ?? readFileSync(path, 'utf8');
23
23
  const { data, body, error } = splitFrontmatter(text);
24
24
  if (!data)
25
25
  return [
@@ -2,11 +2,12 @@ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from '
2
2
  import { dirname, join } from 'node:path';
3
3
  import { parse, stringify } from 'yaml';
4
4
  import { MANIFEST, generateVendorFiles, sha } from './generate.js';
5
- export function readManifest(root) {
6
- const p = join(root, MANIFEST);
7
- if (!existsSync(p))
5
+ import { workTreeReader } from './reader.js';
6
+ export function readManifest(root, rd = workTreeReader(root)) {
7
+ const text = rd.read(MANIFEST);
8
+ if (text === undefined)
8
9
  return { schema: 'reins/generated@1', files: {} };
9
- const m = parse(readFileSync(p, 'utf8'));
10
+ const m = parse(text);
10
11
  return { schema: 'reins/generated@1', files: m?.files ?? {} };
11
12
  }
12
13
  /**
@@ -87,15 +88,15 @@ export function writeGenerated(root, gen, dryRun) {
87
88
  return res;
88
89
  }
89
90
  /** Drift, match layer for generated files: on disk = what reins wrote = what it would write now. */
90
- export function driftGenerated(root) {
91
- if (!existsSync(join(root, MANIFEST)))
91
+ export function driftGenerated(root, rd = workTreeReader(root)) {
92
+ if (rd.read(MANIFEST) === undefined)
92
93
  return [];
93
94
  const findings = [];
94
- const recorded = readManifest(root).files;
95
- const now = new Map(generateVendorFiles(root).writes.map((w) => [w.path, sha(w.content)]));
95
+ const recorded = readManifest(root, rd).files;
96
+ const now = new Map(generateVendorFiles(root, rd).writes.map((w) => [w.path, sha(w.content)]));
96
97
  for (const [path, hash] of Object.entries(recorded)) {
97
- const abs = join(root, path);
98
- if (!existsSync(abs)) {
98
+ const onDisk = rd.read(path);
99
+ if (onDisk === undefined) {
99
100
  findings.push({
100
101
  reason: 'F2',
101
102
  verdict: 'STOP',
@@ -105,7 +106,7 @@ export function driftGenerated(root) {
105
106
  });
106
107
  continue;
107
108
  }
108
- if (sha(readFileSync(abs, 'utf8')) !== hash)
109
+ if (sha(onDisk) !== hash)
109
110
  findings.push({
110
111
  reason: 'C3',
111
112
  verdict: 'STOP',