@bluenyang/reins 0.1.2 → 0.1.3-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +11 -9
  2. package/cli/dist/commands/check.js +32 -1
  3. package/cli/dist/commands/gate.js +83 -1
  4. package/cli/dist/commands/install.js +1 -0
  5. package/cli/dist/commands/knowledge.js +94 -0
  6. package/cli/dist/commands/migrate.js +1 -0
  7. package/cli/dist/commands/new.js +184 -0
  8. package/cli/dist/commands/retro.js +7 -0
  9. package/cli/dist/commands/stages.js +31 -0
  10. package/cli/dist/commands/status.js +9 -0
  11. package/cli/dist/lib/git.js +10 -0
  12. package/cli/dist/lib/retro.js +153 -0
  13. package/cli/dist/lib/upstream.js +14 -1
  14. package/cli/dist/reins.js +86 -3
  15. package/cli/dist/scripts/sync-version.js +23 -7
  16. package/docs/README.ko.md +11 -9
  17. package/harness/CHANGELOG.md +4 -0
  18. package/harness/VERSION +1 -1
  19. package/harness/roles/advisor.md +2 -0
  20. package/harness/roles/code-review.md +2 -0
  21. package/harness/roles/deploy.md +22 -1
  22. package/harness/roles/docs.md +2 -0
  23. package/harness/roles/implementer.md +2 -0
  24. package/harness/roles/lookup.md +2 -0
  25. package/harness/roles/pl.md +2 -0
  26. package/harness/roles/planner.md +2 -0
  27. package/harness/roles/pm.md +3 -1
  28. package/harness/roles/qa-design.md +2 -0
  29. package/harness/roles/qa-run.md +2 -0
  30. package/harness/roles/verify-tool.md +4 -3
  31. package/harness/schemas/intent.schema.json +1 -1
  32. package/package.json +1 -1
  33. package/skills/reins-implement/SKILL.md +20 -0
  34. package/skills/reins-intent/SKILL.md +8 -17
  35. package/skills/reins-loop/SKILL.md +10 -38
  36. package/skills/reins-loop/references/vendor-cli.md +2 -2
  37. package/skills/reins-release/SKILL.md +17 -0
  38. package/skills/reins-retro/SKILL.md +20 -0
  39. package/skills/reins-review/SKILL.md +23 -0
  40. package/skills/reins-roadmap/SKILL.md +17 -0
  41. package/skills/reins-setup/SKILL.md +1 -1
  42. package/skills/reins-spec/SKILL.md +22 -0
  43. package/skills/reins-test/SKILL.md +18 -0
