@bluenyang/reins 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -26
- package/cli/dist/commands/check.js +180 -90
- package/cli/dist/commands/configure.js +79 -0
- package/cli/dist/commands/gate.js +54 -0
- package/cli/dist/commands/install.js +80 -30
- package/cli/dist/commands/metrics.js +138 -0
- package/cli/dist/commands/stages.js +435 -0
- package/cli/dist/commands/status.js +249 -0
- package/cli/dist/commands/update.js +70 -0
- package/cli/dist/lib/blocks.js +6 -1
- package/cli/dist/lib/detect.js +91 -1
- package/cli/dist/lib/fsx.js +8 -3
- package/cli/dist/lib/generate.js +143 -0
- package/cli/dist/lib/git.js +12 -1
- package/cli/dist/lib/harness.js +15 -4
- package/cli/dist/lib/metrics.js +223 -0
- package/cli/dist/lib/reader.js +47 -0
- package/cli/dist/lib/schema.js +23 -2
- package/cli/dist/lib/skills.js +13 -2
- package/cli/dist/lib/upstream.js +8 -0
- package/cli/dist/lib/vendor-write.js +136 -0
- package/cli/dist/lib/work.js +106 -0
- package/cli/dist/reins.js +161 -7
- package/docs/README.ko.md +25 -27
- package/harness/CHANGELOG.md +5 -0
- package/harness/VERSION +1 -1
- package/harness/policy/stops.yaml +2 -2
- package/harness/policy/transitions.yaml +1 -1
- package/harness/roles/code-review.md +6 -3
- package/harness/roles/pl.md +2 -1
- package/harness/roles/qa-design.md +1 -1
- package/harness/roles/qa-run.md +1 -1
- package/harness/templates/bus/request.yaml +8 -2
- package/harness/templates/bus/response.yaml +1 -0
- package/package.json +9 -2
- package/skills/reins-loop/SKILL.md +5 -1
- package/skills/reins-loop/references/vendor-cli.md +40 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { parse } from 'yaml';
|
|
4
|
+
import { defaultsAsker } from '../lib/ask.js';
|
|
5
|
+
import { overrides } from '../lib/blocks.js';
|
|
6
|
+
import { repoRoot } from '../lib/git.js';
|
|
7
|
+
import { harnessVersion, packageHarness } from '../lib/upstream.js';
|
|
8
|
+
import { runInstall } from './install.js';
|
|
9
|
+
/** Numeric dotted-version compare; pre-release suffixes are ignored. */
|
|
10
|
+
export function newer(a, b) {
|
|
11
|
+
const pa = a.split(/[.-]/).map((x) => Number.parseInt(x, 10) || 0);
|
|
12
|
+
const pb = b.split(/[.-]/).map((x) => Number.parseInt(x, 10) || 0);
|
|
13
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
14
|
+
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
15
|
+
if (d !== 0)
|
|
16
|
+
return d > 0;
|
|
17
|
+
}
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
/** Changelog entries for versions in (from, to]. */
|
|
21
|
+
export function changesBetween(changelog, from, to) {
|
|
22
|
+
const out = [];
|
|
23
|
+
let take = false;
|
|
24
|
+
for (const line of changelog.split('\n')) {
|
|
25
|
+
const h = /^## (\S+)/.exec(line);
|
|
26
|
+
if (h)
|
|
27
|
+
take = newer(h[1] ?? '0', from) && !newer(h[1] ?? '0', to);
|
|
28
|
+
else if (take && line.startsWith('- '))
|
|
29
|
+
out.push(line.slice(2));
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* `reins update` (design §5, two paths): the deterministic part — upstream harness files, managed blocks,
|
|
35
|
+
* generated vendor files and the version pin — is re-applied from the package; project-owned files stay.
|
|
36
|
+
* When the changelog says a project section needs changing, it points to the /reins-update skill.
|
|
37
|
+
*/
|
|
38
|
+
export async function runUpdate(o) {
|
|
39
|
+
const root = repoRoot(o.cwd ?? process.cwd());
|
|
40
|
+
const res = { root, changes: [], needsSkill: false, overrides: [] };
|
|
41
|
+
const pinPath = join(root, '.agents/harness/install.yaml');
|
|
42
|
+
if (!existsSync(pinPath))
|
|
43
|
+
return {
|
|
44
|
+
...res,
|
|
45
|
+
refused: 'reins is not installed here — use `reins install` or `reins migrate`',
|
|
46
|
+
};
|
|
47
|
+
const pin = parse(readFileSync(pinPath, 'utf8'));
|
|
48
|
+
const up = packageHarness();
|
|
49
|
+
res.from = pin.version;
|
|
50
|
+
res.to = harnessVersion(up);
|
|
51
|
+
const cl = join(up, 'CHANGELOG.md');
|
|
52
|
+
if (existsSync(cl) && newer(res.to, res.from)) {
|
|
53
|
+
res.changes = changesBetween(readFileSync(cl, 'utf8'), res.from, res.to);
|
|
54
|
+
res.needsSkill = res.changes.some((c) => c.includes('[skill]'));
|
|
55
|
+
}
|
|
56
|
+
const agents = join(root, 'AGENTS.md');
|
|
57
|
+
if (existsSync(agents))
|
|
58
|
+
res.overrides = [...overrides(readFileSync(agents, 'utf8'))];
|
|
59
|
+
res.install = await runInstall({
|
|
60
|
+
tier: pin.tier,
|
|
61
|
+
mode: pin.mode,
|
|
62
|
+
asker: defaultsAsker,
|
|
63
|
+
cwd: root,
|
|
64
|
+
dryRun: o.dryRun,
|
|
65
|
+
now: o.now,
|
|
66
|
+
detectVendors: o.detectVendors,
|
|
67
|
+
recordAs: 'update',
|
|
68
|
+
});
|
|
69
|
+
return res;
|
|
70
|
+
}
|
package/cli/dist/lib/blocks.js
CHANGED
|
@@ -18,6 +18,11 @@ function headingOf(block) {
|
|
|
18
18
|
function outside(text) {
|
|
19
19
|
return text.replace(BLOCK_RE, '');
|
|
20
20
|
}
|
|
21
|
+
/** The project already has this block's `## <heading>` outside any managed block (applyBlocks leaves such a block out). */
|
|
22
|
+
export function hasOwnSection(text, block) {
|
|
23
|
+
const h = headingOf(block);
|
|
24
|
+
return h !== null && new RegExp(`^## ${h}\\s*$`, 'm').test(outside(text));
|
|
25
|
+
}
|
|
21
26
|
/**
|
|
22
27
|
* Put the upstream blocks into an AGENTS.md. Existing blocks are replaced in place; an overridden block is
|
|
23
28
|
* left alone; a block whose heading the project already has outside any block is skipped (migrate replaces it).
|
|
@@ -41,7 +46,7 @@ export function applyBlocks(text, upstream) {
|
|
|
41
46
|
continue;
|
|
42
47
|
}
|
|
43
48
|
const h = headingOf(b);
|
|
44
|
-
if (
|
|
49
|
+
if (hasOwnSection(res.text, b)) {
|
|
45
50
|
res.skipped.push({
|
|
46
51
|
name: b.name,
|
|
47
52
|
why: `the project already has a "## ${h}" section — \`reins migrate\` replaces it`,
|
package/cli/dist/lib/detect.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { execFileSync } from 'node:child_process';
|
|
1
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
2
2
|
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
export function generation(root) {
|
|
@@ -103,3 +103,93 @@ export function discoverGates(root) {
|
|
|
103
103
|
}
|
|
104
104
|
return res;
|
|
105
105
|
}
|
|
106
|
+
/** Vendor of a model ID by prefix, in order: gpt, gemini, cursor-, else claude (spec S-2). */
|
|
107
|
+
export function vendorOf(model) {
|
|
108
|
+
if (model.startsWith('gpt'))
|
|
109
|
+
return 'openai';
|
|
110
|
+
if (model.startsWith('gemini'))
|
|
111
|
+
return 'google';
|
|
112
|
+
if (model.startsWith('cursor-'))
|
|
113
|
+
return 'cursor';
|
|
114
|
+
return 'claude';
|
|
115
|
+
}
|
|
116
|
+
/** Model IDs seen working in this environment. */
|
|
117
|
+
export const CONFIRMED_MODELS = new Set(['claude-opus-5-5', 'claude-fable-5-1']);
|
|
118
|
+
/** Runs `<cli> models` without a shell, stdin closed, 10 s limit. Nothing else is ever run. */
|
|
119
|
+
export const spawnModels = (cli, args) => {
|
|
120
|
+
if (process.env['REINS_NO_VENDOR_SPAWN'])
|
|
121
|
+
throw new Error(`refusing to spawn ${cli} under test`);
|
|
122
|
+
const r = spawnSync(cli, args, {
|
|
123
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
124
|
+
timeout: 10_000,
|
|
125
|
+
encoding: 'utf8',
|
|
126
|
+
});
|
|
127
|
+
const code = r.error?.code;
|
|
128
|
+
return {
|
|
129
|
+
status: r.status,
|
|
130
|
+
stdout: r.stdout ?? '',
|
|
131
|
+
timedOut: code === 'ETIMEDOUT',
|
|
132
|
+
error: r.error?.message,
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
const LISTERS = { google: 'agy', cursor: 'cursor-agent' };
|
|
136
|
+
// eslint-disable-next-line no-control-regex
|
|
137
|
+
const ANSI = /\u001b\[[0-9;?]*[A-Za-z]/g;
|
|
138
|
+
function parseModels(cli, out) {
|
|
139
|
+
const ids = [];
|
|
140
|
+
for (const line of out.replace(ANSI, '').split(/\r?\n/)) {
|
|
141
|
+
if (cli === 'agy') {
|
|
142
|
+
if (line.includes('\t'))
|
|
143
|
+
ids.push(line.split('\t')[0].trim());
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
const m = /^(\S+) - .+$/.exec(line);
|
|
147
|
+
if (m)
|
|
148
|
+
ids.push(m[1]);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return ids.filter(Boolean);
|
|
152
|
+
}
|
|
153
|
+
/** `<cli> models` → model IDs, or the reason it could not be read. */
|
|
154
|
+
export function listModels(vendor, run = spawnModels) {
|
|
155
|
+
const cli = LISTERS[vendor];
|
|
156
|
+
const r = run(cli, ['models']);
|
|
157
|
+
if (r.timedOut)
|
|
158
|
+
return { failed: 'timed out after 10 s' };
|
|
159
|
+
if (r.error)
|
|
160
|
+
return { failed: r.error };
|
|
161
|
+
if (r.status !== 0)
|
|
162
|
+
return { failed: `exit ${r.status}` };
|
|
163
|
+
const ids = parseModels(cli, r.stdout);
|
|
164
|
+
return ids.length ? { ids } : { failed: 'no model IDs in output' };
|
|
165
|
+
}
|
|
166
|
+
export function newModelCache(o = {}) {
|
|
167
|
+
return {
|
|
168
|
+
run: o.run ?? spawnModels,
|
|
169
|
+
onPath: o.onPath ?? (process.env['REINS_NO_VENDOR_SPAWN'] ? () => false : onPath),
|
|
170
|
+
warn: o.warn ?? ((m) => void process.stderr.write(`warning: ${m}\n`)),
|
|
171
|
+
lists: new Map(),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Checks a binding against the vendor CLI's model list (spec S-3). Returns the fields to record,
|
|
176
|
+
* or null when the vendor has no list command or its CLI is absent. Never blocks, never changes the model.
|
|
177
|
+
*/
|
|
178
|
+
export function checkBinding(model, vendor, cache) {
|
|
179
|
+
if (vendor !== 'google' && vendor !== 'cursor')
|
|
180
|
+
return null;
|
|
181
|
+
const cli = LISTERS[vendor];
|
|
182
|
+
if (!cache.onPath(cli))
|
|
183
|
+
return null;
|
|
184
|
+
let res = cache.lists.get(cli);
|
|
185
|
+
if (!res) {
|
|
186
|
+
res = listModels(vendor, cache.run);
|
|
187
|
+
cache.lists.set(cli, res);
|
|
188
|
+
}
|
|
189
|
+
if ('failed' in res)
|
|
190
|
+
return { unverified: true, note: `${cli} models failed: ${res.failed}` };
|
|
191
|
+
if (res.ids.includes(model))
|
|
192
|
+
return {};
|
|
193
|
+
cache.warn(`${model} is not in \`${cli} models\` — recorded as unverified`);
|
|
194
|
+
return { unverified: true, note: `not in ${cli} models` };
|
|
195
|
+
}
|
package/cli/dist/lib/fsx.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
-
import { dirname, join, relative } from 'node:path';
|
|
2
|
+
import { dirname, join, relative, sep } from 'node:path';
|
|
3
3
|
export function apply(root, writes, dryRun) {
|
|
4
4
|
const out = { created: [], changed: [], unchanged: [] };
|
|
5
5
|
for (const w of writes) {
|
|
@@ -17,7 +17,12 @@ export function apply(root, writes, dryRun) {
|
|
|
17
17
|
}
|
|
18
18
|
return out;
|
|
19
19
|
}
|
|
20
|
-
/**
|
|
20
|
+
/** `relative(from, to)` with `/` separators on every platform — the form git, globs and stored paths use. */
|
|
21
|
+
export function relPath(from, to) {
|
|
22
|
+
const rel = relative(from, to);
|
|
23
|
+
return sep === '/' ? rel : rel.split(sep).join('/');
|
|
24
|
+
}
|
|
25
|
+
/** Every file under `dir`, as `/`-separated paths relative to `dir`. */
|
|
21
26
|
export function listFiles(dir) {
|
|
22
27
|
const out = [];
|
|
23
28
|
const walk = (d) => {
|
|
@@ -28,7 +33,7 @@ export function listFiles(dir) {
|
|
|
28
33
|
if (statSync(p).isDirectory())
|
|
29
34
|
walk(p);
|
|
30
35
|
else
|
|
31
|
-
out.push(
|
|
36
|
+
out.push(relPath(dir, p));
|
|
32
37
|
}
|
|
33
38
|
};
|
|
34
39
|
walk(dir);
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { parse, stringify } from 'yaml';
|
|
3
|
+
import { workTreeReader } from './reader.js';
|
|
4
|
+
import { splitFrontmatter } from './skills.js';
|
|
5
|
+
/**
|
|
6
|
+
* Vendor files generated from `.agents/harness/` (design §6). Round one generates Claude Code only:
|
|
7
|
+
* `.claude/agents/reins-<role>.md` for roles bound to Claude, and `.claude/settings.json` deny rules.
|
|
8
|
+
*/
|
|
9
|
+
export const MANIFEST = '.agents/harness/generated.yaml';
|
|
10
|
+
export const sha = (s) => createHash('sha256').update(s).digest('hex').slice(0, 16);
|
|
11
|
+
function readRole(text) {
|
|
12
|
+
const { data, body } = splitFrontmatter(text);
|
|
13
|
+
const d = data ?? {};
|
|
14
|
+
return {
|
|
15
|
+
role: String(d['role']),
|
|
16
|
+
summary: String(d['summary'] ?? ''),
|
|
17
|
+
may: d['may'] ?? [],
|
|
18
|
+
mustNot: d['must_not'] ?? [],
|
|
19
|
+
capabilities: d['capabilities'] ?? {},
|
|
20
|
+
body: body.trim(),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** Capabilities → Claude Code tool names to withhold. Path-level limits are not expressible here; T2 (C10) is the backstop. */
|
|
24
|
+
function disallowed(c) {
|
|
25
|
+
const out = [];
|
|
26
|
+
if (c.write === false)
|
|
27
|
+
out.push('Edit', 'Write', 'NotebookEdit');
|
|
28
|
+
if (c.shell === false)
|
|
29
|
+
out.push('Bash');
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
export function claudeAgent(r, b, version) {
|
|
33
|
+
const fm = {
|
|
34
|
+
name: `reins-${r.role}`,
|
|
35
|
+
description: `reins ${r.role} role. ${r.summary}`,
|
|
36
|
+
model: b.model,
|
|
37
|
+
};
|
|
38
|
+
const dis = disallowed(r.capabilities);
|
|
39
|
+
if (dis.length)
|
|
40
|
+
fm['disallowedTools'] = dis.join(', ');
|
|
41
|
+
return [
|
|
42
|
+
'---',
|
|
43
|
+
stringify(fm).trimEnd(),
|
|
44
|
+
'---',
|
|
45
|
+
`<!-- generated by reins ${version} from .agents/harness/roles/${r.role}.md and bindings.yaml — do not edit; run \`reins update\` -->`,
|
|
46
|
+
'',
|
|
47
|
+
`You are the **${r.role}** role of the reins harness in this repository. ${r.summary}`,
|
|
48
|
+
'',
|
|
49
|
+
'## You must never',
|
|
50
|
+
...r.mustNot.map((m) => `- ${m}`),
|
|
51
|
+
'- break any common red line in `.agents/harness/policy/common-red-lines.yaml` (C1–C10)',
|
|
52
|
+
'',
|
|
53
|
+
'## You may',
|
|
54
|
+
...r.may.map((m) => `- ${m}`),
|
|
55
|
+
'',
|
|
56
|
+
'## Procedure',
|
|
57
|
+
'',
|
|
58
|
+
r.body.replace(/^# .*\n+/, ''),
|
|
59
|
+
'',
|
|
60
|
+
'When a stop condition in `.agents/harness/policy/stops.yaml` applies, stop and report its id. `reins check` is the verifier.',
|
|
61
|
+
'',
|
|
62
|
+
].join('\n');
|
|
63
|
+
}
|
|
64
|
+
/** C4 patterns → Claude Code deny rules. A pattern that would also hide an allowed template (`.env.*` vs `.env.example`) is narrowed. */
|
|
65
|
+
export function denyRules(lines) {
|
|
66
|
+
const c4 = lines.find((r) => r.id === 'C4');
|
|
67
|
+
const globs = new Set();
|
|
68
|
+
for (const p of c4?.patterns ?? []) {
|
|
69
|
+
if (p === '.env.*')
|
|
70
|
+
for (const v of [
|
|
71
|
+
'.env.local',
|
|
72
|
+
'.env.*.local',
|
|
73
|
+
'.env.development',
|
|
74
|
+
'.env.production',
|
|
75
|
+
'.env.staging',
|
|
76
|
+
'.env.test',
|
|
77
|
+
])
|
|
78
|
+
globs.add(v);
|
|
79
|
+
else
|
|
80
|
+
globs.add(p);
|
|
81
|
+
}
|
|
82
|
+
const rules = [];
|
|
83
|
+
for (const g of globs)
|
|
84
|
+
for (const t of ['Read', 'Edit'])
|
|
85
|
+
rules.push(`${t}(${g.startsWith('**/') ? g : `**/${g}`})`);
|
|
86
|
+
// A1 force push and C5 hook bypass: the user runs these explicitly, never an agent
|
|
87
|
+
rules.push('Bash(git push --force *)', 'Bash(git push -f *)', 'Bash(git push --force-with-lease *)', 'Bash(git commit --no-verify *)', 'Bash(git commit -n *)', 'Bash(git push --no-verify *)');
|
|
88
|
+
return rules;
|
|
89
|
+
}
|
|
90
|
+
/** Everything the generator owns, computed from the installed harness. Pure. */
|
|
91
|
+
export function generateVendorFiles(root, rd = workTreeReader(root)) {
|
|
92
|
+
const harness = '.agents/harness';
|
|
93
|
+
const version = rd.read(`${harness}/VERSION`)?.trim() ?? '?';
|
|
94
|
+
const out = { writes: [], skipped: [] };
|
|
95
|
+
if (rd.list(harness).length === 0)
|
|
96
|
+
return out;
|
|
97
|
+
const bindingsText = rd.read(`${harness}/bindings.yaml`);
|
|
98
|
+
const bindings = bindingsText
|
|
99
|
+
? (parse(bindingsText).roles ?? {})
|
|
100
|
+
: {};
|
|
101
|
+
const rolesDir = `${harness}/roles`;
|
|
102
|
+
for (const p of rd
|
|
103
|
+
.list(rolesDir)
|
|
104
|
+
.filter((x) => /^[^/]+\.md$/.test(x.slice(rolesDir.length + 1)))
|
|
105
|
+
.toSorted()) {
|
|
106
|
+
const r = readRole(rd.read(p) ?? '');
|
|
107
|
+
const b = bindings[r.role];
|
|
108
|
+
if (!b)
|
|
109
|
+
continue;
|
|
110
|
+
if (b.vendor !== 'claude') {
|
|
111
|
+
out.skipped.push(`${r.role} → ${b.vendor} ${b.model}`);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
out.writes.push({
|
|
115
|
+
path: `.claude/agents/reins-${r.role}.md`,
|
|
116
|
+
content: claudeAgent(r, b, version),
|
|
117
|
+
why: `role ${r.role}`,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
// skills: Codex, Gemini and Cursor read .agents/skills/ directly; Claude Code reads a byte-identical copy
|
|
121
|
+
const skills = '.agents/skills';
|
|
122
|
+
const names = [
|
|
123
|
+
...new Set(rd.list(skills).map((p) => p.slice(skills.length + 1).split('/')[0] ?? '')),
|
|
124
|
+
].toSorted();
|
|
125
|
+
for (const name of names) {
|
|
126
|
+
if (rd.read(`${skills}/${name}/SKILL.md`) === undefined)
|
|
127
|
+
continue;
|
|
128
|
+
for (const p of rd.list(`${skills}/${name}`).toSorted())
|
|
129
|
+
out.writes.push({
|
|
130
|
+
path: `.claude/skills/${p.slice(skills.length + 1)}`,
|
|
131
|
+
content: rd.read(p) ?? '',
|
|
132
|
+
why: `skill ${name}`,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
const redText = rd.read(`${harness}/policy/common-red-lines.yaml`);
|
|
136
|
+
if (rd.list(`${harness}/policy`).length > 0 && redText !== undefined)
|
|
137
|
+
out.writes.push({
|
|
138
|
+
path: '.claude/settings.json',
|
|
139
|
+
content: `${JSON.stringify({ $schema: 'https://json.schemastore.org/claude-code-settings.json', permissions: { deny: denyRules(parse(redText).rules) } }, null, 2)}\n`,
|
|
140
|
+
why: 'C4 secrets, A1 force push, C5 hook bypass',
|
|
141
|
+
});
|
|
142
|
+
return out;
|
|
143
|
+
}
|
package/cli/dist/lib/git.js
CHANGED
|
@@ -10,8 +10,19 @@ export function stagedFiles(cwd) {
|
|
|
10
10
|
const out = git(['diff', '--cached', '--name-only', '--diff-filter=ACMR'], cwd);
|
|
11
11
|
return out ? out.split('\n') : [];
|
|
12
12
|
}
|
|
13
|
+
/** The checked-out branch; on a repository without commits `rev-parse` fails, so ask for the symbolic ref instead. */
|
|
13
14
|
export function currentBranch(cwd) {
|
|
14
|
-
|
|
15
|
+
try {
|
|
16
|
+
return git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
try {
|
|
20
|
+
return git(['symbolic-ref', '--short', 'HEAD'], cwd);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return '';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
15
26
|
}
|
|
16
27
|
export function isAncestor(ancestor, descendant, cwd) {
|
|
17
28
|
try {
|
package/cli/dist/lib/harness.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from 'node:fs';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { parse } from 'yaml';
|
|
4
|
+
import { workTreeReader } from './reader.js';
|
|
4
5
|
/**
|
|
5
6
|
* Where the harness sources live: an installed project has `.agents/harness/`;
|
|
6
7
|
* this repository (the upstream) keeps them at `harness/`.
|
|
@@ -12,6 +13,13 @@ export function harnessDir(root) {
|
|
|
12
13
|
}
|
|
13
14
|
return null;
|
|
14
15
|
}
|
|
16
|
+
/** Like `harnessDir`, but repository-relative and read through a `Reader` (the index, for pre-commit). */
|
|
17
|
+
export function harnessRel(rd) {
|
|
18
|
+
for (const d of ['.agents/harness', 'harness'])
|
|
19
|
+
if (rd.list(`${d}/policy`).length > 0)
|
|
20
|
+
return d;
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
15
23
|
export function readYaml(path) {
|
|
16
24
|
return parse(readFileSync(path, 'utf8'));
|
|
17
25
|
}
|
|
@@ -22,11 +30,14 @@ export function stops(dir) {
|
|
|
22
30
|
return readYaml(join(dir, 'policy', 'stops.yaml')).stops;
|
|
23
31
|
}
|
|
24
32
|
/** Secret patterns from red line C4, or null when there is no harness to read. */
|
|
25
|
-
export function secretPolicy(root) {
|
|
26
|
-
const
|
|
27
|
-
if (!
|
|
33
|
+
export function secretPolicy(root, rd = workTreeReader(root)) {
|
|
34
|
+
const rel = harnessRel(rd);
|
|
35
|
+
if (!rel)
|
|
36
|
+
return null;
|
|
37
|
+
const text = rd.read(`${rel}/policy/common-red-lines.yaml`);
|
|
38
|
+
if (text === undefined)
|
|
28
39
|
return null;
|
|
29
|
-
const c4 =
|
|
40
|
+
const c4 = parse(text).rules.find((r) => r.id === 'C4');
|
|
30
41
|
if (!c4?.patterns)
|
|
31
42
|
return null;
|
|
32
43
|
return { patterns: c4.patterns, allowed: c4.allowed ?? [] };
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { redLines, stops } from './harness.js';
|
|
4
|
+
/** Metrics live next to the other local evidence; one JSON object per line (design §3, intent 002). */
|
|
5
|
+
export const METRICS_FILE = '.loctx/reports/metrics.jsonl';
|
|
6
|
+
export const METRIC_SCHEMA = 'reins/metric@1';
|
|
7
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
8
|
+
/** Local time to the second, with the UTC offset: `2026-10-25T14:03:07+09:00`. */
|
|
9
|
+
export function localIso(d = new Date()) {
|
|
10
|
+
const off = -d.getTimezoneOffset();
|
|
11
|
+
const sign = off < 0 ? '-' : '+';
|
|
12
|
+
const a = Math.abs(off);
|
|
13
|
+
return (`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
|
|
14
|
+
`T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` +
|
|
15
|
+
`${sign}${pad(Math.floor(a / 60))}:${pad(a % 60)}`);
|
|
16
|
+
}
|
|
17
|
+
/** The intent number is the first three characters of a ticket id (`002-1` → `002`). */
|
|
18
|
+
export function intentOf(ticket) {
|
|
19
|
+
return ticket ? ticket.slice(0, 3) : undefined;
|
|
20
|
+
}
|
|
21
|
+
/** Fill `intent` from `ticket` and put the shared keys first. */
|
|
22
|
+
function stamp(rec) {
|
|
23
|
+
const { ticket, intent, ...rest } = rec;
|
|
24
|
+
const out = { schema: METRIC_SCHEMA, ts: localIso(), ...rest };
|
|
25
|
+
if (ticket)
|
|
26
|
+
out['ticket'] = ticket;
|
|
27
|
+
const i = ticket ? intentOf(ticket) : intent;
|
|
28
|
+
if (i)
|
|
29
|
+
out['intent'] = i;
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Appends one line to the metrics file. A repository without `.loctx/` is skipped, and a write
|
|
34
|
+
* error never escapes: the exit code and output of `check` and `gate` do not depend on metrics.
|
|
35
|
+
* Returns whether a line was written.
|
|
36
|
+
*/
|
|
37
|
+
export function appendMetric(root, rec) {
|
|
38
|
+
try {
|
|
39
|
+
if (!existsSync(join(root, '.loctx')))
|
|
40
|
+
return false;
|
|
41
|
+
const file = join(root, METRICS_FILE);
|
|
42
|
+
mkdirSync(join(root, '.loctx', 'reports'), { recursive: true });
|
|
43
|
+
appendFileSync(file, `${JSON.stringify(stamp(rec))}\n`);
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const strs = (v) => Array.isArray(v) && v.every((x) => typeof x === 'string');
|
|
51
|
+
const opt = (v) => v === undefined || typeof v === 'string';
|
|
52
|
+
function valid(o) {
|
|
53
|
+
if (!o || typeof o !== 'object')
|
|
54
|
+
return false;
|
|
55
|
+
const r = o;
|
|
56
|
+
if (r['schema'] !== METRIC_SCHEMA || typeof r['ts'] !== 'string')
|
|
57
|
+
return false;
|
|
58
|
+
if (!opt(r['ticket']) || !opt(r['intent']))
|
|
59
|
+
return false;
|
|
60
|
+
switch (r['kind']) {
|
|
61
|
+
case 'check': {
|
|
62
|
+
const s = r['stops'];
|
|
63
|
+
return (typeof r['stage'] === 'string' &&
|
|
64
|
+
typeof r['verdict'] === 'string' &&
|
|
65
|
+
strs(r['reasons']) &&
|
|
66
|
+
strs(r['warns']) &&
|
|
67
|
+
!!s &&
|
|
68
|
+
['intent', 'knowledge', 'redline'].every((k) => Number.isInteger(s[k])));
|
|
69
|
+
}
|
|
70
|
+
case 'gate':
|
|
71
|
+
return (typeof r['gate'] === 'string' &&
|
|
72
|
+
typeof r['report'] === 'string' &&
|
|
73
|
+
(r['exit'] === null || typeof r['exit'] === 'number'));
|
|
74
|
+
case 'usage':
|
|
75
|
+
return (typeof r['role'] === 'string' &&
|
|
76
|
+
typeof r['vendor'] === 'string' &&
|
|
77
|
+
typeof r['model'] === 'string' &&
|
|
78
|
+
Number.isInteger(r['tokens']) &&
|
|
79
|
+
r['tokens'] >= 0);
|
|
80
|
+
default:
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Reads every line; lines that are not a valid record are counted, not fatal. */
|
|
85
|
+
export function readMetrics(root) {
|
|
86
|
+
const file = join(root, METRICS_FILE);
|
|
87
|
+
const records = [];
|
|
88
|
+
let broken = 0;
|
|
89
|
+
if (!existsSync(file))
|
|
90
|
+
return { records, broken };
|
|
91
|
+
let text = '';
|
|
92
|
+
try {
|
|
93
|
+
text = readFileSync(file, 'utf8');
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return { records, broken };
|
|
97
|
+
}
|
|
98
|
+
for (const line of text.split('\n')) {
|
|
99
|
+
if (!line.trim())
|
|
100
|
+
continue;
|
|
101
|
+
try {
|
|
102
|
+
const o = JSON.parse(line);
|
|
103
|
+
if (valid(o))
|
|
104
|
+
records.push(o);
|
|
105
|
+
else
|
|
106
|
+
broken++;
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
broken++;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { records, broken };
|
|
113
|
+
}
|
|
114
|
+
/** Stop ids renamed in harness 0.1.1: old records carry the red-line-looking C1 and C2. */
|
|
115
|
+
const LEGACY_IDS = { C1: 'P1', C2: 'P2' };
|
|
116
|
+
/**
|
|
117
|
+
* Counts blocking reason ids by kind. An id found in stops.yaml counts as that stop's kind
|
|
118
|
+
* (so P1 and P2 are knowledge stops; old C1 and C2 read as P1 and P2); otherwise an id in
|
|
119
|
+
* common-red-lines.yaml is a redline;
|
|
120
|
+
* an id in neither is not counted and stays in `reasons` only. Each distinct id counts once.
|
|
121
|
+
*/
|
|
122
|
+
export function classify(reasons, harness) {
|
|
123
|
+
const out = { intent: 0, knowledge: 0, redline: 0 };
|
|
124
|
+
if (!harness)
|
|
125
|
+
return out;
|
|
126
|
+
let kinds = new Map();
|
|
127
|
+
let lines = new Set();
|
|
128
|
+
try {
|
|
129
|
+
kinds = new Map(stops(harness).map((s) => [s.id, s.kind]));
|
|
130
|
+
lines = new Set(redLines(harness).map((r) => r.id));
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
for (const id of new Set(reasons.map((r) => LEGACY_IDS[r] ?? r))) {
|
|
136
|
+
const k = kinds.get(id);
|
|
137
|
+
if (k)
|
|
138
|
+
out[k]++;
|
|
139
|
+
else if (lines.has(id))
|
|
140
|
+
out.redline++;
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
const sortKeys = (o) => Object.fromEntries(Object.entries(o).toSorted(([a], [b]) => a.localeCompare(b)));
|
|
145
|
+
export function summarize(records, opts = {}) {
|
|
146
|
+
const rs = opts.intent ? records.filter((r) => r.intent === opts.intent) : records;
|
|
147
|
+
const counts = { check: 0, gate: 0, usage: 0 };
|
|
148
|
+
const byRole = {};
|
|
149
|
+
const byVendor = {};
|
|
150
|
+
let total = 0;
|
|
151
|
+
const tickets = new Map();
|
|
152
|
+
const intents = new Map();
|
|
153
|
+
const intentRow = (i) => {
|
|
154
|
+
let row = intents.get(i);
|
|
155
|
+
if (!row) {
|
|
156
|
+
row = {
|
|
157
|
+
intent: i,
|
|
158
|
+
tokens: 0,
|
|
159
|
+
checks: 0,
|
|
160
|
+
stops: { intent: 0, knowledge: 0, redline: 0 },
|
|
161
|
+
tickets: 0,
|
|
162
|
+
knowledgeStopsPerTicket: null,
|
|
163
|
+
seen: new Set(),
|
|
164
|
+
};
|
|
165
|
+
intents.set(i, row);
|
|
166
|
+
}
|
|
167
|
+
return row;
|
|
168
|
+
};
|
|
169
|
+
for (const r of rs) {
|
|
170
|
+
counts[r.kind]++;
|
|
171
|
+
const i = r.intent ? intentRow(r.intent) : undefined;
|
|
172
|
+
let t;
|
|
173
|
+
if (r.ticket) {
|
|
174
|
+
t = tickets.get(r.ticket);
|
|
175
|
+
if (!t) {
|
|
176
|
+
t = {
|
|
177
|
+
ticket: r.ticket,
|
|
178
|
+
intent: r.intent ?? intentOf(r.ticket),
|
|
179
|
+
tokens: 0,
|
|
180
|
+
checks: 0,
|
|
181
|
+
knowledgeStops: 0,
|
|
182
|
+
};
|
|
183
|
+
tickets.set(r.ticket, t);
|
|
184
|
+
}
|
|
185
|
+
i?.seen.add(r.ticket);
|
|
186
|
+
}
|
|
187
|
+
if (r.kind === 'usage') {
|
|
188
|
+
total += r.tokens;
|
|
189
|
+
byRole[r.role] = (byRole[r.role] ?? 0) + r.tokens;
|
|
190
|
+
byVendor[r.vendor] = (byVendor[r.vendor] ?? 0) + r.tokens;
|
|
191
|
+
if (t)
|
|
192
|
+
t.tokens += r.tokens;
|
|
193
|
+
if (i)
|
|
194
|
+
i.tokens += r.tokens;
|
|
195
|
+
}
|
|
196
|
+
else if (r.kind === 'check') {
|
|
197
|
+
if (t) {
|
|
198
|
+
t.checks++;
|
|
199
|
+
t.knowledgeStops += r.stops.knowledge;
|
|
200
|
+
}
|
|
201
|
+
if (i) {
|
|
202
|
+
i.checks++;
|
|
203
|
+
i.stops.intent += r.stops.intent;
|
|
204
|
+
i.stops.knowledge += r.stops.knowledge;
|
|
205
|
+
i.stops.redline += r.stops.redline;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const intentRows = [...intents.values()]
|
|
210
|
+
.map(({ seen, ...row }) => ({
|
|
211
|
+
...row,
|
|
212
|
+
tickets: seen.size,
|
|
213
|
+
knowledgeStopsPerTicket: seen.size === 0 ? null : Math.round((row.stops.knowledge / seen.size) * 100) / 100,
|
|
214
|
+
}))
|
|
215
|
+
.toSorted((a, b) => a.intent.localeCompare(b.intent));
|
|
216
|
+
return {
|
|
217
|
+
counts,
|
|
218
|
+
broken: opts.broken ?? 0,
|
|
219
|
+
tokens: { total, byRole: sortKeys(byRole), byVendor: sortKeys(byVendor) },
|
|
220
|
+
tickets: [...tickets.values()].toSorted((a, b) => a.ticket.localeCompare(b.ticket)),
|
|
221
|
+
intents: intentRows,
|
|
222
|
+
};
|
|
223
|
+
}
|