@bluenyang/reins 0.2.0 → 0.3.0-rc.2

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 (97) hide show
  1. package/README.md +50 -203
  2. package/cli/dist/commands/config-models.js +206 -127
  3. package/cli/dist/commands/config.js +104 -16
  4. package/cli/dist/commands/configure.js +166 -134
  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 +111 -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/prompter.js +4 -4
  15. package/cli/dist/lib/reader.js +20 -0
  16. package/cli/dist/lib/upstream.js +0 -17
  17. package/cli/dist/lib/vendor-write.js +9 -56
  18. package/cli/dist/reins.js +59 -270
  19. package/docs/README.ko.md +31 -204
  20. package/harness/CHANGELOG.md +8 -3
  21. package/harness/VERSION +1 -1
  22. package/harness/models.yaml +8 -0
  23. package/harness/policy/common-red-lines.yaml +4 -4
  24. package/harness/roles/advisor.md +10 -14
  25. package/harness/roles/auditor.md +17 -0
  26. package/harness/roles/executor.md +32 -0
  27. package/harness/roles/implementer.md +23 -21
  28. package/harness/roles/pl.md +44 -21
  29. package/harness/roles/planner.md +17 -19
  30. package/harness/roles/pm.md +16 -21
  31. package/harness/schemas/bindings.schema.json +55 -0
  32. package/harness/schemas/install.schema.json +1 -2
  33. package/harness/schemas/intent.schema.json +1 -13
  34. package/harness/templates/agents-md-blocks.md +52 -17
  35. package/harness/templates/audit.md +25 -0
  36. package/harness/templates/history.md +14 -0
  37. package/harness/templates/intent.md +5 -0
  38. package/harness/templates/spec.md +4 -2
  39. package/package.json +1 -2
  40. package/skills/audit/SKILL.md +28 -0
  41. package/skills/implement/SKILL.md +30 -0
  42. package/skills/intent/SKILL.md +28 -0
  43. package/skills/merge/SKILL.md +26 -0
  44. package/skills/onboard/SKILL.md +31 -0
  45. package/skills/reins-setup/SKILL.md +16 -25
  46. package/skills/release/SKILL.md +26 -0
  47. package/skills/retro/SKILL.md +30 -0
  48. package/skills/review/SKILL.md +27 -0
  49. package/skills/roadmap/SKILL.md +29 -0
  50. package/skills/spec/SKILL.md +27 -0
  51. package/skills/test/SKILL.md +26 -0
  52. package/cli/dist/commands/check.js +0 -379
  53. package/cli/dist/commands/gate.js +0 -136
  54. package/cli/dist/commands/knowledge.js +0 -111
  55. package/cli/dist/commands/metrics.js +0 -138
  56. package/cli/dist/commands/new.js +0 -190
  57. package/cli/dist/commands/retro.js +0 -7
  58. package/cli/dist/commands/stages.js +0 -562
  59. package/cli/dist/commands/status.js +0 -281
  60. package/cli/dist/lib/enforcement.js +0 -125
  61. package/cli/dist/lib/memory.js +0 -96
  62. package/cli/dist/lib/metrics.js +0 -223
  63. package/cli/dist/lib/retro.js +0 -179
  64. package/cli/dist/lib/verdict.js +0 -15
  65. package/cli/dist/lib/work.js +0 -106
  66. package/cli/dist/scripts/enforcement.js +0 -24
  67. package/harness/policy/budget.yaml +0 -13
  68. package/harness/policy/enforcement.yaml +0 -98
  69. package/harness/policy/stops.yaml +0 -29
  70. package/harness/policy/transitions.yaml +0 -13
  71. package/harness/roles/code-review.md +0 -27
  72. package/harness/roles/deploy.md +0 -50
  73. package/harness/roles/docs.md +0 -19
  74. package/harness/roles/lookup.md +0 -22
  75. package/harness/roles/qa-design.md +0 -22
  76. package/harness/roles/qa-run.md +0 -19
  77. package/harness/roles/verify-tool.md +0 -21
  78. package/harness/schemas/bindings-local.schema.json +0 -21
  79. package/harness/schemas/bus-request.schema.json +0 -17
  80. package/harness/schemas/bus-response.schema.json +0 -14
  81. package/harness/schemas/enforcement.schema.json +0 -22
  82. package/harness/schemas/plan.schema.json +0 -10
  83. package/harness/schemas/ticket.schema.json +0 -15
  84. package/harness/templates/bus/request.yaml +0 -20
  85. package/harness/templates/bus/response.yaml +0 -10
  86. package/harness/templates/plan.md +0 -23
  87. package/harness/templates/ticket.md +0 -29
  88. package/skills/reins-implement/SKILL.md +0 -20
  89. package/skills/reins-intent/SKILL.md +0 -26
  90. package/skills/reins-loop/SKILL.md +0 -26
  91. package/skills/reins-loop/references/vendor-cli.md +0 -41
  92. package/skills/reins-release/SKILL.md +0 -18
  93. package/skills/reins-retro/SKILL.md +0 -20
  94. package/skills/reins-review/SKILL.md +0 -23
  95. package/skills/reins-roadmap/SKILL.md +0 -17
  96. package/skills/reins-spec/SKILL.md +0 -22
  97. package/skills/reins-test/SKILL.md +0 -18
@@ -2,101 +2,48 @@ import { existsSync, readFileSync, readdirSync, rmdirSync, rmSync } from 'node:f
2
2
  import { dirname, join } from 'node:path';
3
3
  import { parse, stringify } from 'yaml';
4
4
  import { askerPrompter, BACK, EXIT } from '../lib/prompter.js';
