create-pmos 0.829.0 → 0.831.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/package.json +149 -49
  2. package/payload/KIT-VERSION +1 -1
  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/workspace/briefing-premium-board-test.js +1 -1
  7. package/workspace/briefing-premium-insights-test.js +1 -1
  8. package/workspace/changelog.json +148 -22
  9. package/workspace/guide/agent-capabilities.md +1 -1
  10. package/workspace/guide/backlog.md +12 -1
  11. package/workspace/guide/cli.md +20 -1
  12. package/workspace/guide/home.md +1 -1
  13. package/workspace/guide/layout.md +3 -0
  14. package/workspace/lib/anchor-id.js +226 -0
  15. package/workspace/lib/artefacts-cli.js +25 -1
  16. package/workspace/lib/code-map.js +8 -2
  17. package/workspace/lib/factory-floor.js +16 -8
  18. package/workspace/lib/features.json +14 -13
  19. package/workspace/lib/initiative-cli.js +67 -2
  20. package/workspace/lib/lessons-draft.js +242 -0
  21. package/workspace/lib/people-cli.js +9 -1
  22. package/workspace/lib/people-prep.js +140 -0
  23. package/workspace/lib/pmos-verbs.js +2 -0
  24. package/workspace/lib/prefs-sync.js +1 -1
  25. package/workspace/lib/print-cli.js +49 -0
  26. package/workspace/lib/print-pdf.js +96 -0
  27. package/workspace/lib/review-reasons.js +121 -9
  28. package/workspace/lib/route-modules.js +1 -0
  29. package/workspace/lib/routes-c3-strategy.js +2 -1
  30. package/workspace/lib/routes-proposals.js +2 -2
  31. package/workspace/lib/routes-report-design.js +3 -1
  32. package/workspace/lib/routes-skill-map.js +39 -0
  33. package/workspace/lib/routes-strategy-card.js +13 -6
  34. package/workspace/lib/skill-map.js +199 -0
  35. package/workspace/lib/team-cli.js +20 -1
  36. package/workspace/package-lock.json +2 -2
  37. package/workspace/package.json +1 -1
  38. package/workspace/public/pm/action-keys.js +1 -0
  39. package/workspace/public/pm/ask-here-ctx.js +25 -1
  40. package/workspace/public/pm/ask-here.css +7 -0
  41. package/workspace/public/pm/ask-here.js +15 -2
  42. package/workspace/public/pm/bd-backlog.css +61 -0
  43. package/workspace/public/pm/bd-backlog.js +62 -8
  44. package/workspace/public/pm/bd-work.js +12 -1
  45. package/workspace/public/pm/card-fold.js +123 -0
  46. package/workspace/public/pm/code-map.js +15 -4
  47. package/workspace/public/pm/cozy-board.css +5 -1
  48. package/workspace/public/pm/cozy-ev.css +7 -0
  49. package/workspace/public/pm/cozy-nav.js +2 -0
  50. package/workspace/public/pm/cozy-pop-work.js +2 -0
  51. package/workspace/public/pm/cozy-search.js +2 -2
  52. package/workspace/public/pm/factory.js +199 -0
  53. package/workspace/public/pm/pop-cap.js +5 -3
  54. package/workspace/public/pm/premium-board.js +4 -0
  55. package/workspace/public/pm/premium-report-read.js +11 -2
  56. package/workspace/public/pm/print-pdf.js +191 -0
  57. package/workspace/public/pm/readonly.js +2 -0
  58. package/workspace/public/pm/review-reasons.js +19 -5
  59. package/workspace/public/pm/skill-map.js +57 -0
  60. package/workspace/public/premium-board.html +2 -0
  61. package/workspace/test-lists/anchor-id.json +9 -0
  62. package/workspace/test-lists/card-fold.json +9 -0
  63. package/workspace/test-lists/factory-page-ui.json +9 -0
  64. package/workspace/test-lists/lessons-on-close.json +9 -0
  65. package/workspace/test-lists/people-prep.json +9 -0
  66. package/workspace/test-lists/print-pdf.json +9 -0
  67. package/workspace/test-lists/skill-map.json +9 -0
  68. package/workspace/test-lists/surface-ask-card.json +9 -0
  69. package/workspace/test-lists/voice-files.json +9 -0
@@ -135,6 +135,7 @@ None of these briefs an agent or takes an item. Do that from the item's card on
135
135
  - `pmos people show <person>` shows one person's page: interactions, tone, shared work, notes and handles. `<person>` is the id from the list or the full name.
136
136
  - `pmos people record --file <sightings.json>` records the people a session saw. Agent sessions run it. It must name who recorded it: in a workspace session the session token does this; outside the workspace, add `--by <profile>`. A sighting already recorded is skipped and counted.
137
137
  - `pmos people settings` prints `calendar names: on` or `calendar names: off`. The morning brief reads it before it records attendees.
138
+ - `pmos people prep <person>` prepares a 1:1 from the tasks that person owns: what they shipped (Done in the last 14 days), where they are stuck (open tasks that are late or blocked), and one thing to recognise (a task Done on or before its due day). Each line names its task and initiative. `--days N` changes the 14 days; `--json` prints the brief. A one-word name matches a first name only when one owner has it. It reads only. On Today, the Ask card of a person's name offers it as its first ✦, Prepare my 1:1 with them.
138
139
  - `pmos people help` prints the commands.
139
140
  - `pmos people map <initiative>` lists who decides, who must agree and who needs to know on one initiative, and when each last heard from you. The names come from the record's `decider`, `owner` or `sponsor`, the initiative's sign-offs and objections, and the people whose Jira, meeting notes or mail name it. Each is a draft until you keep it. A name not updated in 3 weeks shows a ✦ draft update for you to send. Add `--json` for the rows. The People block of the initiative on Work shows the same map.
140
141
  - `pmos people keep <initiative> <person> [--group decides|agree|know]` keeps a name on the map, in that group. `pmos people drop <initiative> <person>` takes it off for good. `pmos people told <initiative> <person>` records that you sent them an update today. `pmos people undo <initiative> <person>` takes back the last of these. PMOS never sends an update itself.
