create-pmos 0.446.0 → 0.448.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 (35) hide show
  1. package/package.json +25 -25
  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/changelog.json +24 -0
  7. package/workspace/guide/claude-proposes.md +25 -2
  8. package/workspace/guide/forecast.md +53 -0
  9. package/workspace/guide/index.md +1 -0
  10. package/workspace/lib/forecast-cli.js +68 -0
  11. package/workspace/lib/forecast-tick.js +44 -0
  12. package/workspace/lib/forecast.js +209 -0
  13. package/workspace/lib/grill-cli.js +104 -0
  14. package/workspace/lib/grill-runs.js +172 -0
  15. package/workspace/lib/grill.js +172 -0
  16. package/workspace/lib/headless.js +14 -2
  17. package/workspace/lib/intel-report.js +4 -1
  18. package/workspace/lib/pmos-verbs.js +6 -0
  19. package/workspace/lib/proposals.js +11 -4
  20. package/workspace/lib/route-modules.js +1 -0
  21. package/workspace/lib/routes-board-premium.js +26 -1
  22. package/workspace/lib/routes-forecast.js +44 -0
  23. package/workspace/lib/routes-insights-premium.js +9 -1
  24. package/workspace/lib/routes-proposals.js +8 -0
  25. package/workspace/lib/settings-store.js +5 -0
  26. package/workspace/package-lock.json +2 -2
  27. package/workspace/package.json +1 -1
  28. package/workspace/public/pm/cozy-insights.css +4 -0
  29. package/workspace/public/pm/ini-props.js +1 -1
  30. package/workspace/public/pm/premium-insights.js +28 -1
  31. package/workspace/server.js +61 -10
  32. package/workspace/skills/grill.skill +40 -0
  33. package/workspace/test-lists/forecast.json +9 -0
  34. package/workspace/test-lists/grill.json +9 -0
  35. package/workspace/test-run.js +4 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.446.0",
3
+ "version": "0.448.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -32,6 +32,30 @@
32
32
  "audit"
33
33
  ],
34
34
  "pmosChanges": [
35
+ {
36
+ "v": "0.448.0",
37
+ "at": "2026-10-29T07:41:35.601Z",
38
+ "f": 2,
39
+ "prs": [
40
+ {
41
+ "n": 1094,
42
+ "t": "Forecast range bar on Intelligence goal rows",
43
+ "s": "Forecast range bar on Intelligence goal rows"
44
+ }
45
+ ]
46
+ },
47
+ {
48
+ "v": "0.447.0",
49
+ "at": "2026-10-29T07:16:51.492Z",
50
+ "f": 2,
51
+ "prs": [
52
+ {
53
+ "n": 1093,
54
+ "t": "Grill and Forecast backend",
55
+ "s": "Grill and Forecast backend"
56
+ }
57
+ ]
58
+ },
35
59
  {
36
60
  "v": "0.446.0",
37
61
  "at": "2026-10-29T05:26:28.089Z",
@@ -247,30 +271,6 @@
247
271
  "s": "Feedback batch 15"
248
272
  }
249
273
  ]
250
- },
251
- {
252
- "v": "0.428.0",
253
- "at": "2026-10-27T09:47:36.220Z",
254
- "f": 2,
255
- "prs": [
256
- {
257
- "n": 1071,
258
- "t": "Feedback batch 14",
259
- "s": "Feedback batch 14"
260
- }
261
- ]
262
- },
263
- {
264
- "v": "0.427.0",
265
- "at": "2026-10-27T04:17:38.420Z",
266
- "f": 2,
267
- "prs": [
268
- {
269
- "n": 1069,
270
- "t": "How full each session's context is, and Claude proposes Compact (batch 13 item 8)",
271
- "s": "How full each session's context is, and Claude proposes Compact (batch 13 item 8)"
272
- }
273
- ]
274
274
  }
275
275
  ]
276
276
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@c12e364b
1
+ kernel-source: pmos@233d2355
2
2
  assembled: 2026-10-29
3
3
  mode: vendor
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Eval calibration log"
4
4
  description: "Append-only record of every PM override of an evaluator verdict."
