@bluenyang/reins 0.1.3 → 0.1.4-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.
package/README.md CHANGED
@@ -122,7 +122,8 @@ To work on reins itself: `git clone https://github.com/bluenyang/reins.git`, the
122
122
  | `metrics` | implemented | summary of `.loctx/reports/metrics.jsonl`: tokens by role, vendor, ticket and intent, knowledge stops per ticket; `metrics record` adds a role run's tokens |
123
123
  | `recall` | not implemented | search past decisions by symptom |
124
124
  | `doctor` | not implemented | — |
125
- | `configure budget\|gates\|language` | not implemented | — |
125
+ | `configure gates` | implemented | lists subdirectory gate proposals; `--add <name>...` appends them to gates.yaml |
126
+ | `configure budget\|language` | not implemented | — |
126
127
 
127
128
  `install`, `migrate`, `update`, `gate`, `status`, `check` and `metrics` take `--json`. Every `check` and `gate` run also appends a line to `.loctx/reports/metrics.jsonl`. `check` stages map to
128
129
  T1 (`ticket-start`), T2 (`pre-commit`), T3 (`verdict`), T4 (`pre-push`) and T5 (`rc-close`).
@@ -10,6 +10,7 @@ import { harnessVersion, packageHarness, packageSkills, tierSkills } from '../li
10
10
  import { listFiles, relPath } from '../lib/fsx.js';
11
11
  import { driftGenerated } from '../lib/vendor-write.js';
12
12
  import { indexReader, workTreeReader } from '../lib/reader.js';
13
+ import { PROJECT_OWNED, tierFiles } from './install.js';
13
14
  import { rcClose, ticketStart, verdictCheck } from './stages.js';
14
15
  import { parse } from 'yaml';
15
16
  import { report } from '../lib/verdict.js';