5
- import { planMemoryProposals } from '../lib/memory.js';
6
5
  import { draftRelease, releaseDraftNotes } from '../lib/release.js';
7
- import { applyBlocks, parseBlocks } from '../lib/blocks.js';
8
- import { CONFIRMED_MODELS, checkBinding, discoverGates, newModelCache, vendorOf, generation, stacks, vendors, } from '../lib/detect.js';
6
+ import { applyBlocks } from '../lib/blocks.js';
7
+ import { discoverGates, generation, stacks, vendors, } from '../lib/detect.js';
9
8
  import { apply, listFiles } from '../lib/fsx.js';
10
9
  import { repoRoot } from '../lib/git.js';
11
- import { SKILLS_INDEX_HEADER, skillsIndex, splitFrontmatter } from '../lib/skills.js';
12
- import { harnessVersion, packageHarness, packageSkills, packageVersion, tierSkills, } from '../lib/upstream.js';
10
+ import { harnessVersion, packageHarness, packageSkills, packageVersion } from '../lib/upstream.js';
13
11
  import { generateVendorFiles } from '../lib/generate.js';
14
- import { recordDetection } from '../lib/bindings.js';
12
+ import { defaultBindings, readTeam } from '../lib/bindings.js';
13
+ import { overlayReader, workTreeReader } from '../lib/reader.js';
14
+ import { onboardingNote, placeNote, renderBlocks } from '../lib/agents-md.js';
15
15
  import { writeGenerated } from '../lib/vendor-write.js';
