create-pmos 0.422.0 → 0.424.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 (102) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/board-programs-test.js +28 -0
  8. package/workspace/briefing-premium-adddoc-test.js +1 -1
  9. package/workspace/briefing-premium-board-test.js +12 -10
  10. package/workspace/briefing-premium-initiative-test.js +30 -38
  11. package/workspace/briefing-premium-products-test.js +16 -3
  12. package/workspace/changelog.json +24 -0
  13. package/workspace/guide/briefing-premium.md +1 -1
  14. package/workspace/guide/claude-proposes.md +37 -0
  15. package/workspace/guide/home.md +9 -2
  16. package/workspace/guide/index.md +1 -0
  17. package/workspace/guide/programs.md +1 -0
  18. package/workspace/guide/workflows.md +5 -1
  19. package/workspace/home-pill-test.js +138 -0
  20. package/workspace/ini-workflow-test.js +4 -4
  21. package/workspace/lib/board-premium.js +3 -2
  22. package/workspace/lib/custom-docs.js +65 -3
  23. package/workspace/lib/engine/boards.js +25 -2
  24. package/workspace/lib/headless.js +14 -1
  25. package/workspace/lib/initiative-writer.js +63 -1
  26. package/workspace/lib/plan-items.js +36 -5
  27. package/workspace/lib/pmos-verbs.js +3 -0
  28. package/workspace/lib/programs.js +11 -3
  29. package/workspace/lib/proposal-runs.js +148 -0
  30. package/workspace/lib/proposals.js +370 -0
  31. package/workspace/lib/propose-cli.js +96 -0
  32. package/workspace/lib/route-modules.js +2 -0
  33. package/workspace/lib/routes-board-premium.js +33 -0
  34. package/workspace/lib/routes-boards.js +50 -10
  35. package/workspace/lib/routes-initiatives.js +12 -0
  36. package/workspace/lib/routes-proposals.js +325 -0
  37. package/workspace/lib/routes-task-links.js +336 -0
  38. package/workspace/lib/split-merge-suggest.js +162 -0
  39. package/workspace/lib/split-merge.js +379 -0
  40. package/workspace/lib/task-cli.js +58 -5
  41. package/workspace/lib/task-items.js +14 -2
  42. package/workspace/lib/task-links.js +422 -0
  43. package/workspace/package-lock.json +2 -2
  44. package/workspace/package.json +1 -1
  45. package/workspace/premium-board-actions-test.js +4 -4
  46. package/workspace/premium-core-doc-issue-test.js +2 -2
  47. package/workspace/premium-vw-backlog-test.js +3 -3
  48. package/workspace/premium-vw-item-test.js +3 -3
  49. package/workspace/premium-vw-jira-test.js +6 -6
  50. package/workspace/product-lane-test.js +165 -0
  51. package/workspace/program-panel-test.js +1 -1
  52. package/workspace/public/pm/bd-asks.js +3 -0
  53. package/workspace/public/pm/bd-ini-panel.js +16 -6
  54. package/workspace/public/pm/bd-prog.js +6 -1
  55. package/workspace/public/pm/bd-span.js +69 -15
  56. package/workspace/public/pm/bd-views.js +3 -2
  57. package/workspace/public/pm/cozy-board.css +10 -0
  58. package/workspace/public/pm/cozy-today.css +23 -0
  59. package/workspace/public/pm/cozy-viewer.js +14 -3
  60. package/workspace/public/pm/cozy-vw-shell.css +8 -0
  61. package/workspace/public/pm/home-app.js +45 -14
  62. package/workspace/public/pm/home-ini-model.js +0 -34
  63. package/workspace/public/pm/home-ini.js +72 -204
  64. package/workspace/public/pm/home-task.js +2 -1
  65. package/workspace/public/pm/home-today.js +66 -16
  66. package/workspace/public/pm/ini-groups.js +253 -0
  67. package/workspace/public/pm/ini-links.js +519 -0
  68. package/workspace/public/pm/ini-props.js +218 -0
  69. package/workspace/public/pm/ini-tasks.js +58 -22
  70. package/workspace/public/pm/ini-versions.js +14 -9
  71. package/workspace/public/pm/ini-view-model.js +93 -4
  72. package/workspace/public/pm/ini-view.css +306 -18
  73. package/workspace/public/pm/ini-view.js +161 -36
  74. package/workspace/public/pm/premium-board.js +54 -6
  75. package/workspace/public/pm/premium-vw-item.js +2 -1
  76. package/workspace/public/pm/split-merge.css +77 -0
  77. package/workspace/public/pm/split-merge.js +265 -0
  78. package/workspace/public/pm/stage-line.js +414 -0
  79. package/workspace/public/pm/task-card.css +13 -0
  80. package/workspace/public/pm/task-card.js +42 -5
  81. package/workspace/public/pm/wf-page.css +2 -0
  82. package/workspace/public/pm/wf-page.js +2 -0
  83. package/workspace/public/pm/wf-stage.js +2 -1
  84. package/workspace/server.js +52 -3
  85. package/workspace/skills/initiative-propose.skill +45 -0
  86. package/workspace/split-merge-ui-test.js +175 -0
  87. package/workspace/stage-card-test.js +13 -12
  88. package/workspace/task-card-test.js +3 -2
  89. package/workspace/task-delete-test.js +126 -0
  90. package/workspace/task-links-test.js +239 -0
  91. package/workspace/task-milestones-test.js +1 -1
  92. package/workspace/task-plans-test.js +6 -0
  93. package/workspace/task-views-test.js +1 -1
  94. package/workspace/test-lists/bd-ini-panel.json +8 -2
  95. package/workspace/test-lists/claude-proposes.json +5 -0
  96. package/workspace/test-lists/home-sessions-pill.json +6 -0
  97. package/workspace/test-lists/product-lane.json +6 -0
  98. package/workspace/test-lists/split-merge.json +15 -0
  99. package/workspace/test-lists/task-delete.json +5 -0
  100. package/workspace/test-lists/task-links.json +6 -0
  101. package/workspace/tk-tasks-test.js +186 -57
  102. package/workspace/workflows-setup-test.js +4 -3
