create-pmos 0.753.0 → 0.755.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.
@@ -0,0 +1,400 @@
1
+ 'use strict';
2
+ /* setup-station.js — the Setup station of the product line: a new product passes it before PMOS plans its work (initiative setup-station;
3
+ * product line plan, doc Ejs4HXyqpenvaiqiRMtzoF tab Plan, slice 5, agreed by the PM 2026-11-24).
4
+ *
5
+ * read(root, { runtimeDir }) → facts the three exit items as the records state them. Reads only; never writes
6
+ * check(facts) → result PURE. { passed, met, of: 3, items: [item], missing: [label], next: proposal | null }
7
+ * holds(result, steps) → bool PURE. Is the gate shut? Only while Setup has not passed AND the product is new
8
+ * gate(result, steps, { what, data }) → { ok } | { ok: false, error } PURE. May the Driver file this proposal now?
9
+ * stepsOf(root) → [step] | null the lifecycle step of each initiative (lib/stage-read.js), null when unreadable
10
+ * agreeGoal(root, { now, by }) · setOwner(root, name, { now, by }) · undo(root, { now, by }) the PM's approvals, with Undo
11
+ * kinds · rowsFor(w, { lead }) · sig(w) the Today row (lib/needs-providers.js)
12
+ * cli(argv, { say, cwd }) `pmos setup [check|agree goal|owner "<name>"|undo]`
13
+ *
14
+ * THE EXIT TEST (Connect station). A product passes when its records show all three:
15
+ * tracker the tracker was read: a Jira status snapshot (<state>/tracker/jira/<initiative>.md, lib/jira-status.js) or the tracker read stamp
16
+ * (lib/tracker-read.js, `pmos tracker done`). Connecting the tracker is the person's: PMOS cannot do it for them.
17
+ * goal at least one AGREED goal: a key result of the OKR files (lib/okr-goals.js) not marked PROPOSED. A PROPOSED one is a draft PMOS
18
+ * offers for one approval (`pmos setup agree goal`).
19
+ * owner the Owner line of project-context.md (lib/project-onboard.js readContext). With none, PMOS offers the person who committed most
20
+ * in the last 90 days, from git, for one approval (`pmos setup owner "<name>"`).
21
+ * A record that cannot be read is "can't tell", never a pass (the plan's rule 1).
22
+ *
23
+ * THE GATE. Until Setup passes, only Triage and the documents part of Discovery run: the Driver may file problem, evidence, assumption, note,
24
+ * doc, artefact and overlap proposals and a move into a Triage or Discovery stage; sizing, stakeholders and any later move wait. It holds only
25
+ * while the product is NEW: when one of its initiatives already stands past Discovery (its records put it there, by the person or the tracker),
26
+ * the product is running and the gate stays open (the plan's rule 2, the outside wins). A product that cannot be read holds.
27
+ *
28
+ * THE LEDGER is <state>/setup.jsonl, one line per approval: { v: 1, ev: 'agree' | 'owner' | 'undo', file, before, after, at, by }. Undo puts
29
+ * the file back only while nobody changed it since. Nothing here sends anything or calls a model. Works on any product built with PMOS.
30
+ */
31
+ const fs = require('fs');
32
+ const path = require('path');
33
+ const { spawnSync } = require('child_process');
34
+
35
+ const TAG = '[setup]';
36
+ const NAME = 'setup-station';
37
+ const KIND = 'setup-station';
38
+ const LEDGER = 'setup.jsonl';
39
+ const OF = 3;
40
+ const DOC_WHATS = Object.freeze(['problem', 'evidence', 'assumption', 'note', 'doc', 'artefact', 'overlap']);
41
+ const OPEN_STEPS = Object.freeze(['triage', 'discover']);
42
+ const DISCOVER_STAGE = /\b(triage|discover|discovery|intake)\b/i;
43
+ const BOT = /\[bot\]|\bbot\b|^claude$|^github-actions|^dependabot|noreply@anthropic\.com|^noreply@github\.com$|^actions@github/i;
44
+ const LABEL = { tracker: 'tracker read', goal: 'an agreed goal', owner: 'an owner' };
45
+
46
+ const clip = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
47
+ const mtime = (f) => { try { return fs.statSync(f).mtimeMs; } catch { return 0; } };
48
+ const readText = (f) => { try { return fs.readFileSync(f, 'utf8'); } catch { return null; } };
49
+ const day = (ms) => new Date(ms).toISOString().slice(0, 10);
50
+
51
+ function stateDirOf(root) { try { return require('./driver.js').stateDirOf(root); } catch { return null; } }
52
+ function planningOf(root) {
53
+ try { const pm = require('./project-onboard.js').pmosIn(root); if (pm) return pm.planning; } catch { /* below */ }
54
+ return fs.existsSync(path.join(root, 'pmos', 'planning')) ? path.join(root, 'pmos', 'planning') : path.join(root, 'planning');
55
+ }
56
+ const okrDirOf = (root) => [path.join(root, 'pmos', 'planning', 'okrs'), path.join(root, 'planning', 'okrs')].find((d) => fs.existsSync(d)) || null;
57
+
58
+ // ── reading the records ──────────────────────────────────────────────────────────────────────────────────
59
+
60
+ function trackerOf(root, runtimeDir) {
61
+ const out = { at: 0, via: null };
62
+ try {
63
+ const sd = stateDirOf(root);
64
+ const j = sd ? require('./freshness.js').jiraAsOf(sd) : 0;
65
+ if (j > out.at) { out.at = j; out.via = 'Jira status read'; }
66
+ } catch { /* the other read answers */ }
67
+ try {
68
+ const t = runtimeDir ? require('./tracker-read.js').readAtMs(runtimeDir, root) : 0;
69
+ if (t > out.at) { out.at = t; out.via = 'tracker items read'; }
70
+ } catch { /* none */ }
71
+ return out;
72
+ }
73
+
74
+ function goalsOf(root) {
75
+ let okr;
76
+ try { okr = require('./okr-goals.js').read(root); } catch (e) { return { error: 'the OKR files could not be read' }; }
77
+ if (!okr.ok) return { agreed: [], proposed: [], files: [] };
78
+ const krs = okr.objectives.flatMap((o) => o.krs.map((k) => ({ token: `${o.token}.${k.token}`, kr: k.token, title: k.title, proposed: !!k.proposed })));
79
+ return { agreed: krs.filter((k) => !k.proposed), proposed: krs.filter((k) => k.proposed), files: okr.files };
80
+ }
81
+
82
+ function contextOf(root) {
83
+ const file = path.join(planningOf(root), 'project-context.md');
84
+ const text = readText(file);
85
+ if (text == null) return { file, exists: false, ctx: null };
86
+ try { return { file, exists: true, ctx: require('./project-onboard.js').readContext(text) }; } catch { return { file, exists: true, ctx: null, error: true }; }
87
+ }
88
+
89
+ /** The person who committed most in the last 90 days: a draft owner, with its source. null with no git or no commits. */
90
+ function ownerDraftOf(root) {
91
+ const r = spawnSync('git', ['shortlog', '-sne', '--no-merges', '--since=90.days', 'HEAD'], { cwd: root, encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
92
+ if (r.status !== 0) return null;
93
+ for (const line of String(r.stdout || '').split('\n')) {
94
+ const m = /^\s*(\d+)\s+(.+?)\s+<([^>]*)>\s*$/.exec(line);
95
+ if (!m || BOT.test(m[2]) || BOT.test(m[3])) continue; // an agent or a bot commits; it does not own the product
96
+ return { name: clip(m[2], 80), source: `git: ${m[1]} commit${m[1] === '1' ? '' : 's'} in the last 90 days, the most of any person` };
97
+ }
98
+ return null;
99
+ }
100
+
101
+ function read(root, { runtimeDir = null, ownerDraft = ownerDraftOf } = {}) {
102
+ const ctx = contextOf(root);
103
+ const owner = ctx.ctx && ctx.ctx.fields && ctx.ctx.fields.owner ? ctx.ctx.fields.owner : null;
104
+ const g = goalsOf(root);
105
+ return {
106
+ name: (ctx.ctx && ctx.ctx.name) || path.basename(path.resolve(root)),
107
+ tracker: trackerOf(root, runtimeDir),
108
+ goals: g.error ? { error: g.error } : g,
109
+ owner: ctx.error ? { error: 'project-context.md could not be read' } : owner ? { value: owner.value, source: owner.source, file: path.relative(root, ctx.file) } : null,
110
+ ownerDraft: owner || ctx.error ? null : (ownerDraft ? ownerDraft(root) : null),
111
+ goalDraft: ctx.ctx && ctx.ctx.goal ? ctx.ctx.goal : null,
112
+ };
113
+ }
114
+
115
+ // ── the exit test ────────────────────────────────────────────────────────────────────────────────────────
116
+
117
+ /** facts (read() or a test's) → { passed, met, of, items: [{ key, label, status: 'ok'|'missing'|"can't tell", quote }], missing, next }. PURE. */
118
+ function check(facts) {
119
+ const f = facts || {};
120
+ const items = [];
121
+ const t = f.tracker || {};
122
+ items.push(t.at > 0 ? { key: 'tracker', label: LABEL.tracker, status: 'ok', quote: `${t.via || 'tracker read'} on ${day(t.at)}` }
123
+ : { key: 'tracker', label: LABEL.tracker, status: 'missing', quote: 'no Jira status snapshot and no tracker read recorded' });
124
+ const g = f.goals || {};
125
+ if (g.error) items.push({ key: 'goal', label: LABEL.goal, status: "can't tell", quote: g.error });
126
+ else if ((g.agreed || []).length) items.push({ key: 'goal', label: LABEL.goal, status: 'ok', quote: `${g.agreed[0].token}: ${g.agreed[0].title}` + (g.agreed.length > 1 ? ` and ${g.agreed.length - 1} more` : '') });
127
+ else items.push({ key: 'goal', label: LABEL.goal, status: 'missing', quote: (g.proposed || []).length ? `${g.proposed.length} drafted, none agreed yet` : 'no goal in the OKR files' });
128
+ const o = f.owner;
129
+ if (o && o.error) items.push({ key: 'owner', label: LABEL.owner, status: "can't tell", quote: o.error });
130
+ else if (o && o.value) items.push({ key: 'owner', label: LABEL.owner, status: 'ok', quote: `${o.value} (${o.file || 'project-context.md'})` });
131
+ else items.push({ key: 'owner', label: LABEL.owner, status: 'missing', quote: 'no Owner line in project-context.md' });
132
+ const met = items.filter((i) => i.status === 'ok').length;
133
+ const missing = items.filter((i) => i.status !== 'ok').map((i) => i.label);
134
+ return { passed: met === OF, met, of: OF, items, missing, next: nextOf(items, f) };
135
+ }
136
+
137
+ /** The one ✦ proposal for what is still missing, in the order the person can act on it fastest: a drafted goal or owner first (one approval),
138
+ * then the tracker (the person connects it). null when nothing is missing. PURE. */
139
+ function nextOf(items, f) {
140
+ const miss = (k) => items.some((i) => i.key === k && i.status === 'missing');
141
+ const g = f.goals || {};
142
+ if (miss('goal') && (g.proposed || []).length) {
143
+ const p = g.proposed[0];
144
+ return { key: 'goal', label: 'Agree goal', text: `Agree the drafted goal ${p.token}: ${p.title}`, cli: 'pmos setup agree goal', source: (g.files || [])[0] || 'the OKR file' };
145
+ }
146
+ if (miss('goal') && f.goalDraft && f.goalDraft.kr) {
147
+ return { key: 'goal', label: 'Agree goal', text: `Agree the drafted goal: ${clip(f.goalDraft.kr, 120)}`, cli: 'pmos setup agree goal', source: 'project-context.md (Goal draft)' };
148
+ }
149
+ if (miss('owner') && f.ownerDraft && f.ownerDraft.name) {
150
+ return { key: 'owner', label: 'Keep owner', text: `Make ${f.ownerDraft.name} the owner`, cli: `pmos setup owner "${f.ownerDraft.name.replace(/"/g, '')}"`, source: f.ownerDraft.source };
151
+ }
152
+ if (miss('tracker')) return { key: 'tracker', label: 'Connect tracker', text: 'Connect the tracker in Settings › Sources; PMOS reads it on the next refresh', cli: 'pmos setup', source: null };
153
+ if (miss('goal')) return { key: 'goal', label: 'Add a goal', text: 'Add one goal: tell the chat what this product must achieve', cli: 'pmos setup', source: null };
154
+ if (miss('owner')) return { key: 'owner', label: 'Name owner', text: 'Name the owner: pmos setup owner "<name>"', cli: 'pmos setup', source: null };
155
+ return null;
156
+ }
157
+
158
+ // ── the gate ─────────────────────────────────────────────────────────────────────────────────────────────
159
+
160
+ /** Is the gate shut? steps: the lifecycle step of each initiative (lib/one-stage.js keys), or null when unreadable. PURE. */
161
+ function holds(result, steps) {
162
+ if (!result || result.passed) return false;
163
+ if (!Array.isArray(steps)) return true; // can't tell: hold
164
+ return !steps.some((s) => s && !OPEN_STEPS.includes(s));
165
+ }
166
+
167
+ /** May the Driver file this proposal now? PURE. */
168
+ function gate(result, steps, { what, data } = {}) {
169
+ if (!holds(result, steps)) return { ok: true };
170
+ if (DOC_WHATS.includes(what)) return { ok: true };
171
+ if (what === 'move' && data && DISCOVER_STAGE.test(String(data.to || ''))) return { ok: true };
172
+ return { ok: false, error: `this product has not passed Setup yet (missing: ${result.missing.join(', ')}), so only Triage and the documents part of Discovery run: a ${what} proposal waits. See pmos setup` };
173
+ }
174
+
175
+ /** The lifecycle step of every initiative of the product, as the Board reads it. null when the records cannot be read. */
176
+ const RUNNING_FILE = 'setup-running.json';
177
+ const RUNNING_FOR_MS = 24 * 3600 * 1000;
178
+ function stepsOf(root, { now = Date.now(), derive = true } = {}) {
179
+ // reading every stage derives the Board's rows (seconds on a big product); a product seen running stays running for a day
180
+ // the cache is runtime state, never a repository file: <runtime>/setup/<hash of the repository path>.json
181
+ const rd = runtimeDirOf();
182
+ const cache = rd ? path.join(rd, 'setup', require('crypto').createHash('sha1').update(path.resolve(root)).digest('hex').slice(0, 16) + '-' + RUNNING_FILE) : null;
183
+ try { const c = JSON.parse(readText(cache) || 'null'); if (c && c.step && now - Date.parse(c.at) < RUNNING_FOR_MS) return [c.step]; } catch { /* read again */ }
184
+ const steps = readSteps(root, derive);
185
+ const past = (steps || []).find((x) => x && !OPEN_STEPS.includes(x));
186
+ if (past && cache) { try { writeFile(cache, JSON.stringify({ step: past, at: new Date(now).toISOString() }) + '\n'); } catch { /* read again next time */ } }
187
+ return steps;
188
+ }
189
+ function readSteps(root, derive) {
190
+ try {
191
+ const SR = require('./stage-read.js');
192
+ const boards = require('./routes-boards.js');
193
+ const rowsLib = require('./initiative-rows.js');
194
+ const { w, ctx } = SR.cliCtx(root);
195
+ if (!ctx.stateDirFor()) return null;
196
+ // derive: true (a terminal) reads the records now; false (the server's Today row) takes the rows the server already read, and a read
197
+ // still running answers null, "can't tell"
198
+ const was = derive ? rowsLib.setBackground(false) : null;
199
+ try {
200
+ if (derive) { try { rowsLib.deriveNow(root); } catch { /* baseRows says */ } }
201
+ const base = boards.baseRows(w, { ...ctx, boardsPass: new Map() });
202
+ if (!base.ok) return null;
203
+ // one fold of the Board for the whole list; it stops at the first initiative past Discovery, since one is enough to open the gate
204
+ const pass = { ...ctx, boardsPass: new Map() };
205
+ const out = [];
206
+ for (const r of base.rows) {
207
+ let a = null; try { a = SR.stageOf(pass, w, r.id); } catch { a = null; }
208
+ const step = a ? (a.stage === 'shipped' ? 'monitor' : a.step || null) : null;
209
+ out.push(step);
210
+ if (step && !OPEN_STEPS.includes(step)) break;
211
+ }
212
+ return out;
213
+ } finally { if (derive) rowsLib.setBackground(was); }
214
+ } catch { return null; }
215
+ }
216
+
217
+ // ── the person's approvals, with Undo ───────────────────────────────────────────────────────────────────
218
+
219
+ function ledgerFile(root) { const sd = stateDirOf(root); return sd ? path.join(sd, LEDGER) : null; }
220
+ function readLedger(root) {
221
+ const f = ledgerFile(root);
222
+ const t = f ? readText(f) : null;
223
+ if (!t) return [];
224
+ return t.split('\n').map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
225
+ }
226
+ function append(root, line, now) {
227
+ const f = ledgerFile(root);
228
+ if (!f) throw new Error('this repository has no PMOS state folder (pmos/state, state or .pmos)');
229
+ const rec = { v: 1, ...line, at: new Date(now).toISOString() };
230
+ fs.appendFileSync(f, JSON.stringify(rec) + '\n');
231
+ return rec;
232
+ }
233
+ function writeFile(file, text) {
234
+ fs.mkdirSync(path.dirname(file), { recursive: true });
235
+ const tmp = `${file}.${process.pid}.tmp`;
236
+ fs.writeFileSync(tmp, text);
237
+ fs.renameSync(tmp, file);
238
+ }
239
+
240
+ /** Keep the drafted goal: the first PROPOSED key result of the OKR files loses its PROPOSED mark. With no OKR file and a Goal draft in
241
+ * project-context.md, the draft file is written as agreed. → { ok, file, goal } | { ok: false, error } */
242
+ function agreeGoal(root, { now = Date.now(), by = 'pm' } = {}) {
243
+ const dir = okrDirOf(root);
244
+ const g = goalsOf(root);
245
+ if (g.error) return { ok: false, error: g.error };
246
+ if (dir && g.proposed.length) {
247
+ for (const name of g.files) {
248
+ const file = path.join(dir, name);
249
+ const before = readText(file);
250
+ if (before == null) continue;
251
+ const lines = before.split('\n');
252
+ const i = lines.findIndex((l) => /\bPROPOSED\b/.test(l) && /\*\*\s*KR/i.test(l));
253
+ if (i < 0) continue;
254
+ lines[i] = lines[i].replace(/\s*\bPROPOSED\b:?\s*/, ' ').replace(/\*\* +/, '** ');
255
+ const after = lines.join('\n');
256
+ writeFile(file, after);
257
+ append(root, { ev: 'agree', file: path.relative(root, file), before, after, by }, now);
258
+ return { ok: true, file: path.relative(root, file), goal: clip(lines[i].replace(/^\s*-\s*/, ''), 160) };
259
+ }
260
+ }
261
+ const ctx = contextOf(root);
262
+ const draft = ctx.ctx && ctx.ctx.goal;
263
+ if (!draft || !draft.kr) return { ok: false, error: g.agreed.length ? 'a goal is agreed already' : 'there is no drafted goal to agree: tell the chat what this product must achieve' };
264
+ const file = path.join(planningOf(root), 'okrs', 'okrs-draft.md');
265
+ if (fs.existsSync(file)) return { ok: false, error: `${path.relative(root, file)} holds no drafted key result to agree` };
266
+ const OF_ = require('./onboard-fundamentals.js');
267
+ const after = OF_.goalFile(ctx.ctx.name || path.basename(root), draft, ctx.ctx.fields && ctx.ctx.fields.purpose && ctx.ctx.fields.purpose.value, day(now))
268
+ .replace(/\s*\bPROPOSED\b:?\s*/, ' ').replace(/\*\* +/, '** ').replace(' (draft)"', '"').replace(/^# Goals: (.+) \(draft\)$/m, '# Goals: $1')
269
+ .replace(/It is a draft: nothing reads it, and no number is claimed\./, 'The PM agreed it; no number is claimed yet.');
270
+ writeFile(file, after);
271
+ append(root, { ev: 'agree', file: path.relative(root, file), before: null, after, by }, now);
272
+ return { ok: true, file: path.relative(root, file), goal: clip(draft.kr, 160) };
273
+ }
274
+
275
+ /** Name the owner: the Owner line of project-context.md, said by the PM. The file is made when there is none. */
276
+ function setOwner(root, name, { now = Date.now(), by = 'pm' } = {}) {
277
+ const who = clip(name, 80).replace(/[()]/g, '');
278
+ if (!who) return { ok: false, error: 'give the owner\'s name: pmos setup owner "<name>"' };
279
+ const { file } = contextOf(root);
280
+ const before = readText(file);
281
+ const line = `- **Owner:** ${who} (source: the PM)`;
282
+ let after;
283
+ if (before == null) {
284
+ const title = path.basename(path.resolve(root));
285
+ after = ['---', 'type: Reference', `title: "Project context: ${title.replace(/"/g, "'")}"`, `timestamp: ${day(now)}`, '---', '', `# ${title}`, '', line, ''].join('\n');
286
+ } else if (/^- \*\*Owner:\*\*.*$/m.test(before)) after = before.replace(/^- \*\*Owner:\*\*.*$/m, line);
287
+ else after = before.replace(/\n*$/, '\n') + line + '\n';
288
+ writeFile(file, after);
289
+ append(root, { ev: 'owner', file: path.relative(root, file), before, after, by }, now);
290
+ return { ok: true, file: path.relative(root, file), owner: who };
291
+ }
292
+
293
+ /** Undo the newest approval not undone yet, while its file still holds what it wrote. */
294
+ function undo(root, { now = Date.now(), by = 'pm' } = {}) {
295
+ const lines = readLedger(root);
296
+ const undone = new Set(lines.filter((l) => l.ev === 'undo').map((l) => l.of));
297
+ const last = [...lines].reverse().find((l) => (l.ev === 'agree' || l.ev === 'owner') && !undone.has(l.at + '|' + l.file));
298
+ if (!last) return { ok: false, error: 'nothing to undo' };
299
+ const file = path.join(root, last.file);
300
+ if (readText(file) !== last.after) return { ok: false, error: `${last.file} changed since, so it is left as it is` };
301
+ if (last.before == null) fs.unlinkSync(file); else writeFile(file, last.before);
302
+ append(root, { ev: 'undo', of: last.at + '|' + last.file, file: last.file, by }, now);
303
+ return { ok: true, file: last.file, what: last.ev };
304
+ }
305
+
306
+ // ── the Today row (lib/needs-providers.js) ──────────────────────────────────────────────────────────────
307
+
308
+ function runtimeDirOf() { try { return require('./state-root.js').defaultRoot(); } catch { return null; } }
309
+
310
+ function rowsFor(w, { lead, runtimeDir = runtimeDirOf(), facts, steps } = {}) {
311
+ if (!lead || !w || !w.root) return [];
312
+ const f = facts || read(w.root, { runtimeDir });
313
+ const r = check(f);
314
+ if (r.passed) return [];
315
+ // no row (zero is silence) for: a product with no initiative yet (nothing to hold), a running product (an initiative past Discovery),
316
+ // and a product whose stages cannot be read yet ("can't tell")
317
+ const st = steps !== undefined ? steps : stepsOf(w.root, { derive: false });
318
+ if (!Array.isArray(st) || !st.length || !holds(r, st)) return [];
319
+ const name = w.name || f.name;
320
+ const cause = `Set up ${name}: ${r.met} of ${r.of} done, ${r.missing.join(' and ')} still missing`;
321
+ const evidence = [r.next ? `✦ ${r.next.text}` + (r.next.source ? ` (from ${r.next.source})` : '') : '', 'Until then PMOS runs only Triage and the documents part of Discovery here']
322
+ .filter(Boolean).join(' · ');
323
+ return [{
324
+ run_id: `${NAME}:${w.id}`, kind: KIND, initiative_id: null, question: cause, doc: null, ws: w.id,
325
+ today: { kind: 7, source: NAME, cause, evidence, act: { label: r.next ? r.next.label : 'See setup', cli: r.next ? r.next.cli : 'pmos setup' } },
326
+ }];
327
+ }
328
+
329
+ function sig(w) {
330
+ if (!w || !w.root) return '';
331
+ const sd = stateDirOf(w.root);
332
+ const okr = okrDirOf(w.root);
333
+ let okrSig = '-';
334
+ try { okrSig = okr ? fs.readdirSync(okr).map((n) => n + ':' + mtime(path.join(okr, n))).join(',') : '-'; } catch { /* - */ }
335
+ let jira = 0; try { jira = sd ? require('./freshness.js').jiraAsOf(sd) : 0; } catch { /* 0 */ }
336
+ let tr = 0; try { const rd = runtimeDirOf(); tr = rd ? require('./tracker-read.js').readAtMs(rd, w.root) : 0; } catch { /* 0 */ }
337
+ return [okrSig, mtime(path.join(planningOf(w.root), 'project-context.md')), jira, tr, sd ? mtime(path.join(sd, LEDGER)) : 0].join('|');
338
+ }
339
+
340
+ // ── the command line ─────────────────────────────────────────────────────────────────────────────────────
341
+
342
+ const USAGE = [
343
+ 'usage: pmos setup [check|agree goal|owner "<name>"|undo] [--json] [--root <dir>] — the Setup station of this product',
344
+ ' pmos setup what Setup still needs: a tracker read, an agreed goal and an owner; the number met on the last line',
345
+ ' pmos setup agree goal keep the goal PMOS drafted (it loses its PROPOSED mark)',
346
+ ' pmos setup owner "<n>" name the owner in project-context.md',
347
+ ' pmos setup undo take the last of these two back, while nobody changed the file since',
348
+ ];
349
+ const COMMANDS = { setup: ['check', 'agree', 'owner', 'undo'] };
350
+
351
+ function cli(argv, { say = (s) => console.log(s), cwd = process.cwd(), now = Date.now(), runtimeDir = runtimeDirOf(), ownerDraft } = {}) {
352
+ const args = argv.slice();
353
+ const json = args.includes('--json');
354
+ const ri = args.indexOf('--root');
355
+ let root = null;
356
+ if (ri >= 0) { root = args[ri + 1]; args.splice(ri, 2); }
357
+ const pos = args.filter((a) => !a.startsWith('--'));
358
+ const verb = pos[0] || 'check';
359
+ if (['help', '-h'].includes(verb) || args.includes('--help')) { for (const l of USAGE) say(l); return 0; }
360
+ const top = () => { const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : cwd; };
361
+ root = path.resolve(cwd, root || (verb === 'check' && pos[1]) || top());
362
+ const out = (o, text) => { if (json) say(JSON.stringify(o)); else for (const l of [].concat(text)) say(l); };
363
+ if (verb === 'check') {
364
+ const f = read(root, { runtimeDir, ...(ownerDraft !== undefined ? { ownerDraft } : {}) });
365
+ const r = check(f);
366
+ const steps = r.passed ? [] : stepsOf(root);
367
+ const held = holds(r, steps);
368
+ out({ ok: true, ...r, holds: held }, [
369
+ `${TAG} ${f.name}: ${r.passed ? 'Setup passed' : `${r.met} of ${r.of} exit items met`}`,
370
+ ...r.items.map((i) => `${TAG} ${i.status === 'ok' ? '✓' : i.status === 'missing' ? '○' : '?'} ${i.label}: ${i.quote}`),
371
+ ...(r.next ? [`${TAG} ✦ ${r.next.text}${r.next.source ? ` (from ${r.next.source})` : ''}. Say yes and run: ${r.next.cli}`] : []),
372
+ ...(r.passed ? [] : [held ? `${TAG} Until then PMOS runs only Triage and the documents part of Discovery here.` : `${TAG} Work here is already past Discovery, so nothing waits on Setup.`]),
373
+ String(r.met),
374
+ ]);
375
+ return 0;
376
+ }
377
+ let res;
378
+ if (verb === 'agree') {
379
+ if (pos[1] !== 'goal') { say('usage: pmos setup agree goal'); return 2; }
380
+ res = agreeGoal(root, { now });
381
+ if (res.ok) out(res, `✓ goal agreed in ${res.file}: ${res.goal}. Undo: pmos setup undo`);
382
+ } else if (verb === 'owner') {
383
+ res = setOwner(root, pos.slice(1).join(' '), { now });
384
+ if (res.ok) out(res, `✓ owner is ${res.owner} (${res.file}). Undo: pmos setup undo`);
385
+ } else if (verb === 'undo') {
386
+ res = undo(root, { now });
387
+ if (res.ok) out(res, `✓ undone: the ${res.what === 'agree' ? 'agreed goal' : 'owner'} in ${res.file} is back as it was`);
388
+ } else { say(`unknown setup command "${verb}"`); for (const l of USAGE) say(l); return 2; }
389
+ if (!res.ok) { out(res, `✗ ${res.error}`); return 1; }
390
+ console.error(`${TAG} ${verb} ${path.basename(root)}: ${res.file}`);
391
+ return 0;
392
+ }
393
+
394
+ module.exports = {
395
+ NAME, KIND, LEDGER, DOC_WHATS, USAGE, COMMANDS,
396
+ read, check, holds, gate, stepsOf, agreeGoal, setOwner, undo, readLedger, cli,
397
+ kinds: [KIND], rowsFor, sig,
398
+ };
399
+
400
+ if (require.main === module) process.exitCode = cli(process.argv.slice(2));
@@ -28,6 +28,9 @@
28
28
  * OWNER (A440). Jira's assignee becomes the owner when PMOS has none, an agent id, or the owner the task was made or imported with.
29
29
  * An owner someone set later by hand stays: syncOf names the difference. An unassigned ticket clears nothing, and an assignee that is
30
30
  * a bot or an agent is never taken. "Dana" and "Dana Lee" are the same person.
31
+ * SPRINT DATES (product line slice 3, "Discovery reads tracker assignees and sprints"). An open task whose ticket is in an active or planned
32
+ * sprint with a start and an end takes those days as its start and due, unless someone set the task's dates by hand after it was made.
33
+ * A closed sprint, a backlog ticket or a sprint with no dates changes nothing. The task's own dates stay in the ledger; the read is in memory.
31
34
  * SYNC (A439). After the read is applied, a task the read returned is in sync when its state, done day and owner match the reading.
32
35
  * pct = in sync ÷ read; the tasks the read did not return are counted apart (unread). quiet at 95% or more (zero is silence).
33
36
  * STALE. The Jira read is due every day: a read older than 26 hours (lib/freshness.js, jira stale_after_ms) is stale, and so is a task
@@ -38,6 +41,7 @@
38
41
  const H = 3600 * 1000;
39
42
  const STALE_MS = 26 * H;
40
43
  const BY = 'tracker:jira';
44
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
41
45
  const LEAD_KEY = /^\s*\[?([A-Z][A-Z0-9_]{0,19}-\d{1,7})\]?(?![A-Za-z0-9-])/;
42
46
  const CLOSED_NOT_DONE = /invalid|not an issue|won'?t|cancel|duplicate|reject|obsolete|not (?:needed|required|a bug)|declined|abandon/i;
43
47
  const TASK_KINDS = new Set(['task', 'task-update', 'task-remove', 'task-restore']);
@@ -60,7 +64,8 @@ function keyedTasks(lines) {
60
64
  if (all.has(e.task) || typeof e.initiative !== 'string') continue;
61
65
  // stateAt is the time someone CHANGED the state: the state a task was created (or imported) with is no decision
62
66
  all.set(e.task, { task: e.task, initiative: e.initiative, title: String(e.title || ''), state: e.state || 'To do', stateAt: null,
63
- owner: typeof e.owner === 'string' && e.owner.trim() ? e.owner.trim() : null, ownerAt: null, since: null, dayByHand: false });
67
+ owner: typeof e.owner === 'string' && e.owner.trim() ? e.owner.trim() : null, ownerAt: null, since: null, dayByHand: false,
68
+ start: DAY_RE.test(String(e.start || '')) ? e.start : null, due: DAY_RE.test(String(e.due || '')) ? e.due : null, datesByHand: false });
64
69
  } else if (e.kind === 'task-update') {
65
70
  const t = all.get(e.task); if (!t) continue;
66
71
  if (typeof e.initiative === 'string' && e.initiative) t.initiative = e.initiative;
@@ -72,6 +77,8 @@ function keyedTasks(lines) {
72
77
  t.dayByHand = typeof e.happened === 'string' && e.by !== BY;
73
78
  }
74
79
  if (typeof e.owner === 'string') { t.owner = e.owner.trim() || null; if (e.by !== BY) t.ownerAt = e.at || t.ownerAt || 'by-hand'; }
80
+ // SPRINT DATES: a start or due someone wrote after the task was made is theirs; the tracker's own lines are not
81
+ for (const k of ['start', 'due']) if (k in e && e.kind === 'task-update') { t[k] = DAY_RE.test(String(e[k] || '')) ? e[k] : null; if (e.by !== BY) t.datesByHand = true; }
75
82
  } else if (e.kind === 'task-remove') {
76
83
  if (all.has(e.task)) { removed.set(e.task, all.get(e.task)); all.delete(e.task); }
77
84
  } else if (e.kind === 'task-restore') {
@@ -149,6 +156,11 @@ function trackerLines(lines, snapOf) {
149
156
  // OWNER (A440): Jira's assignee, unless someone set the owner by hand
150
157
  const who = humanAssignee(rd.assignee);
151
158
  if (who && !samePerson(who, t.owner) && (!t.ownerAt || isAgent(t.owner))) { line.owner = who; why.push(`Jira assignee ${who}`); }
159
+ // SPRINT DATES (product line slice 3): an open task takes its ticket's active or next sprint as its start and due day
160
+ const sp = sprintDays(rd.sprint);
161
+ if (sp && !t.datesByHand && state !== 'Done' && state !== "Won't do" && (t.start !== sp.start || t.due !== sp.end)) {
162
+ line.start = sp.start; line.due = sp.end; why.push(`Jira sprint ${sp.name}, ${sp.start} to ${sp.end}`);
163
+ }
152
164
  if (!Object.keys(line).length) continue;
153
165
  out.push({ at: s.fetchedAt, by: BY, kind: 'task-update', task: t.task, ...line, tracker: true,
154
166
  why: `${why.join('; ')} (${t.key}, read ${String(s.fetchedAt).slice(0, 16).replace('T', ' ')} UTC)` });
@@ -156,6 +168,13 @@ function trackerLines(lines, snapOf) {
156
168
  return out.sort((a, b) => String(a.at).localeCompare(String(b.at)));
157
169
  }
158
170
 
171
+ /** The days of a ticket's sprint, when it is active or planned and has both: { name, start, end } | null. A closed sprint gives none. */
172
+ function sprintDays(sp) {
173
+ if (!sp || typeof sp !== 'object' || sp.state === 'closed') return null;
174
+ const start = String(sp.start || '').slice(0, 10), end = String(sp.end || '').slice(0, 10);
175
+ if (!DAY_RE.test(start) || !DAY_RE.test(end) || start > end) return null;
176
+ return { name: String(sp.name || 'sprint').slice(0, 60), start, end };
177
+ }
159
178
  function snapMemo(snapOf) {
160
179
  const snaps = new Map();
161
180
  return (ini) => { if (!snaps.has(ini)) { let s = null; try { s = snapOf(ini) || null; } catch { s = null; } snaps.set(ini, s); } return snaps.get(ini); };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.753.0",
3
+ "version": "0.755.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.753.0",
9
+ "version": "0.755.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/sdk": "^1.3.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.753.0",
3
+ "version": "0.755.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -15,7 +15,7 @@ output:
15
15
  The prompt that starts this run names the target, the reason the run started, the stage category and what the PM already kept. Work on that target only.
16
16
 
17
17
  Rules that always hold:
18
- 1. THE ONLY WRITES are `pmos driver propose`, `pmos coredoc write` (a draft of a core document of this initiative, nothing else), `pmos jira guesses` (the dry run of its drafted tickets, step 9) and `pmos signoff ask|answer` (its outside sign-offs, step 10). You have no Write and no Edit tool. Do not change a repository file, do not commit, do not push, and do not move the initiative to another stage. Keeping a proposal is the PM's act, not yours.
18
+ 1. THE ONLY WRITES are `pmos driver propose`, `pmos coredoc write` (a draft of a core document of this initiative, nothing else), `pmos jira guesses` (the dry run of its drafted tickets, step 9) and `pmos signoff ask|answer` (its outside sign-offs, step 10). You have no Write and no Edit tool. Do not change a repository file, do not commit, do not push, and do not move the initiative to another stage yourself: propose the move (step 11), and the Checker's quote check decides whether it applies. Keeping any other proposal is the PM's act, not yours.
19
19
  2. SEND NOTHING. Never send, reply, forward, post, comment, react, create, transition or label anything in mail, Slack, Jira, Confluence, GitHub, Drive, Figma or any other source. Read a connector only where it is already allowed. If a tool is refused, say so in your answer and go on without it.
20
20
  3. EVERY CLAIM CARRIES A POINTER. A pointer is a Jira key, a Slack link, a meeting note path, a requirement note path or a document path. Give it with `--source label=ref`. A claim you cannot point at is not a claim: leave it out. An evidence line with no pointer is not evidence: leave it out.
21
21
  4. NOTHING INVENTED. Write only what you read. Say "not known" and name who could tell you. A run that finds nothing new is a correct run: file nothing.
@@ -24,7 +24,7 @@ Rules that always hold:
24
24
  7. ONE RUN, FEW PROPOSALS. File at most five proposals. Each one is short and stands alone.
25
25
 
26
26
  Procedure:
27
- 1. Orient. Run `pmos driver status initiative <id>`. Read the initiative record (`planning/initiatives/<id>.md`, or `pmos/state/initiatives/<id>.md`) and every file it names: PRD, brief, requirement notes. Run `pmos initiative list` to see the other open initiatives.
27
+ 1. Orient. Run `pmos driver exits <id>` first: it gives the station on the initiative's own workflow, the exit items (To finish lines) still missing, the next move, and who holds each Jira ticket in which sprint. When it says not to work the exit items (the line marks the initiative waiting or can't tell), file nothing about the stage and no move: say so under Blocker. Otherwise the missing exit items are this run's work, in the order given, before anything else in this procedure. Then run `pmos driver status initiative <id>`. Read the initiative record (`planning/initiatives/<id>.md`, or `pmos/state/initiatives/<id>.md`) and every file it names: PRD, brief, requirement notes. Run `pmos initiative list` to see the other open initiatives.
28
28
  2. Check first for a prior rejection and a duplicate. Search `planning/out-of-scope/` for the idea (Grep on its key words). Compare the title and the intent with the other open initiatives.
29
29
  - A prior rejection: file a `note` proposal first that names the file, quotes what it says in one line, and says why this one is the same or different.
30
30
  - Another open initiative that overlaps: file `--what overlap` with a JSON file, never a `note`: `{"with": "<the other initiative's id>", "parts": <how many parts of this plan overlap>, "of": <how many parts this plan has>, "items": ["<one part that overlaps, in plain words>"], "sure": "high|medium|low", "sureWhy": "<one line: what you read that makes you that sure>", "first": "this|other", "firstWhy": "<one line: why that one goes first>", "text": "<one sentence: what overlaps and what is separate>"}`. Give only the fields you know: leave out parts and of when the plans have no parts you can count. Never file an overlap with an initiative the prompt says the PM marked as not an overlap.
@@ -38,7 +38,7 @@ Procedure:
38
38
  e. People. Who to ask and why, one line each, with the pointer that names them (`field: people`).
39
39
  f. Done test. The checks that will say the experiment is done, one proposal per check: `{"artefact": "done-test", "field": "check", "text": "<a check someone can run>"}`. The done test comes before any build (D13 as amended by D107).
40
40
  g. Intent, only when a record you read changes it. The product's Intent (what we want, the limits, what we will not do) is the PM's: you never write it, and your proposal waits for the PM on the product page. To add one line, file `{"artefact": "intent", "field": "limits", "op": "add", "text": "<one line>"}` (field `want`, `limits` or `not`) with the `--source` that says it. Leave out `op` only to replace the whole field.
41
- h. When the problem (a), the evidence (b) and the budget (d) are all kept, propose the move to Plan. File `--what move` with `{"to": "<the name of the first Plan stage of this initiative's workflow>"}` and a `--why` that says what the PM can now decide. You only propose it. The PM moves the stage.
41
+ h. When `pmos driver exits <id>` says every exit item is done, propose the move it names (step 11).
42
42
  5. Plan, Do and Learn. Do not write the missing work yourself. Name the blocker the prompt gives, check that it is true, and propose what would clear it:
43
43
  - Plan: no PRD, no done-criteria, or no anchor. File a `note` that says which is missing and what the PM could do (for a PRD, which requirement notes and evidence it could start from; for an anchor, which KR or health budget fits, with the pointer to it).
44
44
  - Do: no ticket moved, or a ticket is blocked. File a `note` with the ticket keys, how long they have not moved and who could unblock them.
@@ -61,6 +61,11 @@ Procedure:
61
61
  c. Write `{"tickets": [{"id": "<ticket id>", "guesses": [{"question": "…", "prd": ["<quoted line>"], "answered": "yes|partly|no", "default": "<one line>"}]}]}` to a file in your scratch folder and run `pmos jira guesses <id> --from <file>`. PMOS copies the quoted lines into the tickets and puts the gaps on the PM's question list. Never answer a gap yourself, and never keep a default for the PM: the PM answers with `pmos jira answer`.
62
62
  10. Outside sign-offs (Plan and Do). Run `pmos signoff list <id>`. Read the PRD, the record and the notes for each yes the work waits on from someone outside the team (a scope, a price, wording, a go or no-go). For each one not listed, run `pmos signoff ask <id> --who "<name or team>" --what "<what they must say yes to>" --asked <date> [--due <date>] --source "<pointer>"`. When a source you read shows the answer, run `pmos signoff answer <signoff id> --answer "<what they said>" --source "<pointer>"`. Never record an answer you cannot point at. PMOS puts the open ones on the PM's question list.
63
63
 
64
+ 11. The stage move. Propose it only when `pmos driver exits <id>` says every exit item is done and names the next move. File `--what move` with a JSON file:
65
+ `{"to": "<the next stage's name>", "from": "<the key of the stage it leaves, as exits prints it>", "exits": [{"item": "<one To finish line, word for word>", "quote": "<one line copied word for word from the record that shows it is done>", "ref": "<that record's path in the repository, or its Jira key>"}]}`
66
+ Give one entry for EVERY To finish line of the stage it leaves. A quote is at least 12 characters, copied exactly: the Checker looks for it in the file or the Jira reading you name. A link PMOS cannot read fails the check. When every quote is found, the move applies with Undo; when one is not found, the move waits for the PM. When the initiative moved since (the PM or Jira moved it), `pmos driver propose` refuses: do not file it again.
67
+ 12. Owners and dates from the tracker. When you draft tasks, a scope or a timeline, take each owner from the ticket's assignee and each date from the ticket's sprint, as `pmos driver exits <id>` lists them, and cite the ticket key. A task that names a ticket key at the start of its title already takes them by itself: do not propose them again.
68
+
64
69
  Output contract — produce EXACTLY these sections in your final message:
65
70
  - Filed (the proposal ids and their kinds, or "nothing new")
66
71
  - Skipped (what you did not file and why: already kept, no pointer, nothing found)
@@ -0,0 +1,9 @@
1
+ {
2
+ "_comment": "The Driver follows the line (initiative driver-follows-line, done test D1-D9): exit-item wakes, the Checker's quote gate before PMOS moves a stage, the doubtful-Evaluate and waiting-on-another-initiative flags, sprint dates on Jira tasks. Pure checks plus one scratch repository through pmos driver. No server, model or network.",
3
+ "modules": [
4
+ "line-driver.test.js"
5
+ ],
6
+ "seconds": {
7
+ "line-driver.test.js": 15
8
+ }
9
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "_comment": "setup-station: a new product passes a Setup station (tracker read, agreed goal, owner) before PMOS plans its work; the Driver gate, the Today row and pmos setup (lib/setup-station.js, lib/setup-cli.js). Temp product folders only.",
3
+ "modules": [
4
+ "setup-station.test.js"
5
+ ],
6
+ "seconds": {
7
+ "setup-station.test.js": 2
8
+ }
9
+ }