create-pmos 0.564.0 → 0.566.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 (55) hide show
  1. package/package.json +33 -27
  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/scripts/gate-initiative.sh +6 -3
  6. package/payload/scripts/workflow-state.js +39 -11
  7. package/payload/state/discoveries.md +1 -1
  8. package/payload/state/log.md +1 -1
  9. package/workspace/changelog.json +32 -0
  10. package/workspace/fixtures/initiatives-api/list.json +2 -1
  11. package/workspace/guide/cli.md +3 -2
  12. package/workspace/guide/initiatives-and-next-steps.md +4 -4
  13. package/workspace/guide/jira.md +3 -1
  14. package/workspace/lib/agent-team.js +1 -1
  15. package/workspace/lib/board-cli.js +32 -1
  16. package/workspace/lib/description-props.js +53 -2
  17. package/workspace/lib/engine/workflow-state.js +39 -11
  18. package/workspace/lib/grill-cli.js +4 -4
  19. package/workspace/lib/impact-cli.js +3 -3
  20. package/workspace/lib/initiative-cli.js +12 -5
  21. package/workspace/lib/jira-cli.js +2 -0
  22. package/workspace/lib/jira-tickets.js +78 -5
  23. package/workspace/lib/lab-cli.js +1 -1
  24. package/workspace/lib/lead-cli.js +1 -1
  25. package/workspace/lib/measure-cli.js +13 -7
  26. package/workspace/lib/measurements.js +34 -11
  27. package/workspace/lib/metrics-cli.js +4 -4
  28. package/workspace/lib/outcomes-cli.js +2 -2
  29. package/workspace/lib/program-cli.js +2 -2
  30. package/workspace/lib/propose-cli.js +2 -2
  31. package/workspace/lib/report-draft.js +7 -6
  32. package/workspace/lib/report-engine.js +1 -1
  33. package/workspace/lib/routes-artefacts.js +3 -2
  34. package/workspace/lib/routes-board-premium.js +2 -0
  35. package/workspace/lib/routes-initiatives.js +1 -1
  36. package/workspace/lib/routes-notes.js +3 -1
  37. package/workspace/lib/routes-stage-tools.js +1 -1
  38. package/workspace/lib/stage-read.js +155 -0
  39. package/workspace/lib/task-cli.js +2 -16
  40. package/workspace/lib/team-cli.js +4 -1
  41. package/workspace/lib/today-cli.js +19 -6
  42. package/workspace/lib/vendor/scripts/workflow-state.js +39 -11
  43. package/workspace/lib/work-kind.js +16 -4
  44. package/workspace/lib/workflow-cli.js +18 -2
  45. package/workspace/package-lock.json +2 -2
  46. package/workspace/package.json +1 -1
  47. package/workspace/public/pm/bd-asks.js +1 -1
  48. package/workspace/public/pm/bd-ini-panel.js +1 -1
  49. package/workspace/public/pm/bd-next.js +9 -5
  50. package/workspace/public/pm/bd-views.js +1 -1
  51. package/workspace/public/pm/ini-agent.js +14 -7
  52. package/workspace/public/pm/premium-board.js +1 -1
  53. package/workspace/public/pm/work-kind.js +10 -6
  54. package/workspace/skills/measure.skill +6 -6
  55. package/workspace/test-lists/stage-everywhere.json +5 -0
