@bluenyang/reins 0.2.0 → 0.3.0-rc.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 (95) hide show
  1. package/README.md +50 -203
  2. package/cli/dist/commands/config-models.js +175 -126
  3. package/cli/dist/commands/config.js +96 -15
  4. package/cli/dist/commands/configure.js +165 -138
  5. package/cli/dist/commands/install.js +161 -217
  6. package/cli/dist/commands/migrate.js +23 -48
  7. package/cli/dist/commands/update.js +203 -30
  8. package/cli/dist/lib/agents-md.js +102 -0
  9. package/cli/dist/lib/bindings.js +227 -386
  10. package/cli/dist/lib/detect.js +7 -2
  11. package/cli/dist/lib/generate.js +56 -75
  12. package/cli/dist/lib/harness.js +0 -3
  13. package/cli/dist/lib/migrate-plan.js +3 -3
  14. package/cli/dist/lib/reader.js +20 -0
  15. package/cli/dist/lib/upstream.js +0 -17
  16. package/cli/dist/lib/vendor-write.js +9 -56
  17. package/cli/dist/reins.js +59 -270
  18. package/docs/README.ko.md +31 -204
  19. package/harness/CHANGELOG.md +7 -3
  20. package/harness/VERSION +1 -1
  21. package/harness/policy/common-red-lines.yaml +4 -4
  22. package/harness/roles/advisor.md +10 -14
  23. package/harness/roles/auditor.md +17 -0
  24. package/harness/roles/executor.md +32 -0
  25. package/harness/roles/implementer.md +23 -21
  26. package/harness/roles/pl.md +44 -21
  27. package/harness/roles/planner.md +17 -19
  28. package/harness/roles/pm.md +16 -21
  29. package/harness/schemas/bindings.schema.json +55 -0
  30. package/harness/schemas/install.schema.json +1 -2
  31. package/harness/schemas/intent.schema.json +1 -13
  32. package/harness/templates/agents-md-blocks.md +52 -17
  33. package/harness/templates/audit.md +25 -0
  34. package/harness/templates/history.md +14 -0
  35. package/harness/templates/intent.md +5 -0
  36. package/harness/templates/spec.md +4 -2
  37. package/package.json +1 -2
  38. package/skills/audit/SKILL.md +28 -0
  39. package/skills/implement/SKILL.md +30 -0
  40. package/skills/intent/SKILL.md +28 -0
  41. package/skills/merge/SKILL.md +26 -0
  42. package/skills/onboard/SKILL.md +29 -0
  43. package/skills/reins-setup/SKILL.md +16 -25
  44. package/skills/release/SKILL.md +26 -0
  45. package/skills/retro/SKILL.md +30 -0
  46. package/skills/review/SKILL.md +27 -0
  47. package/skills/roadmap/SKILL.md +29 -0
  48. package/skills/spec/SKILL.md +27 -0
  49. package/skills/test/SKILL.md +26 -0
  50. package/cli/dist/commands/check.js +0 -379
  51. package/cli/dist/commands/gate.js +0 -136
  52. package/cli/dist/commands/knowledge.js +0 -111
  53. package/cli/dist/commands/metrics.js +0 -138
  54. package/cli/dist/commands/new.js +0 -190
  55. package/cli/dist/commands/retro.js +0 -7
  56. package/cli/dist/commands/stages.js +0 -562
  57. package/cli/dist/commands/status.js +0 -281
  58. package/cli/dist/lib/enforcement.js +0 -125
  59. package/cli/dist/lib/memory.js +0 -96
  60. package/cli/dist/lib/metrics.js +0 -223
  61. package/cli/dist/lib/retro.js +0 -179
  62. package/cli/dist/lib/verdict.js +0 -15
  63. package/cli/dist/lib/work.js +0 -106
  64. package/cli/dist/scripts/enforcement.js +0 -24
  65. package/harness/policy/budget.yaml +0 -13
  66. package/harness/policy/enforcement.yaml +0 -98
  67. package/harness/policy/stops.yaml +0 -29
  68. package/harness/policy/transitions.yaml +0 -13
  69. package/harness/roles/code-review.md +0 -27
  70. package/harness/roles/deploy.md +0 -50
  71. package/harness/roles/docs.md +0 -19
  72. package/harness/roles/lookup.md +0 -22
  73. package/harness/roles/qa-design.md +0 -22
  74. package/harness/roles/qa-run.md +0 -19
  75. package/harness/roles/verify-tool.md +0 -21
  76. package/harness/schemas/bindings-local.schema.json +0 -21
  77. package/harness/schemas/bus-request.schema.json +0 -17
  78. package/harness/schemas/bus-response.schema.json +0 -14
  79. package/harness/schemas/enforcement.schema.json +0 -22
  80. package/harness/schemas/plan.schema.json +0 -10
  81. package/harness/schemas/ticket.schema.json +0 -15
  82. package/harness/templates/bus/request.yaml +0 -20
  83. package/harness/templates/bus/response.yaml +0 -10
  84. package/harness/templates/plan.md +0 -23
  85. package/harness/templates/ticket.md +0 -29
  86. package/skills/reins-implement/SKILL.md +0 -20
  87. package/skills/reins-intent/SKILL.md +0 -26
  88. package/skills/reins-loop/SKILL.md +0 -26
  89. package/skills/reins-loop/references/vendor-cli.md +0 -41
  90. package/skills/reins-release/SKILL.md +0 -18
  91. package/skills/reins-retro/SKILL.md +0 -20
  92. package/skills/reins-review/SKILL.md +0 -23
  93. package/skills/reins-roadmap/SKILL.md +0 -17
  94. package/skills/reins-spec/SKILL.md +0 -22
  95. package/skills/reins-test/SKILL.md +0 -18
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: test
3
+ description: Run the spec's checks (V-n) exactly as written and judge each against its expected result, keeping the raw output. Use when every work unit of the version is reviewed.
4
+ ---
5
+
6
+ # test
7
+
8
+ ## 1. When
9
+ Every work unit of the version is reviewed.
10
+
11
+ ## 2. Procedure
12
+ 1. Build, then run every check V-n as written. Keep the raw output under `.loctx/reports/<version>/`.
13
+ 2. Judge each against its expected result. Ambiguous is a fail.
14
+ 3. A fail goes back to the PM → `implement`.
15
+
16
+ ## 3. Delegation
17
+ Check the delegation table in AGENTS.md. If the role group named here has a model, hand it the work with the list of files and decisions it needs and wait for its report; otherwise do it yourself. Read-heavy work (research, large log summaries, review) or urgent parallel work on independent units may go to subagents of your own model. A role never calls another model; it returns to you. Executor (qa-runner) runs the checks when switched on; tool-executor summarises a large log.
18
+
19
+ ## 4. Files and lifetime
20
+ - `.loctx/reports/<version>/` test logs — deleted after the retro, once summarised.
21
+
22
+ ## 5. Next
23
+ `merge`.
24
+
25
+ ## 6. Stop and ask
26
+ - Never change a check or its expected result to make it pass.
@@ -1,379 +0,0 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { basename, join } from 'node:path';
3
- import { hasOwnSection, overrides, parseBlocks } from '../lib/blocks.js';
4
- import { currentBranch, isAncestor, pushedSubjects, repoRoot, stagedFiles } from '../lib/git.js';
5
- import { harnessRel, secretPolicy } from '../lib/harness.js';
6
- import { loadSchemasFrom, schemaFor, validateFile } from '../lib/schema.js';
7
- import { DEFAULT_ALLOWED, DEFAULT_SECRET_PATTERNS, isSecretPath } from '../lib/secrets.js';
8
- import { splitFrontmatter, validateSkillFile } from '../lib/skills.js';
9
- import { harnessVersion, packageHarness, packageSkills, tierSkills } from '../lib/upstream.js';
10
- import { listFiles, relPath } from '../lib/fsx.js';
11
- import { driftGenerated } from '../lib/vendor-write.js';
12
- import { indexReader, workTreeReader } from '../lib/reader.js';
13
- import { PROJECT_OWNED, tierFiles } from './install.js';
14
- import { rcClose, ticketStart, verdictCheck } from './stages.js';
15
- import { parse } from 'yaml';
16
- import { report } from '../lib/verdict.js';
17
- export const STAGES = ['ticket-start', 'pre-commit', 'verdict', 'pre-push', 'rc-close'];
18
- const SKILL_ROOTS = ['skills', '.agents/skills', '.claude/skills'];
19
- const LOCAL_DIRS = ['.loctx/', '.ai/'];
20
- function gitignoreHas(root, entry) {
21
- const p = join(root, '.gitignore');
22
- if (!existsSync(p))
23
- return false;
24
- const lines = readFileSync(p, 'utf8')
25
- .split('\n')
26
- .map((l) => l.trim());
27
- const bare = entry.replace(/\/$/, '');
28
- return lines.some((l) => l === entry || l === bare || l === `/${entry}` || l === `/${bare}`);
29
- }
30
- /** T2 — before a commit. */
31
- export function preCommit(root) {
32
- const findings = [];
33
- const rd = indexReader(root);
34
- const policy = secretPolicy(root, rd);
35
- const patterns = policy?.patterns ?? DEFAULT_SECRET_PATTERNS;
36
- const allowed = policy?.allowed ?? DEFAULT_ALLOWED;
37
- const staged = stagedFiles(root);
38
- for (const f of staged) {
39
- const hit = isSecretPath(f, patterns, allowed);
40
- if (hit)
41
- findings.push({
42
- reason: 'C4',
43
- verdict: 'STOP',
44
- path: f,
45
- message: `staged file matches secret pattern "${hit}"`,
46
- resume: `git restore --staged -- "${f}" and add it to .gitignore`,
47
- });
48
- for (const d of LOCAL_DIRS)
49
- if (f.startsWith(d))
50
- findings.push({
51
- reason: 'F2',
52
- verdict: 'STOP',
53
- path: f,
54
- message: `${d} is local-only and must not be committed`,
55
- resume: `git restore --staged -- "${f}"; ensure "${d}" is in .gitignore`,
56
- });
57
- }
58
- const hasLocal = LOCAL_DIRS.some((d) => existsSync(join(root, d)));
59
- if (hasLocal && !LOCAL_DIRS.some((d) => gitignoreHas(root, d)))
60
- findings.push({
61
- reason: 'F2',
62
- verdict: 'STOP',
63
- message: 'local workspace exists but is not in .gitignore',
64
- resume: 'add ".loctx/" (or ".ai/") to .gitignore',
65
- });
66
- // S-1: the checks read the content the commit would contain (the index), not the working tree
67
- findings.push(...driftFormat(root, staged, rd), ...driftConvention(root, staged, rd));
68
- const under = (...dirs) => staged.some((f) => dirs.some((d) => f.startsWith(d)));
69
- if (under('harness/', '.agents/harness/', 'skills/', '.agents/skills/'))
70
- findings.push(...driftMatch(root, rd));
71
- if (staged.includes('AGENTS.md'))
72
- findings.push(...driftBlocks(root, rd));
73
- if (under('.claude/', '.agents/harness/', '.agents/skills/'))
74
- findings.push(...driftGenerated(root, rd));
75
- return findings;
76
- }
77
- /** T4 — before leaving the machine. */
78
- export function prePush(root, refs) {
79
- const findings = [];
80
- const ZERO = /^0+$/;
81
- for (const line of refs) {
82
- const [localRef, localSha, remoteRef, remoteSha] = line.trim().split(/\s+/);
83
- if (!localSha || !remoteSha || !remoteRef)
84
- continue;
85
- if (/^refs\/heads\/(master|main)$/.test(remoteRef)) {
86
- // design §3 T4: work reaches the default branch by PR only; the publish workflow's version commit is the one exception
87
- // creating or deleting the ref has no range to judge: always held
88
- const subjects = ZERO.test(localSha) || ZERO.test(remoteSha)
89
- ? []
90
- : pushedSubjects(remoteSha, localSha, root);
91
- const releaseOnly = process.env.GITHUB_ACTIONS === 'true' &&
92
- subjects.length > 0 &&
93
- subjects.every((m) => m.startsWith('release: v'));
94
- if (!releaseOnly)
95
- findings.push({
96
- reason: 'A4',
97
- verdict: 'HOLD',
98
- path: remoteRef,
99
- message: `push to ${remoteRef.slice('refs/heads/'.length)} outside the PR flow`,
100
- resume: 'push a type/topic branch and open a PR; the deploy role merges it when checks are green',
101
- });
102
- }
103
- if (ZERO.test(localSha) && remoteRef.startsWith('refs/tags/')) {
104
- findings.push({
105
- reason: 'A1',
106
- verdict: 'HOLD',
107
- path: remoteRef,
108
- message: `push deletes tag ${remoteRef.slice('refs/tags/'.length)}`,
109
- resume: 'deleting a published tag is irreversible — the user must run it explicitly',
110
- });
111
- continue;
112
- }
113
- if (ZERO.test(remoteSha) || ZERO.test(localSha))
114
- continue; // new ref or branch deletion
115
- if (!isAncestor(remoteSha, localSha, root))
116
- findings.push({
117
- reason: 'A1',
118
- verdict: 'HOLD',
119
- path: remoteRef,
120
- message: `push of ${localRef ?? '?'} would rewrite ${remoteRef} (remote commit is not an ancestor)`,
121
- resume: 'this is a force push — the user must run it explicitly, every time',
122
- });
123
- }
124
- return findings;
125
- }
126
- /** Drift, format layer — Agent Skills spec on SKILL.md files. */
127
- export function driftFormat(root, only, rd = workTreeReader(root)) {
128
- const files = SKILL_ROOTS.flatMap((r) => rd.list(r).filter((p) => /^[^/]+\/SKILL\.md$/.test(p.slice(r.length + 1))));
129
- const chosen = only ? files.filter((f) => only.includes(f)) : files;
130
- return chosen.flatMap((f) => validateSkillFile(join(root, f), rd.read(f)).map((i) => ({
131
- reason: 'F2',
132
- verdict: 'STOP',
133
- path: relPath(root, i.path),
134
- message: i.message,
135
- resume: 'fix the SKILL.md frontmatter; see agentskills.io/specification',
136
- })));
137
- }
138
- /** Drift, convention layer — frontmatter schemas and role files (design §6). */
139
- export function driftConvention(root, only, rd = workTreeReader(root)) {
140
- const hrel = harnessRel(rd);
141
- if (!hrel)
142
- return [];
143
- const schemas = loadSchemasFrom(rd, hrel);
144
- const findings = [];
145
- const candidates = [
146
- `${hrel}/install.yaml`,
147
- ...rd.list(`${hrel}/templates`),
148
- ...rd.list(`${hrel}/knowledge-seeds`),
149
- ...rd.list('.agents/intent'),
150
- ...rd.list('.agents/knowledge'),
151
- ...rd.list('.loctx/ticket'),
152
- ...rd.list('.loctx/bus'),
153
- ];
154
- for (const rel of candidates) {
155
- if (only && !only.includes(rel))
156
- continue;
157
- const text = rd.read(rel);
158
- if (text === undefined)
159
- continue;
160
- const m = schemaFor(rel);
161
- if (!m)
162
- continue;
163
- const v = schemas.get(m.schema);
164
- if (!v)
165
- continue;
166
- if (m.schema === 'knowledge' && rel.startsWith('.agents/knowledge/')) {
167
- // design §8: an entry reaches .agents/knowledge/ only through the user's approval (presets ship with the package)
168
- const { data } = splitFrontmatter(text);
169
- const ap = data?.['approved'];
170
- if (data && data['source'] !== 'preset' && !(ap && typeof ap.by === 'string' && ap.by))
171
- findings.push({
172
- reason: 'F2',
173
- verdict: 'STOP',
174
- path: rel,
175
- message: 'knowledge entry without approved',
176
- resume: 'propose it with reins knowledge propose; the user approves, then reins knowledge accept',
177
- });
178
- }
179
- for (const i of validateFile(v, join(root, rel), m.whole, text))
180
- findings.push({
181
- reason: 'F2',
182
- verdict: 'STOP',
183
- path: rel,
184
- message: `${m.schema}: ${i.message}`,
185
- resume: `fix the frontmatter to match ${m.schema}.schema.json`,
186
- });
187
- }
188
- // role files: role == file name, must_not present
189
- const roles = `${hrel}/roles`;
190
- for (const rel of rd.list(roles).filter((x) => /^[^/]+\.md$/.test(x.slice(roles.length + 1)))) {
191
- if (only && !only.includes(rel))
192
- continue;
193
- const { data, error } = splitFrontmatter(rd.read(rel) ?? '');
194
- const name = basename(rel, '.md');
195
- if (error)
196
- findings.push({
197
- reason: 'F2',
198
- verdict: 'STOP',
199
- path: rel,
200
- message: `frontmatter is not valid YAML: ${error}`,
201
- });
202
- else if (!data || data['role'] !== name)
203
- findings.push({
204
- reason: 'F2',
205
- verdict: 'STOP',
206
- path: rel,
207
- message: `role file must declare role: ${name}`,
208
- });
209
- else if (!Array.isArray(data['must_not']) || data['must_not'].length === 0)
210
- findings.push({
211
- reason: 'F2',
212
- verdict: 'STOP',
213
- path: rel,
214
- message: 'must_not is the enforced source and cannot be empty',
215
- });
216
- }
217
- return findings;
218
- }
219
- /** Files in an installed harness that belong to the project, not upstream. */
220
- /** Drift, match layer — the installed `.agents/harness/` against the packaged upstream at the pinned version (design §6). */
221
- export function driftMatch(root, rd = workTreeReader(root)) {
222
- const installed = '.agents/harness';
223
- const pinText = rd.read(`${installed}/install.yaml`);
224
- if (pinText === undefined)
225
- return [];
226
- let up;
227
- try {
228
- up = packageHarness();
229
- }
230
- catch {
231
- return [];
232
- }
233
- const pinned = parse(pinText);
234
- const pin = pinned.version;
235
- const upVersion = harnessVersion(up);
236
- if (pin !== upVersion)
237
- return [
238
- {
239
- reason: 'F2',
240
- verdict: 'WARN',
241
- path: '.agents/harness/install.yaml',
242
- message: `installed harness is v${pin}, upstream is v${upVersion}`,
243
- resume: 'run `reins update`',
244
- },
245
- ];
246
- const findings = [];
247
- // only files this tier installs are compared; an upstream file it no longer installs (e.g. CHANGELOG.md
248
- // from a 0.1.0 install) is a leftover that `reins update` removes, not a hand edit
249
- const installs = new Set(tierFiles(listFiles(up), (pinned.tier ?? 'graph')));
250
- for (const entry of rd.list(installed)) {
251
- const rel = entry.slice(installed.length + 1);
252
- if (PROJECT_OWNED.has(rel))
253
- continue;
254
- const src = join(up, rel);
255
- if (!existsSync(src))
256
- continue;
257
- if (!installs.has(rel)) {
258
- findings.push({
259
- reason: 'F2',
260
- verdict: 'WARN',
261
- path: `.agents/harness/${rel}`,
262
- message: `upstream v${upVersion} no longer installs this file for the ${pinned.tier ?? 'graph'} tier`,
263
- resume: 'run `reins update` to remove it',
264
- });
265
- continue;
266
- }
267
- if (readFileSync(src, 'utf8') !== rd.read(entry))
268
- findings.push({
269
- reason: 'F2',
270
- verdict: 'STOP',
271
- path: `.agents/harness/${rel}`,
272
- message: `differs from upstream v${upVersion} (harness files are not edited in place)`,
273
- resume: 'run `reins update` to restore it; change behaviour upstream or with an override',
274
- });
275
- }
276
- // installed skill entry points = the packaged ones
277
- const skillsUp = packageSkills();
278
- for (const name of tierSkills(pinned.tier ?? 'graph')) {
279
- const dir = `.agents/skills/${name}`;
280
- if (rd.list(dir).length === 0)
281
- continue;
282
- for (const f of listFiles(join(skillsUp, name))) {
283
- if (rd.read(`${dir}/${f}`) !== readFileSync(join(skillsUp, name, f), 'utf8'))
284
- findings.push({
285
- reason: 'F2',
286
- verdict: 'STOP',
287
- path: `.agents/skills/${name}/${f}`,
288
- message: `differs from the packaged skill (v${upVersion})`,
289
- resume: 'run `reins update`; a project-specific procedure belongs in its own skill',
290
- });
291
- }
292
- }
293
- return findings;
294
- }
295
- /** Compare a block for drift: CRLF to LF, trailing whitespace per line, blank lines around the content. */
296
- function normBlock(s) {
297
- return s
298
- .replace(/\r\n/g, '\n')
299
- .split('\n')
300
- .map((l) => l.replace(/\s+$/, ''))
301
- .join('\n')
302
- .replace(/^\n+|\n+$/g, '');
303
- }
304
- /** Drift, managed blocks — AGENTS.md blocks against the packaged ones at the pinned version (design §5). */
305
- export function driftBlocks(root, rd = workTreeReader(root)) {
306
- const text = rd.read('AGENTS.md');
307
- if (text === undefined)
308
- return [];
309
- const pinText = rd.read('.agents/harness/install.yaml');
310
- if (pinText === undefined)
311
- return [];
312
- let upBlocks;
313
- try {
314
- const up = packageHarness();
315
- if (parse(pinText).version !== harnessVersion(up))
316
- return []; // driftMatch warns
317
- upBlocks = new Map(parseBlocks(readFileSync(join(up, 'templates/agents-md-blocks.md'), 'utf8')).map((b) => [
318
- b.name,
319
- b,
320
- ]));
321
- }
322
- catch {
323
- return [];
324
- }
325
- const over = overrides(text);
326
- const findings = [];
327
- const have = parseBlocks(text);
328
- for (const [name, up] of upBlocks)
329
- if (!over.has(name) && !have.some((b) => b.name === name) && !hasOwnSection(text, up))
330
- findings.push({
331
- reason: 'F2',
332
- verdict: 'STOP',
333
- path: 'AGENTS.md',
334
- message: `managed block "${name}" is missing`,
335
- resume: `run \`reins update\`, or add <!-- reins:override ${name} -->`,
336
- });
337
- for (const b of have) {
338
- const want = upBlocks.get(b.name);
339
- if (!want || over.has(b.name))
340
- continue;
341
- if (normBlock(b.body) !== normBlock(want.body))
342
- findings.push({
343
- reason: 'F2',
344
- verdict: 'STOP',
345
- path: 'AGENTS.md',
346
- message: `managed block "${b.name}" was edited by hand`,
347
- resume: `run \`reins update\`, or add <!-- reins:override ${b.name} -->`,
348
- });
349
- }
350
- return findings;
351
- }
352
- export function runCheck(opts) {
353
- const root = repoRoot(opts.cwd ?? process.cwd());
354
- const findings = [];
355
- const stage = opts.stage ?? (opts.drift ? 'drift' : 'all');
356
- if (opts.stage === 'pre-commit')
357
- findings.push(...preCommit(root));
358
- else if (opts.stage === 'pre-push')
359
- findings.push(...prePush(root, opts.pushRefs ?? []));
360
- else if (opts.stage === 'ticket-start' || opts.stage === 'verdict') {
361
- if (!opts.ticket)
362
- findings.push({
363
- reason: 'F2',
364
- verdict: 'STOP',
365
- message: `stage needs --ticket <id>`,
366
- });
367
- else
368
- findings.push(...(opts.stage === 'ticket-start'
369
- ? ticketStart(root, opts.ticket)
370
- : verdictCheck(root, opts.ticket)));
371
- }
372
- else if (opts.stage === 'rc-close')
373
- findings.push(...rcClose(root, opts.release, opts.stable));
374
- if (opts.drift || !opts.stage)
375
- findings.push(...driftFormat(root), ...driftConvention(root), ...driftMatch(root), ...driftBlocks(root), ...driftGenerated(root));
376
- if (!currentBranch(root))
377
- findings.push({ reason: 'F2', verdict: 'STOP', message: 'not a git repository' });
378
- return report(stage, findings);
379
- }
@@ -1,136 +0,0 @@
1
- import { spawnSync } from 'node:child_process';
2
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- import { repoRoot } from '../lib/git.js';
5
- import { harnessDir, readYaml } from '../lib/harness.js';
6
- import { loadSchemas, validateFile } from '../lib/schema.js';
7
- import { parse, stringify } from 'yaml';
8
- /** One command per gate (design §5): no pipes, chains or redirects — anything else is massaged output (C5). */
9
- export function compound(cmd) {
10
- return /[|;&<>`]|\$\(/.test(cmd.replace(/'[^']*'|"[^"]*"/g, ''));
11
- }
12
- /**
13
- * Runs gates exactly as gates.yaml declares them and keeps the raw output as evidence:
14
- * `$ <cmd>`, the output untouched, `exit <code>` — the format `check --stage verdict` (T3) reads.
15
- */
16
- export function runGates(o) {
17
- const root = repoRoot(o.cwd ?? process.cwd());
18
- const dir = harnessDir(root);
19
- const path = dir && join(dir, 'gates.yaml');
20
- if (!path || !existsSync(path))
21
- return { runs: [], refused: 'no gates.yaml — run reins install' };
22
- const g = readYaml(path);
23
- const gates = g.gates ?? {};
24
- const names = o.names?.length ? o.names : (g.order ?? Object.keys(gates));
25
- const unknown = names.filter((n) => !gates[n]?.cmd);
26
- if (unknown.length)
27
- return {
28
- runs: [],
29
- refused: `unknown gate${unknown.length > 1 ? 's' : ''}: ${unknown.join(', ')} (gates: ${Object.keys(gates).join(', ')})`,
30
- };
31
- const reports = join(root, '.loctx', 'reports');
32
- mkdirSync(reports, { recursive: true });
33
- const runs = [];
34
- let failed = false;
35
- for (const name of names) {
36
- const cmd = gates[name].cmd;
37
- const report = `.loctx/reports/${o.ticket ?? 'adhoc'}_${name}.log`;
38
- if (failed && !o.all) {
39
- runs.push({ gate: name, cmd, exit: null, report, skipped: 'an earlier gate failed' });
40
- continue;
41
- }
42
- if (compound(cmd)) {
43
- runs.push({ gate: name, cmd, exit: null, report, skipped: 'not a single command (C5)' });
44
- failed = true;
45
- continue;
46
- }
47
- const r = spawnSync(`${cmd} 2>&1`, { cwd: root, shell: true, encoding: 'utf8' });
48
- const exit = r.status ?? 1;
49
- const out = (r.stdout ?? '').replace(/\n?$/, '\n');
50
- writeFileSync(join(root, report), `$ ${cmd}\n${out}exit ${exit}\n`);
51
- runs.push({ gate: name, cmd, exit, report });
52
- if (exit !== 0)
53
- failed = true;
54
- }
55
- return { runs };
56
- }
57
- /** One line per failing gate for stdout: the first failure signature and the first file:line in the raw report. */
58
- export function failureSummary(report) {
59
- const lines = report.split(/\r?\n/).filter((l) => l.trim() && !l.startsWith('$ '));
60
- const sig = lines.find((l) => /\b(error|fail(ed|ure)?|assertion|✗|×)\b/i.test(l) && !/^exit \d+$/.test(l)) ??
61
- lines.find((l) => !/^exit \d+$/.test(l)) ??
62
- '';
63
- const loc = /[\w./-]+\.[a-z]{1,4}:\d+(?::\d+)?/i.exec(lines.join('\n'))?.[0];
64
- const text = sig.trim().slice(0, 160);
65
- return [text, loc && !text.includes(loc) ? loc : ''].filter(Boolean).join(' @ ');
66
- }
67
- /** The newest `kind: verify` request of the ticket that has no response yet, as its id (`<ticket>_<nn>`). */
68
- export function openVerifyRequest(root, ticket) {
69
- const dir = join(root, '.loctx', 'bus');
70
- const files = existsSync(dir) ? readdirSync(dir) : [];
71
- const re = new RegExp(`^(${ticket.replace(/[-.]/g, '\\$&')}_\\d+)\\.request\\.yaml$`);
72
- const open = files
73
- .map((f) => re.exec(f)?.[1])
74
- .filter((id) => !!id && !files.includes(`${id}.response.yaml`))
75
- .filter((id) => {
76
- try {
77
- const y = parse(readFileSync(join(dir, `${id}.request.yaml`), 'utf8'));
78
- return y?.kind === 'verify';
79
- }
80
- catch {
81
- return false;
82
- }
83
- })
84
- .sort();
85
- return open.at(-1) ?? null;
86
- }
87
- /**
88
- * Writes the bus response for the open verify request from a gate run. The verdict is pass only when every
89
- * gate ran and exited 0; evidence points at the report files, which keep the raw output (C5).
90
- */
91
- export function writeResponse(root, ticket, runs) {
92
- const summaries = {};
93
- for (const g of runs) {
94
- if (g.exit === 0)
95
- continue;
96
- summaries[g.gate] = g.skipped
97
- ? `not run: ${g.skipped}`
98
- : failureSummary(readFileSync(join(root, g.report), 'utf8')) || `exit ${g.exit}`;
99
- }
100
- const id = openVerifyRequest(root, ticket);
101
- if (!id)
102
- return { summaries, refused: `no open kind: verify request for ${ticket} in .loctx/bus/` };
103
- const pass = runs.length > 0 && runs.every((g) => g.exit === 0);
104
- const ran = runs.filter((g) => g.exit !== null);
105
- const body = {
106
- schema: 'reins/bus/response@1',
107
- request: id,
108
- from: 'verify-tool',
109
- verdict: pass ? 'pass' : 'fail',
110
- grounds: pass
111
- ? `${runs.length} gate${runs.length === 1 ? '' : 's'} exited 0`
112
- : Object.entries(summaries)
113
- .map(([k, v]) => `${k}: ${v}`)
114
- .join('; ') || 'no gate ran',
115
- evidence: ran.map((g) => g.report).join(' '),
116
- may_proceed: pass,
117
- };
118
- const hd = harnessDir(root);
119
- const v = hd ? loadSchemas(hd).get('bus-response') : undefined;
120
- if (!v)
121
- return { summaries, refused: 'no bus-response schema in the harness' };
122
- const rel = `.loctx/bus/${id}.response.yaml`;
123
- const content = stringify(body);
124
- const issues = validateFile(v, rel, true, content);
125
- if (issues.length)
126
- return {
127
- summaries,
128
- refused: `response would not pass bus-response: ${issues.map((i) => i.message).join('; ')}`,
129
- };
130
- writeFileSync(join(root, rel), content, { flag: 'wx' });
131
- return { response: rel, verdict: body.verdict, summaries };
132
- }
133
- /** `--respond` may only answer for the whole declared order, so a pass never rests on a subset of the gates. */
134
- export function respondRefusal(names) {
135
- return names.length > 0 ? '--respond runs every declared gate; do not name gates' : null;
136
- }
@@ -1,111 +0,0 @@
1
- import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
2
- import { basename, join, relative, resolve } from 'node:path';
3
- import { repoRoot } from '../lib/git.js';
4
- import { harnessDir } from '../lib/harness.js';
5
- import { localIso } from '../lib/metrics.js';
6
- import { bareKey, collectRetro, DISMISSED } from '../lib/retro.js';
7
- import { loadSchemas, validateFile } from '../lib/schema.js';
8
- export const PROPOSALS = '.loctx/knowledge-proposals';
9
- const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
10
- const today = () => localIso().slice(0, 10);
11
- /** Replace the frontmatter line starting with `key:`; `null` removes it. */
12
- function setLine(text, key, value) {
13
- if (value === null)
14
- return text.replace(new RegExp(`^${key}:.*\\n`, 'm'), '');
15
- return text.replace(new RegExp(`^${key}:.*$`, 'm'), () => `${key}: ${value}`);
16
- }
17
- /**
18
- * `reins knowledge propose <key|slug> [--from <history>…]`: a draft from the knowledge template,
19
- * `approved` left out. Writes only under `.loctx/knowledge-proposals/`.
20
- */
21
- export function proposeKnowledge(key, o = {}) {
22
- const root = repoRoot(o.cwd ?? process.cwd());
23
- const slug = bareKey(key);
24
- if (!SLUG.test(slug))
25
- return { refused: `"${key}" is not a usable slug` };
26
- const hd = harnessDir(root);
27
- const tpl = hd && join(hd, 'templates', 'knowledge.md');
28
- if (!tpl || !existsSync(tpl))
29
- return { refused: 'no knowledge template — run reins install' };
30
- const dest = join(root, PROPOSALS, `${slug}.md`);
31
- if (existsSync(dest))
32
- return { refused: `${PROPOSALS}/${slug}.md already exists` };
33
- const hist = resolve(root, '.loctx', 'history');
34
- const from = [];
35
- for (const f of o.from ?? []) {
36
- const abs = resolve(root, f.includes('/') ? f : join('.loctx', 'history', f));
37
- const rel = relative(hist, abs);
38
- if (rel.startsWith('..') || /[\\/]/.test(rel) || !existsSync(abs))
39
- return { refused: `--from ${f}: not a page under .loctx/history/` };
40
- const text = readFileSync(abs, 'utf8');
41
- const lines = [...text.matchAll(/^(?:decisions|reasons):\s*(.+)$/gm)].flatMap((m) => m[1].split(',').map((x) => x.trim()));
42
- const has = key.startsWith('stop:') ? text.includes(slug) : lines.includes(slug);
43
- if (!has)
44
- return { refused: `--from ${f}: does not contain "${slug}"` };
45
- from.push(`.loctx/history/${rel}`);
46
- }
47
- if (from.length === 0)
48
- from.push(...collectRetro(root)
49
- .keys.filter((k) => bareKey(k.key) === slug)
50
- .flatMap((k) => k.pages));
51
- if (from.length === 0)
52
- return { refused: `no record of "${slug}"; pass --from <history>…` };
53
- const asSymptom = /^(stop|reason):/.test(key);
54
- let t = readFileSync(tpl, 'utf8');
55
- t = setLine(t, 'id', `${today()}_${slug}`);
56
- t = setLine(t, 'decisions', asSymptom ? '[]' : `[${slug}]`);
57
- t = setLine(t, 'symptoms', asSymptom ? `[${slug}]` : '[]');
58
- t = setLine(t, 'source', JSON.stringify([...new Set(from)].join(', ')));
59
- t = setLine(t, 'approved', null);
60
- mkdirSync(join(root, PROPOSALS), { recursive: true });
61
- writeFileSync(dest, t);
62
- return { path: `${PROPOSALS}/${slug}.md` };
63
- }
64
- /**
65
- * `reins knowledge accept <slug>`: the only way an `approved` field gets written. The skill calls
66
- * it after the user's answer; the CLI cannot tell who ran it (design §8).
67
- */
68
- export function acceptKnowledge(name, o = {}) {
69
- const root = repoRoot(o.cwd ?? process.cwd());
70
- const base = basename(name, '.md');
71
- const slug = base.replace(/^\d{4}-\d{2}-\d{2}_/, '');
72
- const draft = join(root, PROPOSALS, `${base}.md`);
73
- if (!existsSync(draft))
74
- return { refused: `no draft ${PROPOSALS}/${base}.md` };
75
- const at = today();
76
- let t = readFileSync(draft, 'utf8');
77
- t = setLine(t, 'id', `${at}_${slug}`);
78
- t = setLine(t, 'approved', null);
79
- t = t.replace(/^(source:.*)$/m, (m) => `${m}\napproved: { by: user, at: ${at} }`);
80
- const hd = harnessDir(root);
81
- const v = hd ? loadSchemas(hd).get('knowledge') : undefined;
82
- if (!v)
83
- return { refused: 'no knowledge schema — run reins install' };
84
- const issues = validateFile(v, draft, false, t);
85
- if (issues.length)
86
- return { refused: `draft is invalid: ${issues.map((i) => i.message).join('; ')}` };
87
- const rel = `.agents/knowledge/${at}_${slug}.md`;
88
- if (existsSync(join(root, rel)))
89
- return { refused: `${rel} already exists` };
90
- mkdirSync(join(root, '.agents', 'knowledge'), { recursive: true });
91
- writeFileSync(join(root, rel), t);
92
- rmSync(draft);
93
- return { path: rel };
94
- }
95
- /**
96
- * `reins knowledge dismiss <key> --reason <text>`: the pm judged a current candidate not to be a
97
- * lesson. retro and status stop counting it until it shows up in more units than it had then.
98
- */
99
- export function dismissKnowledge(key, o = {}) {
100
- const root = repoRoot(o.cwd ?? process.cwd());
101
- const reason = o.reason?.trim();
102
- if (!reason)
103
- return { refused: '--reason is required: say why it is not a lesson' };
104
- const c = collectRetro(root).candidates.find((k) => k.key === key);
105
- if (!c)
106
- return { refused: `"${key}" is not a current candidate (reins retro lists them)` };
107
- mkdirSync(join(root, PROPOSALS), { recursive: true });
108
- const line = { key, units: c.units.length, at: today(), reason };
109
- appendFileSync(join(root, DISMISSED), `${JSON.stringify(line)}\n`);
110
- return { path: DISMISSED };
111
- }