5
- generated: {by: process:create-pmos, at: "2026-10-29T05:26:24Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-29T07:41:31Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Health budgets"
4
4
  description: "Closed registry of health-budget anchors (D59), edited only by the PM."
5
- generated: {by: process:create-pmos, at: "2026-10-29T05:26:24Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-29T07:41:31Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-10-29T05:26:24Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-29T07:41:31Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -1,4 +1,28 @@
1
1
  [
2
+ {
3
+ "v": "0.448.0",
4
+ "at": "2026-10-29T07:41:35.601Z",
5
+ "f": 2,
6
+ "prs": [
7
+ {
8
+ "n": 1094,
9
+ "t": "Forecast range bar on Intelligence goal rows",
10
+ "s": "Forecast range bar on Intelligence goal rows"
11
+ }
12
+ ]
13
+ },
14
+ {
15
+ "v": "0.447.0",
16
+ "at": "2026-10-29T07:16:51.492Z",
17
+ "f": 2,
18
+ "prs": [
19
+ {
20
+ "n": 1093,
21
+ "t": "Grill and Forecast backend",
22
+ "s": "Grill and Forecast backend"
23
+ }
24
+ ]
25
+ },
2
26
  {
3
27
  "v": "0.446.0",
4
28
  "at": "2026-10-29T05:26:28.089Z",
@@ -1,8 +1,8 @@
1
1
  ---
2
2
  type: Guide
3
3
  title: "Claude proposes: the one ✦ on each initiative"
4
- description: "What Claude finds when you add an initiative that already lives elsewhere, the new dates, done and tidy names it proposes for late tasks, the clean-up of the work that is not in an initiative, how you keep or drop them in the Viewer, Undo, and the pmos propose commands."
5
- timestamp: 2026-10-27
4
+ description: "What Claude finds when you add an initiative that already lives elsewhere, the new dates, done and tidy names it proposes for late tasks, the clean-up of the work that is not in an initiative, how you keep or drop them in the Viewer, Undo, the pmos propose commands, and how Claude grills an initiative by itself (pmos grill)."
5
+ timestamp: 2026-10-29
6
6
  ---
7
7
 
8
8
  # Claude proposes: the one ✦ on each initiative
@@ -52,3 +52,26 @@ In the pill menu on an initiative's row, a session that is idle and safe to clos
52
52
  Each session shows how full its context window is, as a small pie in the pill list, the chat header, the phone top bar and the Live pill. The pie shows from 50% (grey). It turns amber from 70% and red from 90%. Hover it to see the tokens used, such as "156k of 200k used · last turn 10:12". The window is 1M when the session runs a 1M model, else 200k. From 70%, when it is your turn, Claude proposes Compact: the row's ✦ line says so, and its ✓ types /compact into the session. The chat shows the same offer as a chip. A session that is safe to close shows that ✦ instead. ✕ hides the Compact offer until the context is 10 points fuller.
53
53
 
54
54
  ✓ in the header keeps everything shown. Each proposal has its own ✓ and ✕, and ⌄ shows its rows. ✕ on a row leaves it out of that group for good, with Undo on the row. One toast says what was placed, with Undo. History lists each approval with its own Undo. An initiative that was started stays when you undo: close it on the Board.
55
+
56
+ ## Claude grills an initiative by itself
57
+
58
+ Claude also tests an initiative without being asked. There is no Grill button and no lens to pick. Claude grills an initiative:
59
+
60
+ - before it leaves a stage (the stage has one open task or none left),
61
+ - when its forecast turns at risk or will miss,
62
+ - when its scope or dates move a lot (30% more or fewer tasks, or the end moves 14 days or more),
63
+ - once a month, when it is running and has late work.
64
+
65
+ Each finding is a proposal in the group "Claude grilled it", under the same ✦. Its title starts with the angle that found it: Premortem, Red team, Voices, Reframe, Scope or What-if. Voices are simulated from your stored research and meeting notes, only with 3 sources or more, and say "Simulated, not evidence". A What-if says "Simulated, not the plan". Each finding ends with one next step. ✓ adds that step as a task. ✕ drops the finding. A finding never rides on the header's ✓. Three findings show at a time; the rest come up as you keep or drop one. With no findings, nothing shows.
66
+
67
+ Every run counts against a monthly credit cap. A run starts only when the cap holds its whole budget, and it stops at that budget, so the month never goes past the cap. At the cap Claude pauses until the next month.
68
+
69
+ - `pmos grill mode [full|exits|off]`: when Claude grills by itself. `exits` grills only before a stage ends. `PMOS_GRILL=off` turns it off on this computer.
70
+ - `pmos grill cap [<dollars>]`: the monthly credit cap, in US dollars (10 by default).
71
+ - `pmos grill spend`: what this month spent, each run's cost, and whether Claude paused.
72
+
73
+ Claude's grill run files with these commands, which refuse outside that run:
74
+
75
+ - `pmos grill find <premortem|redteam|voices|reframe|scope|whatif> --json <file|->`: one finding, with its sources and next step.
76
+ - `pmos grill voices --sources <n>`: how many stored sources Voices can use.
77
+ - `pmos grill status`: what is open, kept and dropped.
@@ -0,0 +1,53 @@
1
+ ---
2
+ type: Guide
3
+ title: "Forecasts: goals, deliveries, programs and health budgets"
4
+ description: "How PMOS forecasts a goal, an initiative's delivery, a program's milestones and a health budget, what each state means, the kept baseline, and the pmos forecast commands."
5
+ timestamp: 2026-10-29
6
+ ---
7
+
8
+ # Forecasts
9
+
10
+ PMOS forecasts with one method: straight lines through the most recent readings, carried to the date. Each Intelligence goal row shows its forecast in the pace column: a bar from the low to the high estimate, a tick for the goal, a dot for the likely value, and one word (On track, At risk, Will miss, Too early or Held). Too early draws no bar. Held dims the bar and names the source and the date of the last reading. If a goal was on track earlier, the row adds "Was on track on" and that date. A goal with no target keeps its old pace line. The Board and the goal Viewer do not show forecasts yet. The forecasts are in the data that those pages read, and Claude uses them to decide when to check an initiative.
11
+
12
+ ## A goal
13
+
14
+ A goal with a target and a target date gets a range: the straight lines through its last 3, 4, 5 and 6 readings, carried to the target date. The likely value is the line through the last 4 readings. This is the same line that the Intelligence projection says in words.
15
+
16
+ - **On track**: every line reaches the target.
17
+ - **At risk**: some lines reach the target and some do not.
18
+ - **Will miss**: no line reaches the target.
19
+ - **Too early**: the goal has fewer than 3 readings, or its readings span less than 3 weeks. There is no number.
20
+ - **Held**: the source was not read for more than 7 days. The range stays where it was and is not carried forward.
21
+
22
+ When a goal is no longer on track, the forecast gives the last day it was on track.
23
+
24
+ A limit goal (Stay within) and a done-or-not goal have no range.
25
+
26
+ ## An initiative's delivery
27
+
28
+ The delivery range comes from the Jira tickets of the initiative: the tickets left, closed at the fastest and at the slowest of two closing rates. The range is compared with the planned end date. Under 3 weeks of tickets there is no range. When the Jira reading is more than 7 days old, the range is held.
29
+
30
+ ## A program and a health budget
31
+
32
+ A program counts its milestones at risk: an open milestone that waits on an initiative at risk or set to miss, or whose date is before the end of that initiative's range.
33
+
34
+ A health budget that has a Stay within goal shows how many weeks are left before it crosses its limit. It shows this only when fewer than 8 weeks are left.
35
+
36
+ ## A kept baseline
37
+
38
+ Some readings do not show the usual pace, for example the weeks of a promotion. Keep a baseline with `pmos forecast baseline` to take them out of a goal's range, and drop it with `pmos forecast baseline-off`:
39
+
40
+ ```
41
+ pmos forecast baseline --goal <id> --label "without the promo weeks" --exclude 2026-09-01..2026-09-14
42
+ pmos forecast baseline-off --goal <id>
43
+ ```
44
+
45
+ `--exclude` takes up to 10 spans, separated by commas. The baseline stays until you drop it.
46
+
47
+ ## The forecasts that turned
48
+
49
+ Once an hour, while the workspace server runs, PMOS works out every forecast again, so you do not need to open a page. PMOS records the state of each forecast when it changes. Claude reads these changes to decide when to check an initiative. To list them, run `pmos forecast turned`.
50
+
51
+ ```
52
+ pmos forecast turned --since 2026-10-01T00:00:00Z
53
+ ```
@@ -78,6 +78,7 @@ On a desktop the workspace is one frame. [Layout](layout.md) explains each part.
78
78
  - [Breakdown › Timeline](timeline.md): an initiative's items on a time axis, split by stage, with milestones, today, and the at-risk flag when an item starts before its predecessor ends.
79
79
  - [Initiatives › Timeline](initiatives-timeline.md): when each initiative runs, one row per initiative, and how to reorder rows by their grip.
80
80
  - [Workflows](workflows.md): Settings › Workflows, the stages each kind of initiative goes through, New workflow in the chat, and `pmos workflow`.
81
+ - [Forecasts](forecast.md): how a goal, a delivery, a program and a health budget are forecast, the states, the kept baseline, and `pmos forecast`.
81
82
  - [Programs on the Board](programs.md): All products, programs first then products, By product, the program panel and its milestones, and the 60 % side panels.
82
83
  - [Board](board.md): one Kanban for the items of every initiative, its filters, Release, and `pmos board`.
83
84
  - [The lifecycle](lifecycle.md): the six stages and two milestones of an initiative, what each makes, which steps each lane uses, and how the step is read from the records.
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+ /* forecast-cli.js — `pmos forecast`: the kept baseline of a goal's forecast and the forecasts that turned (build brief Grill and Forecast, F-A).
3
+ *
4
+ * pmos forecast baseline --goal <id> --label "<words>" --exclude <from>..<to>[,<from>..<to>] keep a baseline: those readings leave the range
5
+ * pmos forecast baseline-off --goal <id> back to every reading
6
+ * pmos forecast turned [--since <ISO time>] [--json] the forecasts whose state changed (the Grill reads these)
7
+ *
8
+ * The ledger is <state>/forecast.jsonl of this repository (lib/forecast.js). A baseline is the PM's choice, so only the PM or an agent session
9
+ * acting for the PM (D98) writes one; `turned` only reads. Exit codes: 0 done, 1 refused, 2 usage. */
10
+ const path = require('path');
11
+ const { execFileSync } = require('child_process');
12
+ const actorLib = require('./actor.js');
13
+ const D = require('./driver.js');
14
+ const FC = require('./forecast.js');
15
+
16
+ const COMMANDS = { forecast: ['baseline', 'baseline-off', 'turned'] };
17
+ const USAGE = [
18
+ 'usage: pmos forecast baseline|baseline-off|turned — the forecasts of goals and initiatives',
19
+ ' pmos forecast baseline --goal <id> --label "without the promo weeks" --exclude 2026-09-01..2026-09-14',
20
+ ' Keep a baseline for one goal: the readings in the excluded spans (up to 10, comma-separated) leave its forecast range.',
21
+ ' pmos forecast baseline-off --goal <id>',
22
+ ' Drop the kept baseline: the forecast reads every reading again.',
23
+ ' pmos forecast turned [--since <ISO time>] [--json]',
24
+ ' The forecasts whose state changed (on-track, at-risk, will-miss, too-early), oldest first.',
25
+ ];
26
+
27
+ function repoRoot(cwd) {
28
+ try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; }
29
+ catch { return cwd; }
30
+ }
31
+ function flagsOf(args) {
32
+ const f = {};
33
+ for (let i = 0; i < args.length; i++) {
34
+ const m = /^--([a-z-]+)(?:=(.*))?$/.exec(args[i]);
35
+ if (!m) continue;
36
+ if (m[2] !== undefined) f[m[1]] = m[2];
37
+ else if (args[i + 1] !== undefined && !String(args[i + 1]).startsWith('--')) f[m[1]] = args[++i];
38
+ else f[m[1]] = true;
39
+ }
40
+ return f;
41
+ }
42
+
43
+ function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isTTY, env } = {}) {
44
+ const args = argv[0] === 'forecast' ? argv.slice(1) : argv.slice();
45
+ const verb = args[0], flags = flagsOf(args.slice(1));
46
+ if (!verb || verb === 'help' || verb === '--help' || verb === '-h') { for (const l of USAGE) say(l); return verb ? 0 : 1; }
47
+ if (!COMMANDS.forecast.includes(verb)) { say(`unknown forecast command "${verb}" — one of ${COMMANDS.forecast.join(', ')}`); return 2; }
48
+ const dir = D.stateDirOf(flags.root ? path.resolve(cwd, flags.root) : repoRoot(cwd));
49
+ if (!dir) { say('✗ this repository has no PMOS state folder (pmos/state, state or .pmos)'); return 1; }
50
+ if (verb === 'turned') {
51
+ const L = FC.turnedSince(dir, typeof flags.since === 'string' ? flags.since : null);
52
+ if (flags.json) say(JSON.stringify({ ok: true, turned: L }));
53
+ else if (!L.length) say('No forecast turned.');
54
+ else for (const l of L) say(`${String(l.at).slice(0, 10)} ${l.scope} ${l.id}: ${l.from} → ${l.to}`);
55
+ return 0;
56
+ }
57
+ const actor = actorLib.fromCli({ isTTY: isTTY === undefined ? !!(process.stdin.isTTY && process.stdout.isTTY) : isTTY, env: env === undefined ? process.env : env });
58
+ if (!actorLib.isPm(actor) && !actorLib.isAgent(actor)) { say('✗ only the PM or an agent session can keep a baseline'); return 1; }
59
+ if (typeof flags.goal !== 'string') { say('usage: pmos forecast ' + verb + ' --goal <id>'); return 2; }
60
+ const r = verb === 'baseline-off' ? FC.clearBaseline(dir, actor, flags.goal)
61
+ : FC.setBaseline(dir, actor, { goal: flags.goal, label: typeof flags.label === 'string' ? flags.label : '',
62
+ exclude: String(typeof flags.exclude === 'string' ? flags.exclude : '').split(',').filter(Boolean).map((s) => { const [from, to] = s.trim().split('..'); return { from, to: to || from }; }) });
63
+ if (r.error) { say('✗ ' + r.error); return 1; }
64
+ say(verb === 'baseline-off' ? `Dropped the baseline of ${flags.goal}.` : `Kept the baseline "${r.line.label}" for ${flags.goal}.`);
65
+ return 0;
66
+ }
67
+
68
+ module.exports = { run, COMMANDS, USAGE };
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+ /* forecast-tick.js — the forecasts recompute without a page open (build brief Grill and Forecast, F-A follow-up, Wawan 2026-10-29 "continue").
3
+ *
4
+ * create({ ctx, env, now }) → { tick(o) → Promise<{ ran, boards } | { skipped }> }
5
+ *
6
+ * Once an hour (PMOS_FORECAST_TICK_MS), the server's one-minute tick reads /api/insights-premium and /api/board-premium for every board, in
7
+ * process and one board at a time, exactly as the pages read them. Those routes put the forecasts on their models and write a state that is new
8
+ * or changed to <state>/forecast.jsonl (lib/forecast.js record), so a "forecast turned" line, and its onTurned listeners (the Grill), fire
9
+ * with no one looking. Nothing else is written. PMOS_FORECAST=off stops it (test-run.js sets it off). A read already running skips the tick. */
10
+ const HOUR = 3600e3;
11
+
12
+ function create({ ctx, env = process.env, now = () => Date.now() } = {}) {
13
+ let last = 0, running = false;
14
+ const every = () => Math.max(1000, Number(env.PMOS_FORECAST_TICK_MS) || HOUR);
15
+ /** GET one route module's answer in process, as the premium routes read one another. */
16
+ async function get(mod, pathAndQuery) {
17
+ let out = null;
18
+ const c = Object.assign({}, ctx, { json: (res, obj, code) => { out = { status: code || 200, body: obj }; } });
19
+ await require(mod).handle({ method: 'GET', headers: {} }, {}, new URL('http://local' + pathAndQuery), c);
20
+ return out;
21
+ }
22
+ async function tick(o = {}) {
23
+ if (String(env.PMOS_FORECAST || '').toLowerCase() === 'off') return { skipped: 'off' };
24
+ const t = now();
25
+ if (running) return { skipped: 'running' };
26
+ if (!o.force && t - last < every()) return { skipped: 'not due' };
27
+ running = true; last = t;
28
+ let n = 0;
29
+ try {
30
+ const list = await get('./routes-boards.js', '/api/boards?names=1');
31
+ const boards = (list && list.body && list.body.boards) || [];
32
+ for (const b of boards) {
33
+ const q = '?ws=' + encodeURIComponent(b.ws) + '&board=' + encodeURIComponent(b.id);
34
+ try { await get('./routes-insights-premium.js', '/api/insights-premium' + q); } catch { /* the next board still runs */ }
35
+ try { await get('./routes-board-premium.js', '/api/board-premium' + q); } catch { /* the next board still runs */ }
36
+ n++;
37
+ }
38
+ } finally { running = false; }
39
+ return { ran: true, boards: n };
40
+ }
41
+ return { tick };
42
+ }
43
+
44
+ module.exports = { create };
@@ -0,0 +1,209 @@
1
+ 'use strict';
2
+ /* lib/forecast.js — the one forecast of a goal, an initiative's delivery, a program's milestones and a health budget's burn (build brief Grill and
3
+ * Forecast, part F-A; backend only: the forecasts ride on the API payloads and no page draws them yet).
4
+ *
5
+ * ONE METHOD. A goal's range is lib/intel-report.js rangeOf ("Forecasts are ranges"): straight lines through its last 3, 4, 5 and 6 readings,
6
+ * carried to the target date; the likely end is the four-reading line, the one the Intelligence projection says in words. A delivery range is
7
+ * lib/ready-reports.js forecastOf: the tickets left at the fastest and the slowest of two closing rates. Nothing here fits another curve.
8
+ *
9
+ * goalForecast(g, o) PURE → { state, likely, low, high, target, by, asOf, source, driftFrom, weeks, why, baseline } | null
10
+ * g: a goal of lib/insights-premium.js goalsOf. o: { today, baseline, driftFrom }. null when the goal has no target,
11
+ * no target date ahead, or is a limit or a done-or-not goal (zero is silence)
12
+ * deliveryForecast(r, J, o) PURE → { state, likely, low, high, promised, asOf, source: 'jira', driftFrom, done, total, why } | null
13
+ * r: a Board row (its `end` is the promise). J: its Jira snapshot { at, tickets: [{ category, resolved }] }
14
+ * programForecast(p, byIni) PURE → { atRisk, total } | null p: a program of lib/programs.js; byIni: Map initiative id → its delivery forecast
15
+ * budgetBurn(g) PURE → { weeksLeft } | null g: the Stay within goal that names the budget. Only under 8 weeks
16
+ * decorateInsights(model, F) puts g.forecast on each goal and b.burn on each budget of an Insights model; answers the items to record
17
+ *
18
+ * STATES. on-track (every line reaches the target), at-risk (some do), will-miss (none do), too-early (under 3 weeks or under 3 readings: no
19
+ * number at all), held (the source was not read for more than 7 days: the range stands as it was read and is never carried forward). A delivery's
20
+ * state comes from its range against the promise; with no promised date it has no state (null) and says why.
21
+ *
22
+ * THE LEDGER: <state>/forecast.jsonl, append-only, one line per event { at, by, kind, ... }:
23
+ * seen { scope, id, ws, state } the first forecast of a goal or an initiative: no event
24
+ * turned { scope, id, ws, from, to, likely, low, high, by } its state changed. lib/grill (G-A) reads these: turnedSince(dir, since), or
25
+ * onTurned(fn) in process. A held forecast is never recorded, so a source that
26
+ * pauses and comes back does not read as a turn
27
+ * baseline { goal, label, exclude: [{ from, to }] } the PM's kept baseline ("without the promo weeks"): those readings leave the range
28
+ * baseline-off { goal }
29
+ * record(dir, ws, items, o) → [turned line] · read(dir) → fold · fold(lines) PURE → { last, lastOn, baselines }
30
+ * setBaseline(dir, actor, input) → { ok, line } | { error } · clearBaseline(dir, actor, goal) */
31
+ const fs = require('fs');
32
+ const path = require('path');
33
+ const IR = require('./intel-report.js');
34
+ const RR = require('./ready-reports.js');
35
+
36
+ const LEDGER = 'forecast.jsonl';
37
+ const KINDS = new Set(['seen', 'turned', 'baseline', 'baseline-off']);
38
+ const STATES = Object.freeze(['on-track', 'at-risk', 'will-miss', 'too-early', 'held']);
39
+ const DAY = 864e5, WEEK = 7 * DAY;
40
+ const MIN_WEEKS = 3, MIN_READINGS = 3, HELD_DAYS = 7, BURN_WEEKS = 8;
41
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
42
+ const fin = (v) => typeof v === 'number' && Number.isFinite(v);
43
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
44
+ const str = (v) => (typeof v === 'string' ? v : '');
45
+ const dayMs = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
46
+ const dayOf = (v) => (dayMs(v) !== null ? String(v).slice(0, 10) : null);
47
+ const r2 = (v) => Math.round(v * 100) / 100;
48
+ const addDays = (d, n) => new Date(dayMs(d) + n * DAY).toISOString().slice(0, 10);
49
+
50
+ /** The readings a kept baseline leaves in: every reading outside its excluded spans. */
51
+ const keptOf = (series, B) => (!B || !B.exclude.length ? series : series.filter((r) => !B.exclude.some((x) => r.at >= x.from && r.at <= x.to)));
52
+
53
+ function goalForecast(g, o = {}) {
54
+ if (!g || !fin(g.target) || !g.byAt || g.type === 'Stay within' || g.type === 'Done or not') return null;
55
+ const B = o.baseline || null;
56
+ const S = keptOf((g.series || []).filter((r) => r && fin(r.v) && dayMs(r.at) !== null), B);
57
+ const today = dayMs(o.today), due = dayMs(g.byAt);
58
+ const lastAt = S.length ? S[S.length - 1].at : null;
59
+ if (due === null || (lastAt && due <= dayMs(lastAt))) return null;
60
+ const read = g.lastRead && dayOf(g.lastRead.at || g.lastRead.day);
61
+ const asOf = read && (!lastAt || read >= lastAt) ? read : lastAt;
62
+ const base = { target: g.target, by: g.byAt, asOf, source: g.recipe && g.recipe.connector ? g.recipe.connector : 'readings', driftFrom: null,
63
+ baseline: B ? { label: B.label, exclude: B.exclude } : null };
64
+ const weeks = S.length ? (dayMs(lastAt) - dayMs(S[0].at)) / WEEK : 0;
65
+ if (S.length < MIN_READINGS || weeks < MIN_WEEKS) {
66
+ return { ...base, state: 'too-early', likely: null, low: null, high: null, weeks: r2(weeks), why: 'Under 3 weeks of readings, so there is no forecast yet.' };
67
+ }
68
+ const R = IR.rangeOf({ series: S, byAt: g.byAt, target: g.target, unit: g.unit, direction: g.direction, base: g.base });
69
+ if (!R) return null;
70
+ const state = R.reaches ? 'on-track' : R.none ? 'will-miss' : 'at-risk';
71
+ const out = { ...base, state, likely: r2(R.likely !== null ? R.likely : (R.lo + R.hi) / 2), low: r2(R.lo), high: r2(R.hi), weeks: r2(weeks),
72
+ why: 'Straight lines through the last 3 to ' + (R.n + 2) + ' readings' + (B ? ' (' + B.label + ')' : '') + ', carried to ' + g.byAt + '.' };
73
+ if (today !== null && asOf && today - dayMs(asOf) > HELD_DAYS * DAY) return Object.assign(out, { state: 'held', was: state, why: 'Not read since ' + asOf + ', so the range is held where it was.' });
74
+ if (state !== 'on-track' && o.driftFrom) out.driftFrom = o.driftFrom;
75
+ return out;
76
+ }
77
+
78
+ const DOT_STATE = { on: 'on-track', risk: 'at-risk', behind: 'will-miss' };
79
+ function deliveryForecast(r, J, o = {}) {
80
+ if (!r || !J) return null;
81
+ const today = dayOf(o.today) || new Date().toISOString().slice(0, 10), promised = dayOf(r.end);
82
+ const F = RR.forecastOf(J, today, promised);
83
+ if (!F) return null;
84
+ const asOf = dayOf(F.at);
85
+ const base = { promised, asOf, source: 'jira', driftFrom: null, done: F.done, total: F.total };
86
+ if (!F.lo) return { ...base, state: 'too-early', likely: null, low: null, high: null, why: F.why || 'No forecast range yet' };
87
+ const likely = F.hi ? addDays(F.lo, Math.round((dayMs(F.hi) - dayMs(F.lo)) / DAY / 2)) : F.lo;
88
+ const state = F.finished ? 'on-track' : promised ? DOT_STATE[F.dot] || null : null;
89
+ const out = { ...base, state, likely, low: F.lo, high: F.hi, why: F.finished ? 'Every ticket is done.' : !promised ? 'No promised date to read the range against.' : F.why || 'The tickets left at the fastest and the slowest closing rate.' };
90
+ if (!F.finished && asOf && dayMs(today) - dayMs(asOf) > HELD_DAYS * DAY) return Object.assign(out, { state: 'held', was: state, why: 'Jira not read since ' + asOf + ', so the range is held where it was.' });
91
+ if (state && state !== 'on-track' && o.driftFrom) out.driftFrom = o.driftFrom;
92
+ return out;
93
+ }
94
+
95
+ /** A program's milestones at risk: an open one whose own `risk` mark is set, that waits on an initiative forecast at risk or to miss, or whose
96
+ * date falls before the late end of such an initiative's range. A done milestone or check counts in the total only. */
97
+ function programForecast(p, byIni) {
98
+ const M = (p && Array.isArray(p.milestones) ? p.milestones : []).filter((m) => m && m.name);
99
+ if (!M.length) return null;
100
+ const late = (m) => (m.waits || []).some((id) => {
101
+ const f = byIni && byIni.get(id);
102
+ if (!f) return false;
103
+ if (f.state === 'at-risk' || f.state === 'will-miss') return true;
104
+ return !!(m.date && (f.high || f.low) && (f.high || f.low) > m.date);
105
+ });
106
+ const atRisk = M.filter((m) => !m.done && (m.risk === true || late(m))).length;
107
+ return { atRisk, total: M.length };
108
+ }
109
+
110
+ /** A health budget's burn: the weeks until its Stay within goal crosses its limit, at the straight line through its last four readings.
111
+ * null when it is over already (its reading says so), moving away from the limit, or 8 weeks or more from it. */
112
+ function budgetBurn(g) {
113
+ if (!g || g.type !== 'Stay within' || !fin(g.target)) return null;
114
+ const S = (g.series || []).filter((r) => r && fin(r.v) && dayMs(r.at) !== null).slice(-4);
115
+ if (S.length < 2) return null;
116
+ const a = S[0], z = S[S.length - 1], dt = (dayMs(z.at) - dayMs(a.at)) / WEEK;
117
+ if (!(dt > 0)) return null;
118
+ const ceil = g.limit !== 'floor', perWeek = (z.v - a.v) / dt, room = ceil ? g.target - z.v : z.v - g.target, toward = ceil ? perWeek : -perWeek;
119
+ if (room <= 0 || !(toward > 0)) return null;
120
+ const weeksLeft = Math.floor(room / toward);
121
+ return weeksLeft < BURN_WEEKS ? { weeksLeft } : null;
122
+ }
123
+
124
+ /* ── the ledger ── */
125
+ function ledgerFile(dir) { return dir ? path.join(dir, LEDGER) : null; }
126
+ function readLines(file) {
127
+ if (!file) return [];
128
+ let text = '';
129
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
130
+ const out = [];
131
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && KINDS.has(l.kind)) out.push(l); } catch { /* a torn line is skipped */ } }
132
+ return out;
133
+ }
134
+ const keyOf = (scope, id) => scope + ':' + id;
135
+ function fold(lines) {
136
+ const last = new Map(), lastOn = new Map(), baselines = new Map();
137
+ for (const l of lines || []) {
138
+ if (l.kind === 'seen' || l.kind === 'turned') {
139
+ const k = keyOf(l.scope, l.id), to = l.kind === 'seen' ? l.state : l.to;
140
+ if (l.kind === 'turned' && l.from === 'on-track') lastOn.set(k, dayOf(l.at)); // the day it was last seen on track
141
+ last.set(k, { state: to, at: l.at });
142
+ } else if (l.kind === 'baseline') baselines.set(str(l.goal), { label: str(l.label), exclude: Array.isArray(l.exclude) ? l.exclude : [], at: l.at });
143
+ else if (l.kind === 'baseline-off') baselines.delete(str(l.goal));
144
+ }
145
+ return { last, lastOn, baselines };
146
+ }
147
+ function read(dir) { return fold(readLines(ledgerFile(dir))); }
148
+ function append(dir, actor, ev, at) {
149
+ const line = { at: at || new Date().toISOString(), by: (actor && actor.by) || null, ...ev };
150
+ fs.mkdirSync(dir, { recursive: true });
151
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify(line) + '\n');
152
+ return line;
153
+ }
154
+
155
+ const listeners = new Set();
156
+ /** Subscribe in process to every turned line; answers the unsubscribe. */
157
+ const onTurned = (fn) => { listeners.add(fn); return () => listeners.delete(fn); };
158
+ /** Write the state of each forecast that is new or changed. items: [{ scope, id, state, likely, low, high, by }]. A held or stateless one is skipped. */
159
+ function record(dir, ws, items, o = {}) {
160
+ if (!dir) return [];
161
+ const F = o.fold || read(dir), out = [];
162
+ for (const x of items || []) {
163
+ if (!x || !x.id || !STATES.includes(x.state) || x.state === 'held') continue;
164
+ const prev = F.last.get(keyOf(x.scope, x.id));
165
+ if (prev && prev.state === x.state) continue;
166
+ const line = prev
167
+ ? append(dir, { by: 'agent:forecast' }, { kind: 'turned', scope: x.scope, id: x.id, ws: ws || null, from: prev.state, to: x.state, likely: x.likely, low: x.low, high: x.high, by_date: x.by || null }, o.at)
168
+ : append(dir, { by: 'agent:forecast' }, { kind: 'seen', scope: x.scope, id: x.id, ws: ws || null, state: x.state }, o.at);
169
+ F.last.set(keyOf(x.scope, x.id), { state: x.state, at: line.at });
170
+ if (line.kind === 'turned') { out.push(line); for (const fn of listeners) { try { fn(line); } catch { /* a listener's error is its own */ } } }
171
+ }
172
+ return out;
173
+ }
174
+ /** The turned lines at or after `since` (an ISO time), oldest first. */
175
+ const turnedSince = (dir, since) => readLines(ledgerFile(dir)).filter((l) => l.kind === 'turned' && (!since || String(l.at) >= String(since)));
176
+
177
+ /** What a baseline write accepts: { goal, label, exclude: [{ from, to }] } with 1 to 10 spans of ISO days. */
178
+ function setBaseline(dir, actor, i) {
179
+ const goal = str(i && i.goal).trim().slice(0, 100), label = str(i && i.label).replace(/\s+/g, ' ').trim().slice(0, 80);
180
+ if (!goal) return { error: 'goal is required' };
181
+ if (!label) return { error: 'label is required, e.g. "without the promo weeks"' };
182
+ const ex = Array.isArray(i.exclude) ? i.exclude : [];
183
+ if (!ex.length || ex.length > 10) return { error: 'exclude takes 1 to 10 spans: [{ from: YYYY-MM-DD, to: YYYY-MM-DD }]' };
184
+ const exclude = [];
185
+ for (const x of ex) {
186
+ if (!isObj(x) || !DATE_RE.test(str(x.from)) || !DATE_RE.test(str(x.to)) || x.from > x.to) return { error: 'each span is { from, to } as YYYY-MM-DD with from on or before to' };
187
+ exclude.push({ from: x.from, to: x.to });
188
+ }
189
+ return { ok: true, line: append(dir, actor, { kind: 'baseline', goal, label, exclude }) };
190
+ }
191
+ function clearBaseline(dir, actor, goal) {
192
+ const g = str(goal).trim().slice(0, 100);
193
+ if (!g) return { error: 'goal is required' };
194
+ return { ok: true, line: append(dir, actor, { kind: 'baseline-off', goal: g }) };
195
+ }
196
+
197
+ /** Put g.forecast on each goal and b.burn on each budget of an Insights model (lib/insights-premium.js build). Answers the items to record. */
198
+ function decorateInsights(model, F) {
199
+ const L = F || fold([]), items = [];
200
+ for (const g of (model && model.goals) || []) {
201
+ const k = keyOf('goal', g.id);
202
+ g.forecast = goalForecast(g, { today: model.today, baseline: L.baselines.get(g.id) || null, driftFrom: L.lastOn.get(k) || null });
203
+ if (g.forecast) items.push({ scope: 'goal', id: g.id, state: g.forecast.state, likely: g.forecast.likely, low: g.forecast.low, high: g.forecast.high, by: g.forecast.by });
204
+ }
205
+ for (const b of (model && model.budgets) || []) b.burn = budgetBurn(((model && model.goals) || []).find((g) => g.id === b.goal) || null);
206
+ return items;
207
+ }
208
+
209
+ module.exports = { LEDGER, STATES, goalForecast, deliveryForecast, programForecast, budgetBurn, decorateInsights, ledgerFile, readLines, fold, read, record, onTurned, turnedSince, setBaseline, clearBaseline };