@@ -142,6 +143,7 @@ export function driftConvention(root, only, rd = workTreeReader(root)) {
142
143
  const schemas = loadSchemasFrom(rd, hrel);
143
144
  const findings = [];
144
145
  const candidates = [
146
+ `${hrel}/install.yaml`,
145
147
  ...rd.list(`${hrel}/templates`),
146
148
  ...rd.list(`${hrel}/knowledge-seeds`),
147
149
  ...rd.list('.agents/intent'),
@@ -215,7 +217,6 @@ export function driftConvention(root, only, rd = workTreeReader(root)) {
215
217
  return findings;
216
218
  }
217
219
  /** Files in an installed harness that belong to the project, not upstream. */
218
- const PROJECT_OWNED = new Set(['bindings.yaml', 'gates.yaml', 'install.yaml', 'generated.yaml']);
219
220
  /** Drift, match layer — the installed `.agents/harness/` against the packaged upstream at the pinned version (design §6). */
220
221
  export function driftMatch(root, rd = workTreeReader(root)) {
221
222
  const installed = '.agents/harness';
@@ -243,6 +244,9 @@ export function driftMatch(root, rd = workTreeReader(root)) {
243
244
  },
244
245
  ];
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')));
246
250
  for (const entry of rd.list(installed)) {
247
251
  const rel = entry.slice(installed.length + 1);
248
252
  if (PROJECT_OWNED.has(rel))
@@ -250,6 +254,16 @@ export function driftMatch(root, rd = workTreeReader(root)) {
250
254
  const src = join(up, rel);
251
255
  if (!existsSync(src))
252
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
+ }
253
267
  if (readFileSync(src, 'utf8') !== rd.read(entry))
254
268
  findings.push({
255
269
  reason: 'F2',
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { parse, stringify } from 'yaml';
4
- import { CONFIRMED_MODELS, checkBinding, newModelCache, vendorOf, vendors, } from '../lib/detect.js';
3
+ import { parse, parseDocument, stringify } from 'yaml';
4
+ import { CONFIRMED_MODELS, checkBinding, newModelCache, subdirProposals, vendorOf, vendors, } from '../lib/detect.js';
5
5
  import { generateVendorFiles } from '../lib/generate.js';
6
6
  import { repoRoot } from '../lib/git.js';
7
7
  import { writeGenerated } from '../lib/vendor-write.js';
@@ -77,3 +77,35 @@ export async function configureBindings(o) {
77
77
  .toSorted((a, b) => a.role.localeCompare(b.role));
78
78
  return { changed, table, generated };
79
79
  }
80
+ /** `reins configure gates [--add <name>…]` (spec S-7): subdirectory proposals, appended after the existing gates. */
81
+ export function configureGates(o = {}) {
82
+ const root = repoRoot(o.cwd ?? process.cwd());
83
+ const path = join(root, '.agents/harness/gates.yaml');
84
+ if (!existsSync(path))
85
+ return { refused: 'no gates.yaml — run reins install', code: 2, available: [], added: [] };
86
+ const doc = parseDocument(readFileSync(path, 'utf8'));
87
+ const have = new Set(Object.keys(doc.toJS()?.gates ?? {}));
88
+ const available = subdirProposals(root).filter((g) => !have.has(g.name));
89
+ const names = o.add ?? [];
90
+ const unknown = names.filter((n) => !available.some((g) => g.name === n));
91
+ if (unknown.length)
92
+ return {
93
+ refused: `no such proposal: ${unknown.join(', ')} — available: ${available.map((g) => g.name).join(', ') || 'none'}`,
94
+ code: 1,
95
+ available,
96
+ added: [],
97
+ };
98
+ const added = [];
99
+ for (const n of new Set(names)) {
100
+ const g = available.find((x) => x.name === n);
101
+ doc.setIn(['gates', g.name], doc.createNode({ cmd: g.cmd, from: g.from }));
102
+ if (doc.has('order'))
103
+ doc.addIn(['order'], g.name);
104
+ else
105
+ doc.set('order', doc.createNode([g.name]));
106
+ added.push(g.name);
107
+ }
108
+ if (added.length)
109
+ writeFileSync(path, doc.toString());
110
+ return { available: available.filter((g) => !added.includes(g.name)), added };
111
+ }
@@ -1,6 +1,7 @@
1
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
- import { join } from 'node:path';
1
+ import { existsSync, readFileSync, readdirSync, rmdirSync, rmSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
3
  import { parse, stringify } from 'yaml';
4
+ import { planMemoryProposals } from '../lib/memory.js';
4
5
  import { applyBlocks, parseBlocks } from '../lib/blocks.js';
5
6
  import { CONFIRMED_MODELS, checkBinding, discoverGates, newModelCache, vendorOf, generation, stacks, vendors, } from '../lib/detect.js';
6
7
  import { apply, listFiles } from '../lib/fsx.js';
@@ -10,7 +11,7 @@ import { harnessVersion, packageHarness, packageSkills, packageVersion, tierSkil
10
11
  import { generateVendorFiles } from '../lib/generate.js';
11
12
  import { writeGenerated } from '../lib/vendor-write.js';
12
13
  /** Which upstream harness files a tier installs (design §1, tier table). */
13
- function tierFiles(all, tier) {
14
+ export function tierFiles(all, tier) {
14
15
  return all.filter((f) => {
15
16
  if (f.startsWith('knowledge-seeds/'))
16
17
  return false; // copied into knowledge/, not harness/
@@ -29,6 +30,23 @@ function tierFiles(all, tier) {
29
30
  return tier === 'graph'; // roles/, schemas/
30
31
  });
31
32
  }
33
+ /** Harness files the project owns; update and drift never touch them. */
34
+ export const PROJECT_OWNED = new Set([
35
+ 'bindings.yaml',
36
+ 'gates.yaml',
37
+ 'install.yaml',
38
+ 'generated.yaml',
39
+ ]);
40
+ /**
41
+ * Files installed under `.agents/harness/` that upstream still ships but this tier no longer installs
42
+ * (e.g. `CHANGELOG.md`): in upstream, outside `tierFiles(tier)`, not project-owned. Anything not in
43
+ * upstream is the project's and is never listed.
44
+ */
45
+ export function retiredFiles(installed, upstream, tier) {
46
+ const up = new Set(upstream);
47
+ const keep = new Set(tierFiles(upstream, tier));
48
+ return installed.filter((f) => up.has(f) && !keep.has(f) && !PROJECT_OWNED.has(f));
49
+ }
32
50
  /** bindings.yaml (design §5): defaults from role files; an unavailable vendor falls back, else to pm's model. */
33
51
  export function buildBindings(harness, available, vs, mode, cache) {
34
52
  const roles = {};
@@ -158,14 +176,31 @@ export async function runInstall(o) {
158
176
  const okGates = await o.asker.ask(`gates found: ${gateList} — use them? (y/n)`, 'y');
159
177
  if (!/^y/i.test(okGates))
160
178
  notes.push('gates not confirmed — edit .agents/harness/gates.yaml, then `reins check --dry-run`');
179
+ let chosen = [];
180
+ if (proposal.proposals.length) {
181
+ const listing = proposal.proposals.map((g) => `${g.name}=${g.cmd}`).join('; ');
182
+ if (o.mode === 'manual') {
183
+ const pick = await o.asker.ask(`subdirectory gates (names, comma-separated; empty: none) — ${listing}`, '');
184
+ const names = new Set(pick
185
+ .split(',')
186
+ .map((x) => x.trim())
187
+ .filter(Boolean));
188
+ chosen = proposal.proposals.filter((g) => names.has(g.name));
189
+ for (const n of names)
190
+ if (!chosen.some((g) => g.name === n))
191
+ notes.push(`no such subdirectory gate: ${n}`);
192
+ }
193
+ else
194
+ notes.push(`subdirectory gates not added (auto mode): ${listing} — add with \`reins configure gates --add <name>\``);
195
+ }
161
196
  for (const x of proposal.excluded)
162
197
  notes.push(`excluded from gates: ${x.name} (${x.why})`);
163
- add('.agents/harness/gates.yaml', buildGates(root, /^y/i.test(okGates) ? proposal.gates : []), 'declared gates');
198
+ add('.agents/harness/gates.yaml', buildGates(root, [...(/^y/i.test(okGates) ? proposal.gates : []), ...chosen]), 'declared gates');
164
199
  }
165
200
  // 3. generated configuration
166
201
  if (o.tier === 'graph' && !hasBindings)
167
202
  add('.agents/harness/bindings.yaml', buildBindings(up, avail, vs, o.mode, o.modelCache ?? newModelCache()), 'role ↔ model bindings');
168
- add('.agents/harness/install.yaml', `# version pin and install settings (R25) — read by reins update\n${stringify({ schema: 'reins/install@1', tier: o.tier, version, cli: packageVersion(), mode: o.mode, language })}`, 'version pin');
203
+ add('.agents/harness/install.yaml', `# version pin and install settings (R25) — read by reins update\n${stringify({ ...pinned, schema: 'reins/install@1', tier: o.tier, version, cli: packageVersion(), mode: o.mode, language })}`, 'version pin');
169
204
  // 4. layout skeleton (design §1); never overwrite project files
170
205
  if (o.tier !== 'harness') {
171
206
  addIfMissing('.agents/intent/.gitkeep', '', 'intent folders live here');
@@ -210,6 +245,13 @@ export async function runInstall(o) {
210
245
  : '';
211
246
  if (!/^\/?\.loctx\/?$/m.test(gi))
212
247
  add('.gitignore', `${gi.replace(/\s*$/, '')}\n\n# reins local workspace\n.loctx/\n`, 'keep .loctx out of git');
248
+ // 4b. .claude/memory is never moved: each file becomes a knowledge draft (design §7)
249
+ {
250
+ const d = o.now ?? new Date();
251
+ const memory = planMemoryProposals(root, `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`);
252
+ writes.push(...memory.writes);
253
+ notes.push(...memory.notes);
254
+ }
213
255
  // 5. AGENTS.md managed blocks, CLAUDE.md pointer
214
256
  const agentsPath = join(root, 'AGENTS.md');
215
257
  const agents = existsSync(agentsPath) ? readFileSync(agentsPath, 'utf8') : '# AGENTS.md\n';
@@ -244,6 +286,25 @@ export async function runInstall(o) {
244
286
  notes.push('next: in your agent, run the setup skill (/reins-setup) — the PM reads the project and proposes AGENTS.md project sections');
245
287
  // 8. apply, then record (only when something changed)
246
288
  const applied = apply(root, writes, !!o.dryRun);
289
+ if (o.retire) {
290
+ const harnessDir = join(root, '.agents/harness');
291
+ const here = existsSync(harnessDir) ? listFiles(harnessDir) : [];
292
+ for (const f of retiredFiles(here, listFiles(up), o.tier)) {
293
+ applied.removed.push(`.agents/harness/${f}`);
294
+ if (o.dryRun)
295
+ continue;
296
+ rmSync(join(harnessDir, f), { force: true });
297
+ // prune directories the removal left empty, never the harness root
298
+ for (let d = dirname(join(harnessDir, f)); d !== harnessDir; d = dirname(d)) {
299
+ try {
300
+ rmdirSync(d);
301
+ }
302
+ catch {
303
+ break;
304
+ }
305
+ }
306
+ }
307
+ }
247
308
  // 9. vendor files from the installed harness (design §6) — never over a file reins did not write
248
309
  const generated = o.dryRun ? undefined : writeGenerated(root, generateVendorFiles(root), false);
249
310
  if (generated) {
@@ -254,7 +315,7 @@ export async function runInstall(o) {
254
315
  notes.push(`left alone ${r.path}: ${r.why}`);
255
316
  }
256
317
  let history;
257
- const changedAny = applied.created.length + applied.changed.length > 0;
318
+ const changedAny = applied.created.length + applied.changed.length + applied.removed.length > 0;
258
319
  if (changedAny && !o.dryRun && o.tier !== 'harness') {
259
320
  const now = o.now ?? new Date();
260
321
  // local time, like every other history file name (<YYYY-MM-DD-HHmm>)
@@ -267,9 +328,10 @@ export async function runInstall(o) {
267
328
  `# reins install ${o.tier} (${o.mode}) — v${version}`,
268
329
  '',
269
330
  `- generation before: ${gen}`,
270
- `- created: ${applied.created.length} · changed: ${applied.changed.length} · unchanged: ${applied.unchanged.length}`,
331
+ `- created: ${applied.created.length} · changed: ${applied.changed.length} · unchanged: ${applied.unchanged.length} · removed: ${applied.removed.length}`,
271
332
  ...applied.created.map((p) => ` - + ${p}`),
272
333
  ...applied.changed.map((p) => ` - ~ ${p}`),
334
+ ...applied.removed.map((p) => ` - - ${p}`),
273
335
  '',
274
336
  '## notes',
275
337
  ...notes.map((n) => `- ${n}`),
@@ -4,6 +4,7 @@ import { applyBlocks, parseBlocks, swapSections } from '../lib/blocks.js';
4
4
  import { generation } from '../lib/detect.js';
5
5
  import { repoRoot } from '../lib/git.js';
6
6
  import { convertWorkToTicket, planMigration } from '../lib/migrate-plan.js';
7
+ import { splitFrontmatter } from '../lib/skills.js';
7
8
  import { packageHarness } from '../lib/upstream.js';
8
9
  import { ROADMAP_STUB, runInstall } from './install.js';
9
10
  const pad = (n) => String(n).padStart(2, '0');
@@ -16,6 +17,40 @@ function removeEmptyDirs(dir) {
16
17
  if (readdirSync(dir).length === 0)
17
18
  rmdirSync(dir);
18
19
  }
20
+ /** Intent 000 (draft) that the migrated tickets point at — only when this run made tickets and none exists. */
21
+ function writeMigratedIntent(root, moves) {
22
+ const made = moves.filter((m) => m.result === 'converted');
23
+ const dir = join(root, '.agents/intent');
24
+ if (made.length === 0 || (existsSync(dir) && readdirSync(dir).some((e) => e.startsWith('000_'))))
25
+ return null;
26
+ let version = '0.0.0';
27
+ try {
28
+ const v = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version;
29
+ if (typeof v === 'string' && v)
30
+ version = v;
31
+ }
32
+ catch {
33
+ // no package.json — keep the default
34
+ }
35
+ const { body } = splitFrontmatter(readFileSync(join(packageHarness(), 'templates/intent.md'), 'utf8'));
36
+ const list = made
37
+ .map((m) => `- ${m.to.slice('.loctx/ticket/'.length, m.to.indexOf('_'))} — from .ai/work/${m.from.slice('.ai/work/'.length)}`)
38
+ .join('\n');
39
+ const text = body.replace(/## 문제\n—/, () => `## 문제\nOpen work items that \`reins migrate\` moved out of \`.ai/work/\`. They point at this intent until the PL plans them again:\n\n${list}`);
40
+ const yaml = [
41
+ 'id: "000"',
42
+ 'slug: migrated',
43
+ `version: ${JSON.stringify(version)}`,
44
+ 'status: draft',
45
+ 'origin: user',
46
+ 'approvals: []',
47
+ 'supersedes: null',
48
+ ].join('\n');
49
+ const out = join(dir, '000_migrated/intent.md');
50
+ mkdirSync(dirname(out), { recursive: true });
51
+ writeFileSync(out, `---\n${yaml}\n---\n${text}`);
52
+ return '.agents/intent/000_migrated/intent.md written as a draft listing the migrated tickets — the user approves it before any of them starts';
53
+ }
19
54
  /** `reins migrate <tier>` (design §7): install if needed, move the old workspace, swap AGENTS.md sections. Idempotent. */
20
55
  export async function runMigrate(o) {
21
56
  const root = repoRoot(o.cwd ?? process.cwd());
@@ -45,7 +80,7 @@ export async function runMigrate(o) {
45
80
  res.report.push(...inst.notes.filter((n) => !n.startsWith('next:') && !n.includes('managed') && !n.includes('not placed')));
46
81
  }
47
82
  // 2. move the old workspace
48
- const plan = planMigration(root);
83
+ const plan = planMigration(root, { legacy: o.legacy });
49
84
  res.report.push(...plan.report);
50
85
  for (const m of plan.moves) {
51
86
  const from = join(root, m.from);
@@ -56,8 +91,12 @@ export async function runMigrate(o) {
56
91
  }
57
92
  mkdirSync(dirname(to), { recursive: true });
58
93
  const src = readFileSync(from);
59
- if (m.action === 'ticket') {
60
- writeFileSync(to, convertWorkToTicket(src.toString('utf8'), m.from.split('/').pop() ?? ''));
94
+ if (m.action === 'ticket' && m.existing) {
95
+ unlinkSync(from); // converted by an earlier run
96
+ res.moves.push({ ...m, result: 'same' });
97
+ }
98
+ else if (m.action === 'ticket') {
99
+ writeFileSync(to, convertWorkToTicket(src.toString('utf8'), m.from.slice('.ai/work/'.length), m.n ?? 1, m.idMap, m.dropped, m.group));
61
100
  unlinkSync(from);
62
101
  res.moves.push({ ...m, result: 'converted' });
63
102
  }
@@ -78,6 +117,11 @@ export async function runMigrate(o) {
78
117
  }
79
118
  if (!o.dryRun)
80
119
  removeEmptyDirs(join(root, '.ai'));
120
+ if (!o.dryRun) {
121
+ const made = writeMigratedIntent(root, res.moves);
122
+ if (made)
123
+ res.report.push(made);
124
+ }
81
125
  // 3. AGENTS.md: sections reins owns become managed blocks; the originals are kept locally
82
126
  const agentsPath = join(root, 'AGENTS.md');
83
127
  if (existsSync(agentsPath)) {
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
2
  import { isAbsolute, join, relative, sep } from 'node:path';
3
3
  import { harnessDir, readYaml } from '../lib/harness.js';
4
+ import { dispatchLines, readRelease } from '../lib/release.js';
4
5
  import { loadSchemas, validateFile } from '../lib/schema.js';
5
6
  import { compound } from './gate.js';
6
7
  import { approvedBy, busFor, historyPages, intentFile, intentIds, openTickets, recordedDecisions, ticketFile, } from '../lib/work.js';
@@ -433,8 +434,29 @@ export function rcClose(root, release) {
433
434
  }
434
435
  if (findings.length === 0)
435
436
  findings.push(...nextRc(root, release));
437
+ if (findings.every((f) => f.verdict === 'WARN'))
438
+ findings.push(...dispatchFindings(root, findings));
436
439
  return findings;
437
440
  }
441
+ /** The rc dispatch lines (S-3) from install.yaml `release:`; the rc number comes from the ledger finding. */
442
+ function dispatchFindings(root, found) {
443
+ const rc = found.map((f) => /^next rc: (\S+)$/.exec(f.message)?.[1]).find(Boolean);
444
+ const ws = readRelease(root);
445
+ if (!rc || !ws)
446
+ return [
447
+ {
448
+ reason: 'F2',
449
+ verdict: 'WARN',
450
+ message: 'no release settings (install.yaml has no release:) — merge only',
451
+ },
452
+ ];
453
+ const lines = dispatchLines(ws, 'rc', rc);
454
+ if (lines.length === 0)
455
+ return [
456
+ { reason: 'F2', verdict: 'WARN', message: 'no release workflow is set for the rc stage' },
457
+ ];
458
+ return lines.map((l) => ({ reason: 'F2', verdict: 'WARN', message: `dispatch: ${l}` }));
459
+ }
438
460
  /**
439
461
  * The next rc number from the local ledger `.loctx/release/<V>.md` (one `- rc.N …` line per rc):
440
462
  * rc.1 when there is no ledger, else the last recorded rc + 1. A number already recorded is F2.
@@ -2,7 +2,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
2
  import { basename, join } from 'node:path';
3
3
  import { parse } from 'yaml';
4
4
  import { repoRoot } from '../lib/git.js';
5
- import { harnessVersion, packageHarness } from '../lib/upstream.js';
5
+ import { harnessVersion, packageHarness, packageVersion } from '../lib/upstream.js';
6
6
  import { candidateCount } from '../lib/retro.js';
7
7
  import { driftGenerated } from '../lib/vendor-write.js';
8
8
  import { report } from '../lib/verdict.js';
@@ -34,6 +34,8 @@ function harnessStatus(root) {
34
34
  tier: null,
35
35
  installedVersion: null,
36
36
  packageVersion: null,
37
+ cliInstalled: null,
38
+ cliPackage: null,
37
39
  drift: none,
38
40
  };
39
41
  const y = safe(() => parse(readFileSync(pin, 'utf8')) ?? {}, {});
@@ -43,6 +45,8 @@ function harnessStatus(root) {
43
45
  tier: str(y['tier']) || null,
44
46
  installedVersion: str(y['version']) || null,
45
47
  packageVersion: safe(() => harnessVersion(packageHarness()), null),
48
+ cliInstalled: str(y['cli']) || null,
49
+ cliPackage: safe(() => packageVersion(), null),
46
50
  drift: {
47
51
  ok: findings.length === 0,
48
52
  reasons: distinct(findings.map((f) => f.reason)),
@@ -76,6 +80,15 @@ export function nextForIntent(s) {
76
80
  s.open === 0 &&
77
81
  s.planned.some((t) => closed(t) && !recorded(t)))
78
82
  return 'pl: create tickets';
83
+ const first = [...(s.openTickets ?? [])].sort((a, b) => a.id.localeCompare(b.id, 'en', { numeric: true }))[0];
84
+ if (s.open > 0 && first) {
85
+ if (first.status === 'done')
86
+ return `reins-review: close ${first.id}`;
87
+ if (first.status === 'blocked')
88
+ return `pl: unblock ${first.id}`;
89
+ if (first.status === 'todo' || first.status === 'doing')
90
+ return `implementer: ${first.id} (reins-implement)`;
91
+ }
79
92
  if (s.broken.length > 0)
80
93
  return `invalid frontmatter (F2): ${s.broken.join(', ')}`;
81
94
  return '—';
@@ -113,6 +126,7 @@ function intentsStatus(root, tickets) {
113
126
  plan: statusOf(plan),
114
127
  open,
115
128
  openIds: tickets.map(ticketId),
129
+ openTickets: mine.map((t) => ({ id: ticketId(t), status: str(t.data['status']) || null })),
116
130
  planned,
117
131
  history,
118
132
  broken: [i, spec, plan].filter((f) => !!f?.error).map((f) => f.path),
@@ -208,7 +222,7 @@ export function formatStatus(d) {
208
222
  if (!h.installed)
209
223
  out.push('harness: not installed — run reins install');
210
224
  else
211
- out.push(`harness: ${h.tier ?? '?'} · installed v${h.installedVersion ?? '?'} · package v${h.packageVersion ?? '?'} · drift: ${h.drift.ok ? 'ok' : h.drift.reasons.join(', ')}${h.drift.ok ? '' : ' (reins check --drift)'}`);
225
+ out.push(`harness: ${h.tier ?? '?'} v${h.installedVersion ?? '?'} (package harness v${h.packageVersion ?? '?'}) · cli ${h.cliInstalled ?? 'none'} (running ${h.cliPackage ?? '?'}) · drift: ${h.drift.ok ? 'ok' : h.drift.reasons.join(', ')}${h.drift.ok ? '' : ' (reins check --drift)'}`);
212
226
  out.push('');
213
227
  out.push('intents:');
214
228
  if (d.intents.length === 0)
@@ -4,7 +4,7 @@ import { parse } from 'yaml';
4
4
  import { defaultsAsker } from '../lib/ask.js';
5
5
  import { overrides } from '../lib/blocks.js';
6
6
  import { repoRoot } from '../lib/git.js';
7
- import { harnessVersion, packageHarness } from '../lib/upstream.js';
7
+ import { harnessVersion, packageHarness, packageVersion } from '../lib/upstream.js';
8
8
  import { runInstall } from './install.js';
9
9
  /** Numeric dotted-version compare; pre-release suffixes are ignored. */
10
10
  export function newer(a, b) {
@@ -48,6 +48,8 @@ export async function runUpdate(o) {
48
48
  const up = packageHarness();
49
49
  res.from = pin.version;
50
50
  res.to = harnessVersion(up);
51
+ res.cliFrom = pin.cli ? String(pin.cli) : 'none';
52
+ res.cliTo = packageVersion();
51
53
  const cl = join(up, 'CHANGELOG.md');
52
54
  if (existsSync(cl) && newer(res.to, res.from)) {
53
55
  res.changes = changesBetween(readFileSync(cl, 'utf8'), res.from, res.to);
@@ -65,6 +67,7 @@ export async function runUpdate(o) {
65
67
  now: o.now,
66
68
  detectVendors: o.detectVendors,
67
69
  recordAs: 'update',
70
+ retire: true,
68
71
  });
69
72
  return res;
70
73
  }
@@ -1,5 +1,6 @@
1
1
  import { execFileSync, spawnSync } from 'node:child_process';
2
2
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
+ import { compound } from '../commands/gate.js';
3
4
  import { join } from 'node:path';
4
5
  export function generation(root) {
5
6
  const agents = join(root, 'AGENTS.md');
@@ -66,7 +67,7 @@ const MUTATING = /--fix\b|--write\b|\bfmt\b(?!:check)|(^|\s)format(\s|$)/;
66
67
  * prefer the aggregate `check` the hooks and CI already call.
67
68
  */
68
69
  export function discoverGates(root) {
69
- const res = { gates: [], excluded: [] };
70
+ const res = { gates: [], excluded: [], proposals: subdirProposals(root) };
70
71
  const run = runner(root);
71
72
  const pkgPath = join(root, 'package.json');
72
73
  if (run && run !== 'make' && existsSync(pkgPath)) {
@@ -103,6 +104,118 @@ export function discoverGates(root) {
103
104
  }
104
105
  return res;
105
106
  }
107
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'vendor', '.loctx', '.agents']);
108
+ const MAX_DEPTH = 3;
109
+ const SAFE_DIR = /^[\w@.+-]+(\/[\w@.+-]+)*$/;
110
+ const ROOT_GATE_NAMES = ['check', 'test', 'build', 'e2e'];
111
+ const NODE_SCRIPTS = ['check', 'verify', 'ci', 'typecheck', 'lint', 'test', 'build'];
112
+ function dirRunner(root, dir, rootRunner) {
113
+ if (existsSync(join(root, dir, 'pnpm-lock.yaml')))
114
+ return 'pnpm';
115
+ if (existsSync(join(root, dir, 'yarn.lock')))
116
+ return 'yarn';
117
+ if (existsSync(join(root, dir, 'package-lock.json')))
118
+ return 'npm';
119
+ return rootRunner === 'pnpm' || rootRunner === 'yarn' ? rootRunner : 'npm';
120
+ }
121
+ const SOURCE_ORDER = ['npm', 'make', 'go'];
122
+ /**
123
+ * Gate candidates below the root (spec S-5): package.json scripts, Makefile targets and go.mod,
124
+ * to depth 3. One command each, using the tool's own directory option. The caller chooses.
125
+ */
126
+ export function subdirProposals(root) {
127
+ const cands = [];
128
+ const rootRunner = runner(root);
129
+ const walk = (dir, depth) => {
130
+ let entries;
131
+ try {
132
+ entries = readdirSync(join(root, dir), { withFileTypes: true });
133
+ }
134
+ catch {
135
+ return;
136
+ }
137
+ for (const e of entries) {
138
+ if (!e.isDirectory() || SKIP_DIRS.has(e.name))
139
+ continue;
140
+ const rel = dir ? `${dir}/${e.name}` : e.name;
141
+ if (!SAFE_DIR.test(rel))
142
+ continue;
143
+ const pkg = join(root, rel, 'package.json');
144
+ if (existsSync(pkg)) {
145
+ let scripts = {};
146
+ try {
147
+ scripts =
148
+ JSON.parse(readFileSync(pkg, 'utf8'))
149
+ .scripts ?? {};
150
+ }
151
+ catch {
152
+ // unreadable package.json: no proposals from it
153
+ }
154
+ const run = dirRunner(root, rel, rootRunner);
155
+ for (const sc of NODE_SCRIPTS)
156
+ if (sc in scripts && !MUTATING.test(scripts[sc] ?? '') && /^[\w:.-]+$/.test(sc)) {
157
+ const cmd = run === 'npm'
158
+ ? `npm --prefix ${rel} run ${sc}`
159
+ : run === 'yarn'
160
+ ? `yarn --cwd ${rel} ${sc}`
161
+ : `pnpm --dir ${rel} ${sc}`;
162
+ cands.push({
163
+ rel,
164
+ source: 'npm',
165
+ script: sc,
166
+ cmd,
167
+ from: `${rel}/package.json#scripts.${sc}`,
168
+ });
169
+ }
170
+ }
171
+ const mk = join(root, rel, 'Makefile');
172
+ if (existsSync(mk)) {
173
+ const text = readFileSync(mk, 'utf8');
174
+ for (const t of ['check', 'test', 'build'])
175
+ if (new RegExp(`^${t}:`, 'm').test(text))
176
+ cands.push({
177
+ rel,
178
+ source: 'make',
179
+ script: t,
180
+ cmd: `make -C ${rel} ${t}`,
181
+ from: `${rel}/Makefile:${t}`,
182
+ });
183
+ }
184
+ if (existsSync(join(root, rel, 'go.mod')))
185
+ for (const t of ['test', 'vet'])
186
+ cands.push({
187
+ rel,
188
+ source: 'go',
189
+ script: t,
190
+ cmd: `go -C ${rel} ${t} ./...`,
191
+ from: `${rel}/go.mod`,
192
+ });
193
+ if (depth < MAX_DEPTH)
194
+ walk(rel, depth + 1);
195
+ }
196
+ };
197
+ walk('', 1);
198
+ // Every candidate is kept. Names are settled in a fixed order (path, source, script): the first
199
+ // keeps `<dir-slug>-<script>`, a later one takes a source suffix, then -2, -3 … until free.
200
+ cands.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0) ||
201
+ SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source) ||
202
+ (a.script < b.script ? -1 : a.script > b.script ? 1 : 0));
203
+ const taken = new Set(ROOT_GATE_NAMES);
204
+ const out = [];
205
+ for (const c of cands) {
206
+ if (compound(c.cmd))
207
+ continue;
208
+ const base = `${c.rel.replace(/\//g, '-')}-${c.script}`;
209
+ let name = base;
210
+ if (taken.has(name))
211
+ name = `${base}-${c.source}`;
212
+ for (let i = 2; taken.has(name); i++)
213
+ name = `${base}-${c.source}-${i}`;
214
+ taken.add(name);
215
+ out.push({ name, cmd: c.cmd, from: c.from });
216
+ }
217
+ return out;
218
+ }
106
219
  /** Vendor of a model ID by prefix, in order: gpt, gemini, cursor-, else claude (spec S-2). */
107
220
  export function vendorOf(model) {
108
221
  if (model.startsWith('gpt'))
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join, relative, sep } from 'node:path';
3
3
  export function apply(root, writes, dryRun) {
4
- const out = { created: [], changed: [], unchanged: [] };
4
+ const out = { created: [], changed: [], unchanged: [], removed: [] };
5
5
  for (const w of writes) {
6
6
  const abs = join(root, w.path);
7
7
  const exists = existsSync(abs);
@@ -0,0 +1,96 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { listFiles } from './fsx.js';
4
+ import { isSecretPath } from './secrets.js';
5
+ const slug = (rel) => rel
6
+ .replace(/\.[^./]+$/, '')
7
+ .toLowerCase()
8
+ .replaceAll(/[^a-z0-9]+/g, '-')
9
+ .replaceAll(/^-+|-+$/g, '') || 'note';
10
+ /**
11
+ * `.claude/memory/*` is someone's own memory, not a decision (design §7): it is never moved or
12
+ * deleted. Each file becomes a knowledge draft the user may accept with `reins knowledge accept`.
13
+ * Pure: reads, never writes. A draft that already exists is left alone.
14
+ */
15
+ export function planMemoryProposals(root, today) {
16
+ const out = { writes: [], notes: [] };
17
+ const dir = join(root, '.claude/memory');
18
+ if (!existsSync(dir))
19
+ return out;
20
+ // a draft is identified by its `source:`, so names stay stable across runs
21
+ const pdir = join(root, '.loctx/knowledge-proposals');
22
+ const taken = new Set();
23
+ const drafted = new Set();
24
+ const srcOf = (file) => {
25
+ let text;
26
+ try {
27
+ text = readFileSync(file, 'utf8');
28
+ }
29
+ catch {
30
+ return null; // a directory or an unreadable entry names no source; its name stays taken
31
+ }
32
+ const m = /^source:\s*(.+)$/m.exec(text);
33
+ return m ? m[1].trim().replace(/^"(.*)"$/, '$1') : null;
34
+ };
35
+ // an accepted entry keeps the source: its draft had, so accepting does not cause a re-draft
36
+ const kdir = join(root, '.agents/knowledge');
37
+ if (existsSync(kdir))
38
+ for (const n of readdirSync(kdir)) {
39
+ if (!n.endsWith('.md'))
40
+ continue;
41
+ const src = srcOf(join(kdir, n));
42
+ if (src)
43
+ drafted.add(src);
44
+ }
45
+ if (existsSync(pdir))
46
+ for (const n of readdirSync(pdir)) {
47
+ if (!/^memory-.*\.md$/.test(n))
48
+ continue;
49
+ taken.add(n.slice(0, -3));
50
+ const src = srcOf(join(pdir, n));
51
+ if (src)
52
+ drafted.add(src);
53
+ }
54
+ for (const f of listFiles(dir)) {
55
+ const source = `.claude/memory/${f}`;
56
+ if (isSecretPath(source))
57
+ continue;
58
+ if (drafted.has(source))
59
+ continue;
60
+ const base = `memory-${slug(f)}`;
61
+ let name = base;
62
+ for (let i = 2; taken.has(name); i++)
63
+ name = `${base}-${i}`;
64
+ taken.add(name);
65
+ const path = `.loctx/knowledge-proposals/${name}.md`;
66
+ let text;
67
+ try {
68
+ text = readFileSync(join(dir, f), 'utf8');
69
+ }
70
+ catch {
71
+ continue;
72
+ }
73
+ out.writes.push({
74
+ path,
75
+ why: 'memory draft',
76
+ content: [
77
+ '---',
78
+ `id: ${today}_${name}`,
79
+ 'kind: decision',
80
+ 'status: active',
81
+ 'supersedes: null',
82
+ 'topics: []',
83
+ 'decisions: []',
84
+ 'symptoms: []',
85
+ 'applies_to: all',
86
+ `source: ${JSON.stringify(source)}`,
87
+ '---',
88
+ '## 결정',
89
+ text.replace(/\s*$/, ''),
90
+ '',
91
+ ].join('\n'),
92
+ });
93
+ out.notes.push(`memory draft ${path} from ${source} (original kept) — promote with \`reins knowledge accept ${name}\``);
94
+ }
95
+ return out;
96
+ }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
2
2
  import { basename, extname, join } from 'node:path';
3
3
  import { listFiles } from './fsx.js';
4
+ import { isSecretPath } from './secrets.js';
4
5
  import { splitFrontmatter } from './skills.js';
5
6
  const TOOL_EXT = new Set([
6
7
  '.cjs',
@@ -23,14 +24,131 @@ const isToolFile = (f) => TOOL_EXT.has(extname(f).toLowerCase()) || /dockerfile|
23
24
  function dirFiles(root, rel) {
24
25
  return listFiles(join(root, rel)).map((f) => `${rel}/${f}`);
25
26
  }
27
+ const natural = (a, b) => a.localeCompare(b, 'en', { numeric: true });
28
+ const slugOf = (fileName) => basename(fileName, '.md')
29
+ .toLowerCase()
30
+ .replaceAll(/[^a-z0-9]+/g, '-')
31
+ .replaceAll(/^-+|-+$/g, '') || 'work';
26
32
  /** A work file is open unless its frontmatter says done. */
27
- function isOpen(abs) {
28
- const { data } = splitFrontmatter(readFileSync(abs, 'utf8'));
29
- return !data || String(data['status'] ?? 'todo') !== 'done';
33
+ function workItem(root, path, dir) {
34
+ const { data } = splitFrontmatter(readFileSync(join(root, path), 'utf8'));
35
+ const fm = data ?? {};
36
+ const name = basename(path, '.md');
37
+ const version = String(fm['version'] ?? (name.includes('_') ? name.split('_')[0] : ''));
38
+ const sub = path.slice(dir.length + 1);
39
+ return {
40
+ path,
41
+ group: `${sub.includes('/') ? sub.slice(0, sub.lastIndexOf('/')) : ''}|${version}`,
42
+ id: fm['id'] == null ? '' : String(fm['id']),
43
+ deps: Array.isArray(fm['depends']) ? fm['depends'].map(String) : [],
44
+ open: !data || String(fm['status'] ?? 'todo') !== 'done',
45
+ };
46
+ }
47
+ /** Tickets an earlier run wrote (by `migrated_from`), and the highest `000-<n>` in use. */
48
+ function existingTickets(root) {
49
+ const list = [];
50
+ let max = 0;
51
+ const dir = '.loctx/ticket';
52
+ for (const f of existsSync(join(root, dir)) ? readdirSync(join(root, dir)) : []) {
53
+ const m = /^000-(\d+)_/.exec(f);
54
+ if (!m)
55
+ continue;
56
+ max = Math.max(max, Number(m[1]));
57
+ const { data } = splitFrontmatter(readFileSync(join(root, dir, f), 'utf8'));
58
+ if (!data?.['migrated_from'])
59
+ continue;
60
+ const from = String(data['migrated_from']);
61
+ const slash = from.lastIndexOf('/');
62
+ const name = basename(from, '.md');
63
+ list.push({
64
+ path: `${dir}/${f}`,
65
+ id: `000-${m[1]}`,
66
+ from,
67
+ origId: data['migrated_id'] == null ? '' : String(data['migrated_id']),
68
+ // tickets from before migrated_group: folder plus the filename's version prefix
69
+ group: data['migrated_group'] == null
70
+ ? `${slash < 0 ? '' : from.slice(0, slash)}|${name.includes('_') ? name.split('_')[0] : ''}`
71
+ : String(data['migrated_group']),
72
+ });
73
+ }
74
+ return { list, byFrom: new Map(list.map((t) => [t.from, t])), max };
75
+ }
76
+ /** Open work items become `000-1…000-N` in path order; `depends` is remapped only where exactly one item in the same folder and version carries the id, counting tickets from earlier runs. */
77
+ function planTickets(root, ai, files, moves) {
78
+ for (const f of files.filter((x) => !x.endsWith('.md')))
79
+ moves.push({
80
+ from: f,
81
+ to: `.loctx/history/work/${f.slice(`${ai}/work/`.length)}`,
82
+ action: 'move',
83
+ why: 'closed work item',
84
+ });
85
+ const items = files
86
+ .filter((f) => f.endsWith('.md'))
87
+ .toSorted(natural)
88
+ .map((f) => workItem(root, f, `${ai}/work`));
89
+ const prior = existingTickets(root);
90
+ let next = prior.max;
91
+ const numberOf = new Map();
92
+ const pending = [];
93
+ for (const it of items) {
94
+ const sub = it.path.slice(`${ai}/work/`.length);
95
+ if (!it.open) {
96
+ moves.push({
97
+ from: it.path,
98
+ to: `.loctx/history/work/${sub}`,
99
+ action: 'move',
100
+ why: 'closed work item',
101
+ });
102
+ continue;
103
+ }
104
+ const was = prior.byFrom.get(sub);
105
+ const m = was
106
+ ? { from: it.path, to: was.path, action: 'ticket', existing: true, why: 'already migrated' }
107
+ : {
108
+ from: it.path,
109
+ to: '',
110
+ action: 'ticket',
111
+ why: 'open work item → ticket',
112
+ group: it.group,
113
+ };
114
+ if (was)
115
+ numberOf.set(it.path, was.id);
116
+ else {
117
+ next += 1;
118
+ m.n = next;
119
+ m.to = `.loctx/ticket/000-${next}_${slugOf(it.path)}.md`;
120
+ numberOf.set(it.path, `000-${next}`);
121
+ }
122
+ moves.push(m);
123
+ pending.push({ move: m, item: it });
124
+ }
125
+ const here = new Set(items.map((i) => i.path.slice(`${ai}/work/`.length)));
126
+ for (const { move, item } of pending) {
127
+ if (move.existing)
128
+ continue;
129
+ const idMap = {};
130
+ const dropped = [];
131
+ for (const d of item.deps) {
132
+ const same = items.filter((p) => p.group === item.group && p.id === d);
133
+ const old = prior.list.filter((t) => t.group === item.group && t.origId === d && !here.has(t.from));
134
+ if (same.length + old.length !== 1)
135
+ dropped.push(d);
136
+ else if (old[0])
137
+ idMap[d] = old[0].id;
138
+ else if (same[0]?.open) {
139
+ const target = numberOf.get(same[0].path);
140
+ if (target)
141
+ idMap[d] = target;
142
+ } // finished — nothing to wait for
143
+ }
144
+ move.idMap = idMap;
145
+ move.dropped = dropped;
146
+ }
30
147
  }
31
- export function planMigration(root) {
148
+ export function planMigration(root, opts = {}) {
32
149
  const moves = [];
33
150
  const report = [];
151
+ const legacyDir = opts.legacy === 'committed' ? '.agents/legacy/' : '.loctx/_legacy/';
34
152
  const ai = '.ai';
35
153
  if (!existsSync(join(root, ai)))
36
154
  return { moves, report };
@@ -51,21 +169,7 @@ export function planMigration(root) {
51
169
  });
52
170
  continue;
53
171
  case 'work':
54
- for (const f of files)
55
- if (f.endsWith('.md') && isOpen(join(root, f)))
56
- moves.push({
57
- from: f,
58
- to: `.loctx/ticket/${sub(f)}`,
59
- action: 'ticket',
60
- why: 'open work item → ticket',
61
- });
62
- else
63
- moves.push({
64
- from: f,
65
- to: `.loctx/history/work/${sub(f)}`,
66
- action: 'move',
67
- why: 'closed work item',
68
- });
172
+ planTickets(root, ai, files, moves);
69
173
  continue;
70
174
  case 'release':
71
175
  case 'pr':
@@ -101,7 +205,7 @@ export function planMigration(root) {
101
205
  action: 'legacy',
102
206
  why: 'verification assets — review before committing',
103
207
  });
104
- report.push(`${rel}/ (${files.length} files) kept in .loctx/_legacy/ — promote what should be committed to test/`);
208
+ report.push(`${rel}/ (${files.length} files) moved to ${legacyDir} — promote what should be committed to test/`);
105
209
  continue;
106
210
  case 'plan':
107
211
  for (const f of files)
@@ -176,14 +280,7 @@ export function planMigration(root) {
176
280
  }
177
281
  seen.add(m.to);
178
282
  }
179
- // .claude/memory (AI-GW) → knowledge; old procedures → legacy
180
- for (const f of dirFiles(root, '.claude/memory'))
181
- moves.push({
182
- from: f,
183
- to: `.agents/knowledge/${f.slice('.claude/memory/'.length)}`,
184
- action: 'move',
185
- why: 'shared memory → knowledge',
186
- });
283
+ // old procedures → legacy (.claude/memory is left in place; install drafts knowledge proposals)
187
284
  for (const d of [
188
285
  '.claude/commands',
189
286
  ...(existsSync(join(root, '.claude/skills'))
@@ -201,30 +298,60 @@ export function planMigration(root) {
201
298
  why: 'replaced by reins skills',
202
299
  });
203
300
  if (fs.length)
204
- report.push(`${d}/ moved to .loctx/_legacy/ — keep any project-specific procedure as a skill in .agents/skills/`);
301
+ report.push(`${d}/ moved to ${legacyDir} — keep any project-specific procedure as a skill in .agents/skills/`);
302
+ }
303
+ if (opts.legacy === 'committed') {
304
+ // committed legacy goes to .agents/legacy/ — except what looks like a secret, which stays local
305
+ const kept = [];
306
+ let moved = 0;
307
+ for (const m of moves) {
308
+ if (m.action !== 'legacy')
309
+ continue;
310
+ if (isSecretPath(m.from)) {
311
+ kept.push(m.from);
312
+ m.why += ' (secret pattern — kept local)';
313
+ }
314
+ else {
315
+ m.to = m.to.replace('.loctx/_legacy/', '.agents/legacy/');
316
+ moved += 1;
317
+ }
318
+ }
319
+ for (const k of kept)
320
+ report.push(`${k} matches a secret pattern — kept in .loctx/_legacy/, not .agents/legacy/`);
321
+ if (moved)
322
+ report.push(`.agents/legacy/ (${moved} files) — review before committing: a script or config there can still hold a secret the patterns do not catch`);
205
323
  }
206
324
  return { moves, report };
207
325
  }
208
- /** work → ticket frontmatter (design §7): `release: <ver>-rc.N` becomes planned; the rest carries over. */
209
- export function convertWorkToTicket(text, fileName) {
326
+ /**
327
+ * work → ticket frontmatter (design §7): `release: <ver>-rc.N` becomes planned; the rest carries over.
328
+ * `n` and `idMap` come from planMigration: the number this item gets, and the new ids its `depends` can use.
329
+ */
330
+ export function convertWorkToTicket(text, fileName, n, idMap = {}, dropped = [], group = '') {
210
331
  const { data, body } = splitFrontmatter(text);
211
332
  const fm = data ?? {};
212
333
  const rel = String(fm['release'] ?? '');
334
+ const origId = fm['id'] == null ? '' : String(fm['id']);
335
+ const depends = (Array.isArray(fm['depends']) ? fm['depends'].map(String) : [])
336
+ .map((d) => idMap[d])
337
+ .filter((d) => d !== undefined);
213
338
  const ticket = {
214
339
  // intent 000 = not yet tied to an intent; the PL links it when the work is planned again
215
- id: `000-${Number.parseInt(String(fm['id'] ?? ''), 10) || 1}`,
340
+ id: `000-${n}`,
216
341
  intent: '000',
217
- plan_step: Number(fm['id'] ?? 1) || 1,
342
+ plan_step: Number.parseInt(origId, 10) || 1,
218
343
  title: String(fm['title'] ?? basename(fileName, '.md')),
219
344
  status: ['todo', 'doing', 'blocked', 'done'].includes(String(fm['status']))
220
345
  ? String(fm['status'])
221
346
  : 'todo',
222
- depends: Array.isArray(fm['depends']) ? fm['depends'] : [],
347
+ depends,
223
348
  release: /rc\.(\d+)/.exec(rel) && Number(/rc\.(\d+)/.exec(rel)?.[1]) > 1 ? 'stabilization' : 'planned',
224
349
  role: 'implementer',
225
- asks: [],
350
+ asks: dropped.map((d) => `depends on ${d} (${fileName}) could not be matched to one migrated ticket — set it by hand`),
226
351
  ...(fm['branch'] ? { branch: fm['branch'] } : {}),
227
352
  migrated_from: fileName,
353
+ ...(origId ? { migrated_id: origId } : {}),
354
+ ...(group ? { migrated_group: group } : {}),
228
355
  };
229
356
  const yaml = Object.entries(ticket)
230
357
  .map(([k, v]) => `${k}: ${JSON.stringify(v)}`)
@@ -0,0 +1,54 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ /** Reads `release:` from install.yaml; null when the file or the key is missing or malformed. */
5
+ export function readRelease(root) {
6
+ const p = join(root, '.agents/harness/install.yaml');
7
+ if (!existsSync(p))
8
+ return null;
9
+ let doc;
10
+ try {
11
+ doc = parse(readFileSync(p, 'utf8'));
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ const list = doc?.release?.workflows;
17
+ if (!Array.isArray(list))
18
+ return null;
19
+ const out = [];
20
+ for (const w of list) {
21
+ if (!w || typeof w['file'] !== 'string')
22
+ continue;
23
+ const inputs = {};
24
+ for (const [k, v] of Object.entries(w['inputs'] ?? {}))
25
+ inputs[k] = String(v);
26
+ const explicit = Array.isArray(w['stages']);
27
+ const stages = Array.isArray(w['stages'])
28
+ ? w['stages'].filter((s) => s === 'rc' || s === 'stable')
29
+ : [];
30
+ out.push({
31
+ file: w['file'],
32
+ inputs,
33
+ stages: explicit ? stages : ['rc', 'stable'],
34
+ approval: w['approval'] === 'npm-staged' ? 'npm-staged' : 'none',
35
+ });
36
+ }
37
+ return out;
38
+ }
39
+ /** POSIX single-quote `s` unless it only has safe characters. */
40
+ export function shq(s) {
41
+ return /^[A-Za-z0-9_.,:/@%+=-]+$/.test(s) ? s : `'${s.split("'").join("'\\''")}'`;
42
+ }
43
+ /** The `gh workflow run` lines for one stage; `{version}` in an input value becomes `version`. */
44
+ export function dispatchLines(workflows, stage, version) {
45
+ return workflows
46
+ .filter((w) => w.stages.includes(stage))
47
+ .map((w) => {
48
+ const args = Object.entries(w.inputs).flatMap(([k, v]) => [
49
+ '-f',
50
+ shq(`${k}=${v.split('{version}').join(version)}`),
51
+ ]);
52
+ return ['gh workflow run', shq(w.file), ...args].join(' ');
53
+ });
54
+ }
@@ -83,6 +83,8 @@ export function schemaFor(rel) {
83
83
  if (/(^|\/)(knowledge|knowledge-seeds\/[^/]+)\/[^/]+\.md$/.test(rel) ||
84
84
  rel.endsWith('templates/knowledge.md'))
85
85
  return { schema: 'knowledge', whole: false };
86
+ if (rel.endsWith('.agents/harness/install.yaml'))
87
+ return { schema: 'install', whole: true };
86
88
  if (name.endsWith('.request.yaml') || rel.endsWith('templates/bus/request.yaml'))
87
89
  return { schema: 'bus-request', whole: true };
88
90
  if (name.endsWith('.response.yaml') || rel.endsWith('templates/bus/response.yaml'))
@@ -3,6 +3,7 @@ import { matchesAny } from './glob.js';
3
3
  export const DEFAULT_SECRET_PATTERNS = [
4
4
  '.env',
5
5
  '.env.*',
6
+ '*.env',
6
7
  'secrets/**',
7
8
  '*.key',
8
9
  '*.pem',
package/cli/dist/reins.js CHANGED
@@ -8,7 +8,7 @@ import { acceptKnowledge, dismissKnowledge, proposeKnowledge } from './commands/
8
8
  import { formatRetro, runRetro } from './commands/retro.js';
9
9
  import { runStatus } from './commands/status.js';
10
10
  import { runUpdate } from './commands/update.js';
11
- import { configureBindings } from './commands/configure.js';
11
+ import { configureBindings, configureGates } from './commands/configure.js';
12
12
  import { respondRefusal, runGates, writeResponse } from './commands/gate.js';
13
13
  import { newIntent, newRequest, newTicket } from './commands/new.js';
14
14
  import { collectMetrics, formatMetrics, logCheck, logGates, recordUsage, } from './commands/metrics.js';
@@ -74,15 +74,26 @@ program
74
74
  .description('move an existing harness or .ai/ workspace onto the reins layout')
75
75
  .argument('<tier>', 'harness | loop | graph')
76
76
  .option('--mode <mode>', 'manual | auto', 'manual')
77
+ .option('--legacy <where>', 'local (.loctx/_legacy/) | committed (.agents/legacy/)', 'local')
77
78
  .option('--dry-run', 'show the moves without touching anything')
78
79
  .option('--json')
79
80
  .action(async (tier, o) => {
81
+ if (!['local', 'committed'].includes(o.legacy)) {
82
+ process.stderr.write(`reins migrate: --legacy must be local or committed (got "${o.legacy}")\n`);
83
+ process.exit(2);
84
+ }
80
85
  if (!['harness', 'loop', 'graph'].includes(tier)) {
81
86
  process.stderr.write(`reins migrate: tier must be harness, loop or graph (got "${tier}")\n`);
82
87
  process.exit(2);
83
88
  }
84
89
  const asker = o.mode === 'auto' || o.dryRun ? defaultsAsker : await stdinAsker();
85
- const r = await runMigrate({ tier: tier, mode: o.mode, dryRun: o.dryRun, asker });
90
+ const r = await runMigrate({
91
+ tier: tier,
92
+ mode: o.mode,
93
+ dryRun: o.dryRun,
94
+ legacy: o.legacy,
95
+ asker,
96
+ });
86
97
  asker.close();
87
98
  if (o.json) {
88
99
  process.stdout.write(`${JSON.stringify(r, null, 2)}\n`);
@@ -122,13 +133,17 @@ program
122
133
  process.exit(2);
123
134
  }
124
135
  const a = r.install?.applied;
125
- process.stdout.write(`reins update — harness v${r.from} → v${r.to}${o.dryRun ? ' (dry run)' : ''}\n`);
136
+ process.stdout.write(`reins update — cli ${r.cliFrom === 'none' ? 'none' : `v${r.cliFrom}`} → v${r.cliTo}, harness v${r.from} → v${r.to}${o.dryRun ? ' (dry run)' : ''}\n`);
126
137
  for (const c of r.changes)
127
138
  process.stdout.write(` · ${c}\n`);
128
- if (a) {
129
- process.stdout.write(`${o.dryRun ? 'would write' : 'wrote'}: ${a.created.length} new, ${a.changed.length} changed\n`);
139
+ if (a && a.created.length + a.changed.length + a.removed.length === 0)
140
+ process.stdout.write('already up to date\n');
141
+ else if (a) {
142
+ process.stdout.write(`${o.dryRun ? 'would write' : 'wrote'}: ${a.created.length} new, ${a.changed.length} changed${a.removed.length ? `, ${a.removed.length} removed` : ''}\n`);
130
143
  for (const p of [...a.created, ...a.changed])
131
144
  process.stdout.write(` ~ ${p}\n`);
145
+ for (const p of a.removed)
146
+ process.stdout.write(` - ${p} (no longer installed by this tier)\n`);
132
147
  }
133
148
  for (const n of r.overrides)
134
149
  process.stdout.write(`• block "${n}" is overridden by the project — compare it with the new upstream block\n`);
@@ -175,6 +190,28 @@ configure
175
190
  process.stdout.write(`• left alone ${x.path}: ${x.why}\n`);
176
191
  }
177
192
  });
193
+ configure
194
+ .command('gates')
195
+ .description('subdirectory gate proposals not in gates.yaml; --add <name>… appends them')
196
+ .option('--add <names...>', 'proposal names to append after the existing gates')
197
+ .option('--json')
198
+ .action((o) => {
199
+ const r = configureGates({ add: o.add });
200
+ if (o.json) {
201
+ process.stdout.write(`${JSON.stringify(r, null, 2)}\n`);
202
+ process.exit(r.code ?? 0);
203
+ }
204
+ if (r.refused) {
205
+ process.stderr.write(`reins configure gates: ${r.refused}\n`);
206
+ process.exit(r.code ?? 2);
207
+ }
208
+ for (const n of r.added)
209
+ process.stdout.write(`added: ${n}\n`);
210
+ if (!r.available.length)
211
+ process.stdout.write('no more proposals\n');
212
+ for (const g of r.available)
213
+ process.stdout.write(` ${g.name} ${g.cmd} (${g.from})\n`);
214
+ });
178
215
  program
179
216
  .command('gate')
180
217
  .description('run gates.yaml gates as declared; raw output goes to .loctx/reports/ as T3 evidence')
package/docs/README.ko.md CHANGED
@@ -122,7 +122,8 @@ reins 자체를 개발하려면 `git clone https://github.com/bluenyang/reins.gi
122
122
  | `metrics` | 구현됨 | `.loctx/reports/metrics.jsonl` 요약: 역할·벤더·ticket·intent별 토큰, ticket당 knowledge 정지 수. `metrics record`로 역할 실행의 토큰을 남깁니다 |
123
123
  | `recall` | 미구현 | 증상으로 과거 결정을 찾습니다 |
124
124
  | `doctor` | 미구현 | — |
125
- | `configure budget\|gates\|language` | 미구현 | — |
125
+ | `configure gates` | 구현됨 | 하위 디렉터리 게이트 제안을 보여 줍니다. `--add <name>...`은 gates.yaml 끝에 덧붙입니다 |
126
+ | `configure budget\|language` | 미구현 | — |
126
127
 
127
128
  `install`, `migrate`, `update`, `gate`, `status`, `check`, `metrics`는 `--json`을 받습니다. `check`와 `gate`는 실행할 때마다 `.loctx/reports/metrics.jsonl`에 한 줄을 남깁니다. `check`의 stage는
128
129
  T1(`ticket-start`), T2(`pre-commit`), T3(`verdict`), T4(`pre-push`), T5(`rc-close`)에 대응합니다.
@@ -9,7 +9,7 @@ rules:
9
9
  text: Editing one's own permission file or any generated vendor file.
10
10
  - id: C4
11
11
  text: Reading secret files.
12
- patterns: ['.env', '.env.*', 'secrets/**', '*.key', '*.pem', '*.p12', '*.pfx', '*.properties', 'id_rsa', 'id_rsa.*', 'id_ed25519', 'id_ed25519.*']
12
+ patterns: ['.env', '.env.*', '*.env', 'secrets/**', '*.key', '*.pem', '*.p12', '*.pfx', '*.properties', 'id_rsa', 'id_rsa.*', 'id_ed25519', 'id_ed25519.*']
13
13
  allowed: ['.env.example', '*.example', '*.example.*', '*.sample']
14
14
  - id: C5
15
15
  text: Bypassing hooks (--no-verify) or massaging gate output (pipes that hide the exit code).
@@ -4,7 +4,7 @@ default_binding: "claude-haiku-5-5"
4
4
  summary: "Pushes, opens PRs, cuts rc releases and publishes notes — inside the pre-release loop only."
5
5
  may:
6
6
  - "push the feature branch; open and rebase-merge the PR when checks are green"
7
- - "run the rc release workflow; publish release notes"
7
+ - "dispatch the release workflows the repository configures (install.yaml release:); publish release notes"
8
8
  - "escalate to claude-sonnet-5-5 then claude-opus-5-5 on failure"
9
9
  must_not:
10
10
  - "cut a stable release (user's explicit instruction, every time)"
@@ -20,19 +20,26 @@ Stage skills: `reins-release`.
20
20
 
21
21
  ## Merge procedure (design §4 PR flow)
22
22
 
23
- 1. Push the feature branch (`type/topic`); never push to `master`/`main` (T4 holds it, A4).
23
+ The merge target is the repository's default branch (`gh repo view --json defaultBranchRef -q .defaultBranchRef.name`), never a name assumed in advance.
24
+
25
+ 1. Push the feature branch (`type/topic`); never push to the default branch (T4 holds it, A4).
24
26
  2. Open the PR with `gh pr create`; the body comes from the docs role.
25
27
  3. Wait: `gh pr checks --watch`.
26
28
  4. Only when every required check is green: `gh pr merge --rebase --delete-branch`.
27
29
  5. If any check is red, do not merge. Return it to the PL (D2: a red check twice).
30
+ 6. Without `release:` in `.agents/harness/install.yaml` the work ends here: report "no release settings".
28
31
 
29
32
  ## rc procedure (design §4)
30
33
 
31
34
  1. Run `reins check --stage rc-close --release <V>`. Anything but CONTINUE (open `release: planned` or `release: stabilization` tickets, F2) means no dispatch.
32
- 2. Take the rc number T5 reports (`next rc: <V>-rc.<N>`; rc.1 when `.loctx/release/<V>.md` is missing).
33
- 3. Note the time, then `gh workflow run publish.yml -f version=<V>-rc.<N> -f dry_run=false`.
34
- 4. Identify the dispatched run: poll `gh run list --workflow publish.yml --event workflow_dispatch --json databaseId,displayTitle,headSha,createdAt` (every 5 s, up to ~60 s) for a run whose `displayTitle` is exactly `publish <V>-rc.<N> (dry_run=false)`, `createdAt` is after the noted time and `headSha` is the master commit being released. Never fall back to another run; none found means stop and report to the PL. Then `gh run watch <id> --exit-status`. On failure: no ledger line; report to the PL.
35
- 5. Only on success: read the stage id from that run's log line "staged with id …" and its release commit/tag, then append `- rc.<N> <commit> <stage-id> <date>` to `.loctx/release/<V>.md` (local ledger, not committed).
36
- 6. Ask the user to approve the staged version on npm. Fixes after an rc are `release: stabilization` tickets; the next rc follows the next T5 pass.
37
- 7. Stable (`version=<V>`) only on the user's explicit instruction; the workflow requires a `v<V>-rc.*` tag at master HEAD. After the stable version is approved on npm, set the intent's `status: released` in its intent.md (S-8, intent 011) and commit it.
35
+ 2. T5 prints the next rc (`next rc: <V>-rc.<N>`; rc.1 when `.loctx/release/<V>.md` is missing) and one `dispatch: gh workflow run <file> -f k=v …` line per workflow configured for the rc stage (also in `--json`). Or "no release settings": stop after the merge.
36
+ 3. Before dispatching record the current UTC time and the expected head commit (the default-branch commit being released). Run each `dispatch:` line exactly as printed. If the run is refused for permissions, do not look for another way: hand the printed line to the user and wait.
37
+ 4. Identify the run (every approval mode): `gh run list --workflow <file> --event workflow_dispatch --json databaseId,displayTitle,headSha,createdAt`, keeping runs whose `headSha` equals the expected commit and `createdAt` >= the recorded UTC time. Exactly one match: `gh run watch <id> --exit-status`. Zero or several: stop and ask the user, never guess. On failure: no ledger line; report to the PL.
38
+ 5. On success append `- rc.<N> <commit> <date>` to `.loctx/release/<V>.md` (local ledger, not committed). Fixes after an rc are `release: stabilization` tickets; the next rc follows the next T5 pass.
39
+ 6. Stable only on the user's explicit instruction (A2): the same workflows whose `stages` include stable, with `{version}` = `<V>`. Then set the intent's `status: released` in its intent.md and commit it.
40
+
41
+ ### `approval: npm-staged` (added steps, only for workflows with this value)
38
42
 
43
+ - Step 4: the one matching run must also have a `displayTitle` that carries the dispatched version.
44
+ - Step 5: read the stage id from that run's log line "staged with id …" and add it to the ledger line: `- rc.<N> <commit> <stage-id> <date>`. Then ask the user to approve the staged version on npm.
45
+ - Step 6: the workflow requires a `v<V>-rc.*` tag exactly at the default branch HEAD; after the stable version is approved on npm, set the intent `status: released`.
@@ -0,0 +1,29 @@
1
+ { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "reins/install@1", "type": "object",
2
+ "required": ["schema", "tier", "version"],
3
+ "properties": {
4
+ "schema": { "const": "reins/install@1" },
5
+ "tier": { "enum": ["harness", "loop", "graph"] },
6
+ "version": { "type": "string" },
7
+ "cli": { "type": "string" },
8
+ "mode": { "enum": ["manual", "auto"] },
9
+ "language": { "type": "string" },
10
+ "release": {
11
+ "type": "object",
12
+ "required": ["workflows"],
13
+ "properties": {
14
+ "workflows": {
15
+ "type": "array",
16
+ "items": {
17
+ "type": "object",
18
+ "required": ["file"],
19
+ "properties": {
20
+ "file": { "type": "string", "minLength": 1 },
21
+ "inputs": { "type": "object", "additionalProperties": { "type": "string" } },
22
+ "stages": { "type": "array", "minItems": 1, "items": { "enum": ["rc", "stable"] } },
23
+ "approval": { "enum": ["npm-staged", "none"] }
24
+ }
25
+ }
26
+ }
27
+ }
28
+ }
29
+ } }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bluenyang/reins",
3
- "version": "0.1.3",
3
+ "version": "0.1.4-rc.1",
4
4
  "description": "Installs, migrates and updates an agent harness (harness → loop → graph) that keeps coding agents inside their permitted roles.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: reins-release
3
- description: Release a finished version as the deploy role — T5 rc-close check, then branch → PR → green CI → merge, then the rc dispatch and ledger. Stable only on the user's explicit instruction. Use when the version is tested and the user says release, open the PR or cut the rc. Never pushes to the default branch directly.
3
+ description: Release a finished version as the deploy role — T5 rc-close check, then branch → PR → green CI → merge, then the configured release dispatch and ledger. Stable only on the user's explicit instruction. Use when the version is tested and the user says release, open the PR or cut the rc. Never pushes to the default branch directly.
4
4
  ---
5
5
 
6
6
  # reins-release
@@ -8,7 +8,7 @@ description: Release a finished version as the deploy role — T5 rc-close check
8
8
  deploy role, inside the pre-release loop only. Run the CLI as `npx @bluenyang/reins@<v>` where `<v>` is `cli` in `.agents/harness/install.yaml` (no `cli` line: installed before 0.1.3, run `npx @bluenyang/reins@latest update` once) (inside the reins repository: `node cli/dist/reins.js`). Verdicts: CONTINUE (exit 0) go on · HOLD (10) ask the user, one line: reason id + what you need · STOP (20) do what `resume` says, then re-run the same check · ESCALATE (30) next role in the chain (pl → pm → advisor → user).
9
9
 
10
10
  1. **Check first (T5).** `reins check --stage rc-close --release <version>`. Not CONTINUE → no dispatch; follow the verdict. T4 runs in the pre-push hook and holds a direct push to the default branch.
11
- 2. Follow the deploy role's procedures in `.agents/harness/roles/deploy.md`: **Merge procedure** (push the feature branch, `gh pr create`, `gh pr checks --watch`, `gh pr merge --rebase --delete-branch` on green only) and **rc procedure** (rc number from T5, dispatch, identify the run, ledger line, user approves on npm). Do not restate them here; announce each step.
11
+ 2. Follow the deploy role's procedures in `.agents/harness/roles/deploy.md`: **Merge procedure** (push the feature branch, `gh pr create`, `gh pr checks --watch`, `gh pr merge --rebase --delete-branch` on green only) and **rc procedure** (run the `dispatch:` lines T5 prints, watch the run, ledger line; a workflow with `approval: npm-staged` adds the steps deploy.md lists for it). The merge target is the repository's default branch. With no `release:` in `install.yaml`, stop after the merge and report "no release settings". If a dispatch is refused for permissions, hand the printed line to the user. Do not restate the procedures here; announce each step.
12
12
  3. Stable is always the user's explicit call (A2); then set the intent `status: released` as deploy.md says.
13
13
  4. Anything in stop group A → stop and report.
14
14
 
@@ -6,7 +6,7 @@ description: Install reins in this repository, or move an existing harness onto
6
6
  # reins-setup
7
7
 
8
8
  You act as the **pm** role (`.agents/harness/roles/pm.md` once installed). The CLI does the work; you collect
9
- the answers only the user can give and report what happened. Run the CLI as `npx @bluenyang/reins@0.1.3 …`
9
+ the answers only the user can give and report what happened. Run the CLI as `npx @bluenyang/reins@0.1.4-rc.1 …`
10
10
  (the version is pinned to this skill's release; inside the reins repository itself: `node cli/dist/reins.js …`).
11
11
 
12
12
  Defaults from the plugin settings: language `${user_config.language}`, install mode `${user_config.default_mode}`.