@@ -37,7 +37,8 @@ const consoleState = require('./console-state');
37
37
  const actorLib = require('./actor.js');
38
38
 
39
39
  const LEDGER = 'plan-items.jsonl';
40
- const EVENTS = ['planned', 'set', 'moved', 'flagged', 'withdrawn', 'kept'];
40
+ // `restored` (batch 11 item 16) is the Undo of a Delete: it brings back a withdrawn item as it was. A delete is a withdraw with why "deleted".
41
+ const EVENTS = ['planned', 'set', 'moved', 'flagged', 'withdrawn', 'kept', 'restored'];
41
42
  const STATES = ['todo', 'doing', 'review', 'done'];
42
43
  const PM_SLUG = 'wawan';
43
44
  const ID_RE = /^(.+)\.([0-9a-z]{10})$/;
@@ -218,7 +219,8 @@ function lineErr(r) {
218
219
  if (r.blocked === true) return oneLine(r.reason, 200) ? null : 'a block reason is 1 to 200 characters';
219
220
  if (r.blocked === false) return null;
220
221
  return 'blocked is not true or false';
221
- case 'withdrawn': return null;
222
+ case 'withdrawn': return r.why === undefined || oneLine(r.why, 200) ? null : 'a why is 1 to 200 characters on one line';
223
+ case 'restored': return null;
222
224
  case 'kept':
223
225
  if (r.item !== undefined) return 'a kept line names no item';
224
226
  if (!isStr(r.batch) || !/^agent:/.test(r.batch)) return 'batch is not agent:<session>';
@@ -278,13 +280,14 @@ function historyOf(rec) {
278
280
  if (rec.ev === 'set') h.fields = { ...rec.fields };
279
281
  if (rec.ev === 'moved') { h.to = rec.to; if (rec.evidence) h.evidence = { ...rec.evidence }; if (rec.override) h.override = true; }
280
282
  if (rec.ev === 'flagged') { h.blocked = rec.blocked; if (rec.blocked) h.reason = rec.reason; }
283
+ if (rec.ev === 'withdrawn' && rec.why) h.why = rec.why;
281
284
  return h;
282
285
  }
283
286
  const touch = (it, rec) => { it.updatedBy = rec.by; it.updatedVia = rec.via; it.updatedAt = rec.at; it.history.push(historyOf(rec)); };
284
287
 
285
288
  /** A mutable fold state, so the writer can apply the events of one call to a working copy as it checks them. */
286
289
  function createState() {
287
- return { items: new Map(), withdrawn: new Set(), flags: [] };
290
+ return { items: new Map(), withdrawn: new Set(), gone: new Map(), flags: [] }; // gone: each withdrawn item as it was, for a restore
288
291
  }
289
292
  function flag(S, kind, rec, n, message) {
290
293
  S.flags.push({ kind, line: n == null ? null : n, eid: (rec && rec.eid) || null, item: (rec && rec.item) || null,
@@ -315,6 +318,16 @@ function applyLine(S, rec, n) {
315
318
  }
316
319
  return;
317
320
  }
321
+ if (rec.ev === 'restored') {
322
+ const was = S.gone.get(rec.item);
323
+ if (!S.withdrawn.has(rec.item) || !was) { flag(S, 'restore-not-withdrawn', rec, n, `restored names ${rec.item}, which is not withdrawn — it has no effect`); return; }
324
+ S.withdrawn.delete(rec.item); S.gone.delete(rec.item);
325
+ was.state = was.withdrawnFrom || 'todo';
326
+ delete was.withdrawnFrom;
327
+ S.items.set(rec.item, was);
328
+ touch(was, rec);
329
+ return;
330
+ }
318
331
  if (S.withdrawn.has(rec.item)) { flag(S, 'after-terminal', rec, n, `${rec.item} was withdrawn — a later ${rec.ev} line has no effect`); return; }
319
332
  const it = S.items.get(rec.item);
320
333
  if (!it) { flag(S, 'unknown-item', rec, n, `${rec.ev} names ${rec.item}, which was never planned — it has no effect`); return; }
@@ -346,9 +359,11 @@ function applyLine(S, rec, n) {
346
359
  it.blocked = rec.blocked ? { reason: rec.reason.trim(), by: rec.by, at: rec.at } : null;
347
360
  break;
348
361
  case 'withdrawn':
362
+ it.withdrawnFrom = it.state;
349
363
  it.state = 'withdrawn';
350
364
  S.items.delete(rec.item);
351
365
  S.withdrawn.add(rec.item);
366
+ S.gone.set(rec.item, it);
352
367
  touch(it, rec);
353
368
  return;
354
369
  default: return;
@@ -451,6 +466,8 @@ function finish(S, { now = Date.now(), dupes = 0 } = {}) {
451
466
  return {
452
467
  items, order: list.map((x) => x.id), batches, flags: S.flags.slice(), dupes,
453
468
  withdrawnCount: S.withdrawn.size, withdrawnIds: [...S.withdrawn].sort(),
469
+ // each withdrawn item as it was when it went, so a restore (and the writer's working copy) can bring it back
470
+ withdrawnItems: Object.fromEntries([...S.gone].map(([id, it]) => [id, { ...it, after: it.after.slice(), history: it.history.slice() }])),
454
471
  };
455
472
  }
456
473
 
@@ -513,7 +530,8 @@ function buildRecord(ctx, ev, index) {
513
530
  set: ['ev', 'item', 'initiative', 'fields'],
514
531
  moved: ['ev', 'item', 'initiative', 'to', 'evidence'],
515
532
  flagged: ['ev', 'item', 'initiative', 'blocked', 'reason'],
516
- withdrawn: ['ev', 'item', 'initiative'],
533
+ withdrawn: ['ev', 'item', 'initiative', 'why'],
534
+ restored: ['ev', 'item', 'initiative'],
517
535
  kept: ['ev', 'initiative', 'batch', 'items'],
518
536
  }[ev.ev];
519
537
  for (const k of Object.keys(ev)) if (!allowed.includes(k)) return refuse(400, `field ${k} is not part of a ${ev.ev} line`, index);
@@ -663,7 +681,19 @@ function buildRecord(ctx, ev, index) {
663
681
  case 'withdrawn': {
664
682
  const ex = existing(); if (ex.ok === false) return ex;
665
683
  // D98: any actor withdraws any item; the line names who did it.
666
- return { rec: common(ex.init, ex.it.id, ex.it.updatedAt) };
684
+ if (ev.why !== undefined && !oneLine(ev.why, 200)) return refuse(400, 'a why is 1 to 200 characters on one line', index);
685
+ const rec = common(ex.init, ex.it.id, ex.it.updatedAt);
686
+ if (ev.why !== undefined) rec.why = ev.why.trim();
687
+ return { rec };
688
+ }
689
+ case 'restored': {
690
+ // the Undo of a Delete (batch 11 item 16): only a withdrawn item comes back, as it was
691
+ if (!isStr(ev.item) || !ID_RE.test(ev.item)) return refuse(400, 'item must be an item id, <initiative>.<10 characters>', index);
692
+ const init = initiativeOf(ev.item);
693
+ if (ev.initiative !== undefined && ev.initiative !== init) return refuse(400, `item ${ev.item} does not belong to initiative ${ev.initiative}`, index);
694
+ const was = S.gone.get(ev.item);
695
+ if (!S.withdrawn.has(ev.item) || !was) return refuse(409, `${ev.item} is not withdrawn`, index);
696
+ return { rec: common(init, ev.item, was.updatedAt) };
667
697
  }
668
698
  case 'kept': {
669
699
  const init = ev.initiative;
@@ -715,6 +745,7 @@ function append(root, events, actor, { now, allowKept }) {
715
745
  S.items.set(id, { ...it, after: it.after.slice(), history: it.history.slice() });
716
746
  }
717
747
  for (const id of base.withdrawnIds) S.withdrawn.add(id);
748
+ for (const [id, it] of Object.entries(base.withdrawnItems || {})) S.gone.set(id, { ...it, after: it.after.slice(), history: it.history.slice() });
718
749
  /* Strictly increasing `at`. Lines written by one call (a planned then a set in the same millisecond) must
719
750
  * sort in the order they were written, and the fold sorts by (at, eid). A line dated more than a second
720
751
  * ahead of this clock is ignored for the GLOBAL floor, so one forged future date cannot drag every later write
@@ -75,6 +75,9 @@ const VERBS = Object.freeze({
75
75
  extension: Object.freeze({ module: 'extension-cli.js', run: null, guide: 'console-calendar.md',
76
76
  help: 'pmos extension — the folder of the Chrome extension for Google Meet, and the three steps to load it' }),
77
77
  // Not a pm-os-absorb verb (run: null): initiative initiative-driver added it through the same table.
78
+ // Not a pm-os-absorb verb (run: null): feedback batch 12 items 2, 3 and 4 (Claude proposes, the one ✦) added it through the same table.
79
+ propose: Object.freeze({ module: 'propose-cli.js', run: null, guide: 'claude-proposes.md',
80
+ help: 'pmos propose look|found|date|done|name|status … — what Claude\'s run files under an initiative\'s ✦ for the PM to keep or drop (pmos propose help)' }),
78
81
  driver: Object.freeze({ module: 'driver-cli.js', run: null, guide: 'initiative-driver.md',
79
82
  help: 'pmos driver propose|status|keep|return|drop|pause|resume|mode … — the Initiative Driver: drafts for you to keep, send back or drop (pmos driver help)' }),
80
83
  // Not a pm-os-absorb verb (run: null): initiative horizon-scan added it through the same table; horizon-scan-portfolio added section, propose, setting and --boards.
@@ -107,7 +107,7 @@ const withChecks = (milestones, checks) => (milestones || []).map((m) => {
107
107
  /** The programs one workspace's ledger says, members carrying no workspace yet (merge adds it). `checks` holds the check lines, by milestone id. */
108
108
  function fold(lines) {
109
109
  const out = {};
110
- const get = (id) => out[id] || (out[id] = { ...blank(id), charter: false, checks: {} });
110
+ const get = (id) => out[id] || (out[id] = { ...blank(id), charter: false, checks: {}, touched: [] });
111
111
  for (const l of lines || []) {
112
112
  if (!l || typeof l !== 'object') continue;
113
113
  if (l.kind === 'program' && ID_RE.test(String(l.id || ''))) {
@@ -122,6 +122,7 @@ function fold(lines) {
122
122
  if (l.kind === 'member' || l.kind === 'leave') {
123
123
  if (!INI_RE.test(String(l.initiative || ''))) continue;
124
124
  p.members = p.members.filter((x) => x !== l.initiative);
125
+ if (!p.touched.includes(String(l.initiative))) p.touched.push(String(l.initiative));
125
126
  if (l.kind === 'member') p.members.push(String(l.initiative));
126
127
  } else if (l.kind === 'task' && l.key && l.title) {
127
128
  const t = { key: String(l.key), title: String(l.title), owner: l.owner || '', due: l.due || '', done: false };
@@ -144,18 +145,25 @@ function merge(perWs) {
144
145
  for (const { ws, lines } of perWs || []) {
145
146
  const one = fold(lines);
146
147
  for (const p of Object.values(one)) {
147
- const m = all[p.id] || (all[p.id] = { ...blank(p.id), home: '', checks: {} });
148
+ const m = all[p.id] || (all[p.id] = { ...blank(p.id), home: '', checks: {}, touched: [] });
148
149
  if (p.charter) Object.assign(m, { title: p.title, owner: p.owner, goal: p.goal, why: p.why, start: p.start, target: p.target, jira: p.jira, from: p.from, milestones: p.milestones, home: ws, at: p.at });
149
150
  Object.assign(m.checks, p.checks);
150
151
  // the route writes the order line to the charter's workspace; a line elsewhere counts only while the charter's has none
151
152
  if (p.orderSet && (p.charter || !m.orderHome)) { m.order = p.order; if (p.charter) m.orderHome = true; }
152
153
  for (const ini of p.members) if (!m.members.some((x) => x.ws === ws && x.initiative === ini)) m.members.push({ ws, initiative: ini });
153
154
  for (const t of p.tasks) m.tasks.push({ ...t, ws });
155
+ for (const ini of p.touched) m.touched.push({ ws, initiative: ini });
154
156
  if (p.archived) m.archived = true;
155
157
  }
156
158
  }
157
159
  // the check lines of every workspace apply to the charter's milestones (the route writes them to the charter's workspace)
158
- for (const m of Object.values(all)) { m.milestones = withChecks(m.milestones, m.checks); delete m.checks; delete m.orderHome; }
160
+ // a program turned from Home before batch 11 item 18 wrote its initiative's member line to the charter's workspace, not the initiative's own:
161
+ // a member or leave line for that initiative in another workspace says where it really is, so the charter's stale line is dropped (else it
162
+ // shows twice once the PM adds it again, or stays under its product)
163
+ for (const m of Object.values(all)) {
164
+ if (m.from && m.touched.some((x) => x.initiative === m.from && x.ws !== m.home)) m.members = m.members.filter((x) => !(x.ws === m.home && x.initiative === m.from));
165
+ m.milestones = withChecks(m.milestones, m.checks); delete m.checks; delete m.orderHome; delete m.touched;
166
+ }
159
167
  // a program with no charter anywhere is a member line whose program was never made: it is not shown
160
168
  return Object.values(all).filter((p) => p.home && !p.archived).sort((a, b) => String(a.title).localeCompare(String(b.title)));
161
169
  }
@@ -0,0 +1,148 @@
1
+ 'use strict';
2
+ /* proposal-runs.js — Claude's runs that file what the ✦ proposes (feedback batch 12 items 2, 3 and 4; lib/proposals.js).
3
+ *
4
+ * off(env) → true when PMOS_PROPOSE=off (or 0, false, no)
5
+ * promptOf(skill, o) → the prompt of one run. o: { run, why, ini, title, intent, stages, stage, today, tasks, dropped }
6
+ * create(deps) → { tick(opts), start({ ws, board, ini, why }), stop(run), active() }
7
+ *
8
+ * TWO MOMENTS, ONE RUN KIND (headless kind `propose`, origin `propose:<ws>:<initiative>:<run>`):
9
+ * populate an initiative was just added (devPiRules 1): with no extra press, Claude looks for it in every connected source (the name, the
10
+ * Why, the material and the people in it) and files what it finds as Found elsewhere. The New initiative panel's Create starts it
11
+ * at once (POST /api/proposals/look); the tick starts it for every other way an initiative is made (a `created` placement line).
12
+ * check each morning inside the day-check window, once a day per initiative that has a late or at-risk task (devTpRules 1): Claude finds
13
+ * WHY each one slipped (the stored reads, the calendar, meeting notes, chat, Jira status) and files its dates, "looks done" and
14
+ * tidy names. A date that passes shows at once without a run: lib/proposals.js datesOf proposes from the tasks themselves, with
15
+ * "No reason found" until a run files the reason.
16
+ *
17
+ * WHAT THE RUN MAY DO (lib/headless.js kind `propose`): read and search the repository, read through the PM's own connectors where the PM's
18
+ * Claude Code settings allow it, and file with `pmos propose`, pinned by the server to this initiative and run (PMOS_PROPOSE_FILE, _WS,
19
+ * _BOARD, _INI, _RUN). It writes no task, no document and no stage: only the PM's ✓ does. Nothing is sent.
20
+ *
21
+ * At most 2 runs at once for the machine; one per initiative. A run that ends writes the `end` line; ■ Stop ends it at once.
22
+ *
23
+ * deps: { workspaces() → [w], isLead(w), stateDirFor(w), boardOf(w, id) → board id | null, created(w) → [{ initiative, at }],
24
+ * checks(w, today) → [{ ini, board, title, tasks: [line] }] (the initiatives with a late or at-risk task), rowOf(w, id) → { title, intent,
25
+ * stage, stages } | null, open(now) → bool (the day-check window), headlessOff() → bool, env, promptFor(skillId) → skill body | null,
26
+ * spawn(spec) (through the capacity governor), spawnNow(spec) (a press), stop(session), warn(what, err) }
27
+ */
28
+ const crypto = require('crypto');
29
+ const PR = require('./proposals.js');
30
+
31
+ const flagOff = (v) => /^(off|0|false|no)$/i.test(String(v || '').trim());
32
+ const off = (env) => flagOff((env || process.env).PMOS_PROPOSE);
33
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
34
+ const MAX = 2;
35
+ const localDay = (ms) => { const d = new Date(ms); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
36
+ const WHY = {
37
+ populate: 'The PM just added this initiative. It most likely already lives elsewhere: find it in every connected source and file what you find (Found elsewhere).',
38
+ check: 'The morning check: some tasks are late or at risk. Find why each one slipped and file new dates, "looks done" and tidy names.',
39
+ };
40
+
41
+ function promptOf(skill, o) {
42
+ const list = (a, none) => (a && a.length ? a.map((x) => '- ' + x).join('\n') : '- ' + none);
43
+ return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Why it runs: ${WHY[o.why] || WHY.check} (${o.why})\n- Today: ${o.today}\n`
44
+ + `- Initiative: ${o.ini} · ${one(o.title, 140)}${o.intent ? '\n- Its Why: ' + one(o.intent, 600) : ''}\n- Its stage now: ${o.stage || 'the first stage'}\n`
45
+ + `- Its workflow's stages, in order:\n${list((o.stages || []).map((s) => s.key + ' · ' + s.name), 'not known')}\n`
46
+ + (o.why === 'check' ? `- Its late and at-risk tasks:\n${list(o.tasks, 'none')}\n` : `- The material the PM gave and the people named are in its record and its first questions (\`pmos initiative export ${o.ini}\`).\n`)
47
+ + `- Dropped by the PM (do not file these again unless the evidence is new):\n${list(o.dropped, 'none')}\n\n`
48
+ + 'File with `pmos propose` only (the server pins this initiative and run). Report each source as you read it with `pmos propose look`. Send nothing.';
49
+ }
50
+
51
+ function create(deps) {
52
+ const active = new Map(); // run → { ws, ini, dir, session, why }
53
+ const warn = deps.warn || (() => {});
54
+ const lastScan = new Map(); // ws → ms of the last morning-check scan
55
+
56
+ function ended(run, r, now = Date.now()) {
57
+ const a = active.get(run); if (!a) return;
58
+ active.delete(run);
59
+ const F = PR.read(a.dir), L = F.looks.get(a.ini);
60
+ if (L && L.run === run && L.ended) return; // ■ Stop wrote it already
61
+ const res = (r && r.result) || {};
62
+ const ok = !!(r && !r.timedOut && !r.stopped && r.code === 0 && res.ok !== false && !res.isError);
63
+ // every source still Reading… ends: it read what it could
64
+ if (L && L.run === run) for (const [k, s] of L.sources) if (s.state === 'reading') try { PR.append(a.dir, null, { kind: 'src', ini: a.ini, run, source: k, state: 'done', n: s.n, what: s.what }); } catch { /* best effort */ }
65
+ try { PR.append(a.dir, null, { kind: 'end', ini: a.ini, run, ok, ...(ok ? {} : { error: one((r && r.note) || res.text || 'the run failed', 200) }) }); } catch (e) { warn('proposal run end', e); }
66
+ }
67
+
68
+ /** Start one run now. → { ok, run } | { ok: false, error } */
69
+ function start({ ws, board, ini, why = 'populate', press = true, now = Date.now() } = {}) {
70
+ if (off(deps.env) || (deps.headlessOff && deps.headlessOff())) return { ok: false, error: 'Claude\'s background runs are off (PMOS_PROPOSE or PMOS_HEADLESS)' };
71
+ const w = (deps.workspaces() || []).find((x) => x.id === ws);
72
+ if (!w) return { ok: false, error: 'no such workspace' };
73
+ const dir = deps.stateDirFor(w);
74
+ if (!dir) return { ok: false, error: 'no PMOS state folder' };
75
+ for (const a of active.values()) if (a.ws === ws && a.ini === ini) return { ok: true, run: [...active.entries()].find(([, x]) => x === a)[0], already: true };
76
+ const skill = deps.promptFor('initiative-propose');
77
+ if (!skill) return { ok: false, error: 'the initiative-propose skill is not installed' };
78
+ const run = 'pr' + now.toString(36) + crypto.randomBytes(3).toString('hex');
79
+ const row = (deps.rowOf && deps.rowOf(w, ini)) || {};
80
+ const F = PR.read(dir);
81
+ const dropped = [...F.props.values()].filter((p) => p.ini === ini && F.drops.has(PR.sigOf(p))).slice(0, 20).map((p) => p.group + ' · ' + (p.title || p.type) + ' · ' + one(p.why, 100));
82
+ let tasks = [];
83
+ if (why === 'check') { try { const c = (deps.checks(w, localDay(now)) || []).find((x) => x.ini === ini); tasks = c ? c.tasks : []; } catch { tasks = []; } }
84
+ const prompt = promptOf(skill, { run, why, ini, title: row.title || ini, intent: row.intent || '', stage: row.stage || '', stages: row.stages || [], today: localDay(now), tasks, dropped });
85
+ const go = press && deps.spawnNow ? deps.spawnNow : deps.spawn;
86
+ active.set(run, { ws, ini, dir, session: null, why });
87
+ let session = null;
88
+ try {
89
+ session = go({ name: (why === 'check' ? 'Task check · ' : 'Looking for · ') + one(row.title || ini, 60), ws, origin: `propose:${ws}:${ini}:${run}`, initialInput: prompt + '\r', initiative: ini,
90
+ env: { PMOS_PROPOSE_FILE: PR.ledgerFile(dir), PMOS_PROPOSE_WS: ws, PMOS_PROPOSE_BOARD: board || '', PMOS_PROPOSE_INI: ini, PMOS_PROPOSE_RUN: run }, onDone: (r) => ended(run, r) });
91
+ } catch (e) { warn('proposal run', e); }
92
+ if (session && session.held) { active.delete(run); return { ok: false, held: true, error: 'Claude is busy with other runs; it looks again in a minute' }; }
93
+ // the look line lands before the run's first `pmos propose look` (the run starts reading after this returns)
94
+ // stamped with the tick's clock, so "once a day" compares the same clock the tick reads (a test or a tick near midnight)
95
+ PR.append(dir, null, { kind: 'look', ini, board: board || (deps.boardOf && deps.boardOf(w, ini)) || '', run, why, at: new Date(now).toISOString() });
96
+ if (!session || session.state === 'exited' || session.headless !== 'propose') {
97
+ if (session && session.headless !== 'propose' && session.state !== 'exited' && deps.stop) { try { deps.stop(session); } catch { /* best effort */ } }
98
+ ended(run, { code: 1, note: (session && session.note) || 'the run could not start in the background', result: {} }, now);
99
+ return { ok: false, error: (session && session.note) || 'Claude could not start looking' };
100
+ }
101
+ const a = active.get(run); if (a) a.session = session;
102
+ return { ok: true, run };
103
+ }
104
+
105
+ function stop(run) { const a = active.get(run); if (a && a.session && deps.stop) deps.stop(a.session); }
106
+
107
+ function tick({ now = Date.now(), env } = {}) {
108
+ if (off(env || deps.env) || (deps.headlessOff && deps.headlessOff())) return { off: true };
109
+ if (active.size >= MAX) return { running: active.size };
110
+ let open = true;
111
+ try { open = deps.open ? !!deps.open(now) : true; } catch { open = true; }
112
+ for (const w of deps.workspaces() || []) {
113
+ if (deps.isLead && !deps.isLead(w)) continue;
114
+ const dir = deps.stateDirFor(w); if (!dir) continue;
115
+ const F = PR.read(dir);
116
+ // the first scan writes the epoch: only initiatives made after it are looked for (an old one is history)
117
+ const epoch = F.epoch;
118
+ if (!epoch) { PR.append(dir, null, { kind: 'epoch' }); continue; }
119
+ let created = [];
120
+ try { created = deps.created(w) || []; } catch { created = []; }
121
+ for (const c of created) {
122
+ if (!c || !c.initiative || String(c.at || '') < epoch || F.looks.has(c.initiative)) continue;
123
+ const r = start({ ws: w.id, ini: c.initiative, why: 'populate', press: false, now });
124
+ if (r.ok) return { started: c.initiative, why: 'populate' };
125
+ if (r.held) return { held: true }; // the governor said wait: the next tick tries again
126
+ }
127
+ // the morning check, once a day per initiative, inside the day-check window; the scan itself at most once an hour
128
+ if (!open || now - (lastScan.get(w.id) || 0) < 3600e3) continue;
129
+ lastScan.set(w.id, now);
130
+ const day = localDay(now);
131
+ let due = [];
132
+ try { due = deps.checks(w, day) || []; } catch (e) { warn('proposal check scan', e); }
133
+ for (const c of due) {
134
+ const L = F.looks.get(c.ini);
135
+ if (L && L.why === 'check' && localDay(Date.parse(L.at) || 0) === day) continue;
136
+ if (L && !L.ended) continue;
137
+ const r = start({ ws: w.id, board: c.board, ini: c.ini, why: 'check', press: false, now });
138
+ if (r.ok) return { started: c.ini, why: 'check' };
139
+ if (r.held) { lastScan.delete(w.id); return { held: true }; }
140
+ }
141
+ }
142
+ return { started: null };
143
+ }
144
+
145
+ return { tick, start, stop, active: () => [...active.keys()] };
146
+ }
147
+
148
+ module.exports = { off, promptOf, create, WHY, MAX };