create-pmos 0.575.0 → 0.577.0

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 (62) hide show
  1. package/package.json +27 -27
  2. package/payload/AGENTS.md +35 -2
  3. package/payload/KIT-VERSION +2 -2
  4. package/payload/okf/core/templates/agent-eval-set-template.md +65 -0
  5. package/payload/okf/core/templates/index.md +1 -0
  6. package/payload/planning/evals/eval-calibration.md +1 -1
  7. package/payload/planning/okrs/health-budgets.md +1 -1
  8. package/payload/scripts/agent-eval-set.js +85 -0
  9. package/payload/scripts/factory-guardrail.js +50 -8
  10. package/payload/scripts/work-item.js +49 -3
  11. package/payload/scripts/workflow-state.js +28 -3
  12. package/payload/state/discoveries.md +1 -1
  13. package/payload/state/log.md +1 -1
  14. package/payload/templates/pmos-guardrail.yml +38 -10
  15. package/payload/templates/pmos-review-check.yml +59 -0
  16. package/workspace/changelog.json +26 -0
  17. package/workspace/fixtures/builder-bench.json +121 -0
  18. package/workspace/guide/cli.md +71 -4
  19. package/workspace/guide/settings-and-switches.md +7 -0
  20. package/workspace/lib/agent-team.js +5 -2
  21. package/workspace/lib/build-cli.js +119 -7
  22. package/workspace/lib/build-engine.js +106 -25
  23. package/workspace/lib/builder-bench.js +267 -0
  24. package/workspace/lib/engine/agent-eval-set.js +85 -0
  25. package/workspace/lib/engine/workflow-state.js +28 -3
  26. package/workspace/lib/factory-checks.js +117 -0
  27. package/workspace/lib/factory-ci.js +151 -0
  28. package/workspace/lib/factory-fleet.js +263 -0
  29. package/workspace/lib/factory-identity.js +182 -0
  30. package/workspace/lib/factory-lessons.js +183 -0
  31. package/workspace/lib/factory-needs.js +48 -0
  32. package/workspace/lib/factory-review.js +241 -0
  33. package/workspace/lib/factory-rollout.js +56 -10
  34. package/workspace/lib/factory-traces.js +229 -0
  35. package/workspace/lib/headless.js +11 -2
  36. package/workspace/lib/job-graph.js +9 -1
  37. package/workspace/lib/needs-providers.js +1 -0
  38. package/workspace/lib/pmos-verbs.js +1 -1
  39. package/workspace/lib/project-onboard.js +1 -1
  40. package/workspace/lib/proposals.js +3 -1
  41. package/workspace/lib/route-modules.js +1 -0
  42. package/workspace/lib/routes-factory-metrics.js +41 -0
  43. package/workspace/lib/routes-proposals.js +9 -1
  44. package/workspace/lib/signals.js +272 -0
  45. package/workspace/lib/team-cli.js +2 -2
  46. package/workspace/lib/team-runs.js +13 -3
  47. package/workspace/lib/vendor/scripts/agent-eval-set.js +85 -0
  48. package/workspace/lib/vendor/scripts/workflow-state.js +28 -3
  49. package/workspace/lib/verify-runs.js +89 -1
  50. package/workspace/package-lock.json +2 -2
  51. package/workspace/package.json +1 -1
  52. package/workspace/public/pm/ini-props.js +1 -1
  53. package/workspace/server.js +4 -0
  54. package/workspace/test-files.json +2 -1
  55. package/workspace/test-lists/adlc-identity.json +9 -0
  56. package/workspace/test-lists/build-engine.json +5 -3
  57. package/workspace/test-lists/builder-bench.json +9 -0
  58. package/workspace/test-lists/factory-checks.json +9 -0
  59. package/workspace/test-lists/factory-fleet.json +9 -0
  60. package/workspace/test-lists/factory-lessons.json +9 -0
  61. package/workspace/test-lists/factory-real-run.json +9 -0
  62. package/workspace/test-lists/factory-run-traces.json +9 -0
