create-pmos 0.830.0 → 0.831.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.
- package/package.json +66 -50
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/workspace/changelog.json +65 -36
- package/workspace/guide/cli.md +8 -1
- package/workspace/guide/layout.md +2 -0
- package/workspace/lib/anchor-id.js +226 -0
- package/workspace/lib/artefacts-cli.js +25 -1
- package/workspace/lib/initiative-cli.js +67 -2
- package/workspace/lib/lessons-draft.js +242 -0
- package/workspace/lib/prefs-sync.js +1 -1
- package/workspace/lib/routes-c3-strategy.js +2 -1
- package/workspace/lib/routes-proposals.js +2 -2
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/card-fold.js +123 -0
- package/workspace/public/pm/cozy-ev.css +7 -0
- package/workspace/public/pm/cozy-nav.js +2 -0
- package/workspace/public/pm/readonly.js +2 -0
- package/workspace/test-lists/anchor-id.json +9 -0
- package/workspace/test-lists/card-fold.json +9 -0
- package/workspace/test-lists/lessons-on-close.json +9 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* anchor-id.js — an initiative's anchor is one id (factory job anchor-ids, idea A547; done test planning/done-tests/anchor-ids.md).
|
|
3
|
+
*
|
|
4
|
+
* `parent_kr` names a key result, an objective, `health:<id>` or `domain:<id>`. Many records add free text after the id
|
|
5
|
+
* ("q3-2026:o1:kr2 (the loop runs end-to-end)"). The resolver (scripts/anchor-resolve.js) reads past that text, but a reader
|
|
6
|
+
* that compares the raw text counts such a record under a key of its own, so the counts per key result split.
|
|
7
|
+
*
|
|
8
|
+
* split(raw) → { id, note } the leading id, and the text after it as written ('' when none)
|
|
9
|
+
* anchorId(raw) → id the leading id alone; '' for no anchor. PURE: every reader that compares parent_kr uses it
|
|
10
|
+
* nearest(text, values) → value | null the declared value closest to a refused text (for "nearest: …")
|
|
11
|
+
* check(root, raw) → { ok, id, note, value } | { ok: false, error, nearest } is the id declared (OKR files, health budgets)
|
|
12
|
+
* list(root) → [{ value, kind, group, label }] the ids you can pick (lib/initiative-rows.js anchorsOf list)
|
|
13
|
+
* plan(root) → { total, items: [{ id, from, anchor, note }], kept: [{ id, from, why }] } what a fold would move
|
|
14
|
+
* fold(root, { apply, actor, stateDir, now }) → plan(), and with apply the records written and a batch to undo
|
|
15
|
+
* undo(root, batch, { actor, stateDir }) → { ok, restored, kept }
|
|
16
|
+
* readAnchorLine · foldAnchor · unfoldAnchor the record edits the fold and `pmos initiative new|anchor` make (see THE RECORD EDITS)
|
|
17
|
+
*
|
|
18
|
+
* The fold only moves text: `parent_kr: <id>` and `anchor_note: <the rest>`. It folds a record only when the id alone resolves to
|
|
19
|
+
* the same key as the whole text, so no count changes. Its undo ledger is local runtime state (<stateDir>/anchor-folds.jsonl),
|
|
20
|
+
* not a tracked record: the fold is one command the PM runs once, and its Undo is for that same machine.
|
|
21
|
+
*/
|
|
22
|
+
const fs = require('fs');
|
|
23
|
+
const path = require('path');
|
|
24
|
+
|
|
25
|
+
// The legacy "okrs-q3-2026 → O1.KR1" form: the id is the token after the arrow (planning/initiatives/README.md, canonical form).
|
|
26
|
+
const ARROW = /^(\S+)\s*(?:→|->)\s*(\S+)/;
|
|
27
|
+
const TOKEN = /^[^\s(]+/;
|
|
28
|
+
|
|
29
|
+
function split(raw) {
|
|
30
|
+
const text = raw == null ? '' : String(raw).trim();
|
|
31
|
+
if (!text) return { id: '', note: '' };
|
|
32
|
+
const a = ARROW.exec(text);
|
|
33
|
+
if (a) {
|
|
34
|
+
const id = a[2].replace(/[,;]+$/, '');
|
|
35
|
+
return { id, note: `${a[1]} → ${text.slice(a[0].length).trim()}`.trim() }; // every word stays: "okrs-q3-2026 → # or x"
|
|
36
|
+
}
|
|
37
|
+
const m = TOKEN.exec(text);
|
|
38
|
+
if (!m) return { id: '', note: text };
|
|
39
|
+
const id = m[0].replace(/[,;]+$/, '');
|
|
40
|
+
return { id, note: text.slice(id.length).trim() };
|
|
41
|
+
}
|
|
42
|
+
const anchorId = (raw) => split(raw).id;
|
|
43
|
+
|
|
44
|
+
// The comparable form of an anchor: lower case, no period prefix (q3-2026:), '.' and ':' the same, no word "okrs-…".
|
|
45
|
+
const norm = (s) => String(s || '').toLowerCase().replace(/^okrs-[^\s]*\s*(?:→|->)\s*/, '').replace(/^q[1-4]-\d{4}:/, '').replace(/\./g, ':').replace(/[^a-z0-9:_-]/g, '');
|
|
46
|
+
function dist(a, b) {
|
|
47
|
+
const m = a.length, n = b.length;
|
|
48
|
+
if (!m) return n; if (!n) return m;
|
|
49
|
+
let prev = Array.from({ length: n + 1 }, (_, j) => j);
|
|
50
|
+
for (let i = 1; i <= m; i++) {
|
|
51
|
+
const cur = [i];
|
|
52
|
+
for (let j = 1; j <= n; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
53
|
+
prev = cur;
|
|
54
|
+
}
|
|
55
|
+
return prev[n];
|
|
56
|
+
}
|
|
57
|
+
function nearest(text, values) {
|
|
58
|
+
const t = norm(anchorId(text));
|
|
59
|
+
let best = null, bd = Infinity;
|
|
60
|
+
for (const v of values || []) { const d = dist(t, norm(v)); if (d < bd) { bd = d; best = v; } }
|
|
61
|
+
return best;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const rows = () => require('./initiative-rows.js');
|
|
65
|
+
const list = (root) => rows().anchorsOf(root).list();
|
|
66
|
+
|
|
67
|
+
function check(root, raw) {
|
|
68
|
+
const { id, note } = split(raw);
|
|
69
|
+
if (!id) return { ok: false, error: 'an initiative needs an anchor: a key result, or health:<id> from the health budgets (D59)', nearest: null };
|
|
70
|
+
const A = rows().anchorsOf(root);
|
|
71
|
+
const r = A.resolve(id);
|
|
72
|
+
if (r.status === 'resolved') return { ok: true, id, note, value: id, key: r.key };
|
|
73
|
+
const near = nearest(id, A.list().map((x) => x.value));
|
|
74
|
+
return { ok: false, id, note, error: `the anchor "${id}" is not declared in the OKR files or the health budgets (D59)${near ? `; nearest: ${near}` : ''}. pmos initiative anchors lists the ids`, nearest: near };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
// THE RECORD EDITS. They live here, not in lib/initiative-writer.js, so a change to them reaches only the suites that name this file
|
|
79
|
+
// (run-tests.js --changed follows lib/initiative-writer.js to every suite). They edit the front matter lines of one record, like the
|
|
80
|
+
// writer's own setAnchor: the same record file rule (an id inside the engine's initiatives folder) and the same quoting.
|
|
81
|
+
const ONE_LINE = (v, max) => typeof v === 'string' && v.trim().length >= 1 && v.trim().length <= max && !/[\r\n\x00-\x08\x0b-\x1f]/.test(v);
|
|
82
|
+
const refuse = (status, error, field) => ({ ok: false, status, error, field: field || null });
|
|
83
|
+
const PLAIN = (s) => !/: |:$| #|["\\]/.test(s) && !/^[-?:,[\]{}#&*!|>'%@`]/.test(s);
|
|
84
|
+
const q = (s) => '"' + String(s).trim().replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
|
|
85
|
+
const frontOfText = (text) => /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(text);
|
|
86
|
+
function unquote(v) {
|
|
87
|
+
const t = String(v || '').trim();
|
|
88
|
+
if (/^".*"$/.test(t)) return t.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
|
89
|
+
if (/^'.*'$/.test(t)) return t.slice(1, -1).replace(/''/g, "'");
|
|
90
|
+
return t;
|
|
91
|
+
}
|
|
92
|
+
const actorLib = () => require('./actor.js');
|
|
93
|
+
function recordFile(root, id) {
|
|
94
|
+
const W = require('./initiative-writer.js');
|
|
95
|
+
if (typeof id !== 'string' || !W.ID_RE.test(id) || id.includes('..')) return refuse(400, 'name the initiative by its id', 'id');
|
|
96
|
+
let dir;
|
|
97
|
+
try { dir = fs.realpathSync(require('./console-state').loadEngine().engine.layout(root).initiatives); } catch { return refuse(404, `no initiative ${id}`, 'id'); }
|
|
98
|
+
const file = path.join(dir, `${id}.md`);
|
|
99
|
+
let st;
|
|
100
|
+
try { st = fs.lstatSync(file); } catch { return refuse(404, `no initiative ${id}`, 'id'); }
|
|
101
|
+
if (!st.isFile()) return refuse(409, `the record of ${id} is not a plain file — nothing was saved`, 'id');
|
|
102
|
+
return { ok: true, file };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The `parent_kr:` line of a record as text (anchor-ids, A547): { ok, text, spans, hasNote }. `spans` is true when the value runs on
|
|
106
|
+
* to the next line (an indented continuation), which a one-line edit must not touch. */
|
|
107
|
+
function readAnchorLine(root, id) {
|
|
108
|
+
const f = recordFile(root, id);
|
|
109
|
+
if (!f.ok) return f;
|
|
110
|
+
const m = frontOfText(fs.readFileSync(f.file, 'utf8'));
|
|
111
|
+
if (!m) return { ok: true, text: '', spans: false, hasNote: false };
|
|
112
|
+
const lines = m[1].split(/\r?\n/);
|
|
113
|
+
const at = lines.findIndex((l) => /^parent_kr:/.test(l));
|
|
114
|
+
return { ok: true, text: at >= 0 ? unquote(lines[at].slice(10)) : '', spans: at >= 0 && /^\s+\S/.test(lines[at + 1] || ''), hasNote: lines.some((l) => /^anchor_note:/.test(l)) };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** anchor-ids (A547): `parent_kr: <id>` and `anchor_note: <note>` in place of one anchor with text after its id. Writes only when the
|
|
118
|
+
* line still reads `expect` (lib/anchor-id.js fold checked it), so an edit made since is never overwritten. */
|
|
119
|
+
function foldAnchor(root, id, { anchor, note, expect } = {}, { actor } = {}) {
|
|
120
|
+
if (!actorLib().valid(actor)) return refuse(500, 'initiative-writer: the caller must pass the actor from pm-guard.js or actor.js');
|
|
121
|
+
const a = typeof anchor === 'string' ? anchor.trim() : '', n = typeof note === 'string' ? note.trim() : '';
|
|
122
|
+
if (!a || !ONE_LINE(a, 120) || /\s/.test(a)) return refuse(400, 'the anchor to keep is one id', 'anchor');
|
|
123
|
+
if (!n || /[\r\n]/.test(n)) return refuse(400, 'the note to move is one line', 'anchor');
|
|
124
|
+
return editAnchorLines(root, id, expect, (lines, at) => {
|
|
125
|
+
lines[at] = `parent_kr: ${PLAIN(a) ? a : q(a)}`;
|
|
126
|
+
lines.splice(at + 1, 0, `anchor_note: ${q(n)}`);
|
|
127
|
+
}, { anchor: a, note: n });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The Undo of a foldAnchor: the one anchor line back, exactly `from`, and no anchor_note, while the record still holds what the fold wrote. */
|
|
131
|
+
function unfoldAnchor(root, id, { from, fromLine, anchor, note } = {}, { actor } = {}) {
|
|
132
|
+
if (!actorLib().valid(actor)) return refuse(500, 'initiative-writer: the caller must pass the actor from pm-guard.js or actor.js');
|
|
133
|
+
const f0 = typeof from === 'string' ? from.trim() : '';
|
|
134
|
+
if (!f0 || /[\r\n]/.test(f0)) return refuse(400, 'the anchor to put back is not one line', 'anchor');
|
|
135
|
+
// the line exactly as it was (its quotes too), when the fold kept it and it still reads as that anchor
|
|
136
|
+
const back = typeof fromLine === 'string' && /^parent_kr:/.test(fromLine) && !/[\r\n]/.test(fromLine) && unquote(fromLine.slice(10)) === f0 ? fromLine : `parent_kr: ${PLAIN(f0) ? f0 : q(f0)}`;
|
|
137
|
+
return editAnchorLines(root, id, anchor, (lines, at) => {
|
|
138
|
+
const na = lines.findIndex((l) => /^anchor_note:/.test(l));
|
|
139
|
+
if (na < 0 || unquote(lines[na].slice(12)) !== String(note || '').trim()) return 'its anchor note was edited since the fold';
|
|
140
|
+
lines[at] = back;
|
|
141
|
+
lines.splice(na, 1);
|
|
142
|
+
return null;
|
|
143
|
+
}, { anchor: f0 });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function editAnchorLines(root, id, expect, edit, out) {
|
|
147
|
+
const f = recordFile(root, id);
|
|
148
|
+
if (!f.ok) return f;
|
|
149
|
+
const text = fs.readFileSync(f.file, 'utf8');
|
|
150
|
+
const m = frontOfText(text);
|
|
151
|
+
if (!m) return refuse(409, `the record of ${id} has no front matter — nothing was saved`, 'id');
|
|
152
|
+
const lines = m[1].split(/\r?\n/);
|
|
153
|
+
const at = lines.findIndex((l) => /^parent_kr:/.test(l));
|
|
154
|
+
if (at < 0 || unquote(lines[at].slice(10)) !== String(expect || '').trim()) return refuse(409, `the anchor of ${id} was edited since — nothing was saved`, 'anchor');
|
|
155
|
+
const fromLine = lines[at];
|
|
156
|
+
const why = edit(lines, at);
|
|
157
|
+
if (why) return refuse(409, `${why} — nothing was saved`, 'anchor');
|
|
158
|
+
try { fs.writeFileSync(f.file, '---\n' + lines.join('\n') + '\n---' + m[2] + text.slice(m[0].length), { flag: 'w' }); } catch { return refuse(500, 'the record could not be written — nothing was saved'); }
|
|
159
|
+
return { ok: true, id, fromLine, ...out };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function recordIds(root) {
|
|
163
|
+
let dir = null;
|
|
164
|
+
try { dir = require('./console-state').loadEngine().engine.layout(root).initiatives; } catch { dir = null; }
|
|
165
|
+
if (!dir) return [];
|
|
166
|
+
let names = [];
|
|
167
|
+
try { names = fs.readdirSync(dir); } catch { return []; }
|
|
168
|
+
const W = require('./initiative-writer.js');
|
|
169
|
+
return names.filter((n) => /\.md$/.test(n) && n !== 'README.md' && W.ID_RE.test(n.slice(0, -3))).map((n) => n.slice(0, -3)).sort();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function plan(root) {
|
|
173
|
+
const A = rows().anchorsOf(root);
|
|
174
|
+
const items = [], kept = [];
|
|
175
|
+
let total = 0;
|
|
176
|
+
for (const id of recordIds(root)) {
|
|
177
|
+
const r = readAnchorLine(root, id);
|
|
178
|
+
if (!r.ok || !r.text) continue;
|
|
179
|
+
total++;
|
|
180
|
+
const s = split(r.text);
|
|
181
|
+
if (!s.note) continue; // one id already: stays silent
|
|
182
|
+
if (r.spans) { kept.push({ id, from: r.text, why: 'the anchor runs over more than one line' }); continue; }
|
|
183
|
+
if (r.hasNote) { kept.push({ id, from: r.text, why: 'it has an anchor_note already' }); continue; }
|
|
184
|
+
const whole = A.resolve(r.text), alone = A.resolve(s.id);
|
|
185
|
+
if (whole.key !== alone.key || alone.status !== 'resolved') { kept.push({ id, from: r.text, why: `the id alone (${s.id}) does not name the same anchor` }); continue; }
|
|
186
|
+
items.push({ id, from: r.text, anchor: s.id, note: s.note });
|
|
187
|
+
}
|
|
188
|
+
return { total, items, kept };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const ledger = (stateDir) => path.join(stateDir, 'anchor-folds.jsonl');
|
|
192
|
+
function readLedger(stateDir) {
|
|
193
|
+
try { return fs.readFileSync(ledger(stateDir), 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { return []; }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function fold(root, { apply = false, actor, stateDir, now = Date.now() } = {}) {
|
|
197
|
+
const p = plan(root);
|
|
198
|
+
if (!apply) return { ok: true, ...p };
|
|
199
|
+
if (!stateDir) return { ok: false, status: 500, error: 'anchor-id: fold needs the runtime state folder for its Undo' };
|
|
200
|
+
const batch = 'fold-' + new Date(now).toISOString().replace(/[:.]/g, '-');
|
|
201
|
+
const done = [], at = new Date(now).toISOString(), by = (actor && actor.by) || 'unknown';
|
|
202
|
+
for (const it of p.items) {
|
|
203
|
+
const w = foldAnchor(root, it.id, { anchor: it.anchor, note: it.note, expect: it.from }, { actor });
|
|
204
|
+
if (!w.ok) { p.kept.push({ id: it.id, from: it.from, why: w.error }); continue; }
|
|
205
|
+
done.push({ v: 1, kind: 'fold', batch, id: it.id, from: it.from, fromLine: w.fromLine, anchor: it.anchor, note: it.note, at, by });
|
|
206
|
+
}
|
|
207
|
+
if (done.length) { fs.mkdirSync(stateDir, { recursive: true }); fs.appendFileSync(ledger(stateDir), done.map((d) => JSON.stringify(d)).join('\n') + '\n'); }
|
|
208
|
+
return { ok: true, total: p.total, items: done.map(({ id, from, anchor, note }) => ({ id, from, anchor, note })), kept: p.kept, folded: done.length, batch };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function undo(root, batch, { actor, stateDir, now = Date.now() } = {}) {
|
|
212
|
+
if (!/^fold-[0-9TZ-]+$/.test(String(batch || ''))) return { ok: false, status: 400, error: 'name the fold batch, fold-<time>, from the fold\'s answer' };
|
|
213
|
+
const all = stateDir ? readLedger(stateDir) : [];
|
|
214
|
+
const rowsOf = all.filter((e) => e.kind === 'fold' && e.batch === batch);
|
|
215
|
+
if (!rowsOf.length) return { ok: false, status: 404, error: `no anchor fold ${batch} on this computer` };
|
|
216
|
+
if (all.some((e) => e.kind === 'undo' && e.batch === batch)) return { ok: true, restored: 0, kept: 0, already: true };
|
|
217
|
+
let restored = 0, kept = 0;
|
|
218
|
+
for (const e of rowsOf) {
|
|
219
|
+
const w = unfoldAnchor(root, e.id, { from: e.from, fromLine: e.fromLine, anchor: e.anchor, note: e.note }, { actor });
|
|
220
|
+
if (w.ok) restored++; else kept++;
|
|
221
|
+
}
|
|
222
|
+
fs.appendFileSync(ledger(stateDir), JSON.stringify({ v: 1, kind: 'undo', batch, at: new Date(now).toISOString(), by: (actor && actor.by) || 'unknown' }) + '\n');
|
|
223
|
+
return { ok: true, restored, kept };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
module.exports = { split, anchorId, nearest, check, list, plan, fold, undo, readAnchorLine, foldAnchor, unfoldAnchor };
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* its artefact. Idempotent; it deletes and moves nothing
|
|
8
8
|
* pmos artefacts set <scope> <artefact> [<field>] --text "<…>" [--source label=ref]… one field (PM or agent; Intent is the PM's)
|
|
9
9
|
* pmos artefacts undo <a-id> one set line no longer counts
|
|
10
|
+
* pmos artefacts lessons <id> [--draft] [--json] an initiative's Lessons, with ids for undo; --draft drafts them (lib/lessons-draft.js, lessons-on-close)
|
|
10
11
|
* every command: [--root <dir>]
|
|
11
12
|
* Exit codes: 0 done, 1 refused, 2 usage. */
|
|
12
13
|
const path = require('path');
|
|
@@ -15,7 +16,7 @@ const A = require('./artefacts.js');
|
|
|
15
16
|
const MIRROR = require('./artefact-mirror.js');
|
|
16
17
|
const actorLib = require('./actor.js');
|
|
17
18
|
|
|
18
|
-
const COMMANDS = { artefacts: ['show', 'map', 'migrate', 'set', 'undo'] };
|
|
19
|
+
const COMMANDS = { artefacts: ['show', 'map', 'migrate', 'set', 'undo', 'lessons'] };
|
|
19
20
|
const USAGE = [
|
|
20
21
|
'usage: pmos artefacts show|map|migrate|set|undo — the seven artefacts: Intent, Goal, Narrative, Experiment, Specimens, Done test, Lessons',
|
|
21
22
|
' pmos artefacts show [<scope>] [--json] scope: portfolio (default), board:<id>, goal:<id> or experiment:<id> (an initiative)',
|
|
@@ -24,6 +25,7 @@ const USAGE = [
|
|
|
24
25
|
' pmos artefacts set <scope> <artefact> [<field>] --text "<text>" [--source label=ref]…',
|
|
25
26
|
' an initiative is experiment:<id> (initiative:<id> works too). Its case card: experiment why (Problem), experiment hypothesis (Goal), done-test check (Done when, once per check)',
|
|
26
27
|
' pmos artefacts undo <a-id>',
|
|
28
|
+
' pmos artefacts lessons <initiative> [--draft] [--json] its Lessons lines with their ids; --draft: PMOS drafts them once its experiment closed (never over yours)',
|
|
27
29
|
];
|
|
28
30
|
function parse(args) {
|
|
29
31
|
const pos = []; const flags = { source: [] };
|
|
@@ -37,6 +39,27 @@ function parse(args) {
|
|
|
37
39
|
}
|
|
38
40
|
return { pos, flags };
|
|
39
41
|
}
|
|
42
|
+
/* lessons-on-close (A542): the chat reads an initiative's Lessons and asks PMOS to draft them. The draft is async (a session may answer). */
|
|
43
|
+
function lessonsCmd(pos, flags, { root, dir, f, say, now }) {
|
|
44
|
+
const id = pos[0];
|
|
45
|
+
if (!id || pos.length > 1) { say('usage: pmos artefacts lessons <initiative> [--draft] [--json]'); return 2; }
|
|
46
|
+
const LD = require('./lessons-draft.js');
|
|
47
|
+
const show = () => {
|
|
48
|
+
const h = LD.lessonsHere(A.fold(A.readLines(f)), id), all = [...h.pm, ...h.agent].sort((a, b) => String(a.at).localeCompare(String(b.at)));
|
|
49
|
+
if (flags.json) { say(JSON.stringify({ ok: true, initiative: id, lessons: all.map((l) => ({ id: l.id, text: l.text, by: /^pm:/.test(String(l.by || '')) ? 'you' : 'pmos', sources: l.sources || [], at: l.at })) })); return 0; }
|
|
50
|
+
if (!all.length) { say(`${id} has no lessons yet.`); return 0; }
|
|
51
|
+
for (const l of all) say(`${l.id} ${l.text}${/^pm:/.test(String(l.by || '')) ? '' : ' (PMOS)'}${(l.sources || []).length ? ' ← ' + l.sources.map((x) => x.ref).join(', ') : ''}`);
|
|
52
|
+
say('Undo one: pmos artefacts undo <a-id>');
|
|
53
|
+
return 0;
|
|
54
|
+
};
|
|
55
|
+
if (!('draft' in flags)) return show();
|
|
56
|
+
return LD.draft({}, { root, id, dir, now: now || Date.now() }).then((r) => {
|
|
57
|
+
if (!r.ok) { say('✗ ' + r.error); return 1; }
|
|
58
|
+
if (!r.wrote.length) { say(`Nothing drafted: ${r.why}.`); return 0; }
|
|
59
|
+
say(`✓ PMOS drafted ${r.wrote.length} ${r.wrote.length === 1 ? 'lesson' : 'lessons'} for ${id}, from its experiment and what happened. Nothing was sent.`);
|
|
60
|
+
return show();
|
|
61
|
+
});
|
|
62
|
+
}
|
|
40
63
|
function repoRoot(cwd) { try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; } catch { return cwd; } }
|
|
41
64
|
|
|
42
65
|
function mapRows() {
|
|
@@ -64,6 +87,7 @@ function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), env = pro
|
|
|
64
87
|
let dir = dirIn || null;
|
|
65
88
|
if (!dir) { try { dir = A.dirOf(root); } catch (e) { say('✗ ' + String((e && e.message) || e)); return 1; } }
|
|
66
89
|
const f = A.file(dir);
|
|
90
|
+
if (verb === 'lessons') return lessonsCmd(pos, flags, { root, dir, f, say, now });
|
|
67
91
|
if (verb === 'show') {
|
|
68
92
|
const scope = pos[0] || 'portfolio';
|
|
69
93
|
const v = A.viewOf(A.fold(A.readLines(f)), scope);
|
|
@@ -42,6 +42,7 @@ const rowsLib = require('./initiative-rows.js');
|
|
|
42
42
|
const planRules = require('./plan-rules.js');
|
|
43
43
|
const breakdownExport = require('./breakdown-export.js');
|
|
44
44
|
const triage = require('./triage.js');
|
|
45
|
+
const AID = require('./anchor-id.js');
|
|
45
46
|
const lifecycle = require('./lifecycle-stage.js');
|
|
46
47
|
const { parseArgs } = require('./schedule-cli');
|
|
47
48
|
|
|
@@ -79,11 +80,11 @@ function docNote(docs) {
|
|
|
79
80
|
return `Not on the Roadmap · ${docs.length} on a document lane: ${names}. A document lane does not show on Today or Work. If it is work, set lane: in its record to ${WORK_LANES}.`;
|
|
80
81
|
}
|
|
81
82
|
|
|
82
|
-
const COMMANDS = { initiative: ['new', 'top', 'up', 'down', 'bottom', 'after', 'check-by', 'adopt', 'drop', 'list', 'export', 'describe', 'raised-by', 'kind', 'role', 'status', 'status-migrate', 'status-undo'] };
|
|
83
|
+
const COMMANDS = { initiative: ['new', 'top', 'up', 'down', 'bottom', 'after', 'check-by', 'adopt', 'drop', 'list', 'export', 'describe', 'raised-by', 'kind', 'role', 'status', 'status-migrate', 'status-undo', 'anchor', 'anchors'] };
|
|
83
84
|
/** The horizon verbs D105 retired: they answer with what to use instead. */
|
|
84
85
|
const RETIRED = Object.freeze(['now', 'next', 'later']);
|
|
85
86
|
const USAGE = [
|
|
86
|
-
'usage: pmos initiative new|top|up|down|bottom|after|check-by|adopt|drop|list|export|describe|raised-by|kind|role|status|status-migrate|status-undo — initiatives on the Roadmap',
|
|
87
|
+
'usage: pmos initiative new|top|up|down|bottom|after|check-by|adopt|drop|list|export|describe|raised-by|kind|role|status|status-migrate|status-undo|anchor|anchors — initiatives on the Roadmap',
|
|
87
88
|
' pmos initiative new "<title>" --lane <lane> --anchor <KR|health:id> [--intent "<text>"] [--id <id>] [--kind product|sdlc|project] [--raised-by "<who>"]',
|
|
88
89
|
' pmos initiative new --from capture-YYYY-MM-DD-<n> [--anchor <anchor>] [--lane <lane>] [--title "<title>"]',
|
|
89
90
|
' pmos initiative top|up|down|bottom <id> reorder it on the Roadmap',
|
|
@@ -100,6 +101,10 @@ const USAGE = [
|
|
|
100
101
|
' pmos initiative status <id> ["<text>"] [--line "<12 words>"] its status line and log; with text, save it: the whole text to the log, the line (yours, else its first 12 words) to the record',
|
|
101
102
|
' pmos initiative status-migrate [--apply] every status over 12 words: count them (dry run), or with --apply give each its line and move the whole text to the log',
|
|
102
103
|
' pmos initiative status-undo <batch> undo a status-migrate: each line not edited since gets its whole text back',
|
|
104
|
+
' pmos initiative anchor <id> ["<anchor>"] its anchor; with one, change it (an id the OKR files or health budgets declare, else refused with the nearest)',
|
|
105
|
+
' pmos initiative anchors the anchor ids you can pick: key results, health budgets, domains',
|
|
106
|
+
' pmos initiative anchors fold [--apply] anchors with text after the id: list them (dry run), or with --apply keep the id and move the text to anchor_note',
|
|
107
|
+
' pmos initiative anchors undo <batch> undo a fold: each record not edited since gets its whole anchor back',
|
|
103
108
|
' --lane is a work lane of this repository: new-feature, improvement, bug-fix, discovery or chore in a product repository',
|
|
104
109
|
' (scripts/lane-defs.js; the PMOS repository itself uses feature, discovery, chore, incident, content and prototype)',
|
|
105
110
|
' every command: [--json] [--root <dir>]',
|
|
@@ -175,9 +180,17 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
|
|
|
175
180
|
if (flags.title) input.title = flags.title;
|
|
176
181
|
for (const k of ['lane', 'anchor', 'intent', 'id', 'kind']) if (flags[k]) input[k] = flags[k];
|
|
177
182
|
if (flags['raised-by']) input.raised_by = flags['raised-by'];
|
|
183
|
+
// anchor-ids (A547): the anchor is one declared id; a refused id names the nearest, and text after the id goes to anchor_note
|
|
184
|
+
let anchorNote = '';
|
|
185
|
+
if (input.anchor) {
|
|
186
|
+
const c = AID.check(root, input.anchor);
|
|
187
|
+
if (!c.ok) return fail(c.error);
|
|
188
|
+
input.anchor = c.id; anchorNote = c.note;
|
|
189
|
+
}
|
|
178
190
|
const actor = actorLib.fromCli(who);
|
|
179
191
|
const r = writer.createInitiative(root, input, { actor, now });
|
|
180
192
|
if (!r.ok) return fail(r.error);
|
|
193
|
+
if (anchorNote) AID.foldAnchor(root, r.id, { anchor: input.anchor, note: anchorNote, expect: input.anchor }, { actor });
|
|
181
194
|
startOnDefault(root, r, actor);
|
|
182
195
|
// no initiative without an expected outcome (outcome-for-every-initiative): say what Claude drafts next, or that the PM names it
|
|
183
196
|
return done({ id: r.id, path: r.path }, `✓ ${r.id} added at the end of the Roadmap (${r.path}). Commit the record to keep it.\n`
|
|
@@ -303,6 +316,58 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
|
|
|
303
316
|
return done({ role: pos[0] }, `✓ New work starts as ${WK.LABEL[pos[0]]}. Settings shows it now. Each initiative can still change its own kind.`);
|
|
304
317
|
}
|
|
305
318
|
|
|
319
|
+
if (verb === 'anchors') {
|
|
320
|
+
const stateDir = require('./state-root.js').defaultRoot({ env: who.env });
|
|
321
|
+
const actor = actorLib.fromCli(who);
|
|
322
|
+
if (!pos.length) {
|
|
323
|
+
const all = AID.list(root);
|
|
324
|
+
if (json) { say(JSON.stringify({ ok: true, anchors: all })); return 0; }
|
|
325
|
+
if (!all.length) return fail('no anchor is declared: the OKR files and the health budgets name none');
|
|
326
|
+
let g = null;
|
|
327
|
+
for (const a of all) { if (a.group !== g) { g = a.group; say(g); } say(` ${a.value.padEnd(22)}${a.label}`); }
|
|
328
|
+
return 0;
|
|
329
|
+
}
|
|
330
|
+
if (pos[0] === 'fold') {
|
|
331
|
+
if (pos.length !== 1) { say('usage: pmos initiative anchors fold [--apply]'); return 2; }
|
|
332
|
+
const r = AID.fold(root, { apply: !!flags.apply, actor, stateDir, now: now == null ? Date.now() : now });
|
|
333
|
+
if (!r.ok) return fail(r.error);
|
|
334
|
+
if (json) { say(JSON.stringify(r)); return 0; }
|
|
335
|
+
if (!flags.apply) {
|
|
336
|
+
say(`${r.items.length} of ${r.total} anchors have text after the id.`);
|
|
337
|
+
for (const it of r.items.slice(0, 20)) say(` ${it.id}: ${it.anchor} (note: ${it.note.slice(0, 70)}${it.note.length > 70 ? '…' : ''})`);
|
|
338
|
+
if (r.items.length > 20) say(` … and ${r.items.length - 20} more`);
|
|
339
|
+
for (const k of r.kept) say(` kept ${k.id}: ${k.why}`);
|
|
340
|
+
if (r.items.length) say('Run it again with --apply to keep each id and move its text to anchor_note. Nothing was written.');
|
|
341
|
+
return 0;
|
|
342
|
+
}
|
|
343
|
+
say(`✓ ${r.folded} anchors now hold one id; the text after each is in anchor_note.${r.kept.length ? ` ${r.kept.length} kept as they were.` : ''}${r.folded ? ` Undo: pmos initiative anchors undo ${r.batch}` : ''}`);
|
|
344
|
+
return 0;
|
|
345
|
+
}
|
|
346
|
+
if (pos[0] === 'undo') {
|
|
347
|
+
if (pos.length !== 2) { say('usage: pmos initiative anchors undo <batch>'); return 2; }
|
|
348
|
+
const r = AID.undo(root, pos[1], { actor, stateDir, now: now == null ? Date.now() : now });
|
|
349
|
+
if (!r.ok) return fail(r.error, r.status === 400 ? 2 : 1);
|
|
350
|
+
return done(r, r.already ? `${pos[1]} was undone already.` : `✓ ${r.restored} anchors have their whole text back${r.kept ? `; ${r.kept} edited since keep their edit` : ''}.`);
|
|
351
|
+
}
|
|
352
|
+
say('usage: pmos initiative anchors [fold [--apply] | undo <batch>]'); return 2;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
if (verb === 'anchor') {
|
|
356
|
+
const id = pos[0];
|
|
357
|
+
if (!id || pos.length > 2) { say('usage: pmos initiative anchor <id> ["<anchor>"]'); return 2; }
|
|
358
|
+
const cur = AID.readAnchorLine(root, id);
|
|
359
|
+
if (!cur.ok) return fail(cur.error);
|
|
360
|
+
if (pos.length === 1) return done({ id, anchor: AID.anchorId(cur.text), note: AID.split(cur.text).note }, cur.text ? `${id}: ${AID.anchorId(cur.text)}` : `${id} has no anchor yet.`);
|
|
361
|
+
const c = AID.check(root, pos[1]);
|
|
362
|
+
if (!c.ok) return fail(c.error);
|
|
363
|
+
if (c.note && cur.hasNote) return fail(`${id} has an anchor_note already: give the id alone, ${c.id}`);
|
|
364
|
+
const actor = actorLib.fromCli(who);
|
|
365
|
+
const r = writer.setAnchor(root, id, c.id, { actor });
|
|
366
|
+
if (!r.ok) return fail(r.error);
|
|
367
|
+
if (c.note) AID.foldAnchor(root, id, { anchor: c.id, note: c.note, expect: c.id }, { actor });
|
|
368
|
+
return done({ id, anchor: c.id, from: r.from }, `✓ ${id} is anchored to ${c.id}${r.from && r.from !== c.id ? ` (was ${r.from})` : ''}. Work shows it now.`);
|
|
369
|
+
}
|
|
370
|
+
|
|
306
371
|
if (verb === 'status' || verb === 'status-migrate' || verb === 'status-undo') {
|
|
307
372
|
// status-line (A505): the record's status in one line of at most 12 words; the whole text stays in the item's log
|
|
308
373
|
const SL = require('./status-line.js');
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* lessons-draft.js — PMOS drafts an initiative's Lessons when its experiment closes (initiative lessons-on-close, job #1971, idea A542; done
|
|
3
|
+
* test planning/done-tests/lessons-on-close.md).
|
|
4
|
+
*
|
|
5
|
+
* D107 made Lessons one of the seven artefacts (lib/artefacts.js). An experiment closes when an outcome check is recorded on it, or when the PM
|
|
6
|
+
* keeps the ✦ that stops it (a met kill line or a refuted check: the D70 lifecycle line, state cancelled). Then PMOS reads what the experiment
|
|
7
|
+
* set out to do and what happened, and writes up to five Lessons lines on experiment:<id>, each with its sources. Every line is an agent's
|
|
8
|
+
* set: `pmos artefacts undo <a-id>` takes it back.
|
|
9
|
+
*
|
|
10
|
+
* factsOf(root, id) → { id, title, expected, kill, intent, goal, doneRows: [text], result: { kind, disposition?, evidence, date } | null,
|
|
11
|
+
* decisions: [text], sources: { experiment, done, result, decision } } | null READ-ONLY
|
|
12
|
+
* closedOf(root, id) → the result that closed it ({ kind: 'check'|'stopped', … }) or null
|
|
13
|
+
* promptOf(F) · parse(text, F) the session's prompt and its answer read back ([{ text, sources }], at most MAX) PURE
|
|
14
|
+
* fallbackOf(F) → [{ text, sources }] a plain draft from the facts' own words, when no session answers PURE
|
|
15
|
+
* lessonsHere(state, id) → { pm: [set], agent: [set] } the Lessons lines on experiment:<id>, by who wrote them PURE
|
|
16
|
+
* draft(ctx, { root, id, dir, now }) → { ok, wrote: [line], made: 'session'|'facts' } | { ok: true, wrote: [], why }
|
|
17
|
+
* onClose(ctx, { root, id }) the hook: drafts once, in the background, after a check is recorded or an experiment is stopped
|
|
18
|
+
* due(root, { dir }) → [id] closed experiments with no Lessons line yet
|
|
19
|
+
* kept(dir, { now, days }) → the drafted lines still standing that were written in the last `days` days (the health number)
|
|
20
|
+
*
|
|
21
|
+
* NEVER over the PM: an initiative with a Lessons line the PM wrote gets no draft, and nothing here undoes or edits a line. A second check on
|
|
22
|
+
* an initiative that has drafted Lessons drafts nothing more. The session is one normal PMOS session (`claude -p` through the existing
|
|
23
|
+
* read-only `briefing-ask:` ask kind, no tools but Read), as lib/task-describe.js uses. Tests inject ctx.askClaude(prompt, { job, key }).
|
|
24
|
+
* The copy says PMOS, never the model's name. */
|
|
25
|
+
const fs = require('fs');
|
|
26
|
+
const path = require('path');
|
|
27
|
+
const crypto = require('crypto');
|
|
28
|
+
const A = require('./artefacts.js');
|
|
29
|
+
|
|
30
|
+
const MAX = 5;
|
|
31
|
+
const BY = 'agent:lessons-draft';
|
|
32
|
+
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
|
|
33
|
+
const DAY = 864e5;
|
|
34
|
+
const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return t.length <= n ? t : t.slice(0, n - 1).replace(/[,;:\s]+$/, '') + '…'; };
|
|
35
|
+
const linesOf = (f) => { try { return fs.readFileSync(f, 'utf8').replace(/\r\n?/g, '\n').split('\n'); } catch { return null; } };
|
|
36
|
+
const rel = (root, f) => path.relative(root, f).split(path.sep).join('/');
|
|
37
|
+
const unquote = (v) => String(v || '').trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1');
|
|
38
|
+
function jsonRows(file) { const L = linesOf(file); if (!L) return []; const out = []; for (const s of L) { if (!s.trim()) continue; try { const o = JSON.parse(s); if (o && typeof o === 'object') out.push(o); } catch { /* torn */ } } return out; }
|
|
39
|
+
|
|
40
|
+
function layoutOf(root) {
|
|
41
|
+
const kit = fs.existsSync(path.join(root, 'pmos', 'state'));
|
|
42
|
+
return { kit, initiatives: kit ? path.join(root, 'pmos', 'state', 'initiatives') : path.join(root, 'planning', 'initiatives'), runsDir: kit ? path.join(root, 'pmos', 'state') : path.join(root, 'planning', 'runs') };
|
|
43
|
+
}
|
|
44
|
+
const ledger = (root, L, name) => [...new Set([path.join(L.runsDir, name), path.join(root, 'pmos', 'state', name), path.join(root, 'planning', 'runs', name)])].flatMap(jsonRows);
|
|
45
|
+
function frontOf(L) {
|
|
46
|
+
const fm = {}; let end = 0;
|
|
47
|
+
if (!L || !/^---\s*$/.test(L[0] || '')) return { fm, end };
|
|
48
|
+
for (let i = 1; i < L.length && i < 200; i++) { if (/^---\s*$/.test(L[i])) { end = i + 1; break; } const m = /^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/.exec(L[i]); if (m && !(m[1] in fm)) fm[m[1]] = unquote(m[2]); }
|
|
49
|
+
return { fm, end };
|
|
50
|
+
}
|
|
51
|
+
/** The first paragraph under "## <name>". */
|
|
52
|
+
function sectionOf(L, name) {
|
|
53
|
+
const at = L.findIndex((l) => new RegExp('^##\\s+' + name + '\\s*$', 'i').test(l));
|
|
54
|
+
if (at < 0) return '';
|
|
55
|
+
const out = [];
|
|
56
|
+
for (let i = at + 1; i < L.length && !/^#{1,2}\s/.test(L[i]); i++) { if (!L[i].trim()) { if (out.length) break; continue; } out.push(L[i].trim()); }
|
|
57
|
+
return clip(out.join(' '), 400);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The result that closed the experiment: its standing outcome check, else the D70 line that stopped it. null while it runs. */
|
|
61
|
+
function closedOf(root, id) {
|
|
62
|
+
root = path.resolve(root);
|
|
63
|
+
const L = layoutOf(root);
|
|
64
|
+
let checks = [];
|
|
65
|
+
try { checks = require('./outcomes.js').liveChecks(ledger(root, L, 'outcome_checks.jsonl')); } catch { checks = []; }
|
|
66
|
+
const c = checks.filter((r) => r.initiative_id === id && r.disposition).pop();
|
|
67
|
+
let life = null;
|
|
68
|
+
for (const r of ledger(root, L, 'lifecycle.jsonl')) if (r && r.initiative_id === id && r.state) life = r;
|
|
69
|
+
if (life && life.state === 'cancelled') return { kind: 'stopped', evidence: clip(life.reason || 'Stopped.', 400), date: String(life.at || '').slice(0, 10), ref: rel(root, path.join(L.runsDir, 'lifecycle.jsonl')) };
|
|
70
|
+
if (c) return { kind: 'check', disposition: c.disposition, evidence: clip(c.evidence, 400), date: c.date || String(c.at || '').slice(0, 10), ref: rel(root, path.join(L.runsDir, 'outcome_checks.jsonl')) };
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function factsOf(root, id) {
|
|
75
|
+
root = path.resolve(root);
|
|
76
|
+
if (!ID_RE.test(String(id || ''))) return null;
|
|
77
|
+
const L = layoutOf(root), file = path.join(L.initiatives, id + '.md'), R = linesOf(file);
|
|
78
|
+
if (!R) return null;
|
|
79
|
+
const { fm } = frontOf(R);
|
|
80
|
+
const doneFile = fm.done_test_path ? path.resolve(root, String(fm.done_test_path).replace(/^\//, '')) : null;
|
|
81
|
+
const D = doneFile && doneFile.startsWith(root + path.sep) ? linesOf(doneFile) : null;
|
|
82
|
+
const doneRows = (D || []).map((l) => /^\|\s*([A-Z]{1,3}\d{1,3})\s*\|\s*(.+?)\s*\|/.exec(l)).filter(Boolean).map((m) => clip(m[1] + ': ' + m[2], 240)).slice(0, 8);
|
|
83
|
+
const decFile = path.join(root, 'pm-decisions.md'), DL = linesOf(decFile) || [];
|
|
84
|
+
const idRe = new RegExp('(^|[^a-z0-9-])' + id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^a-z0-9-]|$)', 'i');
|
|
85
|
+
const decisions = DL.filter((l) => idRe.test(l) && l.trim().length > id.length + 8).slice(-3).map((l) => clip(l.replace(/^\s*[-*#|>]+\s*/, ''), 300));
|
|
86
|
+
return {
|
|
87
|
+
id, title: fm.title || id, expected: clip(fm.expected_outcome || '', 300), kill: clip(fm.kill || '', 300),
|
|
88
|
+
intent: sectionOf(R, 'Intent'), goal: sectionOf(R, 'Goal'), doneRows, result: closedOf(root, id), decisions,
|
|
89
|
+
sources: { experiment: rel(root, file), done: D ? rel(root, doneFile) : '', result: '', decision: decisions.length ? 'pm-decisions.md' : '' },
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const SRC = { experiment: 'the experiment', done: 'the done test', result: 'the result', decision: 'a decision' };
|
|
94
|
+
function srcList(F, keys) {
|
|
95
|
+
const out = [];
|
|
96
|
+
for (const k of keys) {
|
|
97
|
+
const ref = k === 'result' ? (F.result && F.result.ref) || '' : F.sources[k];
|
|
98
|
+
if (ref && !out.some((x) => x.ref === ref)) out.push({ label: SRC[k], ref });
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
const WORD = { worked: 'worked', confirmed: 'worked', refuted: 'did not work', 'did-not-work': 'did not work', inconclusive: 'was inconclusive' };
|
|
103
|
+
const resultWord = (r) => (!r ? '' : r.kind === 'stopped' ? 'was stopped' : WORD[r.disposition] || 'was checked (' + r.disposition + ')');
|
|
104
|
+
|
|
105
|
+
/** PURE. */
|
|
106
|
+
function promptOf(F) {
|
|
107
|
+
const r = F.result;
|
|
108
|
+
return [
|
|
109
|
+
'You write the Lessons of one closed product experiment for a product manager. Write from the facts below only. Invent nothing.',
|
|
110
|
+
'Write 1 to 5 lines. Each line is one lesson in plain words (at most 200 characters): what this experiment teaches the next one.',
|
|
111
|
+
'End each line with its source in brackets, one of [experiment], [done test], [result], [decision]. A line with no source is dropped.',
|
|
112
|
+
'Start each line with "- ". Write nothing else.',
|
|
113
|
+
'',
|
|
114
|
+
`Experiment: ${F.title} (${F.id})`,
|
|
115
|
+
F.intent ? `Intent: ${F.intent}` : '',
|
|
116
|
+
F.goal ? `Goal: ${F.goal}` : '',
|
|
117
|
+
F.expected ? `Expected outcome: ${F.expected}` : '',
|
|
118
|
+
F.kill ? `Kill line: ${F.kill}` : '',
|
|
119
|
+
F.doneRows.length ? 'Done test:\n' + F.doneRows.map((x) => ' ' + x).join('\n') : '',
|
|
120
|
+
r ? `Result (${r.date}): it ${resultWord(r)}. ${r.evidence}` : '',
|
|
121
|
+
F.decisions.length ? 'Decisions:\n' + F.decisions.map((x) => ' ' + x).join('\n') : '',
|
|
122
|
+
].filter(Boolean).join('\n');
|
|
123
|
+
}
|
|
124
|
+
const TAG = { experiment: 'experiment', 'done test': 'done', result: 'result', decision: 'decision' };
|
|
125
|
+
/** PURE. The session's lines with a known source, at most MAX. */
|
|
126
|
+
function parse(text, F) {
|
|
127
|
+
const out = [];
|
|
128
|
+
for (const raw of String(text || '').split('\n')) {
|
|
129
|
+
const m = /^\s*[-*]\s+(.+?)\s*\[(experiment|done test|result|decision)\]\s*\.?\s*$/i.exec(raw);
|
|
130
|
+
if (!m) continue;
|
|
131
|
+
const k = TAG[m[2].toLowerCase()], t = clip(m[1].replace(/\s*[—–-]\s*$/, ''), 300);
|
|
132
|
+
const sources = srcList(F, [k]);
|
|
133
|
+
if (t.length < 12 || !sources.length || /\bclaude\b/i.test(t)) continue;
|
|
134
|
+
out.push({ text: t, sources });
|
|
135
|
+
if (out.length >= MAX) break;
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
/** PURE. A plain draft in the facts' own words. */
|
|
140
|
+
function fallbackOf(F) {
|
|
141
|
+
const r = F.result, out = [];
|
|
142
|
+
if (r) out.push({ text: clip(`${F.title} ${resultWord(r)} (${r.date}): ${r.evidence.replace(/[.\s]+$/, '')}.`, 300), sources: srcList(F, ['result']) });
|
|
143
|
+
if (F.expected && r) out.push({ text: clip(`It set out to show: ${F.expected.replace(/[.\s]+$/, '')}.`, 300), sources: srcList(F, ['experiment']) });
|
|
144
|
+
if (F.kill && r && r.kind === 'stopped') out.push({ text: clip(`Its kill line was: ${F.kill.replace(/[.\s]+$/, '')}.`, 300), sources: srcList(F, ['experiment']) });
|
|
145
|
+
if (F.doneRows.length && r) out.push({ text: clip(`The done test checked ${F.doneRows.length} ${F.doneRows.length === 1 ? 'thing' : 'things'}, first ${F.doneRows[0].replace(/[.\s]+$/, '')}.`, 300), sources: srcList(F, ['done']) });
|
|
146
|
+
return out.filter((x) => x.sources.length).slice(0, MAX);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** PURE. */
|
|
150
|
+
function lessonsHere(state, id) {
|
|
151
|
+
const x = state && state.get('experiment:' + id), m = x && x.get('lessons');
|
|
152
|
+
const sets = m ? m.sets.filter((l) => l.field === 'line') : [];
|
|
153
|
+
return { pm: sets.filter((l) => /^pm:/.test(String(l.by || ''))), agent: sets.filter((l) => !/^pm:/.test(String(l.by || ''))) };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/* ── the session ── */
|
|
157
|
+
const MODEL = 'claude-sonnet-5-5';
|
|
158
|
+
const LEAN = Object.freeze([{ flag: '--strict-mcp-config' }, { flag: '--disable-slash-commands' }, { flag: '--setting-sources', value: 'user' }, { flag: '--tools', value: 'Read' }]);
|
|
159
|
+
const TIMEOUT_MS = 90000;
|
|
160
|
+
function viaSession(ctx, prompt, key) {
|
|
161
|
+
if (typeof ctx.askClaude === 'function') return Promise.resolve(ctx.askClaude(prompt, { job: 'lessons-draft', key })).catch(() => null);
|
|
162
|
+
const origin = 'briefing-ask:lessons-draft:' + key;
|
|
163
|
+
let headless = null; try { headless = require('./headless.js'); } catch { headless = null; }
|
|
164
|
+
if (typeof ctx.spawnSession !== 'function' || !headless || headless.kindFor({ agent: 'claude', origin }) !== 'ask') return Promise.resolve(null);
|
|
165
|
+
return new Promise((resolve) => {
|
|
166
|
+
let settled = false; const done = (v) => { if (settled) return; settled = true; clearTimeout(t); resolve(v); };
|
|
167
|
+
const t = setTimeout(() => done(null), TIMEOUT_MS);
|
|
168
|
+
let s = null;
|
|
169
|
+
try {
|
|
170
|
+
s = ctx.spawnSession({ name: 'lessons: draft them', agent: 'claude', origin, initialInput: prompt,
|
|
171
|
+
modelAsk: { explicit: { model: MODEL, effort: 'low' } }, launchFlags: LEAN.map((f) => ({ ...f })),
|
|
172
|
+
onDone: (d) => { const r = d && d.result; done(r && r.ok && !r.isError ? String(r.text || '') : null); } });
|
|
173
|
+
} catch { s = null; }
|
|
174
|
+
if (!s || s.state === 'exited') done(null);
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const RUNNING = new Set();
|
|
179
|
+
async function draft(ctx, { root, id, dir = null, now = Date.now() } = {}) {
|
|
180
|
+
root = path.resolve(root || '.');
|
|
181
|
+
if (!ID_RE.test(String(id || ''))) return { ok: false, error: 'name the initiative by its id' };
|
|
182
|
+
let d = dir; if (!d) { try { d = A.dirOf(root); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } }
|
|
183
|
+
const f = A.file(d);
|
|
184
|
+
const here = lessonsHere(A.fold(A.readLines(f)), id);
|
|
185
|
+
if (here.pm.length) return { ok: true, wrote: [], why: 'you wrote its lessons: PMOS leaves them as they are' };
|
|
186
|
+
if (here.agent.length) return { ok: true, wrote: [], why: 'PMOS drafted its lessons already' };
|
|
187
|
+
const F = factsOf(root, id);
|
|
188
|
+
if (!F) return { ok: false, error: `no initiative ${id} here` };
|
|
189
|
+
if (!F.result) return { ok: true, wrote: [], why: `${id} is still running: its lessons are drafted when its outcome check or kill line closes it` };
|
|
190
|
+
const key = crypto.createHash('sha1').update(root + '\n' + id + '\n' + promptOf(F)).digest('hex').slice(0, 12);
|
|
191
|
+
const said = await viaSession(ctx || {}, promptOf(F), key);
|
|
192
|
+
const got = said != null ? parse(said, F) : [];
|
|
193
|
+
const L = got.length ? got : fallbackOf(F), made = got.length ? 'session' : 'facts';
|
|
194
|
+
// the PM may have written while the session ran: read again, and write nothing over their lessons
|
|
195
|
+
const again = lessonsHere(A.fold(A.readLines(f)), id);
|
|
196
|
+
if (again.pm.length || again.agent.length) return { ok: true, wrote: [], why: again.pm.length ? 'you wrote its lessons: PMOS leaves them as they are' : 'PMOS drafted its lessons already' };
|
|
197
|
+
const wrote = [];
|
|
198
|
+
for (const x of L) {
|
|
199
|
+
const r = A.set(f, { scope: 'experiment:' + id, artefact: 'lessons', field: 'line', text: x.text, sources: x.sources }, { by: BY, via: 'pmos' }, { now });
|
|
200
|
+
if (r.ok) wrote.push(r.line);
|
|
201
|
+
}
|
|
202
|
+
console.info(`[lessons-draft] drafted ${id} lines=${wrote.length} made=${made} closed=${F.result.kind}`);
|
|
203
|
+
return { ok: true, wrote, made };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The hook (lib/routes-proposals.js): after a check is recorded or an experiment is stopped. Drafts in the background, once per id at a time. */
|
|
207
|
+
function onClose(ctx, { root, id, dir = null } = {}) {
|
|
208
|
+
const k = String(root) + '|' + id;
|
|
209
|
+
if (RUNNING.has(k)) return null;
|
|
210
|
+
RUNNING.add(k);
|
|
211
|
+
const p = Promise.resolve().then(() => draft(ctx, { root, id, dir })).catch((e) => { console.warn('[lessons-draft] ' + id + ': ' + String((e && e.message) || e).slice(0, 160)); return null; })
|
|
212
|
+
.finally(() => RUNNING.delete(k));
|
|
213
|
+
return p;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function due(root, { dir = null } = {}) {
|
|
217
|
+
root = path.resolve(root);
|
|
218
|
+
const L = layoutOf(root);
|
|
219
|
+
let d = dir; if (!d) { try { d = A.dirOf(root); } catch { d = null; } }
|
|
220
|
+
const S = d ? A.fold(A.readLines(A.file(d))) : new Map();
|
|
221
|
+
const ids = new Set();
|
|
222
|
+
for (const r of ledger(root, L, 'outcome_checks.jsonl')) if (r && r.initiative_id && r.disposition) ids.add(r.initiative_id);
|
|
223
|
+
for (const r of ledger(root, L, 'lifecycle.jsonl')) if (r && r.initiative_id && r.state === 'cancelled') ids.add(r.initiative_id);
|
|
224
|
+
return [...ids].filter((id) => ID_RE.test(id) && closedOf(root, id) && fs.existsSync(path.join(L.initiatives, id + '.md'))).filter((id) => { const h = lessonsHere(S, id); return !h.pm.length && !h.agent.length; }).sort();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function kept(dir, { now = Date.now(), days = 7 } = {}) {
|
|
228
|
+
const lines = A.readLines(A.file(dir));
|
|
229
|
+
const undone = new Set(lines.filter((l) => l.ev === 'undo').map((l) => l.ref));
|
|
230
|
+
return lines.filter((l) => l.ev === 'set' && l.artefact === 'lessons' && l.by === BY && !undone.has(l.id) && Date.parse(l.at) >= now - days * DAY).length;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
module.exports = { MAX, BY, factsOf, closedOf, promptOf, parse, fallbackOf, lessonsHere, draft, onClose, due, kept };
|
|
234
|
+
|
|
235
|
+
// `node lib/lessons-draft.js kept [--days N]`: the health number on its last line
|
|
236
|
+
if (require.main === module) {
|
|
237
|
+
const a = process.argv.slice(2), i = a.indexOf('--days'), days = i >= 0 ? Number(a[i + 1]) || 7 : 7;
|
|
238
|
+
if (a[0] !== 'kept') { console.log('usage: node lib/lessons-draft.js kept [--days N]'); process.exit(2); }
|
|
239
|
+
let root = process.cwd(); try { root = require('child_process').execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || root; } catch { /* cwd */ }
|
|
240
|
+
let dir = null; try { dir = A.dirOf(root); } catch { dir = null; }
|
|
241
|
+
console.log(String(dir ? kept(dir, { days }) : 0));
|
|
242
|
+
}
|