@@ -292,6 +293,7 @@ PMOS looks for problems that repeat in a product (your Undos and ✕ reasons, re
292
293
  - `pmos team status`: who works on what, what waits, and the inbox entries of ended dispatches.
293
294
  - `pmos team pause <role|all>` and `pmos team resume <role|all>`: stop or restart a role's runs. `pmos ai off team` stops the whole team.
294
295
  - `pmos team dispatch --unit <unit>`: dispatch the roles for the unit's first open initiative in Roadmap order. `pmos team pause --unit <unit>` and `pmos team resume --unit <unit>` stop or restart every role run on that unit's initiatives.
296
+ - `pmos team skills`: the team skill map for the last 90 days. Each person has what they are strong at and what they are often corrected on, from sign-offs and decisions, with no scores and no ranking, and one ✦ pairing. `--as <name>` shows only that person's row. `pmos team skills skip <key>` skips the pairing for the next one, and `pmos team skills undo <key>` brings it back. The same map is the Team skills block on Work. It is only for the person and their lead, so it is never in a report or on a published page.
295
297
  - Inside a role run only: `pmos team wrote <path>`, `pmos team done "<summary>" [--propose <path> "<what>"]` and `pmos team verdict <path> pass|fail "<why>"`.
296
298
 
297
299
  [What PMOS does behind the scenes](agent-capabilities.md) lists each role, what it may write and its rules.
@@ -424,10 +426,20 @@ Show where the team is short before you ask for headcount. Run it in the product
424
426
  - PMOS never writes over a brief. It calls no model and sends nothing. Edit the brief and share it yourself.
425
427
  - `pmos hire count [--days 7]` prints how many briefs were drafted in the last days. Its last line is the number.
426
428
 
429
+ ### pmos print: one clean page to print or save as PDF
430
+
431
+ Print a report, a document or an initiative for a reader who wants paper or a PDF. Run it in the product's repository, or pass `--root <dir>`. No running workspace is needed. In the workspace the same page comes from ⋯ › Print or PDF on an initiative, ⋯ › Download › Print or PDF on a report, and the print icon on Work's list.
432
+
433
+ - `pmos print <initiative id>` writes the initiative's record as a print page. `pmos print <file.md>` does the same for any report or document of the product. The page is `<name>.print.html` in the current folder, or the file `--out` names. Open it and choose Save as PDF.
434
+ - Every printed page shows the title, the date and "page N of M". There are no buttons, panels or chat, and a section does not split across pages. A state prints as its word (On track, Late), not as a colour.
435
+ - `pmos print brand` names the brand at the top right of each page: the product's own design system, when it has one. PMOS's own brand is not printed.
436
+ - PMOS prints only the product's own files: a file outside the product is refused and nothing is written. Nothing is sent.
437
+
427
438
  ### pmos voice: customer comments grouped by reason
428
439
 
429
440
  Act on the reason behind a score, not on the score. Run it in the product's repository, or pass `--root <dir>`, or ask the chat to "import these reviews" or "group the survey comments". No running workspace is needed. Work shows the same reasons as Customer voice, under the strategy, on a Board that shows one product.
430
441
 
442
+ - You do not have to import anything. When Work opens, PMOS reads each review or survey export it finds in the product's folder by itself: a CSV or JSON file whose name says review, survey, nps, csat, feedback or rating, at most 3 folders deep, with a text, comment or review column. Work names the file it read, and Undo on that line takes the file's comments back until the file changes.
431
443
  - `pmos voice import <file>` reads an export from a survey tool or an app store: a CSV with a header row, or a JSON list. The columns are `text`, `reason`, `score` (or `rating`), `scale` (5 for stars, 10 for an NPS survey), `source` (survey, review or other) and `at` (or `date`). A comment imported twice counts once.
432
444
  - `pmos voice add --text "<comment>" [--reason "<reason>"] [--score 2] [--scale 5]` adds one comment.
433
445
  - `pmos voice reason <comment id> "<reason>"` names the reason of a comment. A comment with no reason joins a reason it shares 2 words with; otherwise it stays unsorted, and `pmos voice list` shows its id.
@@ -674,7 +686,7 @@ A page that keeps breaking should get fixed before it gets a new feature. This c
674
686
 
675
687
  | Command | What it does |
676
688
  |---|---|
677
- | `pmos initiative new "<title>" --lane <lane> --anchor <anchor> [--intent "<text>"] [--id <id>] [--raised-by "<who>"]` | Makes the record and puts it at the end of the Roadmap. |
689
+ | `pmos initiative new "<title>" --lane <lane> --anchor <anchor> [--intent "<text>"] [--id <id>] [--raised-by "<who>"]` | Makes the record and puts it at the end of the Roadmap. An anchor id that is not declared is refused, with the nearest id. |
678
690
  | `pmos initiative new --from <capture> [--anchor <anchor>]` | Adds the initiative a capture proposes. |
679
691
  | `pmos initiative top <id>` | Ranks it first. |
680
692
  | `pmos initiative up <id>` | Moves it one place up. |
@@ -692,6 +704,11 @@ A page that keeps breaking should get fixed before it gets a new feature. This c
692
704
  | `pmos initiative status <id> "<text>" [--line "<line>"]` | Saves a status. The full text goes to the log. The line is yours, or else the first 12 words. |
693
705
  | `pmos initiative status-migrate [--apply]` | Counts the statuses longer than 12 words. With `--apply`, gives each one a line and moves the full text to the log. |
694
706
  | `pmos initiative status-undo <batch>` | Undoes a `status-migrate`. A line edited since keeps its edit. |
707
+ | `pmos initiative anchor <id>` | Shows the anchor id it counts under. |
708
+ | `pmos initiative anchor <id> "<anchor>"` | Changes the anchor. The id must be one the OKR files or the health budgets declare; else PMOS refuses it and names the nearest id. Text after the id goes to `anchor_note`. |
709
+ | `pmos initiative anchors` | Lists the anchor ids you can pick: key results, health budgets and domains. |
710
+ | `pmos initiative anchors fold [--apply]` | Lists the anchors that have text after the id, and writes nothing. With `--apply`, keeps the id in `parent_kr` and moves the text to `anchor_note`. The counts per key result do not change. |
711
+ | `pmos initiative anchors undo <batch>` | Undoes a fold on this computer. An anchor edited since keeps its edit. |
695
712
  | `pmos initiative raised-by <id>` | Shows who raised it: you, a teammate, a customer, PMOS or the tracker. |
696
713
  | `pmos initiative raised-by <id> "<who>"` | Saves who raised it: `you`, `pmos`, `tracker`, `"teammate: <name>"` or `"customer: <name>"`. `none` removes it. |
697
714
  | `pmos initiative kind <id>` | Shows the kind of work, and for each lifecycle stage whether PMOS works it with you, watches it in Jira or hides it. |
@@ -860,6 +877,8 @@ The ledger is `driver.jsonl` in the state folder of the repository (`pmos/state`
860
877
 
861
878
  `pmos artefacts show [<scope>]` lists the seven artefacts of a scope: Intent, Goal, Narrative, Experiment, Specimens, Done test and Lessons. The scope is `portfolio` (the default), `board:<id>`, `goal:<id>` or `experiment:<id>`; `experiment:<id>` is an initiative, and `initiative:<id>` works too. `pmos artefacts map` lists what each older core document, driver proposal kind, report cadence and lane becomes. `pmos artefacts migrate` puts every older record under its artefact as a pointer: issued and draft core documents, kept driver proposals and report drafts. It deletes and moves nothing, and a second run carries nothing new. `pmos artefacts set <scope> <artefact> [<field>] --text "<text>"` writes one field, and `pmos artefacts undo <id>` takes it back. A Done test check on `experiment:<id>` is also written to the experiment's done test file (`planning/done-tests/<id>.md`, or the file the record names), and the record gets `done_test_path:`; an Experiment kill condition becomes the record's `kill:`. So the ladder, the gates and `pmos jira draft` count it. A done test file you wrote by hand is left alone. The case card on an initiative reads `experiment:<id>`: Problem is `experiment why`, Goal is `experiment hypothesis` and Done when is `done-test check`. A line the ledger does not hold comes from the record's own Problem, Goal and Done test sections, and `pmos why` and `pmos ready check` read the ledger too, so a line written either way shows in all three. Intent is yours: an agent proposes a change to it and waits for you. Goal is read from the OKRs, health budgets and readings, so you cannot type it.
862
879
 
880
+ `pmos artefacts lessons <initiative>` lists an initiative's Lessons, each with its id so `pmos artefacts undo <id>` can take one back. When an outcome check is recorded on an initiative, or you keep the ✦ that stops it, PMOS drafts up to five Lessons lines from its experiment, its done test, the result and the decisions that name it. Each line names what it came from. `pmos artefacts lessons <initiative> --draft` drafts them from the chat once the experiment has closed. PMOS never drafts where you wrote lessons yourself, and drafts once: a second check adds nothing.
881
+
863
882
  ### pmos coredoc: core documents
864
883
 
865
884
  `pmos coredoc write --scope <scope> --key <key> --file <path>` writes one draft of a core document. The scope is `portfolio`, `board:<id>` or `initiative:<id>`. With `--file -` the command reads the document from standard input. The command refuses a scope it does not know, a key that is not a document of that level, and a document that PMOS reads from another source. A background run can write only the document it was started for. The command writes a draft and nothing else: you issue it on the page.
@@ -189,7 +189,7 @@ Some features, such as Notes, open as a plain card in the Viewer. Each one works
189
189
 
190
190
  - **Guide** (the **?** icon in the menu) opens this guide in the Viewer.
191
191
  - **What PMOS can do** lists every feature by job, each with how to reach it: its command (press it to put it in the chat box), its page, or its keys. Open it from Ctrl K (type "features"), from the ? key list, or from the guide. Features new since you last looked come first.
192
- - **Search** (Ctrl K or ⌘K, or `/`) finds initiatives, documents, sessions and files in your work. It always reads the repository and all its worktrees, so it has no worktree picker. It also reaches every page, each Settings section, the themes and the actions of the item you last pointed at: type "lib" to go to Library, or "conn" for Settings › Connectors.
192
+ - **Search or ask** (Ctrl K or ⌘K, or `/`) finds initiatives, documents, sessions and files in your work. It always reads the repository and all its worktrees, so it has no worktree picker. It also reaches every page, each Settings section, the themes and the actions of the item you last pointed at: type "lib" to go to Library, or "conn" for Settings › Connectors.
193
193
  - **Dates** show the year only when the year is not this year, for example "Jun 23 ’27". New for you shows a due date as "due 25 Nov".
194
194
  - **Settings** holds the workspace settings. **General** holds the theme (Light, Dark or Auto) and **Product**, which names the product the page reads. **Connectors** shows when PMOS last read each source. A source that is old or failed has an amber dot and ↻ to read it again. ↻ in the Connectors header reads every source again. While a source is old, an amber box at the top of Settings names it, with ↻.
195
195
 
@@ -100,6 +100,8 @@ On a phone, PMOS opens on Today. It is one page with no boxes: **Where it stands
100
100
 
101
101
  On a computer, Work is built from the parts of the PMOS design system. The top line shows the path (**Work ›** and the product; press the product to switch it), the tabs **Initiatives**, **Backlog** and **This sprint**, then Ask PMOS, Search, New initiative and More. Ask PMOS (the chat bubble, on a computer) opens a chat about the product shown, in the one popup; with several products it opens Ask PMOS about the page. A program's own chat is the chat bubble in its popup.
102
102
 
103
+ **Fold a big card.** **Strategy**, **Where it stands** and **North Star** each have a chevron at the right of their head. Press it to fold the card to its head line; **Where it stands** keeps its first sentence. When PMOS has a suggestion in a folded card, a small **✦ 1** shows beside the head; press it to open the card. PMOS keeps each fold for you, per page and per card, on every device you use. Press the chevron again to open the card.
104
+
103
105
  **Initiatives** has three blocks:
104
106
 
105
107
  - **Where it stands.** One paragraph that says what is happening and why it matters: an initiative past its milestone, with the cause from the record (a Jira ticket that is blocked, a step that waits on you), an initiative that sat in a stage with no dates and for how long, and the next decision point. Press a name to open the initiative. Under it, PMOS shows one suggestion from its open proposals, with **Why**, **PMOS will** (the exact steps), **What changes** and **Based on** (the sources). The pencil opens the initiative so you can change the proposal first, ✓ does it (with Undo), and ✕ drops it. When nothing needs saying, the block does not show.
@@ -320,6 +322,7 @@ Right-click any part of a page to ask PMOS about it. On a phone, press and hold
320
322
  - When the top line names the wrong thing, press **↑** to step out one level: the field, then the item, then the section, then the page.
321
323
  - Under it is the item as Work holds it now, with its usual buttons. A task's date shows three later dates to move it to. Every change has Undo.
322
324
  - Up to three questions show with ✦. Press one, or type your own question in the box.
325
+ - **What PMOS can do** lists up to four features for that kind of item, such as **Why this work exists** for an initiative or **Strategy** for a product. One press asks it in the card, about that item, with nothing to type. A section, the page, or an item no feature acts on shows no such line.
323
326
  - **⤢** opens the same conversation in the full chat. **×** or Escape closes the card.
324
327
 
325
328
  Right-click keeps the browser's own menu in a text box, on a link, on selected text and in the terminal. Hold Shift to get the browser's menu anywhere.
@@ -0,0 +1,226 @@
1
+ 'use strict';
2
+ /* anchor-id.js — an initiative's anchor is one id (factory job anchor-ids, idea A547; done test planning/done-tests/anchor-ids.md).
3
+ *
4
+ * `parent_kr` names a key result, an objective, `health:<id>` or `domain:<id>`. Many records add free text after the id
5
+ * ("q3-2026:o1:kr2 (the loop runs end-to-end)"). The resolver (scripts/anchor-resolve.js) reads past that text, but a reader
6
+ * that compares the raw text counts such a record under a key of its own, so the counts per key result split.
7
+ *
8
+ * split(raw) → { id, note } the leading id, and the text after it as written ('' when none)
9
+ * anchorId(raw) → id the leading id alone; '' for no anchor. PURE: every reader that compares parent_kr uses it
10
+ * nearest(text, values) → value | null the declared value closest to a refused text (for "nearest: …")
11
+ * check(root, raw) → { ok, id, note, value } | { ok: false, error, nearest } is the id declared (OKR files, health budgets)
12
+ * list(root) → [{ value, kind, group, label }] the ids you can pick (lib/initiative-rows.js anchorsOf list)
13
+ * plan(root) → { total, items: [{ id, from, anchor, note }], kept: [{ id, from, why }] } what a fold would move
14
+ * fold(root, { apply, actor, stateDir, now }) → plan(), and with apply the records written and a batch to undo
15
+ * undo(root, batch, { actor, stateDir }) → { ok, restored, kept }
16
+ * readAnchorLine · foldAnchor · unfoldAnchor the record edits the fold and `pmos initiative new|anchor` make (see THE RECORD EDITS)
17
+ *
18
+ * The fold only moves text: `parent_kr: <id>` and `anchor_note: <the rest>`. It folds a record only when the id alone resolves to
19
+ * the same key as the whole text, so no count changes. Its undo ledger is local runtime state (<stateDir>/anchor-folds.jsonl),
20
+ * not a tracked record: the fold is one command the PM runs once, and its Undo is for that same machine.
21
+ */
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+
25
+ // The legacy "okrs-q3-2026 → O1.KR1" form: the id is the token after the arrow (planning/initiatives/README.md, canonical form).
26
+ const ARROW = /^(\S+)\s*(?:→|->)\s*(\S+)/;
27
+ const TOKEN = /^[^\s(]+/;
28
+
29
+ function split(raw) {
30
+ const text = raw == null ? '' : String(raw).trim();
31
+ if (!text) return { id: '', note: '' };
32
+ const a = ARROW.exec(text);
33
+ if (a) {
34
+ const id = a[2].replace(/[,;]+$/, '');
35
+ return { id, note: `${a[1]} → ${text.slice(a[0].length).trim()}`.trim() }; // every word stays: "okrs-q3-2026 → # or x"
36
+ }
37
+ const m = TOKEN.exec(text);
38
+ if (!m) return { id: '', note: text };
39
+ const id = m[0].replace(/[,;]+$/, '');
40
+ return { id, note: text.slice(id.length).trim() };
41
+ }
42
+ const anchorId = (raw) => split(raw).id;
43
+
44
+ // The comparable form of an anchor: lower case, no period prefix (q3-2026:), '.' and ':' the same, no word "okrs-…".
45
+ const norm = (s) => String(s || '').toLowerCase().replace(/^okrs-[^\s]*\s*(?:→|->)\s*/, '').replace(/^q[1-4]-\d{4}:/, '').replace(/\./g, ':').replace(/[^a-z0-9:_-]/g, '');
46
+ function dist(a, b) {
47
+ const m = a.length, n = b.length;
48
+ if (!m) return n; if (!n) return m;
49
+ let prev = Array.from({ length: n + 1 }, (_, j) => j);
50
+ for (let i = 1; i <= m; i++) {
51
+ const cur = [i];
52
+ for (let j = 1; j <= n; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
53
+ prev = cur;
54
+ }
55
+ return prev[n];
56
+ }
57
+ function nearest(text, values) {
58
+ const t = norm(anchorId(text));
59
+ let best = null, bd = Infinity;
60
+ for (const v of values || []) { const d = dist(t, norm(v)); if (d < bd) { bd = d; best = v; } }
61
+ return best;
62
+ }
63
+
64
+ const rows = () => require('./initiative-rows.js');
65
+ const list = (root) => rows().anchorsOf(root).list();
66
+
67
+ function check(root, raw) {
68
+ const { id, note } = split(raw);
69
+ if (!id) return { ok: false, error: 'an initiative needs an anchor: a key result, or health:<id> from the health budgets (D59)', nearest: null };
70
+ const A = rows().anchorsOf(root);
71
+ const r = A.resolve(id);
72
+ if (r.status === 'resolved') return { ok: true, id, note, value: id, key: r.key };
73
+ const near = nearest(id, A.list().map((x) => x.value));
74
+ return { ok: false, id, note, error: `the anchor "${id}" is not declared in the OKR files or the health budgets (D59)${near ? `; nearest: ${near}` : ''}. pmos initiative anchors lists the ids`, nearest: near };
75
+ }
76
+
77
+
78
+ // THE RECORD EDITS. They live here, not in lib/initiative-writer.js, so a change to them reaches only the suites that name this file
79
+ // (run-tests.js --changed follows lib/initiative-writer.js to every suite). They edit the front matter lines of one record, like the
80
+ // writer's own setAnchor: the same record file rule (an id inside the engine's initiatives folder) and the same quoting.
81
+ const ONE_LINE = (v, max) => typeof v === 'string' && v.trim().length >= 1 && v.trim().length <= max && !/[\r\n\x00-\x08\x0b-\x1f]/.test(v);
82
+ const refuse = (status, error, field) => ({ ok: false, status, error, field: field || null });
83
+ const PLAIN = (s) => !/: |:$| #|["\\]/.test(s) && !/^[-?:,[\]{}#&*!|>'%@`]/.test(s);
84
+ const q = (s) => '"' + String(s).trim().replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
85
+ const frontOfText = (text) => /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(text);
86
+ function unquote(v) {
87
+ const t = String(v || '').trim();
88
+ if (/^".*"$/.test(t)) return t.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
89
+ if (/^'.*'$/.test(t)) return t.slice(1, -1).replace(/''/g, "'");
90
+ return t;
91
+ }
92
+ const actorLib = () => require('./actor.js');
93
+ function recordFile(root, id) {
94
+ const W = require('./initiative-writer.js');
95
+ if (typeof id !== 'string' || !W.ID_RE.test(id) || id.includes('..')) return refuse(400, 'name the initiative by its id', 'id');
96
+ let dir;
97
+ try { dir = fs.realpathSync(require('./console-state').loadEngine().engine.layout(root).initiatives); } catch { return refuse(404, `no initiative ${id}`, 'id'); }
98
+ const file = path.join(dir, `${id}.md`);
99
+ let st;
100
+ try { st = fs.lstatSync(file); } catch { return refuse(404, `no initiative ${id}`, 'id'); }
101
+ if (!st.isFile()) return refuse(409, `the record of ${id} is not a plain file — nothing was saved`, 'id');
102
+ return { ok: true, file };
103
+ }
104
+
105
+ /** The `parent_kr:` line of a record as text (anchor-ids, A547): { ok, text, spans, hasNote }. `spans` is true when the value runs on
106
+ * to the next line (an indented continuation), which a one-line edit must not touch. */
107
+ function readAnchorLine(root, id) {
108
+ const f = recordFile(root, id);
109
+ if (!f.ok) return f;
110
+ const m = frontOfText(fs.readFileSync(f.file, 'utf8'));
111
+ if (!m) return { ok: true, text: '', spans: false, hasNote: false };
112
+ const lines = m[1].split(/\r?\n/);
113
+ const at = lines.findIndex((l) => /^parent_kr:/.test(l));
114
+ return { ok: true, text: at >= 0 ? unquote(lines[at].slice(10)) : '', spans: at >= 0 && /^\s+\S/.test(lines[at + 1] || ''), hasNote: lines.some((l) => /^anchor_note:/.test(l)) };
115
+ }
116
+
117
+ /** anchor-ids (A547): `parent_kr: <id>` and `anchor_note: <note>` in place of one anchor with text after its id. Writes only when the
118
+ * line still reads `expect` (lib/anchor-id.js fold checked it), so an edit made since is never overwritten. */
119
+ function foldAnchor(root, id, { anchor, note, expect } = {}, { actor } = {}) {
120
+ if (!actorLib().valid(actor)) return refuse(500, 'initiative-writer: the caller must pass the actor from pm-guard.js or actor.js');
121
+ const a = typeof anchor === 'string' ? anchor.trim() : '', n = typeof note === 'string' ? note.trim() : '';
122
+ if (!a || !ONE_LINE(a, 120) || /\s/.test(a)) return refuse(400, 'the anchor to keep is one id', 'anchor');
123
+ if (!n || /[\r\n]/.test(n)) return refuse(400, 'the note to move is one line', 'anchor');
124
+ return editAnchorLines(root, id, expect, (lines, at) => {
125
+ lines[at] = `parent_kr: ${PLAIN(a) ? a : q(a)}`;
126
+ lines.splice(at + 1, 0, `anchor_note: ${q(n)}`);
127
+ }, { anchor: a, note: n });
128
+ }
129
+
130
+ /** The Undo of a foldAnchor: the one anchor line back, exactly `from`, and no anchor_note, while the record still holds what the fold wrote. */
131
+ function unfoldAnchor(root, id, { from, fromLine, anchor, note } = {}, { actor } = {}) {
132
+ if (!actorLib().valid(actor)) return refuse(500, 'initiative-writer: the caller must pass the actor from pm-guard.js or actor.js');
133
+ const f0 = typeof from === 'string' ? from.trim() : '';
134
+ if (!f0 || /[\r\n]/.test(f0)) return refuse(400, 'the anchor to put back is not one line', 'anchor');
135
+ // the line exactly as it was (its quotes too), when the fold kept it and it still reads as that anchor
136
+ const back = typeof fromLine === 'string' && /^parent_kr:/.test(fromLine) && !/[\r\n]/.test(fromLine) && unquote(fromLine.slice(10)) === f0 ? fromLine : `parent_kr: ${PLAIN(f0) ? f0 : q(f0)}`;
137
+ return editAnchorLines(root, id, anchor, (lines, at) => {
138
+ const na = lines.findIndex((l) => /^anchor_note:/.test(l));
139
+ if (na < 0 || unquote(lines[na].slice(12)) !== String(note || '').trim()) return 'its anchor note was edited since the fold';
140
+ lines[at] = back;
141
+ lines.splice(na, 1);
142
+ return null;
143
+ }, { anchor: f0 });
144
+ }
145
+
146
+ function editAnchorLines(root, id, expect, edit, out) {
147
+ const f = recordFile(root, id);
148
+ if (!f.ok) return f;
149
+ const text = fs.readFileSync(f.file, 'utf8');
150
+ const m = frontOfText(text);
151
+ if (!m) return refuse(409, `the record of ${id} has no front matter — nothing was saved`, 'id');
152
+ const lines = m[1].split(/\r?\n/);
153
+ const at = lines.findIndex((l) => /^parent_kr:/.test(l));
154
+ if (at < 0 || unquote(lines[at].slice(10)) !== String(expect || '').trim()) return refuse(409, `the anchor of ${id} was edited since — nothing was saved`, 'anchor');
155
+ const fromLine = lines[at];
156
+ const why = edit(lines, at);
157
+ if (why) return refuse(409, `${why} — nothing was saved`, 'anchor');
158
+ try { fs.writeFileSync(f.file, '---\n' + lines.join('\n') + '\n---' + m[2] + text.slice(m[0].length), { flag: 'w' }); } catch { return refuse(500, 'the record could not be written — nothing was saved'); }
159
+ return { ok: true, id, fromLine, ...out };
160
+ }
161
+
162
+ function recordIds(root) {
163
+ let dir = null;
164
+ try { dir = require('./console-state').loadEngine().engine.layout(root).initiatives; } catch { dir = null; }
165
+ if (!dir) return [];
166
+ let names = [];
167
+ try { names = fs.readdirSync(dir); } catch { return []; }
168
+ const W = require('./initiative-writer.js');
169
+ return names.filter((n) => /\.md$/.test(n) && n !== 'README.md' && W.ID_RE.test(n.slice(0, -3))).map((n) => n.slice(0, -3)).sort();
170
+ }
171
+
172
+ function plan(root) {
173
+ const A = rows().anchorsOf(root);
174
+ const items = [], kept = [];
175
+ let total = 0;
176
+ for (const id of recordIds(root)) {
177
+ const r = readAnchorLine(root, id);
178
+ if (!r.ok || !r.text) continue;
179
+ total++;
180
+ const s = split(r.text);
181
+ if (!s.note) continue; // one id already: stays silent
182
+ if (r.spans) { kept.push({ id, from: r.text, why: 'the anchor runs over more than one line' }); continue; }
183
+ if (r.hasNote) { kept.push({ id, from: r.text, why: 'it has an anchor_note already' }); continue; }
184
+ const whole = A.resolve(r.text), alone = A.resolve(s.id);
185
+ if (whole.key !== alone.key || alone.status !== 'resolved') { kept.push({ id, from: r.text, why: `the id alone (${s.id}) does not name the same anchor` }); continue; }
186
+ items.push({ id, from: r.text, anchor: s.id, note: s.note });
187
+ }
188
+ return { total, items, kept };
189
+ }
190
+
191
+ const ledger = (stateDir) => path.join(stateDir, 'anchor-folds.jsonl');
192
+ function readLedger(stateDir) {
193
+ try { return fs.readFileSync(ledger(stateDir), 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { return []; }
194
+ }
195
+
196
+ function fold(root, { apply = false, actor, stateDir, now = Date.now() } = {}) {
197
+ const p = plan(root);
198
+ if (!apply) return { ok: true, ...p };
199
+ if (!stateDir) return { ok: false, status: 500, error: 'anchor-id: fold needs the runtime state folder for its Undo' };
200
+ const batch = 'fold-' + new Date(now).toISOString().replace(/[:.]/g, '-');
201
+ const done = [], at = new Date(now).toISOString(), by = (actor && actor.by) || 'unknown';
202
+ for (const it of p.items) {
203
+ const w = foldAnchor(root, it.id, { anchor: it.anchor, note: it.note, expect: it.from }, { actor });
204
+ if (!w.ok) { p.kept.push({ id: it.id, from: it.from, why: w.error }); continue; }
205
+ done.push({ v: 1, kind: 'fold', batch, id: it.id, from: it.from, fromLine: w.fromLine, anchor: it.anchor, note: it.note, at, by });
206
+ }
207
+ if (done.length) { fs.mkdirSync(stateDir, { recursive: true }); fs.appendFileSync(ledger(stateDir), done.map((d) => JSON.stringify(d)).join('\n') + '\n'); }
208
+ return { ok: true, total: p.total, items: done.map(({ id, from, anchor, note }) => ({ id, from, anchor, note })), kept: p.kept, folded: done.length, batch };
209
+ }
210
+
211
+ function undo(root, batch, { actor, stateDir, now = Date.now() } = {}) {
212
+ if (!/^fold-[0-9TZ-]+$/.test(String(batch || ''))) return { ok: false, status: 400, error: 'name the fold batch, fold-<time>, from the fold\'s answer' };
213
+ const all = stateDir ? readLedger(stateDir) : [];
214
+ const rowsOf = all.filter((e) => e.kind === 'fold' && e.batch === batch);
215
+ if (!rowsOf.length) return { ok: false, status: 404, error: `no anchor fold ${batch} on this computer` };
216
+ if (all.some((e) => e.kind === 'undo' && e.batch === batch)) return { ok: true, restored: 0, kept: 0, already: true };
217
+ let restored = 0, kept = 0;
218
+ for (const e of rowsOf) {
219
+ const w = unfoldAnchor(root, e.id, { from: e.from, fromLine: e.fromLine, anchor: e.anchor, note: e.note }, { actor });
220
+ if (w.ok) restored++; else kept++;
221
+ }
222
+ fs.appendFileSync(ledger(stateDir), JSON.stringify({ v: 1, kind: 'undo', batch, at: new Date(now).toISOString(), by: (actor && actor.by) || 'unknown' }) + '\n');
223
+ return { ok: true, restored, kept };
224
+ }
225
+
226
+ module.exports = { split, anchorId, nearest, check, list, plan, fold, undo, readAnchorLine, foldAnchor, unfoldAnchor };
@@ -7,6 +7,7 @@
7
7
  * its artefact. Idempotent; it deletes and moves nothing
8
8
  * pmos artefacts set <scope> <artefact> [<field>] --text "<…>" [--source label=ref]… one field (PM or agent; Intent is the PM's)
9
9
  * pmos artefacts undo <a-id> one set line no longer counts
10
+ * pmos artefacts lessons <id> [--draft] [--json] an initiative's Lessons, with ids for undo; --draft drafts them (lib/lessons-draft.js, lessons-on-close)
10
11
  * every command: [--root <dir>]
11
12
  * Exit codes: 0 done, 1 refused, 2 usage. */
12
13
  const path = require('path');
@@ -15,7 +16,7 @@ const A = require('./artefacts.js');
15
16
  const MIRROR = require('./artefact-mirror.js');
16
17
  const actorLib = require('./actor.js');
17
18
 
18
- const COMMANDS = { artefacts: ['show', 'map', 'migrate', 'set', 'undo'] };
19
+ const COMMANDS = { artefacts: ['show', 'map', 'migrate', 'set', 'undo', 'lessons'] };
19
20
  const USAGE = [
20
21
  'usage: pmos artefacts show|map|migrate|set|undo — the seven artefacts: Intent, Goal, Narrative, Experiment, Specimens, Done test, Lessons',
21
22
  ' pmos artefacts show [<scope>] [--json] scope: portfolio (default), board:<id>, goal:<id> or experiment:<id> (an initiative)',
@@ -24,6 +25,7 @@ const USAGE = [
24
25
  ' pmos artefacts set <scope> <artefact> [<field>] --text "<text>" [--source label=ref]…',
25
26
  ' an initiative is experiment:<id> (initiative:<id> works too). Its case card: experiment why (Problem), experiment hypothesis (Goal), done-test check (Done when, once per check)',
26
27
  ' pmos artefacts undo <a-id>',
28
+ ' pmos artefacts lessons <initiative> [--draft] [--json] its Lessons lines with their ids; --draft: PMOS drafts them once its experiment closed (never over yours)',
27
29
  ];
28
30
  function parse(args) {
29
31
  const pos = []; const flags = { source: [] };
@@ -37,6 +39,27 @@ function parse(args) {
37
39
  }
38
40
  return { pos, flags };
39
41
  }
42
+ /* lessons-on-close (A542): the chat reads an initiative's Lessons and asks PMOS to draft them. The draft is async (a session may answer). */
43
+ function lessonsCmd(pos, flags, { root, dir, f, say, now }) {
44
+ const id = pos[0];
45
+ if (!id || pos.length > 1) { say('usage: pmos artefacts lessons <initiative> [--draft] [--json]'); return 2; }
46
+ const LD = require('./lessons-draft.js');
47
+ const show = () => {
48
+ const h = LD.lessonsHere(A.fold(A.readLines(f)), id), all = [...h.pm, ...h.agent].sort((a, b) => String(a.at).localeCompare(String(b.at)));
49
+ if (flags.json) { say(JSON.stringify({ ok: true, initiative: id, lessons: all.map((l) => ({ id: l.id, text: l.text, by: /^pm:/.test(String(l.by || '')) ? 'you' : 'pmos', sources: l.sources || [], at: l.at })) })); return 0; }
50
+ if (!all.length) { say(`${id} has no lessons yet.`); return 0; }
51
+ for (const l of all) say(`${l.id} ${l.text}${/^pm:/.test(String(l.by || '')) ? '' : ' (PMOS)'}${(l.sources || []).length ? ' ← ' + l.sources.map((x) => x.ref).join(', ') : ''}`);
52
+ say('Undo one: pmos artefacts undo <a-id>');
53
+ return 0;
54
+ };
55
+ if (!('draft' in flags)) return show();
56
+ return LD.draft({}, { root, id, dir, now: now || Date.now() }).then((r) => {
57
+ if (!r.ok) { say('✗ ' + r.error); return 1; }
58
+ if (!r.wrote.length) { say(`Nothing drafted: ${r.why}.`); return 0; }
59
+ say(`✓ PMOS drafted ${r.wrote.length} ${r.wrote.length === 1 ? 'lesson' : 'lessons'} for ${id}, from its experiment and what happened. Nothing was sent.`);
60
+ return show();
61
+ });
62
+ }
40
63
  function repoRoot(cwd) { try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; } catch { return cwd; } }
41
64
 
42
65
  function mapRows() {
@@ -64,6 +87,7 @@ function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), env = pro
64
87
  let dir = dirIn || null;
65
88
  if (!dir) { try { dir = A.dirOf(root); } catch (e) { say('✗ ' + String((e && e.message) || e)); return 1; } }
66
89
  const f = A.file(dir);
90
+ if (verb === 'lessons') return lessonsCmd(pos, flags, { root, dir, f, say, now });
67
91
  if (verb === 'show') {
68
92
  const scope = pos[0] || 'portfolio';
69
93
  const v = A.viewOf(A.fold(A.readLines(f)), scope);
@@ -20,6 +20,8 @@
20
20
  * · A folder that is mostly tests (tests/, test/, spec/ …) is not a part; each test file in it counts for the part whose name appears
21
21
  * in its path. Code files at the top level form a part "(top level)" when there are 3 or more.
22
22
  * · At most MAX_PARTS parts, most code files first; the rest are counted in `more`.
23
+ * · PMOS's own kit folder (a top-level pmos/ holding the kit's AGENTS.md) is PMOS, not the product: never a part.
24
+ * · A repository with fewer than MIN_CODE code files in its parts (a PM's records folder with a script or two) gets no map at all.
23
25
  * · Risky: no test files, or RISKY_FIXES or more fix commits touching the part in the last 30 days that are at least half of its
24
26
  * commits there (a busy, well-kept part is not risky only for being busy). */
25
27
  const fs = require('fs');
@@ -29,6 +31,7 @@ const { execFile } = require('child_process');
29
31
  const MAP_FILE = 'code-map.json';
30
32
  const NOTES_FILE = 'code-map-notes.jsonl';
31
33
  const MAX_PARTS = 12;
34
+ const MIN_CODE = 20; // fewer code files than this in the whole repository: a records or notes folder, not a product's code — no map
32
35
  const RISKY_FIXES = 5;
33
36
  const FIX_DAYS = 30;
34
37
  const FIX_SHARE = 0.5; // fixes must be at least half the part's commits in the window, so a busy part is not risky only for being busy
@@ -65,7 +68,9 @@ function keyOf(f, open) {
65
68
 
66
69
  /** Group a repository's files into its main parts. PURE. */
67
70
  function partsOf(files) {
68
- const list = (Array.isArray(files) ? files : []).map(String).filter((f) => f && !skipped(f) && !f.split('/').pop().startsWith('.'));
71
+ const all = (Array.isArray(files) ? files : []).map(String);
72
+ const kit = all.includes('pmos/AGENTS.md'); // the vendored PMOS kit (kit/build-kit.sh): PMOS's files, not the product's
73
+ const list = all.filter((f) => f && !skipped(f) && !f.split('/').pop().startsWith('.') && !(kit && f.startsWith('pmos/')));
69
74
  // a container opens only when it has sub-folders with code (a flat src/ stays one part)
70
75
  const open = new Set();
71
76
  for (const f of list) { const s = f.split('/'); if (CONTAINERS.has(s[0]) && s.length > 2 && isCode(f)) open.add(s[0]); }
@@ -90,6 +95,7 @@ function partsOf(files) {
90
95
  if (hit) { hit.tests++; hit.testsOutside++; }
91
96
  }
92
97
  parts.sort((a, b) => b.code - a.code || a.name.localeCompare(b.name));
98
+ if (parts.reduce((n, p) => n + p.code, 0) < MIN_CODE) return { parts: [], more: 0 };
93
99
  const more = Math.max(0, parts.length - MAX_PARTS);
94
100
  return { parts: parts.slice(0, MAX_PARTS).map(({ _tests, ...p }) => p), more };
95
101
  }
@@ -244,4 +250,4 @@ function describe(dir, name, text, now = Date.now()) {
244
250
  return { ok: true, part: p.name, map: view(dir) };
245
251
  }
246
252
 
247
- module.exports = { partsOf, summarize, riskOf, build, headOf, read, save, view, describe, findPart, isTest, MAP_FILE, NOTES_FILE, MAX_PARTS, RISKY_FIXES, FIX_DAYS, FIX_SHARE };
253
+ module.exports = { partsOf, summarize, riskOf, build, headOf, read, save, view, describe, findPart, isTest, MAP_FILE, NOTES_FILE, MAX_PARTS, RISKY_FIXES, FIX_DAYS, FIX_SHARE, MIN_CODE };
@@ -18,8 +18,8 @@
18
18
  * load(root) → the saved snapshot | null reads one file, folds nothing
19
19
  * ageMinutes(root, now) → whole minutes since the snapshot was saved, or -1 (the health number)
20
20
  *
21
- * THE SNAPSHOT { v: 1, at, ws, name, days, from, stations: [{ key, name, waiting, made, undone, minutes, items }], unplaced: { made, minutes },
22
- * runs, tokens: null, money: null, usage: 'not recorded yet' }
21
+ * THE SNAPSHOT { v: 1, at, ws, name, days, from, stations: [{ key, name, waiting, made, undone, minutes, runs, items, madeItems }],
22
+ * unplaced: { made, minutes }, runs, lastRun, tokens: null, money: null, usage: 'not recorded yet' }
23
23
  * waiting what waits at the station now. Intake to Evaluate: the initiatives and Work tasks whose agent blocker of the latest sweep day
24
24
  * belongs to it (one per target). Check: the Driver drafts of ended runs the Checker has not graded yet. You: the open sign-offs
25
25
  * and the Driver drafts that have waited on the PM for a day (pm-open).
@@ -30,6 +30,8 @@
30
30
  * minutes PMOS minutes of the Driver's runs that ended in the window (run-start to run-end), split evenly over the stations of what each
31
31
  * run filed; a run that filed nothing counts for the station of the blocker that woke it; else it is unplaced.
32
32
  * items up to MAX_ITEMS waiting items: { kind, id, title, code, text }, what each one waits on.
33
+ * madeItems the newest MAX_MADE change rows it made: { ref, title, at, state, ini, undo } (undo: the Factory page offers Undo on it).
34
+ * runs the Driver runs whose minutes went to the station. lastRun: when the newest run of the window ended (the page's status line).
33
35
  * tokens and money stay null ("not recorded yet") until each run records its usage (a later slice). An honest gap, never a guess.
34
36
  *
35
37
  * Every log line carries [factory-floor]. Nothing here sends anything, and the factory graph never writes it (D65): the server writes it
@@ -41,6 +43,9 @@ const FILE = 'factory-floor.json';
41
43
  const DAY = 86400000;
42
44
  const DAYS = 7;
43
45
  const MAX_ITEMS = 50;
46
+ const MAX_MADE = 30; // the station popup's "Made this week": the newest 30 rows (factory-page-ui)
47
+ // a change the PM can undo from the station popup (POST /api/autonomy/undo): applied by PMOS, inside its Undo, with a ref that route knows
48
+ const canUndo = (r) => r.state === 'applied' && /^(p|pk|im)-/.test(String(r.ref || ''));
44
49
  const LOG = '[factory-floor]';
45
50
  const NOT_RECORDED = 'not recorded yet';
46
51
  const STATIONS = Object.freeze([
@@ -88,7 +93,7 @@ function compute(input = {}, { now = Date.now(), days = DAYS, ws = null, name =
88
93
  const CR = require('./change-record.js');
89
94
  const from = now - days * DAY;
90
95
  const inWin = (at) => { const t = ms(at); return t != null && t >= from && t <= now + 60000; };
91
- const st = new Map(STATIONS.map((s) => [s.key, { key: s.key, name: s.name, waiting: 0, made: 0, undone: 0, minutes: 0, items: [], _targets: new Set() }]));
96
+ const st = new Map(STATIONS.map((s) => [s.key, { key: s.key, name: s.name, waiting: 0, made: 0, undone: 0, minutes: 0, runs: 0, items: [], madeItems: [], _targets: new Set() }]));
92
97
  const unplaced = { made: 0, minutes: 0 };
93
98
  const wait = (key, item) => {
94
99
  const s = st.get(key);
@@ -110,6 +115,7 @@ function compute(input = {}, { now = Date.now(), days = DAYS, ws = null, name =
110
115
  const s = st.get(key);
111
116
  s.made++;
112
117
  if (r.state === 'undone') s.undone++;
118
+ s.madeItems.push({ ref: r.ref || null, title: one(r.title || r.job, 120), at: r.at, state: r.state, ini: r.ini || null, undo: canUndo(r) });
113
119
  }
114
120
  for (const l of Array.isArray(input.bgQueue) ? input.bgQueue : []) {
115
121
  if (!isObj(l) || l.kind !== 'done' || !inWin(l.at) || (ws && l.ws && l.ws !== ws)) continue;
@@ -154,12 +160,13 @@ function compute(input = {}, { now = Date.now(), days = DAYS, ws = null, name =
154
160
 
155
161
  // MINUTES: the Driver's runs that ended in the window
156
162
  const wakeOf = new Map(state.wakes.map((w) => [w.key, w]));
157
- let runs = 0;
163
+ let runs = 0, lastRun = null;
158
164
  for (const r of state.runs.values()) {
159
165
  if (!r.end || !inWin(r.end)) continue;
160
166
  const t0 = ms(r.start), t1 = ms(r.end);
161
167
  if (t0 == null || t1 == null || t1 < t0) continue;
162
168
  runs++;
169
+ if (!lastRun || t1 > ms(lastRun)) lastRun = new Date(t1).toISOString();
163
170
  const mins = (t1 - t0) / 60000;
164
171
  let keys = [...new Set([...state.proposals.values()].filter((p) => p.run === r.run).map((p) => stationOfJob('driver:' + p.what, { kind: p.target.kind })).filter(Boolean))];
165
172
  if (!keys.length) {
@@ -170,12 +177,13 @@ function compute(input = {}, { now = Date.now(), days = DAYS, ws = null, name =
170
177
  }
171
178
  }
172
179
  if (!keys.length) { unplaced.minutes += mins; continue; }
173
- for (const k of keys) st.get(k).minutes += mins / keys.length;
180
+ for (const k of keys) { st.get(k).minutes += mins / keys.length; st.get(k).runs++; }
174
181
  }
175
182
 
176
- const stations = [...st.values()].map(({ _targets, ...s }) => ({ ...s, minutes: Math.round(s.minutes) }));
183
+ const newest = (a, b) => String(b.at || '').localeCompare(String(a.at || ''));
184
+ const stations = [...st.values()].map(({ _targets, ...s }) => ({ ...s, minutes: Math.round(s.minutes), madeItems: s.madeItems.sort(newest).slice(0, MAX_MADE) }));
177
185
  return { v: 1, at: new Date(now).toISOString(), ws, name, days, from: new Date(from).toISOString(), stations,
178
- unplaced: { made: unplaced.made, minutes: Math.round(unplaced.minutes) }, runs, tokens: null, money: null, usage: NOT_RECORDED };
186
+ unplaced: { made: unplaced.made, minutes: Math.round(unplaced.minutes) }, runs, lastRun, tokens: null, money: null, usage: NOT_RECORDED };
179
187
  }
180
188
 
181
189
  /* ── the read (no write) ── */
@@ -234,7 +242,7 @@ function ageMinutes(root, now = Date.now()) {
234
242
  return t == null ? -1 : Math.max(0, Math.floor((now - t) / 60000));
235
243
  }
236
244
 
237
- module.exports = { STATIONS, WHAT_STATION, GROUP_STATION, RUN_STATION, CODE_STATION, FILE, DAYS, LOG, NOT_RECORDED, MAX_ITEMS,
245
+ module.exports = { STATIONS, WHAT_STATION, GROUP_STATION, RUN_STATION, CODE_STATION, FILE, DAYS, LOG, NOT_RECORDED, MAX_ITEMS, MAX_MADE,
238
246
  stationOfJob, stationOfCode, compute, read, build, fileOf, save, load, ageMinutes };
239
247
 
240
248
  // `node lib/factory-floor.js age <checkout>`: the health number, minutes since the snapshot was saved (-1 when there is none)