@@ -0,0 +1,229 @@
1
+ 'use strict';
2
+ /* factory-traces.js — one trace per factory run, and the factory's numbers over a window (ADLC gap P1, initiative factory-run-traces).
3
+ *
4
+ * tracker() → { see(line), items(), item(), tools(), files() } reads a headless run's stream-json lines; keeps names and counts only
5
+ * record(stateDir, { item, role, result, tracker, ok, now? }) → the line written, or null
6
+ * recordRun(root, { role, result, tracker, ok, now? }) → the line written, or null the server's hook: the product's state folder
7
+ * note(root, { item, kind: 'opened'|'undo', verdict?, rules?, now? }) → the line written, or null build-engine open() and close()
8
+ * read(stateDir, { sinceMs? }) → [line]
9
+ * metrics({ traces, ledger, rollout, edits, now, days }) → PURE, the numbers (see METRICS)
10
+ * metricsOf(root, { now, days }) → metrics() over this repository's files, or null when no factory runs here
11
+ *
12
+ * THE TRACE. <product state>/factory-traces.jsonl (pmos/state: runtime, gitignored, never a control-graph record). One line per Builder
13
+ * or reviewer run that named a work item (`pmos build claim|propose|open|policy|status <item>`):
14
+ * { at, kind: 'run', item, role, turns, tools: { Name: count }, files: [rel], model, input, cacheCreate, cacheRead, output, costUsd, ok }
15
+ * tools are the tool NAMES the run called; files are the paths Write and Edit touched, relative to the item's worktree. The tokens and the
16
+ * cost come from lib/headless.js parseResult and usageOf, the same reads lib/run-tokens.js keeps. No line holds a prompt, an answer, a
17
+ * tool input, a command or a key. The server writes the line after the run ends, from the run's own stdout: the Builder's run gains no
18
+ * write path and no outward channel (kit/AGENTS.md, the trifecta audit).
19
+ * Notes from PMOS's own process, keyed by item: { kind: 'opened', verdict: 'auto'|'human', rules } (build-engine open) and
20
+ * { kind: 'undo' } (build-engine close: Undo closed the pull request).
21
+ *
22
+ * METRICS over [now - days, now]. An item is in the window when its first `claimed` event is in it.
23
+ * claimed items claimed in the window
24
+ * merged of those, the items the ledger saw `integrated` or `shipped`
25
+ * completionRate merged / claimed
26
+ * prs { auto, human }: the guardrail verdicts open() noted in the window
27
+ * reverts · revertRate the items the rollout reverted in the window (factory-rollout.jsonl step breach); / merged
28
+ * medianClaimToMergeHours first `claimed` to `integrated`, over the merged items
29
+ * costUsd · costPerMergedUsd every factory run's cost in the window; / merged (the runs of failed items count too)
30
+ * corrections { undo, human, edits, total, perItem }: Undo notes + human verdicts + PM edits (commits on pmos/<item> that do
31
+ * not carry the factory's Work-Item trailer, as this checkout last fetched them); perItem = total / claimed
32
+ * Zero is silence: with no run and no claim the answer is { days, runs: 0, empty: true } and the CLI and the page show no numbers.
33
+ * Nothing here calls a model. A failed append is lost, never thrown: a trace never stops a run. */
34
+ const fs = require('fs');
35
+ const path = require('path');
36
+ const cp = require('child_process');
37
+
38
+ const FILE = 'factory-traces.jsonl';
39
+ const DAY = 86400000;
40
+ const ITEM_RE = /\bpmos build (?:claim|propose|open|policy|status|close)\s+["']?([a-z0-9][a-z0-9_-]*\.[0-9]+)\b/g;
41
+ const FILE_TOOLS = { Write: 'file_path', Edit: 'file_path', MultiEdit: 'file_path', NotebookEdit: 'notebook_path' };
42
+ const MAX_FILES = 200;
43
+ const num = (v) => (Number.isFinite(v) && v >= 0 ? v : 0);
44
+ const jsonOf = (s) => { const t = String(s || '').trim(); if (!t.startsWith('{')) return null; try { const o = JSON.parse(t); return o && typeof o === 'object' ? o : null; } catch { return null; } };
45
+
46
+ /** Reads a run's stream-json lines. Keeps the names of the tools, how often each was called, the work items the run named and the files it wrote. */
47
+ function tracker() {
48
+ const tools = new Map();
49
+ const items = [];
50
+ const named = new Map(); // item -> the verb that named it last
51
+ const raw = new Set(); // absolute or relative paths, relativized at the end
52
+ const see = (line) => {
53
+ const o = jsonOf(line);
54
+ if (!o || o.type !== 'assistant' || !o.message || !Array.isArray(o.message.content)) return;
55
+ for (const c of o.message.content) {
56
+ if (!c || c.type !== 'tool_use' || typeof c.name !== 'string') continue;
57
+ const name = c.name.slice(0, 80);
58
+ tools.set(name, (tools.get(name) || 0) + 1);
59
+ const inp = c.input && typeof c.input === 'object' ? c.input : {};
60
+ if (name === 'Bash' && typeof inp.command === 'string') {
61
+ for (const m of inp.command.matchAll(ITEM_RE)) {
62
+ if (!items.includes(m[1])) items.push(m[1]);
63
+ named.set(m[1], /pmos build propose/.test(m[0]) ? 'propose' : /pmos build claim/.test(m[0]) ? 'claim' : 'other');
64
+ }
65
+ }
66
+ const key = FILE_TOOLS[name];
67
+ if (key && typeof inp[key] === 'string' && raw.size < MAX_FILES) raw.add(inp[key]);
68
+ }
69
+ };
70
+ /** The run's work item: the one it proposed, else the one it claimed, else the first one it named. */
71
+ const item = () => items.find((x) => named.get(x) === 'propose') || items.find((x) => named.get(x) === 'claim') || items[0] || null;
72
+ /** The written paths, relative to the item's worktree (…/<item>/<path>); a path outside it is left out. */
73
+ const files = (it = item()) => {
74
+ const out = new Set();
75
+ for (const p of raw) {
76
+ const s = String(p).replace(/\\/g, '/');
77
+ const at = it ? s.lastIndexOf('/' + it + '/') : -1;
78
+ const rel = at >= 0 ? s.slice(at + it.length + 2) : (!s.startsWith('/') && !/^[a-z]:\//i.test(s) && !s.split('/').includes('..') ? s : '');
79
+ if (rel) out.add(rel.slice(0, 300));
80
+ }
81
+ return [...out].sort();
82
+ };
83
+ return { see, items: () => items.slice(), item, tools: () => Object.fromEntries([...tools].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))), files };
84
+ }
85
+
86
+ function append(stateDir, line) {
87
+ if (!stateDir) return null;
88
+ try {
89
+ fs.mkdirSync(stateDir, { recursive: true });
90
+ fs.appendFileSync(path.join(stateDir, FILE), JSON.stringify(line) + '\n', { mode: 0o600 });
91
+ } catch { return null; }
92
+ return line;
93
+ }
94
+
95
+ /** One run's trace. Only names, counts, relative paths, tokens and cost: never the result's text. */
96
+ function record(stateDir, { item, role = '', result = null, tracker: t = null, ok = null, now = Date.now() } = {}) {
97
+ const it = item || (t && t.item());
98
+ if (!stateDir || !it || !/^[a-z0-9][a-z0-9_-]*\.[0-9]+$/.test(it)) return null;
99
+ const r = result || {};
100
+ const tk = r.tokens || {};
101
+ return append(stateDir, {
102
+ at: new Date(now).toISOString(), kind: 'run', item: it, role: String(role || '').slice(0, 40) || null,
103
+ turns: Number.isFinite(r.turns) ? r.turns : null,
104
+ tools: t ? t.tools() : {}, files: t ? t.files(it) : [],
105
+ model: typeof r.model === 'string' ? r.model.slice(0, 80) : null,
106
+ input: num(tk.input), cacheCreate: num(tk.cacheCreate), cacheRead: num(tk.cacheRead), output: num(tk.output),
107
+ costUsd: Number.isFinite(r.costUsd) ? Math.round(r.costUsd * 10000) / 10000 : null,
108
+ ok: ok == null ? null : !!ok,
109
+ });
110
+ }
111
+
112
+ function topOf(root) {
113
+ const r = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8' });
114
+ return r.status === 0 ? String(r.stdout).trim() : null;
115
+ }
116
+ const stateDirOf = (root, create) => { try { return require('./driver.js').stateDirOf(topOf(root) || root, { create }); } catch { return null; } };
117
+
118
+ /** The server's hook at the end of a team run: a trace in the PRODUCT's state folder, when the run named a work item. */
119
+ function recordRun(root, { role, result, tracker: t, ok, now } = {}) {
120
+ if (!root || !t || !t.item()) return null;
121
+ return record(stateDirOf(root, true), { role, result, tracker: t, ok, now });
122
+ }
123
+
124
+ /** A note from PMOS's own process: the pull request opened with the guardrail's verdict, or Undo closed it. */
125
+ function note(root, { item, kind, verdict = null, rules = [], now = Date.now() } = {}) {
126
+ if (!root || !item || !['opened', 'undo'].includes(kind)) return null;
127
+ const line = { at: new Date(now).toISOString(), kind, item: String(item).slice(0, 120) };
128
+ if (kind === 'opened') { line.verdict = verdict === 'auto' ? 'auto' : 'human'; line.rules = (Array.isArray(rules) ? rules : []).map((x) => String((x && x.rule) || x).slice(0, 40)).slice(0, 20); }
129
+ return append(stateDirOf(root, true), line);
130
+ }
131
+
132
+ function readJsonl(file, sinceMs = 0) {
133
+ let text = '';
134
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
135
+ const out = [];
136
+ for (const s of text.split('\n')) {
137
+ if (!s.trim()) continue;
138
+ try { const o = JSON.parse(s); if (o && typeof o === 'object' && (!sinceMs || Date.parse(o.at) >= sinceMs)) out.push(o); } catch { /* a torn line */ }
139
+ }
140
+ return out;
141
+ }
142
+ const read = (stateDir, { sinceMs = 0 } = {}) => (stateDir ? readJsonl(path.join(stateDir, FILE), sinceMs) : []);
143
+
144
+ const median = (a) => { if (!a.length) return null; const s = a.slice().sort((x, y) => x - y); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
145
+ const ratio = (a, b) => (b > 0 ? Math.round((a / b) * 1000) / 1000 : null);
146
+
147
+ /** PURE. traces: factory-traces lines; ledger: raw work-items.jsonl events; rollout: factory-rollout lines; edits: { item: count }. */
148
+ function metrics({ traces = [], ledger = [], rollout = [], edits = {}, now = Date.now(), days = 30 } = {}) {
149
+ const from = now - days * DAY;
150
+ const inWin = (at) => { const t = Date.parse(at); return Number.isFinite(t) && t >= from && t <= now; };
151
+ const claimedAt = new Map(), mergedAt = new Map();
152
+ for (const e of ledger) {
153
+ if (!e || typeof e.item_id !== 'string') continue;
154
+ const t = Date.parse(e.at);
155
+ if (!Number.isFinite(t)) continue;
156
+ if (e.event === 'claimed' && !claimedAt.has(e.item_id)) claimedAt.set(e.item_id, t);
157
+ if ((e.event === 'integrated' || e.event === 'shipped') && !mergedAt.has(e.item_id)) mergedAt.set(e.item_id, t);
158
+ }
159
+ const items = [...claimedAt].filter(([, t]) => t >= from && t <= now).map(([id]) => id);
160
+ const runs = traces.filter((l) => l.kind === 'run' && inWin(l.at));
161
+ if (!runs.length && !items.length) return { days, runs: 0, empty: true };
162
+ const merged = items.filter((id) => mergedAt.has(id));
163
+ const hours = merged.map((id) => (mergedAt.get(id) - claimedAt.get(id)) / 3600000).filter((h) => h >= 0);
164
+ const opened = traces.filter((l) => l.kind === 'opened' && inWin(l.at));
165
+ const prs = { auto: opened.filter((l) => l.verdict === 'auto').length, human: opened.filter((l) => l.verdict !== 'auto').length };
166
+ const reverts = new Set(rollout.filter((l) => l && l.step === 'breach' && l.item && inWin(l.at)).map((l) => l.item)).size;
167
+ const costUsd = Math.round(runs.reduce((s, l) => s + num(l.costUsd), 0) * 100) / 100;
168
+ const undo = traces.filter((l) => l.kind === 'undo' && inWin(l.at)).length;
169
+ const edit = items.reduce((s, id) => s + num(Number(edits[id])), 0);
170
+ const total = undo + prs.human + edit;
171
+ const h = median(hours);
172
+ return {
173
+ days, runs: runs.length, empty: false,
174
+ claimed: items.length, merged: merged.length, completionRate: ratio(merged.length, items.length),
175
+ prs, reverts, revertRate: ratio(reverts, merged.length),
176
+ medianClaimToMergeHours: h == null ? null : Math.round(h * 10) / 10,
177
+ costUsd, costPerMergedUsd: merged.length ? Math.round((costUsd / merged.length) * 100) / 100 : null,
178
+ turns: runs.reduce((s, l) => s + num(l.turns), 0),
179
+ corrections: { undo, human: prs.human, edits: edit, total, perItem: ratio(total, items.length) },
180
+ };
181
+ }
182
+
183
+ /** Commits on pmos/<item> (as this checkout last fetched it) that propose() did not make: they lack the Work-Item trailer. */
184
+ function editsOf(top, items) {
185
+ const out = {};
186
+ let base = null;
187
+ try { const d = require('./build-engine.js').defaultBranch(top); base = d && d.ref; } catch { base = null; }
188
+ if (!base) return out;
189
+ for (const id of items) {
190
+ const br = 'pmos/' + id;
191
+ const ref = ['refs/remotes/origin/' + br, 'refs/heads/' + br].find((r) => cp.spawnSync('git', ['rev-parse', '--verify', '--quiet', r], { cwd: top, encoding: 'utf8' }).status === 0);
192
+ if (!ref) continue;
193
+ const l = cp.spawnSync('git', ['log', '--format=%B%x00', `${base}..${ref}`], { cwd: top, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
194
+ if (l.status !== 0) continue;
195
+ const n = String(l.stdout).split('\0').map((s) => s.trim()).filter(Boolean).filter((b) => !/^Work-Item:\s*\S+\s*$/m.test(b)).length;
196
+ if (n) out[id] = n;
197
+ }
198
+ return out;
199
+ }
200
+
201
+ /** metrics() over this repository's own files. null when no factory runs here. */
202
+ function metricsOf(root, { now = Date.now(), days = 30 } = {}) {
203
+ const WK = require('./work-kind.js');
204
+ if (!root || !WK.factoryRuns(root)) return null;
205
+ const dir = WK.factoryDir(root);
206
+ const top = topOf(root) || root;
207
+ const sd = stateDirOf(root, false);
208
+ const ledger = dir ? readJsonl(path.join(dir, 'planning', 'work-items.jsonl')) : [];
209
+ const traces = read(sd);
210
+ const rollout = sd ? readJsonl(path.join(sd, require('./factory-rollout.js').LEDGER)) : [];
211
+ const from = now - days * DAY;
212
+ const claimed = [...new Set(ledger.filter((e) => e && e.event === 'claimed' && Date.parse(e.at) >= from).map((e) => e.item_id))];
213
+ return metrics({ traces, ledger, rollout, edits: editsOf(top, claimed), now, days });
214
+ }
215
+
216
+ /** The lines `pmos build metrics` prints. [] when the window is empty (zero is silence). */
217
+ function linesOf(m) {
218
+ if (!m || m.empty) return [];
219
+ const pct = (v) => (v == null ? '–' : Math.round(v * 100) + '%');
220
+ const usd = (v) => (v == null ? '–' : '$' + v.toFixed(2));
221
+ return [
222
+ `Factory, last ${m.days} days: ${m.runs} run${m.runs === 1 ? '' : 's'}, ${m.claimed} item${m.claimed === 1 ? '' : 's'} claimed, ${m.merged} merged (${pct(m.completionRate)}).`,
223
+ ` Pull requests: ${m.prs.auto} auto, ${m.prs.human} human. Reverts: ${m.reverts} (${pct(m.revertRate)} of merged).`,
224
+ ` Claim to merge (median): ${m.medianClaimToMergeHours == null ? '–' : m.medianClaimToMergeHours + ' h'}. Cost: ${usd(m.costUsd)}, ${usd(m.costPerMergedUsd)} per merged pull request.`,
225
+ ` Human corrections: ${m.corrections.total} (${m.corrections.undo} Undo, ${m.corrections.human} human guardrail, ${m.corrections.edits} PM edits), ${m.corrections.perItem == null ? '–' : m.corrections.perItem} per item.`,
226
+ ];
227
+ }
228
+
229
+ module.exports = { FILE, tracker, record, recordRun, note, read, metrics, metricsOf, editsOf, linesOf };
@@ -3,7 +3,7 @@
3
3
  * (initiative workspace-headless-jobs; PM decision 2026-10-11: keep Jev, no direct Claude API, background
4
4
  * jobs that need no human run headless).
5
5
  *
6
- * kindFor({ agent, origin, skill, env }) → 'notes' | 'skill' | 'ask' | 'drive' | 'scan-web' | 'scan-repo' | 'scan-research-web' | 'scan-research-repo' | 'report-setup' | 'report-find' | 'core-doc' | 'report-design' | 'report-structure-pull' | 'report-sample-fetch' | 'report-structure' | 'report-structure-dry' | 'ms-review' | 'propose' | 'metric-draft' | 'grill' | 'impact' | 'verify' | 'metric-read' | 'lab-proto' | 'lab-scan' | 'team' | null (null: open a pane, as before)
6
+ * kindFor({ agent, origin, skill, env }) → 'notes' | 'skill' | 'ask' | 'drive' | 'scan-web' | 'scan-repo' | 'scan-research-web' | 'scan-research-repo' | 'report-setup' | 'report-find' | 'core-doc' | 'report-design' | 'report-structure-pull' | 'report-sample-fetch' | 'report-structure' | 'report-structure-dry' | 'ms-review' | 'propose' | 'metric-draft' | 'grill' | 'impact' | 'verify' | 'review' | 'metric-read' | 'lab-proto' | 'lab-scan' | 'team' | null (null: open a pane, as before)
7
7
  * argsFor(kind, { modelArgs, addDirs, writePaths }) → the argv after `claude` (writePaths: the one render file a report-design job may write;
8
8
  * for the skill kind, the folders the run may write in, from skillWriteDirs)
9
9
  * skillWriteDirs(skill, { root, scratch }) → the absolute folders a background skill run may write in: its scratch folder and the state folders its skill writes
@@ -127,6 +127,9 @@ const IMPACT_ORIGINS = Object.freeze(['impact:']);
127
127
  // loop-telemetry: the verifier after merge (origin `verify:<run_id>:<token>`, lib/verify-runs.js). A fresh evaluator grades one merged run;
128
128
  // its only write is `node scripts/verifier.js record`, pinned by PMOS_VERIFY_RUN to that run (D65(i): never the builder's own session).
129
129
  const VERIFY_ORIGINS = Object.freeze(['verify:']);
130
+ // factory-premerge-reviewer: the independent review of a factory pull request before it merges by itself (origin `factory-review:<item>:<token>`,
131
+ // lib/factory-review.js). Read-only; its only write is `pmos build reviewed`, pinned by PMOS_REVIEW_RUN to one item and commit. Never the Builder's run.
132
+ const REVIEW_ORIGINS = Object.freeze(['factory-review:']);
130
133
  // batch 16 item 6: Claude reads the goals with their recipes (origin `metric-read:<ws>:<run>`, lib/metric-read-runs.js). Its only write is
131
134
  // `pmos metrics reading`, pinned by the server to that run and those goals.
132
135
  const METRIC_READ_ORIGINS = Object.freeze(['metric-read:']);
@@ -213,6 +216,9 @@ const TOOLS = Object.freeze({
213
216
  // is `pmos autonomy check`, pinned by PMOS_CHECK_REF and PMOS_CHECK_DIR to that change. The read verbs show the record it changed.
214
217
  verify: Object.freeze(['Read', 'Glob', 'Grep', 'Bash(git show *)', 'Bash(git log *)', 'Bash(git diff *)', 'Bash(node scripts/verifier.js record *)',
215
218
  'Bash(node scripts/workflow-state.js *)', 'Bash(pmos autonomy check *)', 'Bash(pmos initiative export *)', 'Bash(pmos artefacts show *)', 'Bash(date *)']),
219
+ // The pre-merge review run (lib/factory-review.js): read and search, git only to read, and the one verb that records the verdict for the item
220
+ // and commit PMOS_REVIEW_RUN pins. It reads the diff, which is untrusted text, so it holds nothing that sends: no gh, no push, no web, no Write.
221
+ review: Object.freeze(['Read', 'Glob', 'Grep', 'Bash(git show *)', 'Bash(git log *)', 'Bash(git diff *)', 'Bash(pmos build reviewed *)', 'Bash(date *)']),
216
222
  // The reading run (lib/metric-read-runs.js): read and search, and the one verb that files a reading. The PM's analytics and Jira are read through
217
223
  // the PM's own connectors only where the PM's settings allow it. No Write, no Edit, no web fetch, nothing that sends.
218
224
  'metric-read': Object.freeze(['Read', 'Glob', 'Grep', 'Bash(pmos metrics reading *)', 'Bash(pmos source show *)', 'Bash(pmos source status *)', 'Bash(date *)']),
@@ -289,6 +295,8 @@ const HEADLESS_ENV = Object.freeze({ MAX_MCP_OUTPUT_TOKENS: '100000' });
289
295
  /** The run's environment with HEADLESS_ENV added where the PM has not set the variable. */
290
296
  function headlessEnv(env) {
291
297
  const out = { ...(env || {}) };
298
+ // ADLC P1: the factory's token (pmos/factory.json identity.token_env, always PMOS_FACTORY_*) is for PMOS's own gh calls; no agent run gets it
299
+ for (const k of Object.keys(out)) if (/^PMOS_FACTORY_/.test(k)) delete out[k];
292
300
  for (const [k, v] of Object.entries(HEADLESS_ENV)) if (!out[k]) out[k] = v;
293
301
  return out;
294
302
  }
@@ -355,6 +363,7 @@ function kindFor({ agent, origin, skill, env } = {}) {
355
363
  if (GRILL_ORIGINS.some((p) => o.startsWith(p))) return 'grill';
356
364
  if (IMPACT_ORIGINS.some((p) => o.startsWith(p))) return 'impact';
357
365
  if (VERIFY_ORIGINS.some((p) => o.startsWith(p))) return 'verify';
366
+ if (REVIEW_ORIGINS.some((p) => o.startsWith(p))) return 'review';
358
367
  if (METRIC_READ_ORIGINS.some((p) => o.startsWith(p))) return 'metric-read';
359
368
  if (LAB_PROTO_ORIGINS.some((p) => o.startsWith(p))) return 'lab-proto';
360
369
  if (TEAM_ORIGINS.some((p) => o.startsWith(p))) return 'team';
@@ -652,7 +661,7 @@ const RUN_ENV = Object.freeze(['PMOS_SCAN_FILE', 'PMOS_SCAN_ORIGIN', 'PMOS_SCAN_
652
661
  'PMOS_METRIC_READ_FILE', 'PMOS_METRIC_READ_RECORDS', 'PMOS_METRIC_READ_DRAFTS', 'PMOS_METRIC_READ_WS', 'PMOS_METRIC_READ_RUN', 'PMOS_METRIC_READ_RIDS', 'PMOS_METRIC_READ_TEST',
653
662
  'PMOS_PROPOSE_FILE', 'PMOS_PROPOSE_WS', 'PMOS_PROPOSE_BOARD', 'PMOS_PROPOSE_INI', 'PMOS_PROPOSE_RUN',
654
663
  'PMOS_GRILL_FILE', 'PMOS_GRILL_LOG', 'PMOS_GRILL_WS', 'PMOS_GRILL_BOARD', 'PMOS_GRILL_INI', 'PMOS_GRILL_RUN', 'PMOS_GRILL_BUDGET',
655
- 'PMOS_IMPACT_FILE', 'PMOS_IMPACT_RUN', 'PMOS_VERIFY_RUN', 'PMOS_CHECK_REF', 'PMOS_CHECK_DIR', 'PMOS_MS_REVIEW_FILE', 'PMOS_MS_REVIEW_RUN', 'PMOS_MS_REVIEW_PROGRAM',
664
+ 'PMOS_IMPACT_FILE', 'PMOS_IMPACT_RUN', 'PMOS_VERIFY_RUN', 'PMOS_REVIEW_RUN', 'PMOS_CHECK_REF', 'PMOS_CHECK_DIR', 'PMOS_MS_REVIEW_FILE', 'PMOS_MS_REVIEW_RUN', 'PMOS_MS_REVIEW_PROGRAM',
656
665
  'PMOS_TEAM_FILE', 'PMOS_TEAM_ROOT', 'PMOS_TEAM_WS', 'PMOS_TEAM_ROLE', 'PMOS_TEAM_RUN', 'PMOS_TEAM_INI', 'PMOS_TEAM_MODE',
657
666
  'PMOS_LAB_RUN', 'PMOS_LAB_KIND', 'PMOS_LAB_PENDING', 'PMOS_LAB_INI', 'PMOS_LAB_BUDGET', 'PMOS_LAB_PAGES', 'PMOS_LAB_SPECIMENS']);
658
667
  function runEnvOf(extra) {
@@ -100,6 +100,11 @@ const LEDGERS = Object.freeze({
100
100
  'repo:planning/runs/evals.jsonl': { concept: 'review-verdicts', owner: 'repo:scripts/record-eval.js', readers: [
101
101
  r('repo:scripts/check-calibration.js', 'evals.jsonl', 'κ per evaluator model against the PM\'s labels'),
102
102
  r('repo:scripts/verifier.js', 'verdictOracle', 'a verdict closes its queue entry')] },
103
+ // improve-signals: one ledger per repository (lib/signals.js); the loop engine (lib/improve-*.js) reads it through signals.readSignals
104
+ 'repo:planning/improve/signals.jsonl': { concept: 'improve-signals', owner: 'lib/signals.js', readers: [
105
+ r('repo:scripts/signals.js', 'readSignals', '`node scripts/signals.js list`: the signals of PMOS itself')] },
106
+ '<state>/improve-signals.jsonl': { concept: 'improve-signals-product', owner: 'lib/signals.js', readers: [
107
+ r('repo:scripts/signals.js', 'productFile', "`node scripts/signals.js list --state <dir>`: a product's signals, counts and links only")] },
103
108
  'repo:planning/work-items.jsonl': { concept: 'work-items', owner: 'repo:scripts/work-item.js', readers: [
104
109
  r('lib/factory-join.js', 'work-items.jsonl', 'a plan item reads Done once its work item is integrated')] },
105
110
  // goals (one goal source, T2): the OKR files are the only goal list; lib/goal-source.js joins each key result to the kr-metrics record that reads it,
@@ -129,7 +134,10 @@ const JOBS = Object.freeze([
129
134
  q('grill', 'lib/grill-runs.js', [props, '<runtime>/grill-runs.jsonl'], [props, 'repo:DECISIONS.md']),
130
135
  q('metric-drafts', 'lib/metric-draft-runs.js', ['<state>/metric-drafts.jsonl'], ['<state>/metric-reads.jsonl']),
131
136
  q('impact', 'lib/impact-runs.js', ['<runtime>/impact.jsonl'], ['connectors']),
132
- q('verify', 'lib/verify-runs.js', ['repo:planning/runs/evals.jsonl', 'repo:planning/runs/verify-queue.jsonl', 'repo:planning/work-items.jsonl', '<state>/autonomy.jsonl'], ['repo:planning/runs/verify-queue.jsonl', '<state>/autonomy.jsonl', 'git']),
137
+ // improve-signals: the verify tick also harvests the improvement signals (lib/signals.js) into one ledger per repository, at most hourly
138
+ q('verify', 'lib/verify-runs.js', ['repo:planning/runs/evals.jsonl', 'repo:planning/runs/verify-queue.jsonl', 'repo:planning/work-items.jsonl', '<state>/autonomy.jsonl',
139
+ 'repo:planning/improve/signals.jsonl', '<state>/improve-signals.jsonl'],
140
+ ['repo:planning/runs/verify-queue.jsonl', '<state>/autonomy.jsonl', 'git', 'repo:discoveries.md', 'repo:planning/runs/outcome_checks.jsonl', props]),
133
141
  q('metric-reads', 'lib/metric-read-runs.js', ['<state>/metric-reads.jsonl'], ['connectors']),
134
142
  q('forecast', 'lib/forecast-tick.js', ['<state>/forecast.jsonl'], ['<state>/boards.jsonl']),
135
143
  q('report-design', 'lib/routes-report-design.js', ['<state>/design.jsonl']),
@@ -37,6 +37,7 @@ const PROVIDERS = Object.freeze([
37
37
  'core-docs-needs', // core-documents: one row per scope with core document drafts waiting for the PM (kind 1)
38
38
  'report-structure-needs', // report-structure: a Chrome or computer source that failed its check while a draft waits for it (kind 8)
39
39
  'folder-needs', // folder repair: a folder PMOS could not put back on its default branch alone, in one plain sentence (kind 8)
40
+ 'factory-needs', // factory-builder-inner-loop: a work item blocked after the Builder's CI-fix rounds, with the reason (kind 8)
40
41
  ]);
41
42
  /** Kinds that already mean something in the needs queue. A provider may not reuse one. */
42
43
  const RESERVED_KINDS = Object.freeze(['question', 'accept', 'outcome', 'keep', 'evidence', 'plan-flag', 'provider-error']);
@@ -35,7 +35,7 @@ const VERBS = Object.freeze({
35
35
  help: 'pmos verify-work — mark work items integrated from the default branch (local refs only)' }),
36
36
  // Not a pm-os-absorb verb (run: null): launch simulation W7 (kit-factory-builder) added it through the same table.
37
37
  build: Object.freeze({ module: 'build-cli.js', run: null, guide: 'cli.md',
38
- help: 'pmos build next|claim|propose|open|status|policy|rollout|rollback — the Builder: a declared work item becomes a pull request; the product\'s guardrail decides who merges (pmos build help)' }),
38
+ help: 'pmos build next|claim|propose|check|fix|open|status|policy|rollout|rollback|review|metrics|bench|integrate — the Builder: a declared work item becomes a pull request; the product\'s guardrail decides who merges (pmos build help)' }),
39
39
  report: Object.freeze({ module: 'report-cli.js', run: 5, guide: 'cli.md',
40
40
  help: 'pmos report draft|issue|list … — draft and issue reports (pmos report help)' }),
41
41
  // Not a pm-os-absorb verb (run: null): initiative jira-wbs added it through the same table.
@@ -431,4 +431,4 @@ function initialize({ plan, journalFile, kit = kitSource(), git = 'git', now = (
431
431
  return { ok: true, root, journal: j };
432
432
  }
433
433
 
434
- module.exports = { discover, inventory, search, factsOf, readTool, parseMcpList, prefixOf, folderFacts, proposeFolder, draftContext, contextMarkdown, readContext, initialize, kitSource, pmosIn, slug, spawnLines, LOCKED };
434
+ module.exports = { discover, inventory, search, factsOf, readTool, parseMcpList, prefixOf, folderFacts, proposeFolder, draftContext, contextMarkdown, readContext, initialize, kitSource, installKit, pmosIn, slug, spawnLines, LOCKED };
@@ -25,6 +25,8 @@
25
25
  * build the factory's draft pull request (launch simulation W7; filed by lib/build-engine.js propose): type pr, data { item, branch,
26
26
  * base, commit, files }; one item { id: the work item, title: what it does }. Class C, always section 'check': ✓ pushes the one
27
27
  * branch and opens the DRAFT pull request (build-engine open). Nothing merges here (build-engine mergePolicy)
28
+ * harness a factory failure that repeated 3 times in 14 days (factory-learning-loop; filed by lib/factory-lessons.js): type factory,
29
+ * data { failure, count, items, next }; one item { id: the failure kind }. Class C, section 'check': ✓ adds a task for the PM
28
30
  * prototyped · improved · scanned what the idle lab made while the PM was away (lib/idle-lab.js result): a first round of 2–3 specimens,
29
31
  * a new round of one, a scan finding to attach as evidence. No items; always section 'check'. ✓ keeps it as a document
30
32
  * grill what Claude found when it grilled the initiative by itself (lib/grill.js): type = the angle, no items, a next step in data.next;
@@ -406,7 +408,7 @@ function datesOf(ini, T, o = {}) {
406
408
  }
407
409
 
408
410
  /* ── what r.props carries ── */
409
- const ORDER = { build: -3, description: -2, outcome: -1, prototyped: -0.6, improved: -0.5, scanned: -0.4, found: 0, dates: 1, status: 2, names: 3, links: 4, grill: 5 };
411
+ const ORDER = { build: -3, harness: -2.5, description: -2, outcome: -1, prototyped: -0.6, improved: -0.5, scanned: -0.4, found: 0, dates: 1, status: 2, names: 3, links: 4, grill: 5 };
410
412
  const GRILL_SHOWN = 3;
411
413
  /**
412
414
  * One initiative's proposals, as the ✦ and the Viewer draw them, or null when there is nothing to show.
@@ -79,6 +79,7 @@ const MODULES = Object.freeze([
79
79
  'routes-roadmap-ops', // console3 E1b: bets (add, move with swap proposal, take off, anchor suggestions), breakdown, people
80
80
  'routes-c3-strategy', // console3 Calendar Quarter and Year panes: outcomes, north star, signals, synergy, bets (read-only)
81
81
  'routes-c3-reports', // console3 Reports dashboards: library, per-scope data, page-press layouts (layouts are the only write)
82
+ 'routes-factory-metrics', // ADLC gap P1 (factory-run-traces): the factory's numbers per product from its run traces (read-only)
82
83
  'routes-onboarding', // onboarding-scan-and-map slice 2: first run (scan read-only, structure, import into the overlay, undo, first Briefing)
83
84
  'routes-boards', // c3-initiative-boards: Portfolio, Board, Backlog, Triage asks, workflows and moves (boards.jsonl)
84
85
  'routes-task-plans', // batch 11 item 8: drafts of an initiative's tasks, saved plans, Make live (task-plans.jsonl; page-press POST)
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+ /* routes-factory-metrics.js — the factory's numbers for the Intelligence page (ADLC gap P1, initiative factory-run-traces). Read-only.
3
+ *
4
+ * GET /api/factory/metrics?ws&days → { ok, days, products: [{ ws, name, metrics }] }
5
+ * ws: one workspace (404 when unknown); without it, every workspace that runs a factory. days: 1 to 365, default 30.
6
+ * metrics is lib/factory-traces.js metricsOf: claimed, completion rate, pull requests auto and human, revert rate, median claim to
7
+ * merge, cost per merged pull request, human corrections per item. Zero is silence: a product with no factory run in the window
8
+ * is left out, so no factory runs anywhere answers products: [].
9
+ * `pmos build metrics` prints the same numbers for one repository.
10
+ */
11
+ const FT = require('./factory-traces.js');
12
+
13
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
14
+
15
+ function metricsFor(ctx, { ws = '', days = 30, now = Date.now() } = {}) {
16
+ let list;
17
+ if (ws) {
18
+ const w = ctx.getWs(ws);
19
+ if (!w || w.id !== ws) return bad(404, 'no such workspace');
20
+ list = [w];
21
+ } else list = (ctx.workspaceList ? ctx.workspaceList() : []).filter((w) => w && w.root && !w.linked);
22
+ const products = [];
23
+ for (const w of list) {
24
+ let m = null;
25
+ try { m = FT.metricsOf(w.root, { now, days }); } catch { m = null; }
26
+ if (m && !m.empty) products.push({ ws: w.id, name: w.name || w.id, metrics: m });
27
+ }
28
+ return { status: 200, body: { ok: true, days, products } };
29
+ }
30
+
31
+ async function handle(req, res, url, ctx) {
32
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
33
+ if (url.pathname !== '/api/factory/metrics') return send(bad(404, 'no such factory route'));
34
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
35
+ const d = url.searchParams.get('days');
36
+ const days = d == null || d === '' ? 30 : Number(d);
37
+ if (!Number.isInteger(days) || days < 1 || days > 365) return send(bad(400, 'days is a whole number from 1 to 365'));
38
+ return send(metricsFor(ctx, { ws: String(url.searchParams.get('ws') || ''), days }));
39
+ }
40
+
41
+ module.exports = { prefixes: ['/api/factory/metrics'], handle, metricsFor };
@@ -238,8 +238,16 @@ function applyOne(ctx, p, g, f, ini, x, choices, outbox) {
238
238
  // opens the DRAFT PR; it merges nothing. A failure writes nothing, so the proposal stays open (keepCore).
239
239
  const d = x.data || {};
240
240
  const r = require('./build-engine.js').open(p.w.root, d.item, { title: x.title || '' });
241
- if (r.ok) add({ op: 'pr', item: d.item, branch: d.branch, url: r.url || '' });
241
+ // guard: the guardrail's verdict, so a HUMAN for a Builder reason becomes a factory lesson (lib/factory-lessons.js)
242
+ const pol = r.policy || null, guard = pol ? { verdict: pol.verdict, rules: (pol.reasons || []).map((y) => String(y.rule || '')).filter(Boolean).slice(0, 12), detail: String(pol.why || '').slice(0, 300) } : null;
243
+ if (r.ok) add({ op: 'pr', item: d.item, branch: d.branch, url: r.url || '', ...(guard ? { guard } : {}) });
242
244
  else x.failed = r.error;
245
+ } else if (x.group === 'harness') {
246
+ // a failure the factory repeated (lib/factory-lessons.js). Class C: only the PM's ✓ reaches here. It adds a task for the PM with the
247
+ // evidence; the harness itself changes only through the PM's own reviewed pull request
248
+ const next = String((x.data && x.data.next) || x.title || 'Change the factory harness').slice(0, 200);
249
+ const r = RB.taskAdd(ctx, { ws: p.w.id, board: p.board.id, initiative: ini, title: next, notes: [x.why, source ? 'From ' + source : ''].filter(Boolean).join('\n').slice(0, 1900) }, g);
250
+ if (W.ok(r)) add({ op: 'add', task: r.body.item && (r.body.item.uid || r.body.item.id), title: next, to: { start: '', due: '' } });
243
251
  } else if (x.group === 'outcome' && x.type === 'refuted') {
244
252
  // a refuted outcome's next step (launch simulation W2; lib/outcomes.js refutedDrafts). Class C: only the PM's ✓ reaches here.
245
253
  // kill the experiment is cancelled with the check as its reason (the D70 lifecycle line the Board's ⋯ Cancel writes)