@@ -351,6 +351,14 @@ function buildRange(root, { spec, whole }) {
351
351
  * ordering rule; "I cannot tell" is not, and collapsing the second into the first is exactly how a
352
352
  * shallow clone would turn every order check into a silent pass.
353
353
  */
354
+ /** The unix seconds of the commit that first added `rel`, or null when git cannot say. */
355
+ function addedDate(root, rel) {
356
+ const out = git(root, ['log', '--diff-filter=A', '--format=%ct', '--', rel]);
357
+ const lines = out ? out.split('\n').map((x) => x.trim()).filter(Boolean) : [];
358
+ const t = lines.length ? Number(lines[lines.length - 1]) : NaN;
359
+ return Number.isFinite(t) ? t : null;
360
+ }
361
+
354
362
  function firstAppearance(root, range, rel) {
355
363
  const onDisk = fs.existsSync(path.join(root, rel));
356
364
  if (!range.ok) return onDisk ? undefined : null;
@@ -685,7 +693,12 @@ function computeWorkflowDerived(id, opts) {
685
693
  // would suddenly be enforced. So the commit DATE decides whenever the range can supply it, and
686
694
  // -1 keeps its meaning for the gate's range. Same question, asked of evidence that survives both.
687
695
  const recIdx = firstAppearance(root, range, recRel);
688
- const recAt = (range.dates && typeof recIdx === 'number' && recIdx >= 0) ? range.dates[recIdx] : null;
696
+ // An EMPTY range (a branch level with main, a fresh clone, a kit repository on its trunk) gates nothing, so -1 there only means "committed
697
+ // before HEAD". It used to read every record as legacy, a record written today too, which turned the order rules off on the ladder
698
+ // (launch simulation W1, 2026-11-12). With nothing to gate, the record's own first commit dates it.
699
+ const emptyRange = range.ok && Array.isArray(range.shas) && range.shas.length === 0;
700
+ const addedAt = (recIdx === -1 && emptyRange) ? addedDate(root, recRel) : null;
701
+ const recAt = (range.dates && typeof recIdx === 'number' && recIdx >= 0) ? range.dates[recIdx] : addedAt;
689
702
  /*
690
703
  * `reconstructed_from` — the merge date of work whose record was written afterwards.
691
704
  *
@@ -698,7 +711,7 @@ function computeWorkflowDerived(id, opts) {
698
711
  * genuinely skipped the loop still reports blocked, which is the point of writing it down.
699
712
  */
700
713
  const recon = String(fm.reconstructed_from || '').trim().slice(0, 10);
701
- const legacy = recIdx === -1 ? true
714
+ const legacy = (recIdx === -1 && !addedAt) ? true
702
715
  : /^\d{4}-\d{2}-\d{2}$/.test(recon) ? recon < ENFORCED_FROM
703
716
  : recAt ? new Date(recAt * 1000).toISOString().slice(0, 10) < ENFORCED_FROM
704
717
  : String(fm.timestamp || generatedAt(fm.generated) || '').slice(0, 10) < ENFORCED_FROM; // fallback — see ENFORCED_FROM; D74: OKF v0.2 `generated.at` stands in for `timestamp`
@@ -847,7 +860,7 @@ function computeWorkflowDerived(id, opts) {
847
860
 
848
861
  // ── D68: the pm-artifacts ladder replaces everything after the anchor ─────────────────────────
849
862
  if (pmProfile) {
850
- return pmLadder({ id, fm, lane, effLane, knownLane, legacy, steps, root, L, recRel, range, inChange, lastActivity, opts });
863
+ return pmLadder({ id, fm, lane, effLane, knownLane, legacy, steps, root, L, recRel, range, inChange, lastActivity, opts, doneTest, killCond });
851
864
  }
852
865
 
853
866
  const prd = String(fm.prd_path || '').trim();
@@ -1523,7 +1536,8 @@ function jiraKeysOf(L, id, fm) {
1523
1536
  * every profile — D59/D67); route is re-stated here because its product-code form asks the
1524
1537
  * specimen/surface questions, which a PM document does not need. What follows is evidence-derived
1525
1538
  * like every other rung — nothing is declared done:
1526
- * brief — the brief file (`brief_path`, or `prd_path`) exists
1539
+ * brief — the brief file (`brief_path`, or `prd_path`) exists; or, for a D107 experiment, its done test
1540
+ * (`done_test_path`, present) and its kill condition (`kill:`), as the Viewer gate reads them (launch simulation W4)
1527
1541
  * draft — the deliverable (`doc_path`) exists, and — governed only — did not appear before the brief
1528
1542
  * review — an evals.jsonl verdict for this id, or a named `reviewed_by:` (a rubric, an agent, a human)
1529
1543
  * approved — the PM's acceptance in acceptances.jsonl (D12, never automatic)
@@ -1535,7 +1549,7 @@ function jiraKeysOf(L, id, fm) {
1535
1549
  * existence and their order fail CI for a non-legacy record). Review, approval and handoff are never
1536
1550
  * CI-blocking in either track: none can be true before the PR exists.
1537
1551
  */
1538
- function pmLadder({ id, fm, lane, effLane, knownLane, legacy, steps, root, L, recRel, range, inChange, lastActivity, opts }) {
1552
+ function pmLadder({ id, fm, lane, effLane, knownLane, legacy, steps, root, L, recRel, range, inChange, lastActivity, opts, doneTest = '', killCond = '' }) {
1539
1553
  const declared = String(fm.track || '').trim().toLowerCase();
1540
1554
  const track = declared === 'light' || declared === 'governed' ? declared
1541
1555
  : (laneDefs.laneDef('pm-artifacts', effLane) || laneDefs.laneDef('pm-artifacts', 'prd')).track;
@@ -1547,7 +1561,9 @@ function pmLadder({ id, fm, lane, effLane, knownLane, legacy, steps, root, L, re
1547
1561
  const skipped = (key, label) => step(key, label, 'na', `${effLane} lane — ${label} is not part of this flow`);
1548
1562
 
1549
1563
  // route — the lane is a pm-artifacts lane
1550
- steps[0] = knownLane
1564
+ steps[0] = doneTest
1565
+ ? step('route', 'route', 'done', 'experiment — its done test and specimens route it (D107)')
1566
+ : knownLane
1551
1567
  ? step('route', 'route', 'done', `${lane} lane · ${track} track (pm-artifacts profile, D68)`)
1552
1568
  : step('route', 'route', 'done', `unknown lane '${lane}' — treated as a governed prd, the profile's strictest (D68)`,
1553
1569
  `set lane: to one of ${laneNames('pm-artifacts').join(', ')}`);
@@ -1558,10 +1574,18 @@ function pmLadder({ id, fm, lane, effLane, knownLane, legacy, steps, root, L, re
1558
1574
  const docPath = String(fm.doc_path || '').trim();
1559
1575
  const foundBrief = exists(briefPath) ? null : foundOf('brief');
1560
1576
  const foundDraft = exists(docPath) ? null : foundOf('draft');
1561
- const briefIdx = briefPath ? firstAppearance(root, range, briefPath) : null;
1577
+ // D107: a done test with its kill condition is the experiment's brief; the deliverable is ordered after it like any brief.
1578
+ const dtPresent = exists(doneTest);
1579
+ const briefIdx = dtPresent && killCond ? firstAppearance(root, range, doneTest)
1580
+ : briefPath ? firstAppearance(root, range, briefPath) : null;
1562
1581
  const docIdx = docPath ? firstAppearance(root, range, docPath) : null;
1563
1582
 
1564
- if (!flows('brief')) steps.push(skipped('brief', def.brief_label));
1583
+ if (doneTest && dtPresent && killCond) steps.push(step('brief', def.brief_label, 'done', `done test ${doneTest} + kill condition (D107)`));
1584
+ else if (doneTest && dtPresent) steps.push(step('brief', def.brief_label, 'blocked', 'no kill condition — an experiment states what would stop it (D107)',
1585
+ `write kill: "<the result that would make us stop>" in ${recRel}`, { blocking: !legacy, rule: 'R2' }));
1586
+ else if (doneTest) steps.push(step('brief', def.brief_label, 'blocked', `done_test_path '${doneTest}' does not exist in the repo`,
1587
+ 'create the done test the record points at, or correct done_test_path', { blocking: !legacy, rule: 'R2' }));
1588
+ else if (!flows('brief')) steps.push(skipped('brief', def.brief_label));
1565
1589
  else if (foundBrief) steps.push(step('brief', def.brief_label, 'done', `${foundBrief} — found by the repository scan`));
1566
1590
  else if (exists(briefPath)) steps.push(step('brief', def.brief_label, 'done', `${briefPath} present`));
1567
1591
  else steps.push(step('brief', def.brief_label, enforce ? 'blocked' : 'pending',
@@ -1574,7 +1598,7 @@ function pmLadder({ id, fm, lane, effLane, knownLane, legacy, steps, root, L, re
1574
1598
  else if (exists(docPath)) {
1575
1599
  const inOrder = briefIdx == null || docIdx == null ? null : docIdx >= briefIdx;
1576
1600
  if (enforce && inOrder === false) {
1577
- steps.push(step('draft', def.draft_label, 'blocked', `${docPath} appeared before its brief ${briefPath}`,
1601
+ steps.push(step('draft', def.draft_label, 'blocked', `${docPath} appeared before its brief ${dtPresent && killCond ? doneTest : briefPath}`,
1578
1602
  'a governed document is briefed before it is drafted — the brief must land first', { blocking: true, rule: 'P2' }));
1579
1603
  } else steps.push(step('draft', def.draft_label, 'done', `${docPath} present`));
1580
1604
  } else steps.push(step('draft', def.draft_label, enforce && docPath ? 'blocked' : 'pending',
@@ -1735,7 +1759,11 @@ function renderLadder(w) {
1735
1759
  const head = `${c(1, w.id)} · ${w.lane}${w.laneKnown ? '' : c(33, ' (unknown lane — enforcing feature)')} · ${w.anchor ? brief(w.anchor, 46) : c(31, 'unanchored')}`;
1736
1760
  out.push('');
1737
1761
  out.push(` ${head}`);
1738
- out.push(` ${c(90, 'stage')} ${c(1, w.stage)}${w.legacy ? c(33, ` legacy — record predates ${w.enforced_from}, order rules report but do not fail`) : ''}`);
1762
+ // The gate rung, not the initiative's stage: the stage the pages and `pmos initiative list` show is the Board's one stage (PM moves,
1763
+ // Jira, dated plan items, then these files; workspace/lib/stage-read.js). Printing the rung as "stage" gave one record four stages
1764
+ // (launch simulation W1, 2026-11-12). The engine never reads the Board (X29), so it names the rung and says where the stage is.
1765
+ out.push(` ${c(90, 'gate')} ${c(1, w.stage)}${w.legacy ? c(33, ` legacy — record predates ${w.enforced_from}, order rules report but do not fail`) : ''}`);
1766
+ out.push(` ${c(90, 'stage')} ${c(90, `pmos workflow of ${w.id} — the stage every page shows`)}`);
1739
1767
  out.push(` ${c(90, '─'.repeat(78))}`);
1740
1768
  for (const s of w.steps) {
1741
1769
  const label = s.label.padEnd(11);
@@ -1901,7 +1929,7 @@ function main(argv) {
1901
1929
  }
1902
1930
  if (w.legacy) process.stdout.write(`ℹ️ '${w.id}' is LEGACY (record predates ${ENFORCED_FROM}) — order rules reported, not enforced.\n`);
1903
1931
  if (w.range.error) process.stdout.write(`⚠️ order checks degraded — ${w.range.error}\n`);
1904
- process.stdout.write(`✅ workflow gate PASSED — '${w.id}' (${w.lane}) at stage ${w.stage}.\n`);
1932
+ process.stdout.write(`✅ workflow gate PASSED — '${w.id}' (${w.lane}) at gate rung ${w.stage}.\n`);
1905
1933
  return 0;
1906
1934
  }
1907
1935
 
@@ -20,7 +20,7 @@ const PR = require('./proposals.js');
20
20
 
21
21
  const COMMANDS = { grill: ['find', 'voices', 'status', 'decisions', 'mode', 'cap', 'spend'] };
22
22
  const USAGE = [
23
- 'usage: pmos grill find|voices|status|mode|cap|spend — Claude grills an initiative by itself; each finding waits under its ✦',
23
+ 'usage: pmos grill find|voices|status|mode|cap|spend — PMOS grills an initiative by itself; each finding waits under its ✦',
24
24
  ' pmos grill find <' + G.ANGLES.join('|') + '> --json <file|->',
25
25
  ' { "title": "<the finding, one short line>", "why": "<the evidence, one line>", "next": "<one next step>", "sources": [{ "label", "ref" }], "key"?, "rank"?: 1-9 }',
26
26
  ' voices needs ' + G.VOICES_MIN + ' sources or more and is tagged "' + G.SIMULATED.voices + '"; whatif is tagged "' + G.SIMULATED.whatif + '".',
@@ -29,8 +29,8 @@ const USAGE = [
29
29
  ' pmos grill decisions [--all] the decisions that stand (with --all: what superseded the others)',
30
30
  ' pmos grill find decision --json - { "decision": "D79", "quote": "<its words>", "plan": { "label", "ref": "<path>:<line>", "quote": "<the plan\'s words>" },',
31
31
  ' "conflict": "<one line>", "recommend": "keep|change|drop", "next": "<one next step>", "confidence": "high|medium" }',
32
- ' pmos grill mode [full|exits|off] when Claude grills by itself',
33
- ' pmos grill cap [<dollars>] the monthly credit cap; at the cap Claude pauses',
32
+ ' pmos grill mode [full|exits|off] when PMOS grills by itself',
33
+ ' pmos grill cap [<dollars>] the monthly credit cap; at the cap PMOS pauses',
34
34
  ' pmos grill spend what this month spent',
35
35
  'Every finding carries its source and a next step. It waits for the PM\'s ✓. Nothing is sent.',
36
36
  ];
@@ -80,7 +80,7 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, stdin
80
80
 
81
81
  /* ── the run's verbs ── */
82
82
  const file = env.PMOS_GRILL_FILE, log = env.PMOS_GRILL_LOG, runId = env.PMOS_GRILL_RUN, ini = env.PMOS_GRILL_INI, board = env.PMOS_GRILL_BOARD || '';
83
- if (!file || !log || !runId || !ini) { say('✗ pmos grill ' + verb + ' is for Claude\'s grill run. The PM keeps and drops findings under the initiative\'s ✦'); return 1; }
83
+ if (!file || !log || !runId || !ini) { say('✗ pmos grill ' + verb + ' is for PMOS\'s grill run. The PM keeps and drops findings under the initiative\'s ✦'); return 1; }
84
84
  const L = G.fold(G.readLines(log)), me = L.runs.get(runId);
85
85
  if (!me || me.ended) { say('✗ this run is not grilling now (it ended, or it was stopped)'); return 1; }
86
86
  const P = PR.fold(PR.readLines(file));
@@ -14,13 +14,13 @@ const IM = require('./impact.js');
14
14
  const COMMANDS = { impact: ['add', 'end', 'status'] };
15
15
  const SUBS = COMMANDS.impact;
16
16
  const USAGE = [
17
- 'usage: pmos impact add|end|status — what Claude\'s impact run files for the PM to check (✓ real, ✕ not real)',
17
+ 'usage: pmos impact add|end|status — what PMOS\'s impact run files for the PM to check (✓ real, ✕ not real)',
18
18
  ' pmos impact add --json <file|->',
19
19
  ' { "kind": "' + IM.KINDS.join('" | "') + '", "text": "<one plain sentence, no counts>", "who": "<a name, or empty>",',
20
20
  ' "at": "<ISO 8601, when it happened>", "source": { "url": "<https link>", "type": "' + IM.SOURCE_TYPES.join('" | "') + '", "label": "Slack · #shop-data" } }',
21
21
  ' pmos impact end [--error "<why the run could not finish>"]',
22
22
  ' pmos impact status',
23
- 'Only what a person or a system outside you did in reaction to your work. Never Claude\'s own work. No source, no item. Nothing is sent.',
23
+ 'Only what a person or a system outside you did in reaction to your work. Never PMOS\'s own work. No source, no item. Nothing is sent.',
24
24
  ];
25
25
  const flag = (args, k) => { const i = args.indexOf('--' + k); return i >= 0 ? (args[i + 1] === undefined || args[i + 1].startsWith('--') ? true : args[i + 1]) : undefined; };
26
26
  function readJson(src, stdin) {
@@ -35,7 +35,7 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, stdin
35
35
  if (!sub || ['help', '--help', '-h'].includes(sub)) { for (const l of USAGE) say(l); return sub ? 0 : 1; }
36
36
  if (!SUBS.includes(sub)) { say(`unknown impact command "${sub}". Use one of: ${SUBS.join(', ')}`); return 2; }
37
37
  const file = env.PMOS_IMPACT_FILE, runId = env.PMOS_IMPACT_RUN;
38
- if (!file || !runId) { say('✗ pmos impact is for Claude\'s impact run. The PM checks each item in Home\'s chat.'); return 1; }
38
+ if (!file || !runId) { say('✗ pmos impact is for PMOS\'s impact run. The PM checks each item in Home\'s chat.'); return 1; }
39
39
  const F = IM.fold(IM.readLines(file));
40
40
  const at = new Date(now).toISOString();
41
41
  const line = (ev) => { fs.appendFileSync(file, JSON.stringify({ at, by: null, run: runId, ...ev }) + '\n', { mode: 0o600 }); };
@@ -11,7 +11,7 @@
11
11
  * pmos initiative drop <proposal-eid>
12
12
  * pmos initiative list
13
13
  * pmos initiative export <id> the breakdown as markdown on stdout; nothing is written
14
- * pmos initiative describe <id> ["<text>"] no text: its description and the cited lines Claude can draft it from; with text: write
14
+ * pmos initiative describe <id> ["<text>"] no text: its description and the cited lines PMOS can draft it from; with text: write
15
15
  * its `description:` line (initiative-description-field). An agent writes only after the PM's yes
16
16
  * every command: [--json] [--root <dir>]
17
17
  *
@@ -76,6 +76,8 @@ const USAGE = [
76
76
  ' pmos initiative list the Roadmap, ranked, with each lifecycle stage',
77
77
  ' pmos initiative export <id> the breakdown as markdown on stdout',
78
78
  ' pmos initiative describe <id> ["<text>"] read its description and what to draft it from; with text, save it (after the PM\'s yes)',
79
+ ' --lane is a work lane of this repository: new-feature, improvement, bug-fix, discovery or chore in a product repository',
80
+ ' (scripts/lane-defs.js; the PMOS repository itself uses feature, discovery, chore, incident, content and prototype)',
79
81
  ' every command: [--json] [--root <dir>]',
80
82
  'An agent session\'s move applies at once and names the agent. A new initiative lands at the end of the Roadmap.',
81
83
  'Now, Next and Later are retired (D105): the rank says what comes first, the lifecycle stage says where it is.',
@@ -154,14 +156,18 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
154
156
  startOnDefault(root, r, actor);
155
157
  // no initiative without an expected outcome (outcome-for-every-initiative): say what Claude drafts next, or that the PM names it
156
158
  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`
157
- + `✦ It needs an expected outcome and a date to check it. Claude drafts them from the PRD's success criteria once it is written (pmos outcomes propose ${r.id}); until then, ask the PM what should change once it ships.`);
159
+ + `✦ It needs an expected outcome and a date to check it. PMOS drafts them from the PRD's success criteria once it is written (pmos outcomes propose ${r.id}); until then, ask the PM what should change once it ships.`);
158
160
  }
159
161
 
160
162
  if (verb === 'list') {
161
163
  const o = order();
162
164
  if (o.error) return fail(o.error);
163
165
  const byRow = new Map(o.rows.map((r) => [r.id, r]));
164
- const stage = (id) => lifecycle.labelOf(byRow.get(id), root); // W1: the one stage
166
+ // the one stage, as the Board row holds it (lib/stage-read.js): a workflow move and the PM's word count, as on every page
167
+ const SR = require('./stage-read.js');
168
+ const { w: sw, ctx: sctx } = SR.cliCtx(root);
169
+ const read = SR.stagesOf(sctx, sw, o.placed.ranked);
170
+ const stage = (id) => { const a = read.get(id); return a ? a.label : lifecycle.labelOf(byRow.get(id), root); };
165
171
  if (json) {
166
172
  say(JSON.stringify({ ok: true, ranked: o.placed.ranked, byInit: o.placed.byInit, stages: Object.fromEntries(o.placed.ranked.map((id) => [id, stage(id)])),
167
173
  proposals: o.placed.proposals.map((p) => ({ ...p, by: actorLib.pageName(p.by) })), documents: documentsOf(o.rows) }));
@@ -222,11 +228,12 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
222
228
  const it = S.subjects.find((x) => x.id === did);
223
229
  if (!it) return fail(`no initiative ${did} here (or it is stopped, or on a document lane)`);
224
230
  const cur = it.fm.description ? String(it.fm.description.value || '') : '';
225
- const srcs = [DP.fromPrd(S, it), DP.fromRecord(S, it)].filter(Boolean);
231
+ const ex = DP.fromExperiment(S, it);
232
+ const srcs = [DP.fromPrd(S, it), ...(ex ? ex.parts : []), DP.fromRecord(S, it)].filter(Boolean);
226
233
  if (json) { say(JSON.stringify({ ok: true, id: did, description: cur || null, sources: srcs.map((x) => ({ label: x.source.label, ref: x.source.ref, text: x.text })) })); return 0; }
227
234
  say(cur ? `${did}: ${cur}` : `${did} has no description yet.`);
228
235
  if (srcs.length) say('Draft it from:\n' + srcs.map((x) => ` · ${x.source.label} [${x.source.ref}]: ${x.text}`).join('\n'));
229
- else say('Nothing readable to draft it from (no PRD paragraph, no paragraph in its record): ask the PM what it is.');
236
+ else say('Nothing readable to draft it from (no PRD paragraph, no experiment hypothesis or problem, no paragraph in its record): ask the PM what it is.');
230
237
  say(`Show the draft to the PM; after a yes: pmos initiative describe ${did} "<text>"`);
231
238
  return 0;
232
239
  }
@@ -35,6 +35,7 @@ const COMMANDS = { jira: ['draft', 'show', 'epic', 'approve', 'pending', 'record
35
35
  const USAGE = [
36
36
  'usage: pmos jira draft|show|epic|approve|pending|record|query|sync|summary|which — Jira tickets from the PRD, and their status',
37
37
  ' pmos jira draft <initiative> [--dry-run] draft one ticket per PRD item, in the ticket template',
38
+ ' With no PRD stories section: one ticket per done-test check, else one per open task.',
38
39
  ' pmos jira show <initiative> every ticket, what needs you, and its status in Jira',
39
40
  ' pmos jira epic <initiative> new|<KEY or link> [--group <g>] create a new epic at the first push, or use an existing one',
40
41
  ' pmos jira approve <initiative> <ID> … select tickets to push (you, in your own terminal)',
@@ -188,6 +189,7 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
188
189
  const r = jiraTickets.draft(root, initiative, { dryRun: !!flags['dry-run'], now });
189
190
  if (!r.ok) return fail(r.error);
190
191
  const lines = [`${initiative} · ${r.tickets} ${r.tickets === 1 ? 'ticket' : 'tickets'} in ${r.draft}${r.changed ? '' : ' · no change'}${flags['dry-run'] ? ' · dry run, nothing written' : ''}`];
192
+ if (r.from === 'done-test' || r.from === 'tasks') lines.push(` From ${r.from === 'done-test' ? 'the done test\'s checks' : 'the open tasks'} (${r.sources.join(', ')}): the PRD has no stories section.`);
191
193
  for (const c of r.changes) lines.push(` ${c.what.padEnd(9)} ${c.ticket} · ${c.summary}${c.why ? ` (${c.why})` : ''}`);
192
194
  lines.push('Read them on the Jira tickets tab, or with pmos jira show. Select the ready ones there, or with pmos jira approve.');
193
195
  return out(r, lines);
@@ -2,7 +2,9 @@
2
2
  /* jira-tickets.js — Jira tickets drafted from the PRD in the PM's template, selected by the PM, then pushed (initiative
3
3
  * jira-wbs, PRD J1 to J10 and J12, proposed D88).
4
4
  *
5
- * items(root, initiative) → { items, sources, prd } J1: the ticket items of the PRD and story files
5
+ * items(root, initiative) → { items, sources, prd, from } J1: the ticket items of the PRD and story files;
6
+ * with none, the done test's checks (D107), else the initiative's open tasks
7
+ * (launch simulation W4). `from` is 'prd', 'done-test' or 'tasks'.
6
8
  * fromItem(item, prd) → a ticket J2: one item in the PM's template
7
9
  * draft(root, initiative, opts) → the merged draft, written J3: new items added, unedited ones redrafted
8
10
  * view(root, initiative) → what the tab draws J4, J5, J10, J12
@@ -213,6 +215,65 @@ function readPrd(root, prd) {
213
215
  try { return fs.readFileSync(path.join(root, prd), 'utf8'); } catch { /* the main tree */ }
214
216
  try { return fs.readFileSync(path.join(mainRoot(root), prd), 'utf8'); } catch { return null; }
215
217
  }
218
+ /** The checks of a done test (D107): its table rows `| n | check | how |`, else its top-level bullets. → [{ n, check, how }] */
219
+ function checksInDoneTest(text) {
220
+ const lines = stripFm(text).split('\n');
221
+ const out = [];
222
+ for (const l of lines) {
223
+ const m = /^\|\s*(\d+)\s*\|\s*(.+?)\s*\|\s*(.*?)\s*\|?\s*$/.exec(l);
224
+ if (m && m[2] && !/^-+$/.test(m[2])) out.push({ n: Number(m[1]), check: m[2].replace(/\\\|/g, '|'), how: m[3] || '' });
225
+ }
226
+ if (out.length) return out;
227
+ let n = 0;
228
+ for (const l of lines) {
229
+ const b = /^[-*] (?:\[[ xX]\] )?(.+)$/.exec(l);
230
+ if (b) out.push({ n: ++n, check: b[1].trim(), how: '' });
231
+ }
232
+ return out;
233
+ }
234
+ /** The done test a record names, read from the worktree or the main tree (a kit repository may name it under pmos/). */
235
+ function readDoneTest(root, rfm) {
236
+ const p = rfm && isStr(rfm.done_test_path) ? rfm.done_test_path.trim() : '';
237
+ if (!p) return null;
238
+ for (const base of [root, mainRoot(root)]) {
239
+ for (const rel of [p, path.join('pmos', p)]) {
240
+ const abs = path.resolve(base, rel);
241
+ if (abs !== path.resolve(base) && !abs.startsWith(path.resolve(base) + path.sep)) continue;
242
+ try { return { path: path.relative(mainRoot(root), abs).split(path.sep).join('/') || rel, text: fs.readFileSync(abs, 'utf8') }; } catch { /* next */ }
243
+ }
244
+ }
245
+ return null;
246
+ }
247
+ /** One ticket item per done-test check: the check is the requirement, and how to check it is the acceptance. */
248
+ function itemsFromDoneTest(dt, title) {
249
+ return checksInDoneTest(dt.text).map((c) => {
250
+ const check = oneLine(c.check);
251
+ return {
252
+ id: `DT-${String(c.n).padStart(2, '0')}`, title: clip(check.replace(/\.$/, ''), 120), epic: null, refLabel: 'Done test', source: dt.path,
253
+ body: [`### User Story`, `As the PM of ${title}, I want this check of the done test to pass: ${check}`,
254
+ `### Functional Requirements`, check,
255
+ `### Acceptance Criteria`, `- ${check}`, ...(c.how ? [`- How to check: ${oneLine(c.how)}`] : [])].join('\n'),
256
+ };
257
+ });
258
+ }
259
+ /** One ticket item per open task of the initiative (its breakdown in plan-items.jsonl), in breakdown order. */
260
+ function itemsFromTasks(root, initiative, title) {
261
+ let fold;
262
+ try { fold = planItems.readFold(root, { now: 0 }); } catch { return []; }
263
+ const rel = path.relative(mainRoot(root), planItems.ledgerPath(root)).split(path.sep).join('/');
264
+ return (fold.order || []).map((id) => fold.items[id]).filter((it) => it && it.initiative === initiative && it.state !== 'done' && !it.proposed)
265
+ .map((it) => {
266
+ const what = oneLine(it.title);
267
+ const note = oneLine(it.note || '');
268
+ return {
269
+ id: `TK-${slug(what)}`, title: clip(what, 120), epic: null, refLabel: 'Task', source: rel, task: it.id,
270
+ body: [`### User Story`, `As the PM of ${title}, I want this task done: ${what}`,
271
+ ...(note ? [`### Additional Context`, note] : []),
272
+ `### Functional Requirements`, what,
273
+ `### Acceptance Criteria`, `- ${what}${it.due ? ` by ${it.due}` : ''}`].join('\n'),
274
+ };
275
+ });
276
+ }
216
277
  function items(root, initiative) {
217
278
  const fm = recordFm(root, initiative);
218
279
  if (!fm) return { ok: false, error: `no initiative ${initiative} in this repository` };
@@ -237,6 +298,18 @@ function items(root, initiative) {
237
298
  for (const x of s) x.source = rel;
238
299
  if (s.length) { found.push(...s); sources.push(rel); }
239
300
  }
301
+ // D107: no PRD stories section. The done test says what must be true, else the breakdown says what to do (launch simulation W4).
302
+ let from = found.length ? 'prd' : null;
303
+ const title = oneLine(fm.title || initiative);
304
+ if (!found.length) {
305
+ const dt = readDoneTest(root, fm);
306
+ const s = dt ? itemsFromDoneTest(dt, title) : [];
307
+ if (s.length) { found.push(...s); sources.push(dt.path); from = 'done-test'; }
308
+ }
309
+ if (!found.length) {
310
+ const s = itemsFromTasks(root, initiative, title);
311
+ if (s.length) { found.push(...s); sources.push(s[0].source); from = 'tasks'; }
312
+ }
240
313
  // Ids: the item's own (TD-01, S3) or a slug of its title; a repeat gets -2, -3.
241
314
  const seen = new Map();
242
315
  for (const s of found) {
@@ -248,7 +321,7 @@ function items(root, initiative) {
248
321
  s.epic = s.epic || null;
249
322
  s.hash = sha(s.title + '\n' + s.body + (s.epic ? '\n' + s.epic : ''));
250
323
  }
251
- return { ok: true, initiative, items: found, sources, prd: prd || null };
324
+ return { ok: true, initiative, items: found, sources, prd: prd || null, from };
252
325
  }
253
326
 
254
327
  // ── J2 · one item in the PM's template ─────────────────────────────────────────────────────────────
@@ -307,7 +380,7 @@ function fromItem(item, prd) {
307
380
  if (k === 'refs') continue;
308
381
  for (const l of lines) for (const m of l.matchAll(LINK_RE)) if (!own.includes(m[0]) && !links.includes(m[0])) links.push(m[0]);
309
382
  }
310
- const refs = [prd ? `- PRD: \`${prd}\` · ${item.id}` : `- Item: ${item.id}`];
383
+ const refs = [prd ? `- ${item.refLabel || 'PRD'}: \`${prd}\` · ${item.task || item.id}` : `- Item: ${item.id}`];
311
384
  if (own) refs.push(own);
312
385
  for (const l of links) refs.push(`- ${l}`);
313
386
  t.sections.refs = refs.join('\n');
@@ -414,7 +487,7 @@ function anchorOf(rfm) {
414
487
  function draft(root, initiative, { dryRun = false, now } = {}) {
415
488
  const st = items(root, initiative);
416
489
  if (!st.ok) return st;
417
- if (!st.items.length) return { ok: false, error: `no ticket items found for ${initiative} — add a "User stories" or "Tickets" section to its PRD${st.prd ? ` (${st.prd})` : ''}, one subheading per ticket, such as "### TD-01 · Title"` };
490
+ if (!st.items.length) return { ok: false, error: `no ticket items found for ${initiative} — add a "User stories" or "Tickets" section to its PRD${st.prd ? ` (${st.prd})` : ''}, one subheading per ticket, such as "### TD-01 · Title"; or give it a done test (done_test_path) with its checks, or tasks (pmos item)` };
418
491
  const old = readDraft(root, initiative);
419
492
  const prev = old ? old.tickets : [];
420
493
  const byId = new Map(prev.map((t) => [t.id, t]));
@@ -447,7 +520,7 @@ function draft(root, initiative, { dryRun = false, now } = {}) {
447
520
  fm.epic_mode = anchor ? 'existing' : 'new';
448
521
  if (anchor && !fm.epic) fm.epic = anchor;
449
522
  }
450
- const result = { ok: true, initiative, draft: draftRel(root, initiative), sources: st.sources, tickets: out.length, changes, changed: !old || changes.length > 0 };
523
+ const result = { ok: true, initiative, draft: draftRel(root, initiative), sources: st.sources, from: st.from, tickets: out.length, changes, changed: !old || changes.length > 0 };
451
524
  if (dryRun || (old && !changes.length)) return result;
452
525
  writeDraft(root, initiative, { fm, tickets: out }, { now, prd: st.prd });
453
526
  return result;
@@ -17,7 +17,7 @@ const E = require('./idle-lab-engine.js');
17
17
  const COMMANDS = { lab: ['page', 'file', 'status'] };
18
18
  const GROUPS = { 'prototype-new': ['prototyped'], 'prototype-improve': ['improved'], 'scan-new': ['scanned', 'scan'], 'scan-improve': ['scanned', 'scan'] };
19
19
  const USAGE = [
20
- 'usage: pmos lab page|file|status — the idle lab: Claude prototypes and scans while you are away; each result waits under ✦ for your ✓',
20
+ 'usage: pmos lab page|file|status — the idle lab: PMOS prototypes and scans while you are away; each result waits under ✦ for your ✓',
21
21
  ' pmos lab page <url> (scan run) read one public page; it prints the page with line numbers',
22
22
  ' pmos lab page <n> [--from <line>] (scan run) print page n of this run again, from a line',
23
23
  ' pmos lab file prototyped --json - { "title", "why", "specimens": [{ "key": "A", "title", "caption", "file": "a.html" }] (2 or 3),',
@@ -12,7 +12,7 @@ const SR = require('./source-reads.js');
12
12
 
13
13
  const COMMANDS = { lead: ['put', 'show', 'due'] };
14
14
  const USAGE = [
15
- 'usage: pmos lead put|show|due — Claude\'s short lead for a popup, written ahead and shown first',
15
+ 'usage: pmos lead put|show|due — PMOS\'s short lead for a popup, written ahead and shown first',
16
16
  ' pmos lead put --key <pop:kind:id> --text "<lead>" [--cite "<what you read, when>"] …',
17
17
  ' the lead: why it matters now, what is asked or blocking, and what to do, in at most 400 characters; at most 4 cites',
18
18
  ' pmos lead show [<key>] the stored lead of one popup, or every stored lead',
@@ -2,13 +2,14 @@
2
2
  /* measure-cli.js — `pmos measure …`: record a measured value of a KR or a health budget, with its source (pm-os-absorb
3
3
  * Run 2, PRD R17, R23, R24).
4
4
  *
5
- * pmos measure add <anchor> <value> --source <path>@<sha> [--target <number>] [--unit <unit>] [--as-of YYYY-MM-DD]
5
+ * pmos measure add <anchor> <value> --source <path>@<sha>|connector:<name>|document:<path or link> [--how "<how it was read>"]
6
+ * [--target <number>] [--unit <unit>] [--as-of YYYY-MM-DD]
6
7
  * pmos measure list [<anchor>]
7
8
  * every command: [--json] [--root <dir>]
8
9
  *
9
10
  * The SAME writer the workspace page uses (lib/measurements.js). A measurement is evidence, not a PM act, so an agent
10
11
  * may write one: the line is attributed by lib/actor.js fromCli (the PM at a terminal, the bound agent session from
11
- * PMOS_SESSION, `agent:unknown` otherwise). The source is required: the workspace never computes a KR value, so a
12
+ * PMOS_SESSION, `agent:unknown` otherwise). The source is required, and a connector or document source needs --how: the workspace never computes a KR value, so a
12
13
  * group shows a value only from a line that says where it was read. `--as-of` is today (UTC) when it is not given.
13
14
  * Exit codes: 0 done, 1 refused, 2 usage.
14
15
  */
@@ -21,14 +22,18 @@ const { parseArgs } = require('./schedule-cli');
21
22
  const COMMANDS = { measure: ['add', 'list'] };
22
23
  const USAGE = [
23
24
  'usage: pmos measure add|list — measured values of KRs and health budgets',
24
- ' pmos measure add <anchor> <value> --source <path>@<sha> [--target <number>] [--unit <unit>] [--as-of YYYY-MM-DD]',
25
+ ' pmos measure add <anchor> <value> --source <source> [--how "<how it was read>"] [--target <number>] [--unit <unit>] [--as-of YYYY-MM-DD]',
25
26
  ' pmos measure list [<anchor>]',
26
27
  ' every command: [--json] [--root <dir>]',
27
28
  'The anchor is the parent_kr an initiative names: a KR such as "KR 2.1", or health:<id>. Quote an anchor with a space.',
28
- 'The source is the file the value was read from and the commit it was read at, for example planning/okrs/q4.md@1a2b3c4.',
29
+ 'The source is where the value was read:',
30
+ ' <path>@<sha> a file in this repository at a commit, for example planning/okrs/q4.md@1a2b3c4',
31
+ ' connector:<name> an analytics tool or tracker read through a connector, for example connector:amplitude',
32
+ ' document:<path or link> a shared document or sheet outside the repository',
33
+ 'A connector or document source needs --how: the query, chart or cell, so the value can be read again. --as-of is the day it was read.',
29
34
  ];
30
35
  const BOOL = new Set(['json', 'help']);
31
- const VALUE = new Set(['source', 'target', 'unit', 'as-of', 'root']);
36
+ const VALUE = new Set(['source', 'how', 'target', 'unit', 'as-of', 'root']);
32
37
 
33
38
  function parse(argv) {
34
39
  const rest = []; const bools = {};
@@ -70,7 +75,7 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
70
75
  if (json) { say(JSON.stringify({ ok: true, byAnchor: Object.fromEntries(anchors.map((a) => [a, (m.byAnchor[a] || []).map((x) => ({ ...x, by: actorLib.pageName(x.by) }))])), flags: m.flags })); return 0; }
71
76
  if (!anchors.length) say('No measurements yet.');
72
77
  for (const a of anchors) {
73
- for (const x of m.byAnchor[a] || []) say(`${a} · ${x.value}${x.unit || ''}${x.target === null ? '' : ` → ${x.target}${x.unit || ''}`} on ${x.as_of} · ${x.source} · ${actorLib.pageName(x.by)}`);
78
+ for (const x of m.byAnchor[a] || []) say(`${a} · ${x.value}${x.unit || ''}${x.target === null ? '' : ` → ${x.target}${x.unit || ''}`} on ${x.as_of} · ${x.source}${x.how ? ` (${x.how})` : ''} · ${actorLib.pageName(x.by)}`);
74
79
  }
75
80
  for (const f of m.flags) say(`! ${f.why}`);
76
81
  return 0;
@@ -89,11 +94,12 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
89
94
  if (flags.unit !== undefined) ev.unit = flags.unit;
90
95
  ev.as_of = flags['as-of'] || new Date(now == null ? Date.now() : now).toISOString().slice(0, 10);
91
96
  if (flags.source !== undefined) ev.source = flags.source;
97
+ if (flags.how !== undefined) ev.how = String(flags.how).trim();
92
98
  const actor = actorLib.fromCli({ isTTY: isTTY === undefined ? !!(process.stdin.isTTY && process.stdout.isTTY) : isTTY, env: env === undefined ? process.env : env });
93
99
  const r = measurements.appendFromCli(root, [ev], { actor, now });
94
100
  if (!r.ok) return fail(r.error);
95
101
  if (json) say(JSON.stringify({ ok: true, written: r.written, eid: r.lines[0].eid }));
96
- else say(`✓ ${anchor}: ${value}${ev.unit || ''} on ${ev.as_of} recorded (source ${ev.source})`);
102
+ else say(`✓ ${anchor}: ${value}${ev.unit || ''} on ${ev.as_of} recorded (source ${ev.source}${ev.how ? `, ${ev.how}` : ''})`);
97
103
  return 0;
98
104
  }
99
105
 
@@ -4,13 +4,15 @@
4
4
  *
5
5
  * readMeasurements(root) → {
6
6
  * ok: true,
7
- * byAnchor: { [anchor]: [{ value, target, unit, as_of, source, by, at }] }, oldest first; `source` is "path@sha"
7
+ * byAnchor: { [anchor]: [{ value, target, unit, as_of, source, how, by, at }] }, oldest first; `source` is "path@sha",
8
+ * "connector:<name>" or "document:<path or link>"; `how` is null for path@sha
8
9
  * flags: [{ kind, eid, why }],
9
10
  * }
10
11
  * latest(result, anchor) → the newest measurement of `anchor` by as_of, or null
11
12
  * appendFromUi(root, events, { actor, now }) → { ok, written, lines } | { ok: false, status, error, index }
12
13
  * appendFromCli(root, events, { actor, now }) → the same
13
14
  * checkEvent(ev) → null | error text the caller-side checks, shared with `pmos measure`
15
+ * sourceKind(source) → 'repo' | 'connector' | 'document' | null
14
16
  *
15
17
  * `anchor` is the initiative's parent_kr as written (a KR id, or `health:<id>`, D59). A measurement needs a source; an
16
18
  * agent may write one (it is evidence, not a PM act), so the actor comes from actor.js, never from the caller.
@@ -18,12 +20,18 @@
18
20
  *
19
21
  * THE `measured` LINE (the shared contract):
20
22
  * { v: 1, eid, ev: 'measured', anchor, value: <number>, target: <number> | null, unit?: '%'|…, as_of: 'YYYY-MM-DD',
21
- * source: '<path>@<sha>', by, via, at }
23
+ * source: '<path>@<sha>' | 'connector:<name>' | 'document:<path or link>', how?: '<how it was read>', by, via, at }
22
24
  * pmOnly(rec) → false: a measurement is evidence, not a PM act.
23
25
  *
24
- * `source` is a repository-relative path, `@`, and a commit sha of 7 to 40 hex characters: the file the number was
25
- * read from, at the commit it was read at. The writer does not open it (no read outside the call's own checks), so a
26
- * wrong path is the writer's caller's error; scripts/check-measurements.js reports a path that is not in the tree.
26
+ * `source` is one of three kinds:
27
+ * repo a repository-relative path, `@`, and a commit sha of 7 to 40 hex characters: the file the number was read
28
+ * from, at the commit it was read at.
29
+ * connector `connector:<name>`: an analytics tool or tracker read through a connector (Amplitude, GA4, Jira, …).
30
+ * document `document:<path or link>`: a shared document or sheet outside the repository.
31
+ * A connector or document source carries `how`, one line on how the value was read (the query, the chart, the cell), so
32
+ * a reader can read it again; `as_of` is the date it was read. This matches `pmos report read` (launch simulation W4).
33
+ * The writer does not open a source (no read outside the call's own checks), so a wrong path is the writer's caller's
34
+ * error; scripts/check-measurements.js reports a path that is not in the tree.
27
35
  *
28
36
  * The fold is order-free, like lib/plan-items.js: byte-identical duplicates count once, one eid with two contents keeps
29
37
  * the first. The ledger is one per repository: lib/plan-ledgers.js ledgerPath(root, 'measurements'). Nothing is cached.
@@ -42,9 +50,12 @@ const AT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
42
50
  /** A KR id as the OKR files write it, or a health budget or a domain (D59, D67). One line, no control characters. */
43
51
  const ANCHOR_RE = /^(?:health:[a-z0-9][a-z0-9-]{0,59}|domain:[a-z0-9][a-z0-9-]{0,59}|[A-Za-z0-9][A-Za-z0-9 .:_-]{0,79})$/;
44
52
  const SOURCE_RE = /^([A-Za-z0-9_][A-Za-z0-9_./-]{0,239})@([0-9a-f]{7,40})$/;
53
+ const CONNECTOR_RE = /^connector:([A-Za-z0-9][A-Za-z0-9 ._-]{0,59})$/;
54
+ const DOCUMENT_RE = /^document:([^\x00-\x1f\x7f]{1,300})$/;
55
+ const HOW_RE = /^[^\x00-\x1f\x7f]{1,200}$/;
45
56
  const UNIT_RE = /^[^\s\x00-\x1f]{1,12}$/;
46
57
  const WRITER_SET = Object.freeze(['v', 'eid', 'by', 'via', 'at', 'override', 'pm', 'actor', 'nonce']);
47
- const CALLER_KEYS = Object.freeze(['anchor', 'value', 'target', 'unit', 'as_of', 'source']);
58
+ const CALLER_KEYS = Object.freeze(['anchor', 'value', 'target', 'unit', 'as_of', 'source', 'how']);
48
59
  const STORED_KEYS = Object.freeze(['v', 'eid', 'ev', 'by', 'via', 'at', ...CALLER_KEYS]);
49
60
  const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
50
61
 
@@ -73,6 +84,15 @@ function parseSource(s) {
73
84
  return { path: m[1], sha: m[2] };
74
85
  }
75
86
 
87
+ /** 'repo' (path@sha), 'connector' (connector:<name>), 'document' (document:<path or link>), or null. */
88
+ function sourceKind(s) {
89
+ if (!isStr(s) || s !== s.trim()) return null;
90
+ if (parseSource(s)) return 'repo';
91
+ if (CONNECTOR_RE.test(s)) return 'connector';
92
+ const d = DOCUMENT_RE.exec(s);
93
+ return d && d[1].trim() ? 'document' : null;
94
+ }
95
+
76
96
  /** The checks on what a caller sends (the writer runs them; `pmos measure` runs them before it writes). */
77
97
  function checkEvent(ev) {
78
98
  if (!ev || typeof ev !== 'object' || Array.isArray(ev)) return 'each line must be a JSON object';
@@ -86,8 +106,11 @@ function checkEvent(ev) {
86
106
  if (has(ev, 'target') && ev.target !== null && (typeof ev.target !== 'number' || !Number.isFinite(ev.target))) return 'target must be a number, or null';
87
107
  if (has(ev, 'unit') && !(isStr(ev.unit) && UNIT_RE.test(ev.unit))) return 'unit must be a short word with no spaces, like %';
88
108
  if (!dateOk(ev.as_of)) return 'as_of must be YYYY-MM-DD';
89
- if (!has(ev, 'source') || ev.source === '' || ev.source == null) return 'a measurement needs a source: <path>@<commit sha>';
90
- if (!parseSource(ev.source)) return 'source must be <repository-relative path>@<commit sha of 7 to 40 hex characters>';
109
+ if (!has(ev, 'source') || ev.source === '' || ev.source == null) return 'a measurement needs a source: <path>@<commit sha>, connector:<name> or document:<path or link>';
110
+ const kind = sourceKind(ev.source);
111
+ if (!kind) return 'source must be <repository-relative path>@<commit sha of 7 to 40 hex characters>, connector:<name> or document:<path or link>';
112
+ if (has(ev, 'how') && !(isStr(ev.how) && HOW_RE.test(ev.how) && ev.how.trim() === ev.how)) return 'how must be one line of at most 200 characters';
113
+ if (kind !== 'repo' && !has(ev, 'how')) return `a ${kind} source needs how the value was read (the query, chart or cell), so it can be read again`;
91
114
  return null;
92
115
  }
93
116
 
@@ -127,7 +150,7 @@ function readMeasurements(root) {
127
150
  seen.set(rec.eid, text);
128
151
  (out.byAnchor[rec.anchor] = out.byAnchor[rec.anchor] || []).push({
129
152
  value: rec.value, target: Number.isFinite(rec.target) ? rec.target : null, unit: rec.unit || null,
130
- as_of: rec.as_of, source: rec.source, by: rec.by, at: rec.at,
153
+ as_of: rec.as_of, source: rec.source, how: isStr(rec.how) ? rec.how : null, by: rec.by, at: rec.at,
131
154
  });
132
155
  }
133
156
  for (const rows of Object.values(out.byAnchor)) rows.sort((a, b) => String(a.as_of).localeCompare(String(b.as_of)) || String(a.at).localeCompare(String(b.at)));
@@ -164,7 +187,7 @@ function append(root, events, actor, { now } = {}) {
164
187
  last = Math.max(clock, last + 1);
165
188
  const rec = { v: 1, eid: newEventId(), ev: 'measured', anchor: ev.anchor, value: ev.value, target: has(ev, 'target') ? ev.target : null };
166
189
  if (has(ev, 'unit')) rec.unit = ev.unit;
167
- Object.assign(rec, { as_of: ev.as_of, source: ev.source, by: actor.by, via: actor.via, at: new Date(last).toISOString() });
190
+ Object.assign(rec, { as_of: ev.as_of, source: ev.source }, has(ev, 'how') ? { how: ev.how } : {}, { by: actor.by, via: actor.via, at: new Date(last).toISOString() });
168
191
  return rec;
169
192
  });
170
193
  let file;
@@ -186,4 +209,4 @@ function appendFromUi(root, events, { actor, now } = {}) { return append(root, e
186
209
  /** `pmos measure` (actor.fromCli's actor; an agent may write a measurement). */
187
210
  function appendFromCli(root, events, { actor, now } = {}) { return append(root, events, actor, { now }); }
188
211
 
189
- module.exports = { MAX_LINES, readMeasurements, latest, pmOnly, checkEvent, parseSource, lineErr, appendFromUi, appendFromCli };
212
+ module.exports = { MAX_LINES, readMeasurements, latest, pmOnly, checkEvent, parseSource, sourceKind, lineErr, appendFromUi, appendFromCli };