package/README.md CHANGED
@@ -129,22 +129,24 @@ T1 (`ticket-start`), T2 (`pre-commit`), T3 (`verdict`), T4 (`pre-push`) and T5 (
129
129
 
130
130
  ## Skills
131
131
 
132
- Three skills are the entry points for an agent; they follow the `SKILL.md` standard.
132
+ Ten skills follow the `SKILL.md` standard: `reins-setup` bootstraps, `reins-loop` conducts, and eight stage skills each take one stage and can be called alone.
133
133
 
134
134
  | Skill | Use when |
135
135
  |---|---|
136
136
  | `reins-setup` | installing reins, or moving an existing harness onto it |
137
- | `reins-intent` | a new request arrives: questionnaire, approved intent, accepted spec |
138
- | `reins-loop` | a spec is accepted: plan, tickets, implement, verify, review, history |
137
+ | `reins-roadmap` | updating the public roadmap and picking the target version |
138
+ | `reins-intent` | a new request arrives: questionnaire and approved intent |
139
+ | `reins-spec` | an intent is approved: accepted spec, plan and tickets |
140
+ | `reins-implement` | a ticket is ready: implement it in committed units |
141
+ | `reins-review` | a ticket is finished: verify, review and close it |
142
+ | `reins-test` | all tickets of a version are done: scenarios and build |
143
+ | `reins-release` | a version is tested: PR, CI, merge and rc |
144
+ | `reins-retro` | a version is released: retrospective and knowledge proposals |
145
+ | `reins-loop` | a spec is accepted: calls the stage skills in order |
139
146
 
140
147
  ## Roadmap
141
148
 
142
- | Version | Content |
143
- |---|---|
144
- | 0.1 | graph design, self-install and self-migrate of this repository, the verifier, three skills, metrics, violation scenarios. 0.1.0 published; 0.1.1 stabilisation (fixes the loop found); 0.1.2 Claude Code plugin (marketplace install) |
145
- | 0.2 | carve the loop and harness tiers out of the graph; generated files for Codex, Gemini and Cursor; `recall`, `doctor`, budget stops; trial migration of older harnesses |
146
- | 0.3 | application to Team Croffle repositories |
147
- | 1.0 | not scheduled: reins stays on 0.x and gains features until the maintainer considers the system settled; stabilising alone does not make it 1.0 |
149
+ The full plan is in [docs/ROADMAP.md](docs/ROADMAP.md) ([한국어](docs/ROADMAP.ko.md)).
148
150
 
149
151
  ## Documents
150
152
 
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { basename, join } from 'node:path';
3
3
  import { hasOwnSection, overrides, parseBlocks } from '../lib/blocks.js';
4
- import { currentBranch, isAncestor, repoRoot, stagedFiles } from '../lib/git.js';
4
+ import { currentBranch, isAncestor, pushedSubjects, repoRoot, stagedFiles } from '../lib/git.js';
5
5
  import { harnessRel, secretPolicy } from '../lib/harness.js';
6
6
  import { loadSchemasFrom, schemaFor, validateFile } from '../lib/schema.js';
7
7
  import { DEFAULT_ALLOWED, DEFAULT_SECRET_PATTERNS, isSecretPath } from '../lib/secrets.js';
@@ -81,6 +81,24 @@ export function prePush(root, refs) {
81
81
  const [localRef, localSha, remoteRef, remoteSha] = line.trim().split(/\s+/);
82
82
  if (!localSha || !remoteSha || !remoteRef)
83
83
  continue;
84
+ if (/^refs\/heads\/(master|main)$/.test(remoteRef)) {
85
+ // design §3 T4: work reaches the default branch by PR only; the publish workflow's version commit is the one exception
86
+ // creating or deleting the ref has no range to judge: always held
87
+ const subjects = ZERO.test(localSha) || ZERO.test(remoteSha)
88
+ ? []
89
+ : pushedSubjects(remoteSha, localSha, root);
90
+ const releaseOnly = process.env.GITHUB_ACTIONS === 'true' &&
91
+ subjects.length > 0 &&
92
+ subjects.every((m) => m.startsWith('release: v'));
93
+ if (!releaseOnly)
94
+ findings.push({
95
+ reason: 'A4',
96
+ verdict: 'HOLD',
97
+ path: remoteRef,
98
+ message: `push to ${remoteRef.slice('refs/heads/'.length)} outside the PR flow`,
99
+ resume: 'push a type/topic branch and open a PR; the deploy role merges it when checks are green',
100
+ });
101
+ }
84
102
  if (ZERO.test(localSha) && remoteRef.startsWith('refs/tags/')) {
85
103
  findings.push({
86
104
  reason: 'A1',
@@ -143,6 +161,19 @@ export function driftConvention(root, only, rd = workTreeReader(root)) {
143
161
  const v = schemas.get(m.schema);
144
162
  if (!v)
145
163
  continue;
164
+ if (m.schema === 'knowledge' && rel.startsWith('.agents/knowledge/')) {
165
+ // design §8: an entry reaches .agents/knowledge/ only through the user's approval (presets ship with the package)
166
+ const { data } = splitFrontmatter(text);
167
+ const ap = data?.['approved'];
168
+ if (data && data['source'] !== 'preset' && !(ap && typeof ap.by === 'string' && ap.by))
169
+ findings.push({
170
+ reason: 'F2',
171
+ verdict: 'STOP',
172
+ path: rel,
173
+ message: 'knowledge entry without approved',
174
+ resume: 'propose it with reins knowledge propose; the user approves, then reins knowledge accept',
175
+ });
176
+ }
146
177
  for (const i of validateFile(v, join(root, rel), m.whole, text))
147
178
  findings.push({
148
179
  reason: 'F2',
@@ -1,8 +1,10 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { repoRoot } from '../lib/git.js';
5
5
  import { harnessDir, readYaml } from '../lib/harness.js';
6
+ import { loadSchemas, validateFile } from '../lib/schema.js';
7
+ import { parse, stringify } from 'yaml';
6
8
  /** One command per gate (design §5): no pipes, chains or redirects — anything else is massaged output (C5). */
7
9
  export function compound(cmd) {
8
10
  return /[|;&<>`]|\$\(/.test(cmd.replace(/'[^']*'|"[^"]*"/g, ''));
@@ -52,3 +54,83 @@ export function runGates(o) {
52
54
  }
53
55
  return { runs };
54
56
  }
57
+ /** One line per failing gate for stdout: the first failure signature and the first file:line in the raw report. */
58
+ export function failureSummary(report) {
59
+ const lines = report.split('\n').filter((l) => l.trim() && !l.startsWith('$ '));
60
+ const sig = lines.find((l) => /\b(error|fail(ed|ure)?|assertion|✗|×)\b/i.test(l) && !/^exit \d+$/.test(l)) ??
61
+ lines.find((l) => !/^exit \d+$/.test(l)) ??
62
+ '';
63
+ const loc = /[\w./-]+\.[a-z]{1,4}:\d+(?::\d+)?/i.exec(lines.join('\n'))?.[0];
64
+ const text = sig.trim().slice(0, 160);
65
+ return [text, loc && !text.includes(loc) ? loc : ''].filter(Boolean).join(' @ ');
66
+ }
67
+ /** The newest `kind: verify` request of the ticket that has no response yet, as its id (`<ticket>_<nn>`). */
68
+ export function openVerifyRequest(root, ticket) {
69
+ const dir = join(root, '.loctx', 'bus');
70
+ const files = existsSync(dir) ? readdirSync(dir) : [];
71
+ const re = new RegExp(`^(${ticket.replace(/[-.]/g, '\\$&')}_\\d+)\\.request\\.yaml$`);
72
+ const open = files
73
+ .map((f) => re.exec(f)?.[1])
74
+ .filter((id) => !!id && !files.includes(`${id}.response.yaml`))
75
+ .filter((id) => {
76
+ try {
77
+ const y = parse(readFileSync(join(dir, `${id}.request.yaml`), 'utf8'));
78
+ return y?.kind === 'verify';
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ })
84
+ .sort();
85
+ return open.at(-1) ?? null;
86
+ }
87
+ /**
88
+ * Writes the bus response for the open verify request from a gate run. The verdict is pass only when every
89
+ * gate ran and exited 0; evidence points at the report files, which keep the raw output (C5).
90
+ */
91
+ export function writeResponse(root, ticket, runs) {
92
+ const summaries = {};
93
+ for (const g of runs) {
94
+ if (g.exit === 0)
95
+ continue;
96
+ summaries[g.gate] = g.skipped
97
+ ? `not run: ${g.skipped}`
98
+ : failureSummary(readFileSync(join(root, g.report), 'utf8')) || `exit ${g.exit}`;
99
+ }
100
+ const id = openVerifyRequest(root, ticket);
101
+ if (!id)
102
+ return { summaries, refused: `no open kind: verify request for ${ticket} in .loctx/bus/` };
103
+ const pass = runs.length > 0 && runs.every((g) => g.exit === 0);
104
+ const ran = runs.filter((g) => g.exit !== null);
105
+ const body = {
106
+ schema: 'reins/bus/response@1',
107
+ request: id,
108
+ from: 'verify-tool',
109
+ verdict: pass ? 'pass' : 'fail',
110
+ grounds: pass
111
+ ? `${runs.length} gate${runs.length === 1 ? '' : 's'} exited 0`
112
+ : Object.entries(summaries)
113
+ .map(([k, v]) => `${k}: ${v}`)
114
+ .join('; ') || 'no gate ran',
115
+ evidence: ran.map((g) => g.report).join(' '),
116
+ may_proceed: pass,
117
+ };
118
+ const hd = harnessDir(root);
119
+ const v = hd ? loadSchemas(hd).get('bus-response') : undefined;
120
+ if (!v)
121
+ return { summaries, refused: 'no bus-response schema in the harness' };
122
+ const rel = `.loctx/bus/${id}.response.yaml`;
123
+ const content = stringify(body);
124
+ const issues = validateFile(v, rel, true, content);
125
+ if (issues.length)
126
+ return {
127
+ summaries,
128
+ refused: `response would not pass bus-response: ${issues.map((i) => i.message).join('; ')}`,
129
+ };
130
+ writeFileSync(join(root, rel), content, { flag: 'wx' });
131
+ return { response: rel, verdict: body.verdict, summaries };
132
+ }
133
+ /** `--respond` may only answer for the whole declared order, so a pass never rests on a subset of the gates. */
134
+ export function respondRefusal(names) {
135
+ return names.length > 0 ? '--respond runs every declared gate; do not name gates' : null;
136
+ }
@@ -262,6 +262,7 @@ export async function runInstall(o) {
262
262
  history = `.loctx/history/${stamp}_${o.recordAs ?? 'install'}-${o.tier}.md`;
263
263
  const body = [
264
264
  `decisions: install-${o.tier}`,
265
+ 'source: tool',
265
266
  '',
266
267
  `# reins install ${o.tier} (${o.mode}) — v${version}`,
267
268
  '',
@@ -0,0 +1,94 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { basename, join, relative, resolve } from 'node:path';
3
+ import { repoRoot } from '../lib/git.js';
4
+ import { harnessDir } from '../lib/harness.js';
5
+ import { localIso } from '../lib/metrics.js';
6
+ import { bareKey, collectRetro } from '../lib/retro.js';
7
+ import { loadSchemas, validateFile } from '../lib/schema.js';
8
+ export const PROPOSALS = '.loctx/knowledge-proposals';
9
+ const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
10
+ const today = () => localIso().slice(0, 10);
11
+ /** Replace the frontmatter line starting with `key:`; `null` removes it. */
12
+ function setLine(text, key, value) {
13
+ if (value === null)
14
+ return text.replace(new RegExp(`^${key}:.*\\n`, 'm'), '');
15
+ return text.replace(new RegExp(`^${key}:.*$`, 'm'), () => `${key}: ${value}`);
16
+ }
17
+ /**
18
+ * `reins knowledge propose <key|slug> [--from <history>…]`: a draft from the knowledge template,
19
+ * `approved` left out. Writes only under `.loctx/knowledge-proposals/`.
20
+ */
21
+ export function proposeKnowledge(key, o = {}) {
22
+ const root = repoRoot(o.cwd ?? process.cwd());
23
+ const slug = bareKey(key);
24
+ if (!SLUG.test(slug))
25
+ return { refused: `"${key}" is not a usable slug` };
26
+ const hd = harnessDir(root);
27
+ const tpl = hd && join(hd, 'templates', 'knowledge.md');
28
+ if (!tpl || !existsSync(tpl))
29
+ return { refused: 'no knowledge template — run reins install' };
30
+ const dest = join(root, PROPOSALS, `${slug}.md`);
31
+ if (existsSync(dest))
32
+ return { refused: `${PROPOSALS}/${slug}.md already exists` };
33
+ const hist = resolve(root, '.loctx', 'history');
34
+ const from = [];
35
+ for (const f of o.from ?? []) {
36
+ const abs = resolve(root, f.includes('/') ? f : join('.loctx', 'history', f));
37
+ const rel = relative(hist, abs);
38
+ if (rel.startsWith('..') || rel.includes('/') || !existsSync(abs))
39
+ return { refused: `--from ${f}: not a page under .loctx/history/` };
40
+ const text = readFileSync(abs, 'utf8');
41
+ const lines = [...text.matchAll(/^(?:decisions|reasons):\s*(.+)$/gm)].flatMap((m) => m[1].split(',').map((x) => x.trim()));
42
+ const has = key.startsWith('stop:') ? text.includes(slug) : lines.includes(slug);
43
+ if (!has)
44
+ return { refused: `--from ${f}: does not contain "${slug}"` };
45
+ from.push(`.loctx/history/${rel}`);
46
+ }
47
+ if (from.length === 0)
48
+ from.push(...collectRetro(root)
49
+ .keys.filter((k) => bareKey(k.key) === slug)
50
+ .flatMap((k) => k.pages));
51
+ if (from.length === 0)
52
+ return { refused: `no record of "${slug}"; pass --from <history>…` };
53
+ const asSymptom = /^(stop|reason):/.test(key);
54
+ let t = readFileSync(tpl, 'utf8');
55
+ t = setLine(t, 'id', `${today()}_${slug}`);
56
+ t = setLine(t, 'decisions', asSymptom ? '[]' : `[${slug}]`);
57
+ t = setLine(t, 'symptoms', asSymptom ? `[${slug}]` : '[]');
58
+ t = setLine(t, 'source', JSON.stringify([...new Set(from)].join(', ')));
59
+ t = setLine(t, 'approved', null);
60
+ mkdirSync(join(root, PROPOSALS), { recursive: true });
61
+ writeFileSync(dest, t);
62
+ return { path: `${PROPOSALS}/${slug}.md` };
63
+ }
64
+ /**
65
+ * `reins knowledge accept <slug>`: the only way an `approved` field gets written. The skill calls
66
+ * it after the user's answer; the CLI cannot tell who ran it (design §8).
67
+ */
68
+ export function acceptKnowledge(name, o = {}) {
69
+ const root = repoRoot(o.cwd ?? process.cwd());
70
+ const base = basename(name, '.md');
71
+ const slug = base.replace(/^\d{4}-\d{2}-\d{2}_/, '');
72
+ const draft = join(root, PROPOSALS, `${base}.md`);
73
+ if (!existsSync(draft))
74
+ return { refused: `no draft ${PROPOSALS}/${base}.md` };
75
+ const at = today();
76
+ let t = readFileSync(draft, 'utf8');
77
+ t = setLine(t, 'id', `${at}_${slug}`);
78
+ t = setLine(t, 'approved', null);
79
+ t = t.replace(/^(source:.*)$/m, (m) => `${m}\napproved: { by: user, at: ${at} }`);
80
+ const hd = harnessDir(root);
81
+ const v = hd ? loadSchemas(hd).get('knowledge') : undefined;
82
+ if (!v)
83
+ return { refused: 'no knowledge schema — run reins install' };
84
+ const issues = validateFile(v, draft, false, t);
85
+ if (issues.length)
86
+ return { refused: `draft is invalid: ${issues.map((i) => i.message).join('; ')}` };
87
+ const rel = `.agents/knowledge/${at}_${slug}.md`;
88
+ if (existsSync(join(root, rel)))
89
+ return { refused: `${rel} already exists` };
90
+ mkdirSync(join(root, '.agents', 'knowledge'), { recursive: true });
91
+ writeFileSync(join(root, rel), t);
92
+ rmSync(draft);
93
+ return { path: rel };
94
+ }
@@ -104,6 +104,7 @@ export async function runMigrate(o) {
104
104
  const count = (r) => res.moves.filter((m) => m.result === r).length;
105
105
  writeFileSync(join(root, res.history), [
106
106
  `decisions: migrate-${o.tier}`,
107
+ 'source: tool',
107
108
  '',
108
109
  `# reins migrate ${o.tier} — from ${gen}`,
109
110
  '',
@@ -0,0 +1,184 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { harnessDir } from '../lib/harness.js';
4
+ import { loadSchemas, validateFile } from '../lib/schema.js';
5
+ import { intentDir, intentFile, intentIds, openTickets } from '../lib/work.js';
6
+ const fail = (m) => ({ code: 1, stdout: '', stderr: `reins new: ${m}\n` });
7
+ const pad = (n, w) => String(n).padStart(w, '0');
8
+ const ls = (d) => (existsSync(d) ? readdirSync(d).toSorted() : []);
9
+ // ---- numbering (pure) -------------------------------------------------------------------------
10
+ /** Next intent id: the highest number in `.agents/intent/` plus one, three digits. */
11
+ export function nextIntentId(existing) {
12
+ return pad(Math.max(0, ...existing.map(Number)) + 1, 3);
13
+ }
14
+ /** Next ticket number of an intent: the highest among open tickets, history records and the plan's ids, plus one. */
15
+ export function nextTicketNumber(intent, ...sources) {
16
+ const re = new RegExp(`^${intent}-(\\d+)$`);
17
+ const ns = sources.flat().map((s) => Number(re.exec(s)?.[1] ?? 0));
18
+ return Math.max(0, ...ns) + 1;
19
+ }
20
+ /** Next two-digit bus number of a ticket, from the file names already in `.loctx/bus/`. */
21
+ export function nextBusNumber(ticket, files) {
22
+ const ns = files.map((f) => {
23
+ const m = /^(.+)_(\d+)\.(request|response)\.yaml$/.exec(f);
24
+ return m && m[1] === ticket ? Number(m[2]) : 0;
25
+ });
26
+ return pad(Math.max(0, ...ns) + 1, 2);
27
+ }
28
+ /** Ticket ids that history pages record, from their file names and first heading (`# 009-2 — …`). */
29
+ function historyTicketIds(root, intent) {
30
+ const dir = join(root, '.loctx', 'history');
31
+ const re = new RegExp(`(?<![0-9])(${intent}-\\d+)(?![0-9])`, 'g');
32
+ const out = [];
33
+ for (const f of ls(dir).filter((e) => e.endsWith('.md'))) {
34
+ const head = readFileSync(join(dir, f), 'utf8')
35
+ .split('\n')
36
+ .find((l) => l.startsWith('# ')) ?? '';
37
+ for (const m of `${f}\n${head}`.matchAll(re))
38
+ out.push(m[1]);
39
+ }
40
+ return out;
41
+ }
42
+ /** How many numbered items the plan's order of work lists, or null when it cannot be read. */
43
+ export function planStepCount(body) {
44
+ const m = /^##\s+(?:작업 순서|order of work)[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/im.exec(body);
45
+ if (!m)
46
+ return null;
47
+ const n = (m[1].match(/^\d+\.\s/gm) ?? []).length;
48
+ return n || null;
49
+ }
50
+ // ---- writing ----------------------------------------------------------------------------------
51
+ /** Replaces top-level `key: value` lines of the frontmatter; the body stays as the template has it. */
52
+ function fill(text, values) {
53
+ const m = /^(---\n)([\s\S]*?\n)(---\n[\s\S]*)$/.exec(text);
54
+ const [head, mid, tail] = m ? [m[1], m[2], m[3]] : ['', text, ''];
55
+ const lines = mid.split('\n').map((l) => {
56
+ const k = /^([A-Za-z_]+):/.exec(l)?.[1];
57
+ return k && k in values ? `${k}: ${values[k]}` : l;
58
+ });
59
+ return `${head}${lines.join('\n')}${tail}`;
60
+ }
61
+ const q = (s) => JSON.stringify(s);
62
+ function emit(root, rel, content, schemaName, whole) {
63
+ const hd = harnessDir(root);
64
+ const v = hd ? loadSchemas(hd).get(schemaName) : undefined;
65
+ if (!v)
66
+ return fail(`no ${schemaName} schema in the harness`);
67
+ const issues = validateFile(v, rel, whole, content);
68
+ if (issues.length)
69
+ return fail(`output would not pass ${schemaName}: ${issues.map((i) => i.message).join('; ')}`);
70
+ const abs = join(root, rel);
71
+ if (existsSync(abs))
72
+ return fail(`${rel} already exists; not overwritten`);
73
+ mkdirSync(dirname(abs), { recursive: true });
74
+ writeFileSync(abs, content, { flag: 'wx' });
75
+ return { code: 0, stdout: `${rel}\n`, stderr: '' };
76
+ }
77
+ function template(root, rel) {
78
+ const hd = harnessDir(root);
79
+ const p = hd && join(hd, 'templates', rel);
80
+ return p && existsSync(p) ? readFileSync(p, 'utf8') : null;
81
+ }
82
+ const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
83
+ export function newIntent(root, slug, o = {}) {
84
+ if (!SLUG.test(slug))
85
+ return fail(`slug must be kebab-case (got "${slug}")`);
86
+ const t = template(root, 'intent.md');
87
+ if (!t)
88
+ return fail('no intent template in the harness');
89
+ const id = nextIntentId(intentIds(root));
90
+ const vals = { id: q(id), slug, status: 'draft', approvals: '[]' };
91
+ if (o.version)
92
+ vals['version'] = q(o.version);
93
+ if (o.origin)
94
+ vals['origin'] = o.origin;
95
+ return emit(root, `.agents/intent/${id}_${slug}/intent.md`, fill(t, vals), 'intent', false);
96
+ }
97
+ export function newTicket(root, intent, step, slug, o = {}) {
98
+ if (!/^\d{3}$/.test(intent))
99
+ return fail(`intent must be three digits (got "${intent}")`);
100
+ if (!/^[1-9]\d*$/.test(step))
101
+ return fail(`step must be a positive integer (got "${step}")`);
102
+ if (!SLUG.test(slug))
103
+ return fail(`slug must be kebab-case (got "${slug}")`);
104
+ const idir = intentDir(root, intent);
105
+ if (!idir)
106
+ return fail(`no intent ${intent} in .agents/intent/`);
107
+ const plan = intentFile(root, intent, 'plan');
108
+ if (!plan)
109
+ return fail(`intent ${intent} has no plan.md; write the plan before its tickets`);
110
+ const max = planStepCount(plan.body);
111
+ if (max === null)
112
+ return fail(`plan.md of intent ${intent} has no readable order of work`);
113
+ if (Number(step) > max)
114
+ return fail(`step ${step} is outside the plan's order of work (1..${max})`);
115
+ const t = template(root, 'ticket.md');
116
+ if (!t)
117
+ return fail('no ticket template in the harness');
118
+ const planned = Array.isArray(plan?.data['tickets'])
119
+ ? plan.data['tickets'].map(String)
120
+ : [];
121
+ const open = openTickets(root).map((f) => String(f.data['id'] ?? ''));
122
+ const n = nextTicketNumber(intent, open, historyTicketIds(root, intent), planned);
123
+ const iSlug = idir
124
+ .split('/')
125
+ .pop()
126
+ .replace(/^\d{3}_/, '');
127
+ const branch = typeof plan.data['branch'] === 'string' ? plan.data['branch'] : `feat/${intent}-${iSlug}`;
128
+ const depends = (o.depends ?? '')
129
+ .split(',')
130
+ .map((s) => s.trim())
131
+ .filter(Boolean);
132
+ const vals = {
133
+ id: `${intent}-${n}`,
134
+ intent: q(intent),
135
+ plan_step: step,
136
+ depends: `[${depends.join(', ')}]`,
137
+ branch,
138
+ };
139
+ if (o.title)
140
+ vals['title'] = q(o.title);
141
+ if (o.release)
142
+ vals['release'] = o.release;
143
+ if (o.role)
144
+ vals['role'] = o.role;
145
+ return emit(root, `.loctx/ticket/${intent}-${n}_${slug}.md`, fill(t, vals), 'ticket', false);
146
+ }
147
+ const KIND_ROUTE = {
148
+ implement: { from: 'pl', to: 'implementer' },
149
+ verify: { from: 'pl', to: 'verify-tool' },
150
+ review: { from: 'pl', to: 'code-review' },
151
+ };
152
+ export function newRequest(root, ticket, kind, o = {}) {
153
+ if (!/^\d{3}-\d+$/.test(ticket))
154
+ return fail(`ticket must look like 011-1 (got "${ticket}")`);
155
+ const fixed = KIND_ROUTE[kind];
156
+ if (!fixed && kind !== 'question' && kind !== 'stop-report')
157
+ return fail(`kind must be implement, verify, review, question or stop-report (got "${kind}")`);
158
+ const from = o.from ?? fixed?.from;
159
+ if (!from)
160
+ return fail(`${kind} needs --from`);
161
+ const to = o.to ?? fixed?.to ?? 'pl';
162
+ const hd = harnessDir(root);
163
+ const roles = new Set(ls(hd ? join(hd, 'roles') : '').map((f) => f.replace(/\.md$/, '')));
164
+ for (const [flag, r] of [
165
+ ['--from', from],
166
+ ['--to', to],
167
+ ])
168
+ if (!roles.has(r))
169
+ return fail(`${flag} "${r}" is not a harness role (${[...roles].join(', ')})`);
170
+ const t = template(root, 'bus/request.yaml');
171
+ if (!t)
172
+ return fail('no bus request template in the harness');
173
+ const nn = nextBusNumber(ticket, ls(join(root, '.loctx', 'bus')));
174
+ const id = `${ticket}_${nn}`;
175
+ const vals = {
176
+ id,
177
+ from,
178
+ to,
179
+ ticket,
180
+ intent: q(ticket.slice(0, 3)),
181
+ kind,
182
+ };
183
+ return emit(root, `.loctx/bus/${id}.request.yaml`, fill(t, vals), 'bus-request', true);
184
+ }
@@ -0,0 +1,7 @@
1
+ import { repoRoot } from '../lib/git.js';
2
+ import { collectRetro, formatRetro } from '../lib/retro.js';
3
+ /** `reins retro [--release <v>] [--json]` (design §8): counts only; the summary sentences are the pm's. */
4
+ export function runRetro(o = {}) {
5
+ return collectRetro(repoRoot(o.cwd ?? process.cwd()), { release: o.release });
6
+ }
7
+ export { formatRetro };
@@ -431,5 +431,36 @@ export function rcClose(root, release) {
431
431
  resume: 'add it to plan.md (departure log) or close it',
432
432
  });
433
433
  }
434
+ if (findings.length === 0)
435
+ findings.push(...nextRc(root, release));
434
436
  return findings;
435
437
  }
438
+ /**
439
+ * The next rc number from the local ledger `.loctx/release/<V>.md` (one `- rc.N …` line per rc):
440
+ * rc.1 when there is no ledger, else the last recorded rc + 1. A number already recorded is F2.
441
+ */
442
+ function nextRc(root, release) {
443
+ const path = join(root, '.loctx', 'release', `${release}.md`);
444
+ const recorded = existsSync(path)
445
+ ? [...readFileSync(path, 'utf8').matchAll(/^\s*[-*]\s*rc\.(\d+)\b/gm)].map((m) => Number(m[1]))
446
+ : [];
447
+ const next = (recorded.at(-1) ?? 0) + 1;
448
+ if (recorded.includes(next))
449
+ return [
450
+ {
451
+ reason: 'F2',
452
+ verdict: 'STOP',
453
+ path,
454
+ message: `${release}-rc.${next} is already recorded`,
455
+ resume: 'a version number is never reused; fix the ledger order or record the later rc last',
456
+ },
457
+ ];
458
+ return [
459
+ {
460
+ reason: 'F2',
461
+ verdict: 'WARN',
462
+ path: existsSync(path) ? path : undefined,
463
+ message: `next rc: ${release}-rc.${next}`,
464
+ },
465
+ ];
466
+ }
@@ -3,6 +3,7 @@ import { basename, join } from 'node:path';
3
3
  import { parse } from 'yaml';
4
4
  import { repoRoot } from '../lib/git.js';
5
5
  import { harnessVersion, packageHarness } from '../lib/upstream.js';
6
+ import { candidateCount } from '../lib/retro.js';
6
7
  import { driftGenerated } from '../lib/vendor-write.js';
7
8
  import { report } from '../lib/verdict.js';
8
9
  import { historyPages, intentDir, intentFile, intentIds, openTickets, } from '../lib/work.js';
@@ -51,6 +52,8 @@ function harnessStatus(root) {
51
52
  }
52
53
  /** The S-3 table: the first row that matches wins. */
53
54
  export function nextForIntent(s) {
55
+ if (s.intent === 'released')
56
+ return '—';
54
57
  if (s.intent === 'draft')
55
58
  return 'user: approve the intent';
56
59
  if (s.intent === 'approved' && s.spec === null)
@@ -195,6 +198,7 @@ export function collectStatus(root) {
195
198
  tickets: open.map((t) => ticketStatus(root, t)),
196
199
  bus: safe(() => busCount(root), 0),
197
200
  lastHistory: pages.length ? basename(pages[pages.length - 1].path) : null,
201
+ knowledgeCandidates: safe(() => candidateCount(root), 0),
198
202
  };
199
203
  }
200
204
  /** The text view of the same object `--json` prints. */
@@ -210,6 +214,10 @@ export function formatStatus(d) {
210
214
  if (d.intents.length === 0)
211
215
  out.push(' none');
212
216
  for (const i of d.intents) {
217
+ if (i.intent === 'released') {
218
+ out.push(` ${i.id} ${i.slug}${i.version ? ` v${i.version}` : ''} — released`);
219
+ continue;
220
+ }
213
221
  out.push(` ${i.id} ${i.slug}${i.version ? ` v${i.version}` : ''} — intent: ${i.intent ?? '—'} · spec: ${i.spec ?? '—'} · plan: ${i.plan ?? '—'} · tickets: ${i.tickets.open} open / ${i.tickets.planned} planned`);
214
222
  out.push(` next: ${i.next}`);
215
223
  }
@@ -229,6 +237,7 @@ export function formatStatus(d) {
229
237
  out.push('');
230
238
  out.push(`bus: ${d.bus} file${d.bus === 1 ? '' : 's'}`);
231
239
  out.push(`last history: ${d.lastHistory ?? '—'}`);
240
+ out.push(`knowledge candidates: ${d.knowledgeCandidates}`);
232
241
  return `${out.join('\n')}\n`;
233
242
  }
234
243
  /** `reins status [--json]`: exit 0 anywhere inside a git repository, 2 outside one. */
@@ -39,3 +39,13 @@ export function isAncestor(ancestor, descendant, cwd) {
39
39
  export function repoRoot(cwd) {
40
40
  return git(['rev-parse', '--show-toplevel'], cwd);
41
41
  }
42
+ /** Subjects of the commits an update of an existing ref adds: `remote..local`. */
43
+ export function pushedSubjects(remoteSha, localSha, cwd) {
44
+ try {
45
+ const out = git(['log', '--format=%s', `${remoteSha}..${localSha}`], cwd);
46
+ return out ? out.split('\n') : [];
47
+ }
48
+ catch {
49
+ return [];
50
+ }
51
+ }