16
- /** Which upstream harness files a tier installs (design §1, tier table). */
17
- export function tierFiles(all, tier) {
18
- return all.filter((f) => {
19
- if (f.startsWith('knowledge-seeds/'))
20
- return false; // copied into knowledge/, not harness/
21
- if (f === 'CHANGELOG.md')
22
- return false; // read by update from the package, not installed
23
- if (f === 'VERSION' || f.startsWith('policy/'))
24
- return true;
25
- if (f === 'templates/agents-md-blocks.md')
26
- return true;
27
- if (tier === 'harness')
28
- return false;
29
- if (f.startsWith('templates/bus/'))
30
- return tier === 'graph';
31
- if (f.startsWith('templates/'))
32
- return true;
33
- return tier === 'graph'; // roles/, schemas/
34
- });
16
+ /** Upstream harness files installed into `.agents/harness/` (design §1): everything but seeds and the changelog. */
17
+ export function harnessFiles(all) {
18
+ return all.filter((f) => !f.startsWith('knowledge-seeds/') && f !== 'CHANGELOG.md');
35
19
  }
36
- /** Harness files the project owns; update and drift never touch them. */
20
+ /** Folders under `.agents/harness/` that upstream owns; a file there that upstream no longer ships is retired. */
21
+ const UPSTREAM_DIRS = ['policy/', 'roles/', 'schemas/', 'templates/'];
22
+ /** Harness files the project owns; update never touches them. */
37
23
  export const PROJECT_OWNED = new Set([
38
24
  'bindings.yaml',
39
25
  'gates.yaml',
40
26
  'install.yaml',
41
27
  'generated.yaml',
42
28
  ]);
43
- /**
44
- * Files installed under `.agents/harness/` that upstream still ships but this tier no longer installs
45
- * (e.g. `CHANGELOG.md`): in upstream, outside `tierFiles(tier)`, not project-owned. Anything not in
46
- * upstream is the project's and is never listed.
47
- */
48
- export function retiredFiles(installed, upstream, tier) {
49
- const up = new Set(upstream);
50
- const keep = new Set(tierFiles(upstream, tier));
51
- return installed.filter((f) => up.has(f) && !keep.has(f) && !PROJECT_OWNED.has(f));
29
+ /** Installed upstream-owned files this version no longer ships (an older reins wrote them). */
30
+ export function retiredFiles(installed, upstream) {
31
+ const keep = new Set(harnessFiles(upstream));
32
+ return installed.filter((f) => !keep.has(f) &&
33
+ !PROJECT_OWNED.has(f) &&
34
+ (f === 'CHANGELOG.md' || UPSTREAM_DIRS.some((d) => f.startsWith(d))));
52
35
  }
53
- /** bindings.yaml (design §5): defaults from role files; an unavailable vendor falls back, else to pm's model. */
54
- export function buildBindings(harness, available, vs, mode, cache) {
55
- const roles = {};
56
- const files = readdirSync(join(harness, 'roles'))
57
- .filter((f) => f.endsWith('.md'))
58
- .toSorted();
59
- const meta = new Map();
60
- for (const f of files) {
61
- const { data } = splitFrontmatter(readFileSync(join(harness, 'roles', f), 'utf8'));
62
- meta.set(f.replace(/\.md$/, ''), {
63
- def: String(data?.['default_binding']),
64
- fb: data?.['fallback_binding'],
65
- });
66
- }
67
- const pm = meta.get('pm')?.def ?? 'claude-opus-5-5';
68
- for (const [role, m] of meta) {
69
- let model = m.def;
70
- let note;
71
- if (!available.has(vendorOf(model))) {
72
- note = `${vendorOf(model)} not available — default was ${model}`;
73
- model = m.fb && available.has(vendorOf(m.fb)) ? m.fb : pm;
74
- }
75
- const entry = { vendor: vendorOf(model), model };
76
- if (role === 'implementer')
77
- entry['parallel'] = 4;
78
- const chk = cache ? checkBinding(model, entry['vendor'], cache) : null;
79
- if (chk) {
80
- if (chk.unverified)
81
- entry['unverified'] = true;
82
- if (chk.note)
83
- note = note ? `${note}; ${chk.note}` : chk.note;
84
- }
85
- else if (!CONFIRMED_MODELS.has(model))
86
- entry['unverified'] = true;
87
- if (note)
88
- entry['note'] = note;
89
- roles[role] = entry;
90
- }
91
- const doc = {
92
- schema: 'reins/bindings@1',
93
- mode,
94
- vendors: Object.fromEntries(vs.map((v) => [v.name, { cli: v.cli, available: available.has(v.name) }])),
95
- roles,
96
- escalation: ['pl', 'pm', 'advisor', 'user'],
97
- limits: {},
98
- };
99
- return `# generated by reins install — change with \`reins configure bindings\`\n${stringify(doc)}`;
36
+ /** Skills that ship with the plugin only and are not installed into a project. */
37
+ const PLUGIN_ONLY = new Set(['reins-setup', 'setup']);
38
+ /** The hook tool the project already uses (design §6), if any. */
39
+ export function hookTool(root) {
40
+ if (existsSync(join(root, '.husky')))
41
+ return 'husky';
42
+ if (['lefthook.yml', 'lefthook.yaml', '.lefthook.yml', '.lefthook.yaml'].some((f) => existsSync(join(root, f))))
43
+ return 'lefthook';
44
+ if (existsSync(join(root, '.pre-commit-config.yaml')))
45
+ return 'pre-commit';
46
+ return null;
100
47
  }
101
48
  export function buildGates(root, gates) {
102
49
  const doc = {
@@ -116,19 +63,28 @@ export function buildGates(root, gates) {
116
63
  export const ROADMAP_STUB = '# ROADMAP (local)\n\n— 산발적 아이디어를 여기에. 확정되면 docs/ROADMAP.md\n';
117
64
  const LOCTX_README = `# .loctx — 이 머신·이 개발자만 (gitignore)
118
65
 
119
- | 경로 | 무엇 |
120
- |---|---|
121
- | ROADMAP.local.md | 날 것의 큰 그림 — 산발적 아이디어, 미확정 기능을 예상 버전별로. 확정되면 docs/ROADMAP.md |
122
- | ticket/ | 지금 하는 일 하나 = 파일 하나. 끝나면 history에 한 줄 쓰고 삭제 |
123
- | reports/ | 테스트·게이트 증거 (툴체인 출력 그대로) |
124
- | pr/ release/ | PR 본문·릴리스 노트 초안 |
125
- | context/ | 개인 컨텍스트 — 대화·메모 |
126
- | bus/ | 에이전트간 인계 파일 (스키마 강제, 끝나면 삭제) |
127
- | test/ | 로컬 스크래치·휘발성 벤치마크 |
128
- | history/ | 버전별 완료 보고서 — 노하우. 공유할 결정은 .agents/knowledge/ 로 |
66
+ | 경로 | 무엇 | 지우는 때 |
67
+ |---|---|---|
68
+ | ROADMAP.local.md | 날 것의 아이디어. 사용자와 정리되면 docs/ROADMAP.md | 사용자 |
69
+ | history/<version>.md | 버전마다 한 장: 결정, 판정, 건너뛴 단계, 감사·회고 요약 | 지우지 않음 |
70
+ | reports/<version>/ | 게이트·테스트 원본 로그, 하위 보고 | 회고 뒤 (history·감사에 요약한 다음) |
71
+ | context/ | 개인 컨텍스트 — 대화·메모 | 사용자 |
72
+ | bindings.local.yaml | 나만 쓰는 모델 할당 (있으면 팀 설정보다 우선) | 사용자 |
129
73
  `;
130
- const hookLine = (stage) => `npx @bluenyang/reins check --stage ${stage}`;
131
- const pad = (n) => String(n).padStart(2, '0');
74
+ const TOOL_NAMES = ['claude', 'openai', 'google', 'gemini', 'copilot', 'cursor'];
75
+ /** The gate commands, in order, as hook lines (design §6). */
76
+ function gateLines(root) {
77
+ const p = join(root, '.agents/harness/gates.yaml');
78
+ if (!existsSync(p))
79
+ return [];
80
+ const g = parse(readFileSync(p, 'utf8'));
81
+ const gates = g?.gates ?? {};
82
+ return (g?.order ?? Object.keys(gates))
83
+ .map((n) => gates[n])
84
+ .filter((x) => !!x?.cmd && !x.optional)
85
+ .map((x) => x.cmd);
86
+ }
87
+ /** `reins install` (design §9): place the harness, ask, propose hooks, mark onboarding. Never writes history. */
132
88
  export async function runInstall(o) {
133
89
  const root = repoRoot(o.cwd ?? process.cwd());
134
90
  const gen = generation(root);
@@ -138,7 +94,7 @@ export async function runInstall(o) {
138
94
  root,
139
95
  generation: gen,
140
96
  notes,
141
- refused: `an existing ${gen} harness is here — run \`reins migrate ${o.tier}\` instead`,
97
+ refused: `an existing ${gen} harness is here — run \`reins migrate\` instead`,
142
98
  };
143
99
  const up = packageHarness();
144
100
  const version = harnessVersion(up);
@@ -148,12 +104,15 @@ export async function runInstall(o) {
148
104
  if (!existsSync(join(root, path)))
149
105
  add(path, content, why);
150
106
  };
151
- // 1. upstream harness files for the tier
152
- for (const f of tierFiles(listFiles(up), o.tier))
107
+ // 1. upstream harness files
108
+ for (const f of harnessFiles(listFiles(up)))
153
109
  add(`.agents/harness/${f}`, readFileSync(join(up, f), 'utf8'), 'upstream harness');
154
- // 2. questions (manual) / detection (auto) — only for what does not exist yet.
155
- // bindings.yaml and gates.yaml belong to the project once written; `reins configure` changes them.
156
- const hasBindings = existsSync(join(root, '.agents/harness/bindings.yaml'));
110
+ // 2. questions (manual) / detection (auto) — only for what does not exist yet
111
+ const pendingBindings = o.pending?.find((p) => p.path === '.agents/harness/bindings.yaml');
112
+ const team = pendingBindings
113
+ ? { doc: parse(pendingBindings.content) }
114
+ : readTeam(root);
115
+ const hasBindings = team.doc !== null;
157
116
  const hasGates = existsSync(join(root, '.agents/harness/gates.yaml'));
158
117
  const pinPath = join(root, '.agents/harness/install.yaml');
159
118
  const pinned = existsSync(pinPath)
@@ -161,17 +120,16 @@ export async function runInstall(o) {
161
120
  : null;
162
121
  const vs = (o.detectVendors ?? vendors)();
163
122
  const detected = vs.filter((v) => v.detected).map((v) => v.name);
164
- const avail = new Set(['claude']); // claude is the floor (R22)
123
+ const use = new Set(['claude']); // claude is the floor (R22)
165
124
  const screens = o.mode === 'manual' ? o.prompter : undefined;
166
- const line = askerPrompter(o.asker); // the piped, line-based form: today's strings and parsing
125
+ const line = askerPrompter(o.asker); // the piped, line-based form
167
126
  const cancelled = () => ({ root, generation: gen, notes, cancelled: true });
168
127
  const isNav = (v) => v === BACK || v === EXIT;
169
- const VENDOR_NAMES = ['claude', 'openai', 'google', 'cursor'];
170
- if (o.tier === 'graph' && !hasBindings) {
128
+ if (!hasBindings && !team.v1) {
171
129
  if (screens) {
172
130
  const picked = await screens.multiselect({
173
- message: 'Vendors you can use (claude is always on)',
174
- options: VENDOR_NAMES.map((n) => ({
131
+ message: 'Agent tools you use (claude is always on)',
132
+ options: TOOL_NAMES.map((n) => ({
175
133
  value: n,
176
134
  label: n,
177
135
  hint: n === 'claude' ? 'always' : detected.includes(n) ? 'detected' : undefined,
@@ -181,18 +139,18 @@ export async function runInstall(o) {
181
139
  if (isNav(picked))
182
140
  return cancelled();
183
141
  for (const v of picked)
184
- avail.add(v);
142
+ use.add(v);
185
143
  }
186
144
  else {
187
145
  const ans = await line.text({
188
- message: `vendors you can use (claude,openai,google,cursor) — detected: ${detected.join(',') || 'none'}`,
146
+ message: `agent tools you use (${TOOL_NAMES.join(',')}) — detected: ${detected.join(',') || 'none'}`,
189
147
  initial: ['claude', ...detected.filter((d) => d !== 'claude')].join(','),
190
148
  });
191
149
  for (const v of String(ans)
192
150
  .split(',')
193
151
  .map((s) => s.trim()))
194
- if (VENDOR_NAMES.includes(v))
195
- avail.add(v);
152
+ if (TOOL_NAMES.includes(v))
153
+ use.add(v);
196
154
  }
197
155
  }
198
156
  let language = pinned?.language;
@@ -232,7 +190,7 @@ export async function runInstall(o) {
232
190
  if (isNav(gateAns))
233
191
  return cancelled();
234
192
  if (!gateAns)
235
- notes.push('gates not confirmed — edit .agents/harness/gates.yaml, then `reins check --dry-run`');
193
+ notes.push('gates not confirmed — edit .agents/harness/gates.yaml');
236
194
  let chosen = [];
237
195
  if (proposal.proposals.length) {
238
196
  const listing = proposal.proposals.map((g) => `${g.name}=${g.cmd}`).join('; ');
@@ -266,80 +224,101 @@ export async function runInstall(o) {
266
224
  notes.push(`no such subdirectory gate: ${n}`);
267
225
  }
268
226
  else
269
- notes.push(`subdirectory gates not added (auto mode): ${listing} — add with \`reins configure gates --add <name>\``);
227
+ notes.push(`subdirectory gates not added (auto mode): ${listing} — add with \`reins config gates --add <name>\``);
270
228
  }
271
229
  for (const x of proposal.excluded)
272
230
  notes.push(`excluded from gates: ${x.name} (${x.why})`);
273
231
  add('.agents/harness/gates.yaml', buildGates(root, [...(gateAns ? proposal.gates : []), ...chosen]), 'declared gates');
274
232
  }
275
- // 3. generated configuration
276
- if (o.tier === 'graph' && !hasBindings) {
277
- // detection results are per-user: .loctx/bindings.local.yaml, never the committed file
278
- if (!o.dryRun)
279
- recordDetection(root, vs);
280
- add('.agents/harness/bindings.yaml', buildBindings(up, avail, vs, o.mode, o.modelCache ?? newModelCache()), 'role ↔ model bindings');
233
+ // 3. settings: a new bindings file in single mode (an old one is converted by update)
234
+ let doc = team.doc;
235
+ if (!doc && !team.v1) {
236
+ doc = defaultBindings(vs.map((v) => ({ name: v.name, cli: v.cli, use: use.has(v.name) })));
237
+ add('.agents/harness/bindings.yaml', `# reins model assignment (design §5) — the user changes it with \`reins config\`; nothing reads it while you work\n${stringify(doc)}`, 'model assignment (single mode)');
281
238
  }
282
- 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');
239
+ const { tier: _tier, ...keep } = pinned ?? {};
240
+ add('.agents/harness/install.yaml', `# version pin and install settings (R25) — read by reins update\n${stringify({ ...keep, schema: 'reins/install@1', version, cli: packageVersion(), mode: o.mode, language })}`, 'version pin');
283
241
  // 4. layout skeleton (design §1); never overwrite project files
284
- if (o.tier !== 'harness') {
285
- addIfMissing('.agents/intent/.gitkeep', '', 'intent folders live here');
286
- addIfMissing('.agents/knowledge/.gitkeep', '', 'explicit knowledge');
287
- for (const s of stacks(root)) {
288
- const seeds = join(up, 'knowledge-seeds', s);
289
- if (existsSync(seeds))
290
- for (const f of listFiles(seeds))
291
- addIfMissing(`.agents/knowledge/${f}`, readFileSync(join(seeds, f), 'utf8'), `seed for ${s}`);
292
- }
293
- add('.loctx/.gitignore', '*\n', 'double ignore (kestrel pattern)');
294
- add('.loctx/README.md', LOCTX_README, 'local workspace layout');
295
- addIfMissing('.loctx/ROADMAP.local.md', ROADMAP_STUB, 'raw roadmap');
242
+ addIfMissing('.agents/intent/.gitkeep', '', 'intent folders live here');
243
+ addIfMissing('.agents/audit/.gitkeep', '', 'version audit records');
244
+ addIfMissing('.agents/knowledge/.gitkeep', '', 'explicit knowledge');
245
+ for (const s of stacks(root)) {
246
+ const seeds = join(up, 'knowledge-seeds', s);
247
+ if (existsSync(seeds))
248
+ for (const f of listFiles(seeds))
249
+ addIfMissing(`.agents/knowledge/${f}`, readFileSync(join(seeds, f), 'utf8'), `seed for ${s}`);
296
250
  }
297
- // skill entry points: upstream-owned copies under the Agent Skills path, plus the index
251
+ add('.loctx/.gitignore', '*\n', 'double ignore');
252
+ add('.loctx/README.md', LOCTX_README, 'local workspace layout and lifetimes');
253
+ addIfMissing('.loctx/ROADMAP.local.md', ROADMAP_STUB, 'raw roadmap');
254
+ // stage skills: upstream-owned copies under the Agent Skills path
298
255
  const skillsUp = packageSkills();
299
- const installed = [];
300
- for (const name of tierSkills(o.tier)) {
301
- for (const f of listFiles(join(skillsUp, name)))
302
- add(`.agents/skills/${name}/${f}`, readFileSync(join(skillsUp, name, f), 'utf8'), 'upstream skill');
303
- }
304
- const skillsDir = join(root, '.agents', 'skills');
305
- const names = new Set([
306
- ...tierSkills(o.tier),
307
- ...(existsSync(skillsDir) ? readdirSync(skillsDir) : []).filter((n) => existsSync(join(skillsDir, n, 'SKILL.md'))),
308
- ]);
309
- for (const n of names) {
310
- const src = tierSkills(o.tier).includes(n) ? join(skillsUp, n) : join(skillsDir, n);
311
- const { data } = splitFrontmatter(readFileSync(join(src, 'SKILL.md'), 'utf8'));
312
- installed.push({ name: n, description: String(data?.['description'] ?? '') });
313
- }
314
- const indexPath = join(root, '.agents', 'SKILLS.md');
315
- const index = existsSync(indexPath) ? readFileSync(indexPath, 'utf8') : null;
316
- if (index === null ||
317
- index.startsWith(SKILLS_INDEX_HEADER) ||
318
- /^# Skills\n\n\| skill \| does \|\n\|---\|---\|\n$/.test(index))
319
- add('.agents/SKILLS.md', skillsIndex(installed), 'skill index');
320
- else
321
- notes.push('.agents/SKILLS.md is written by the project — add the reins skills to it by hand');
256
+ if (existsSync(skillsUp))
257
+ for (const name of readdirSync(skillsUp).toSorted()) {
258
+ if (PLUGIN_ONLY.has(name) || !existsSync(join(skillsUp, name, 'SKILL.md')))
259
+ continue;
260
+ for (const f of listFiles(join(skillsUp, name)))
261
+ add(`.agents/skills/${name}/${f}`, readFileSync(join(skillsUp, name, f), 'utf8'), 'upstream skill');
262
+ }
322
263
  const gi = existsSync(join(root, '.gitignore'))
323
264
  ? readFileSync(join(root, '.gitignore'), 'utf8')
324
265
  : '';
325
266
  if (!/^\/?\.loctx\/?$/m.test(gi))
326
267
  add('.gitignore', `${gi.replace(/\s*$/, '')}\n\n# reins local workspace\n.loctx/\n`, 'keep .loctx out of git');
327
- // 4b. .claude/memory is never moved: each file becomes a knowledge draft (design §7)
328
- {
329
- const d = o.now ?? new Date();
330
- const memory = planMemoryProposals(root, `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`);
331
- writes.push(...memory.writes);
332
- notes.push(...memory.notes);
333
- }
268
+ // 4b. .claude/memory is never moved or drafted (design §8): the PM proposes knowledge in the retro
269
+ if (existsSync(join(root, '.claude/memory')))
270
+ notes.push('.claude/memory found — left as it is; the PM can propose knowledge entries from it in a retro');
334
271
  // 4c. a release: draft from dispatchable workflows — proposal only, never written
335
272
  notes.push(...releaseDraftNotes(draftRelease(root)));
336
- // 5. AGENTS.md managed blocks, CLAUDE.md pointer
273
+ // 5. hooks: the project's own gate commands in its own hook tool (design §6)
274
+ const tool = hookTool(root);
275
+ const cmds = gateLines(root);
276
+ const pending = writes.find((w) => w.path === '.agents/harness/gates.yaml');
277
+ const lines = pending
278
+ ? (() => {
279
+ const g = parse(pending.content);
280
+ return (g.order ?? [])
281
+ .map((n) => g.gates?.[n])
282
+ .filter((x) => x && !x.optional)
283
+ .map((x) => x.cmd);
284
+ })()
285
+ : cmds;
286
+ let addHooks = !!o.hooks;
287
+ if (lines.length && tool === 'husky' && !addHooks && o.confirmHooks && !o.dryRun) {
288
+ const yes = await o.confirmHooks.confirm({
289
+ message: `Add the project gates to husky pre-commit and pre-push? (${lines.join(' && ')})`,
290
+ initial: true,
291
+ });
292
+ if (yes === EXIT)
293
+ return cancelled();
294
+ addHooks = yes === true;
295
+ }
296
+ if (lines.length) {
297
+ if (tool === 'husky' && addHooks) {
298
+ for (const stage of ['pre-commit', 'pre-push']) {
299
+ const p = join(root, '.husky', stage);
300
+ const cur = existsSync(p) ? readFileSync(p, 'utf8') : '';
301
+ if (cur.includes('# reins:begin hooks'))
302
+ continue;
303
+ add(`.husky/${stage}`, `${cur.replace(/\s*$/, '')}\n# reins:begin hooks\n${lines.join('\n')}\n# reins:end hooks\n`.replace(/^\n/, ''), 'hook: the project gates');
304
+ }
305
+ }
306
+ else if (tool)
307
+ notes.push(`hook proposal (${tool}): run the project gates in pre-commit and pre-push — ${lines.join(' && ')}${tool === 'husky' ? '; re-run with --hooks to add them' : ` (reins proposes ${tool} lines only; add them to its config yourself)`}`);
308
+ else
309
+ notes.push('no hook tool found — the PM asks which one to use during onboarding');
310
+ }
311
+ // 6. AGENTS.md: managed blocks, the onboarding note; CLAUDE.md pointer
337
312
  const agentsPath = join(root, 'AGENTS.md');
338
- const agents = existsSync(agentsPath) ? readFileSync(agentsPath, 'utf8') : '# AGENTS.md\n';
339
- const blocks = parseBlocks(readFileSync(join(up, 'templates/agents-md-blocks.md'), 'utf8'));
340
- const br = applyBlocks(agents, blocks);
341
- if (br.text !== agents)
342
- add('AGENTS.md', br.text, `managed blocks: ${[...br.inserted, ...br.replaced].join(', ')}`);
313
+ const before = existsSync(agentsPath) ? readFileSync(agentsPath, 'utf8') : '# AGENTS.md\n';
314
+ const blocks = renderBlocks(up, doc ?? defaultBindings([]), String(language ?? 'ko'));
315
+ const br = applyBlocks(before, blocks);
316
+ let agents = br.text;
317
+ // a reconcile note already sends the PM to `onboard`; one note is enough
318
+ if (!/<!-- reins:onboarding done -->/.test(agents) && !agents.includes('<!-- reins:reconcile'))
319
+ agents = placeNote(agents, onboardingNote(tool === null), 'onboarding');
320
+ if (agents !== before)
321
+ add('AGENTS.md', agents, `managed blocks: ${[...br.inserted, ...br.replaced].join(', ') || 'onboarding'}`);
343
322
  for (const s of br.skipped)
344
323
  notes.push(`AGENTS.md block "${s.name}" not placed: ${s.why}`);
345
324
  const claude = join(root, 'CLAUDE.md');
@@ -347,35 +326,22 @@ export async function runInstall(o) {
347
326
  add('CLAUDE.md', '@AGENTS.md\n', 'Claude Code reads AGENTS.md');
348
327
  else if (!readFileSync(claude, 'utf8').includes('@AGENTS.md'))
349
328
  notes.push('CLAUDE.md does not import @AGENTS.md — add it');
350
- // 6. hooks: propose only, unless asked (user decision 2026-10-25)
351
- const husky = existsSync(join(root, '.husky'));
352
- for (const stage of ['pre-commit', 'pre-push']) {
353
- const p = join(root, '.husky', stage);
354
- const cur = existsSync(p) ? readFileSync(p, 'utf8') : '';
355
- if (/reins(\.js)?\s+check/.test(cur))
356
- continue; // already calls the verifier
357
- if (husky && o.hooks)
358
- add(`.husky/${stage}`, `${cur.replace(/\s*$/, '')}\n# reins:begin hooks\n${hookLine(stage)}\n# reins:end hooks\n`.replace(/^\n/, ''), 'hook');
359
- else
360
- notes.push(`hook proposal (${husky ? 'husky' : 'no hook tool found — lefthook or husky'}): run \`${hookLine(stage)}\` in ${stage}; re-run with --hooks to add it`);
361
- }
362
329
  // 7. legacy workspace — migrate owns it
363
330
  if (existsSync(join(root, '.ai')) && !o.overExisting)
364
- notes.push('legacy workspace .ai/ found — left untouched; run `reins migrate ' +
365
- o.tier +
366
- '` to move it into .agents/ and .loctx/');
367
- notes.push('next: in your agent, run the setup skill (/reins-setup) — the PM reads the project and proposes AGENTS.md project sections');
368
- // 8. apply, then record (only when something changed)
331
+ notes.push('legacy workspace .ai/ found — left untouched; run `reins migrate` to move it');
332
+ notes.push('next: open your agent in this repository — the onboarding note in AGENTS.md starts the first conversation');
333
+ // 8. apply
369
334
  const applied = apply(root, writes, !!o.dryRun);
335
+ const retired = [];
370
336
  if (o.retire) {
371
337
  const harnessDir = join(root, '.agents/harness');
372
338
  const here = existsSync(harnessDir) ? listFiles(harnessDir) : [];
373
- for (const f of retiredFiles(here, listFiles(up), o.tier)) {
339
+ for (const f of retiredFiles(here, listFiles(up))) {
340
+ retired.push(`.agents/harness/${f}`);
374
341
  applied.removed.push(`.agents/harness/${f}`);
375
342
  if (o.dryRun)
376
343
  continue;
377
344
  rmSync(join(harnessDir, f), { force: true });
378
- // prune directories the removal left empty, never the harness root
379
345
  for (let d = dirname(join(harnessDir, f)); d !== harnessDir; d = dirname(d)) {
380
346
  try {
381
347
  rmdirSync(d);
@@ -386,39 +352,17 @@ export async function runInstall(o) {
386
352
  }
387
353
  }
388
354
  }
389
- // 9. vendor files from the installed harness (design §6) — never over a file reins did not write
390
- const generated = o.dryRun ? undefined : writeGenerated(root, generateVendorFiles(root), false);
355
+ // 9. generated files from the installed harness (design §6) — never over a file reins did not write
356
+ // a dry run computes the same plan without writing, so update can show hand-edited files first
357
+ const rd = o.dryRun
358
+ ? overlayReader(workTreeReader(root), [...(o.pending ?? []), ...writes], [...retired, ...(o.pendingDeletes ?? [])])
359
+ : workTreeReader(root);
360
+ const generated = writeGenerated(root, generateVendorFiles(root, rd), !!o.dryRun, !!o.force);
391
361
  if (generated) {
392
362
  applied.created.push(...generated.written.filter((p) => !applied.created.includes(p)));
393
- for (const s of generated.skipped)
394
- notes.push(`not generated this round (vendor CLI files arrive in round two): ${s}`);
363
+ applied.removed.push(...generated.removed);
395
364
  for (const r of generated.refused)
396
365
  notes.push(`left alone ${r.path}: ${r.why}`);
397
366
  }
398
- let history;
399
- const changedAny = applied.created.length + applied.changed.length + applied.removed.length > 0;
400
- if (changedAny && !o.dryRun && o.tier !== 'harness') {
401
- const now = o.now ?? new Date();
402
- // local time, like every other history file name (<YYYY-MM-DD-HHmm>)
403
- const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
404
- history = `.loctx/history/${stamp}_${o.recordAs ?? 'install'}-${o.tier}.md`;
405
- const body = [
406
- `decisions: install-${o.tier}`,
407
- 'source: tool',
408
- '',
409
- `# reins install ${o.tier} (${o.mode}) — v${version}`,
410
- '',
411
- `- generation before: ${gen}`,
412
- `- created: ${applied.created.length} · changed: ${applied.changed.length} · unchanged: ${applied.unchanged.length} · removed: ${applied.removed.length}`,
413
- ...applied.created.map((p) => ` - + ${p}`),
414
- ...applied.changed.map((p) => ` - ~ ${p}`),
415
- ...applied.removed.map((p) => ` - - ${p}`),
416
- '',
417
- '## notes',
418
- ...notes.map((n) => `- ${n}`),
419
- '',
420
- ].join('\n');
421
- apply(root, [{ path: history, content: body, why: 'install record' }], false);
422
- }
423
- return { root, generation: gen, applied, generated, notes, history };
367
+ return { root, generation: gen, applied, generated, notes };
424
368
  }
@@ -1,6 +1,5 @@
1
1
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
- import { applyBlocks, parseBlocks, swapSections } from '../lib/blocks.js';
4
3
  import { relPath } from '../lib/fsx.js';
5
4
  import { generation } from '../lib/detect.js';
6
5
  import { repoRoot } from '../lib/git.js';
@@ -8,8 +7,7 @@ import { convertWorkToTicket, planMigration } from '../lib/migrate-plan.js';
8
7
  import { splitFrontmatter } from '../lib/skills.js';
9
8
  import { packageHarness } from '../lib/upstream.js';
10
9
  import { ROADMAP_STUB, runInstall } from './install.js';
11
- const pad = (n) => String(n).padStart(2, '0');
12
- const stampOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}`;
10
+ import { placeNote, reconcileNote } from '../lib/agents-md.js';
13
11
  function removeEmptyDirs(dir) {
14
12
  if (!existsSync(dir) || !statSync(dir).isDirectory())
15
13
  return;
@@ -18,7 +16,7 @@ function removeEmptyDirs(dir) {
18
16
  if (readdirSync(dir).length === 0)
19
17
  rmdirSync(dir);
20
18
  }
21
- /** Intent 000 (draft) that the migrated tickets point at — only when this run made tickets and none exists. */
19
+ /** Intent 000 (draft) whose plan lists the migrated work — only when this run moved work and none exists. */
22
20
  function writeMigratedIntent(root, moves) {
23
21
  const made = moves.filter((m) => m.result === 'converted');
24
22
  const dir = join(root, '.agents/intent');
@@ -35,9 +33,11 @@ function writeMigratedIntent(root, moves) {
35
33
  }
36
34
  const { body } = splitFrontmatter(readFileSync(join(packageHarness(), 'templates/intent.md'), 'utf8'));
37
35
  const list = made
38
- .map((m) => `- ${m.to.slice('.loctx/ticket/'.length, m.to.indexOf('_'))} — from .ai/work/${m.from.slice('.ai/work/'.length)}`)
36
+ .map((m) => `- ${m.to.slice('.loctx/context/migrated-work/'.length, m.to.indexOf('_'))} — from .ai/work/${m.from.slice('.ai/work/'.length)} (${m.to})`)
39
37
  .join('\n');
40
- 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}`);
38
+ const text = body
39
+ .replace(/## 문제\n—/, () => '## 문제\nOpen work items that `reins migrate` moved out of `.ai/work/`. The PM plans them again: approve this intent, then write a spec whose work units cover them.')
40
+ .replace(/## 계획\n—/, () => `## 계획\n${list}`);
41
41
  const yaml = [
42
42
  'id: "000"',
43
43
  'slug: migrated',
@@ -50,9 +50,9 @@ function writeMigratedIntent(root, moves) {
50
50
  const out = join(dir, '000_migrated/intent.md');
51
51
  mkdirSync(dirname(out), { recursive: true });
52
52
  writeFileSync(out, `---\n${yaml}\n---\n${text}`);
53
- 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
+ return '.agents/intent/000_migrated/intent.md written as a draft whose plan lists the migrated work — the user approves it before any of it starts';
54
54
  }
55
- /** `reins migrate <tier>` (design §7): install if needed, move the old workspace, swap AGENTS.md sections. Idempotent. */
55
+ /** `reins migrate` (design §7): install, move the old workspace, set AGENTS.md aside for the PM to reconcile. Idempotent. */
56
56
  export async function runMigrate(o) {
57
57
  const root = repoRoot(o.cwd ?? process.cwd());
58
58
  const gen = generation(root);
@@ -65,10 +65,12 @@ export async function runMigrate(o) {
65
65
  };
66
66
  if (gen === 'none')
67
67
  return { ...res, refused: 'no existing harness or workspace here — use `reins install`' };
68
+ // the project's own AGENTS.md before reins touches it: the PM reconciles it in the next conversation
69
+ const agentsPath = join(root, 'AGENTS.md');
70
+ const original = existsSync(agentsPath) && gen !== 'reins' ? readFileSync(agentsPath, 'utf8') : undefined;
68
71
  // 1. make sure the target layout exists (install is idempotent)
69
72
  {
70
73
  const inst = await runInstall({
71
- tier: o.tier,
72
74
  mode: o.mode,
73
75
  asker: o.asker,
74
76
  cwd: root,
@@ -124,46 +126,19 @@ export async function runMigrate(o) {
124
126
  if (made)
125
127
  res.report.push(made);
126
128
  }
127
- // 3. AGENTS.md: sections reins owns become managed blocks; the originals are kept locally
128
- const agentsPath = join(root, 'AGENTS.md');
129
- if (existsSync(agentsPath)) {
130
- const up = parseBlocks(readFileSync(join(packageHarness(), 'templates/agents-md-blocks.md'), 'utf8'));
131
- const before = readFileSync(agentsPath, 'utf8');
132
- const swap = swapSections(before, up);
133
- const placed = applyBlocks(swap.text, up);
134
- res.agents = { swapped: swap.swapped, inserted: placed.inserted };
135
- if (placed.text !== before && !o.dryRun) {
136
- writeFileSync(agentsPath, placed.text);
137
- if (swap.removed) {
138
- const keep = join(root, '.loctx/context/agents-md.before.md');
139
- mkdirSync(dirname(keep), { recursive: true });
140
- const prev = existsSync(keep) ? `${readFileSync(keep, 'utf8')}\n\n` : '';
141
- writeFileSync(keep, `${prev}<!-- replaced by reins migrate, ${stampOf(o.now ?? new Date())} -->\n${swap.removed}\n`);
142
- res.report.push('AGENTS.md: the replaced sections are in .loctx/context/agents-md.before.md — move project-specific rules back outside the blocks');
143
- }
129
+ // 3. AGENTS.md (design §5): the previous text is kept aside as reference; the PM merges what applies
130
+ if (original !== undefined && original.trim() && !o.dryRun) {
131
+ const prev = join(root, '.agents/AGENTS.previous.md');
132
+ if (!existsSync(prev)) {
133
+ mkdirSync(dirname(prev), { recursive: true });
134
+ writeFileSync(prev, original);
135
+ const now = readFileSync(agentsPath, 'utf8');
136
+ const next = placeNote(now, reconcileNote('reins migrate replaced the harness this repository used.'), 'reconcile');
137
+ if (next !== now)
138
+ writeFileSync(agentsPath, next);
139
+ res.agents.inserted.push('reconcile');
140
+ res.report.push('AGENTS.md: the previous text is in .agents/AGENTS.previous.md — the PM reconciles it in the next conversation');
144
141
  }
145
142
  }
146
- // 4. record, only when something happened
147
- const happened = res.moves.length > 0 || res.agents.swapped.length > 0;
148
- if (happened && !o.dryRun) {
149
- res.history = `.loctx/history/${stampOf(o.now ?? new Date())}_migrate-${o.tier}.md`;
150
- const count = (r) => res.moves.filter((m) => m.result === r).length;
151
- writeFileSync(join(root, res.history), [
152
- `decisions: migrate-${o.tier}`,
153
- 'source: tool',
154
- '',
155
- `# reins migrate ${o.tier} — from ${gen}`,
156
- '',
157
- `- moved ${count('moved')} · converted to tickets ${count('converted')} · identical ${count('same')} · kept both ${count('kept-both')}`,
158
- `- AGENTS.md: swapped ${res.agents.swapped.join(', ') || 'none'}; inserted ${res.agents.inserted.join(', ') || 'none'}`,
159
- '',
160
- '## for a person to look at',
161
- ...res.report.map((r) => `- ${r}`),
162
- '',
163
- '## moves',
164
- ...res.moves.map((m) => `- ${m.from} → ${m.to} (${m.result})`),
165
- '',
166
- ].join('\n'));
167
- }
168
143
  return res;
169
144
  }