create-pmos 0.842.0 → 0.843.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.
- package/package.json +20 -3
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/workspace/changelog.json +19 -2
- package/workspace/guide/cli.md +11 -0
- package/workspace/guide/layout.md +2 -0
- package/workspace/guide/settings-and-switches.md +1 -0
- package/workspace/lib/build-engine.js +4 -1
- package/workspace/lib/factory-traces.js +2 -1
- package/workspace/lib/features.json +1 -0
- package/workspace/lib/initiative-cost.js +259 -0
- package/workspace/lib/pmos-verbs.js +3 -0
- package/workspace/lib/routes-factory-metrics.js +54 -1
- package/workspace/lib/routes-proposals.js +7 -0
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/bd-backlog.css +3 -0
- package/workspace/public/pm/bd-backlog.js +36 -7
- package/workspace/public/pm/cozy-pop-work.js +14 -1
- package/workspace/public/pm/initiative-cost.js +103 -0
- package/workspace/test-lists/initiative-cost.json +9 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-pmos",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.843.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": {
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
],
|
|
35
35
|
"pmosChanges": [
|
|
36
36
|
{
|
|
37
|
-
"v": "0.
|
|
38
|
-
"at": "2026-11-25T17:
|
|
37
|
+
"v": "0.843.0",
|
|
38
|
+
"at": "2026-11-25T17:32:30.120Z",
|
|
39
39
|
"f": 4,
|
|
40
40
|
"prs": [
|
|
41
41
|
{
|
|
@@ -71,6 +71,23 @@
|
|
|
71
71
|
"open": "/premium-events.html"
|
|
72
72
|
},
|
|
73
73
|
"i": "tb-events-bring"
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
"n": 1958,
|
|
77
|
+
"t": "What each initiative and merged pull request cost, and a pause for a stall (job #1906)",
|
|
78
|
+
"s": "What each initiative and merged pull request cost, and a pause for a stall (job #1906)",
|
|
79
|
+
"k": "new",
|
|
80
|
+
"h": "What each initiative and merged pull request cost, and a pause for a stall (job #1906)",
|
|
81
|
+
"try": {
|
|
82
|
+
"steps": [
|
|
83
|
+
"Open Work and press the Cost tab: read each initiative's agent hours, spend and result",
|
|
84
|
+
"Open an initiative from Work, press ⋯ and pick Cost: one row per merged pull request with its own cost",
|
|
85
|
+
"Where a row says 0 merged in 7 days, press the pause button on its ✦, then Undo in the toast"
|
|
86
|
+
],
|
|
87
|
+
"see": "One row per initiative the factory worked on: agent hours, spend in dollars and how many pull requests merged. An initiative that spent for 7 days with no merge shows one ✦ asking to pause its jobs.…",
|
|
88
|
+
"open": "/premium-board.html?work=cost"
|
|
89
|
+
},
|
|
90
|
+
"i": "initiative-cost"
|
|
74
91
|
}
|
|
75
92
|
]
|
|
76
93
|
},
|
package/payload/KIT-VERSION
CHANGED
|
@@ -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-11-25T17:
|
|
5
|
+
generated: {by: process:create-pmos, at: "2026-11-25T17:32:26Z"}
|
|
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-11-25T17:
|
|
5
|
+
generated: {by: process:create-pmos, at: "2026-11-25T17:32:26Z"}
|
|
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-11-25T17:
|
|
5
|
+
generated: {by: process:create-pmos, at: "2026-11-25T17:32:26Z"}
|
|
6
6
|
status: stable
|
|
7
7
|
---
|
|
8
8
|
|
package/workspace/changelog.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[
|
|
2
2
|
{
|
|
3
|
-
"v": "0.
|
|
4
|
-
"at": "2026-11-25T17:
|
|
3
|
+
"v": "0.843.0",
|
|
4
|
+
"at": "2026-11-25T17:32:30.120Z",
|
|
5
5
|
"f": 4,
|
|
6
6
|
"prs": [
|
|
7
7
|
{
|
|
@@ -37,6 +37,23 @@
|
|
|
37
37
|
"open": "/premium-events.html"
|
|
38
38
|
},
|
|
39
39
|
"i": "tb-events-bring"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"n": 1958,
|
|
43
|
+
"t": "What each initiative and merged pull request cost, and a pause for a stall (job #1906)",
|
|
44
|
+
"s": "What each initiative and merged pull request cost, and a pause for a stall (job #1906)",
|
|
45
|
+
"k": "new",
|
|
46
|
+
"h": "What each initiative and merged pull request cost, and a pause for a stall (job #1906)",
|
|
47
|
+
"try": {
|
|
48
|
+
"steps": [
|
|
49
|
+
"Open Work and press the Cost tab: read each initiative's agent hours, spend and result",
|
|
50
|
+
"Open an initiative from Work, press ⋯ and pick Cost: one row per merged pull request with its own cost",
|
|
51
|
+
"Where a row says 0 merged in 7 days, press the pause button on its ✦, then Undo in the toast"
|
|
52
|
+
],
|
|
53
|
+
"see": "One row per initiative the factory worked on: agent hours, spend in dollars and how many pull requests merged. An initiative that spent for 7 days with no merge shows one ✦ asking to pause its jobs.…",
|
|
54
|
+
"open": "/premium-board.html?work=cost"
|
|
55
|
+
},
|
|
56
|
+
"i": "initiative-cost"
|
|
40
57
|
}
|
|
41
58
|
]
|
|
42
59
|
},
|
package/workspace/guide/cli.md
CHANGED
|
@@ -1147,6 +1147,17 @@ PMOS never pushes to the default branch and never merges. Every command takes `-
|
|
|
1147
1147
|
|
|
1148
1148
|
The benchmark needs a signed-in agent CLI. It never pushes and never opens a pull request. A role run cannot start it.
|
|
1149
1149
|
|
|
1150
|
+
### pmos cost: what the factory spent per initiative and pull request
|
|
1151
|
+
|
|
1152
|
+
Where PMOS's factory builds a product's work items, each run leaves its tokens, its cost and its time. These commands add them up per initiative and per merged pull request. Work › Cost shows the same rows.
|
|
1153
|
+
|
|
1154
|
+
- `pmos cost` (or `pmos cost show`) prints one line per initiative the factory worked on: its agent hours, its spend in dollars and how many pull requests merged. An initiative that spent in the last 7 days and has had no merge for 7 days says "0 merged in 7 days", with the `pmos cost pause` that would pause it. `--json` prints the rows.
|
|
1155
|
+
- `pmos cost <initiative>` prints one line per merged pull request of that initiative, each with its own agent hours, spend and tokens, and its link when PMOS opened it.
|
|
1156
|
+
- `pmos cost pause <initiative>` pauses the initiative's new factory jobs: the Builder takes no new work item of it. Work a Builder holds now finishes. PMOS also files one ✦ for a stalled initiative, and its ✓ does the same, with Undo.
|
|
1157
|
+
- `pmos cost resume <initiative>` lets the factory take its jobs again.
|
|
1158
|
+
|
|
1159
|
+
Money shows only in these commands, on Work › Cost and in the initiative's ⋯ › Cost. `PMOS_INITIATIVE_COST=off` stops the ✦.
|
|
1160
|
+
|
|
1150
1161
|
### pmos jira
|
|
1151
1162
|
|
|
1152
1163
|
[Jira tickets](jira.md) explains each step with its examples.
|
|
@@ -117,6 +117,8 @@ On a computer, Work is built from the parts of the PMOS design system. The top l
|
|
|
117
117
|
- **Add to the backlog.** Type a line and press Enter. Name the initiative ("for Migration from Okta") or PMOS puts it in the closest one; when none is close, it asks.
|
|
118
118
|
- **Items.** A table grouped by initiative, each group with "n items · r ready". The tabs show **All**, **Ready**, **Needs detail** or **Untouched 60 days**. Drag a row by its grip to change the rank (with Undo); the number is its place in the one rank. **Last change** shows when the item last changed; an item untouched for 30 days or more has a badge, for example "79 days untouched". **Group** also groups the rows by what PMOS can do, with its ✓ buttons. Tick rows to change them together. The tune icon filters the rows.
|
|
119
119
|
|
|
120
|
+
**Cost** shows on a computer when PMOS's factory has built work items for the product. One row per initiative it worked on: **Agent hours**, **Spend** in dollars and **Result**, for example "3 PRs merged". Press a name to open the initiative. An initiative that spent in the last 7 days and has had no merge for 7 days says "0 merged in 7 days" in red, and one ✦ under the table asks to pause its jobs. The pause button stops new jobs: the factory takes no new work item of it, and the work it holds now finishes. The toast has **Undo**. ✕ keeps it going, and PMOS does not ask again until it stalls again. A paused initiative has a play button that starts its jobs again. Money shows only here and in the initiative's ⋯ › **Cost**, which lists each merged pull request with its own cost. `pmos cost` reads the same rows.
|
|
121
|
+
|
|
120
122
|
**This sprint** shows all work in the sprint's dates, in Jira and outside it. It holds every ticket of the active Jira sprint, done ones too, and every PMOS task whose dates meet the sprint's dates. A task under way with no date is in it too. Early stages often have no tickets, so their work still shows here.
|
|
121
123
|
|
|
122
124
|
- **The sprint card.** The sprint's name, its end date and what it holds, for example "21 Jira tickets and 7 tasks outside Jira". Under it, "11 of 28 done" with a bar. Then four columns: **Sprint goal**, **In progress**, **To do** and **Done**, each with its count and its first tasks. PMOS drafts the goal from the sprint's work. Press the pencil to write your own; it can name work outside Jira, and PMOS does not write over it. When PMOS has a newer draft, ✓ uses it and ✕ keeps yours. Press the sprint's name to open a past sprint. The arrow icon reads Jira again; a red dot on it means the last read is old. Under the columns, PMOS shows one suggestion, for example to place tickets in an initiative, with **Why**, **PMOS will**, **What changes** and **Based on**. The pencil picks another initiative first, ✓ does it (with Undo) and ✕ says not now.
|
|
@@ -173,6 +173,7 @@ An "off" switch accepts `off`, `0`, `false` or `no` unless the row says a differ
|
|
|
173
173
|
| `PMOS_CORRECTION_MEMORY` | `off` stops your ✕ reasons from becoming memory. By default a reason of 12 characters or more is remembered as one unconfirmed entry for 30 days, at most 6 at once. | on | — |
|
|
174
174
|
| `PMOS_CORRECTION_RULES` | `off` stops PMOS from recording each ✕ reason with a kind and offering a kind that repeats 3 times in 30 days as a standing rule in the Lab. | on | — |
|
|
175
175
|
| `PMOS_FACTORY_LESSONS` | `off` stops factory lessons. By default each factory setback (a failed check, a revert or rollback, a pull request the guardrail sent to a person, your Undo of one, a reviewer FAIL) becomes one Lessons line on its initiative and one line in the Builder's notebook. The Builder prompt carries the last 5. The same setback 3 times in 14 days files one proposal, "Change the factory harness", for your ✓. | on | — |
|
|
176
|
+
| `PMOS_INITIATIVE_COST` | `off` stops the pause proposal of the factory's cost. By default, when the factory has spent on an initiative for 7 days with no merge, PMOS files one ✦ to pause its new jobs, for your ✓. Work › Cost and `pmos cost` still show the cost. | on | — |
|
|
176
177
|
| `PMOS_CLAUDE_HOME` | The one folder where PMOS looks for PMOS transcripts. | the PMOS config folders | — |
|
|
177
178
|
| `PMOS_HEADLESS_TIMEOUT_MS` | The longest time a background run may take. | 20 minutes | — |
|
|
178
179
|
|
|
@@ -134,7 +134,9 @@ function itemsOf(root) {
|
|
|
134
134
|
}
|
|
135
135
|
const itemOf = (root, item) => itemsOf(root).find((x) => x.item_id === item) || null;
|
|
136
136
|
// factory-fleet-scale: an item whose dependencies are not integrated yet is not offered (lib/factory-fleet.js waitingOn)
|
|
137
|
-
|
|
137
|
+
// initiative-cost (A17): a paused initiative's declared items are not offered; an item already claimed is not touched, so running work finishes
|
|
138
|
+
const pausedOf = (root) => { try { return require('./initiative-cost.js').pausedOf(require('./driver.js').stateDirOf(root, { create: false })); } catch { return new Set(); } };
|
|
139
|
+
const next = (root, ini) => { const all = itemsOf(root), off = pausedOf(root); return all.filter((x) => x.state === 'declared' && (!ini || x.initiative_id === ini) && !off.has(x.initiative_id) && !require('./factory-fleet.js').waitingOn(x, all).length); };
|
|
138
140
|
|
|
139
141
|
function claim(root, item, { agent = 'pmos:builder' } = {}) {
|
|
140
142
|
if (!ITEM_RE.test(String(item || ''))) return { ok: false, error: 'name a work item, <initiative>.<n>' };
|
|
@@ -143,6 +145,7 @@ function claim(root, item, { agent = 'pmos:builder' } = {}) {
|
|
|
143
145
|
const it = all.find((x) => x.item_id === item) || null;
|
|
144
146
|
if (!it) return { ok: false, error: `${item} is not a declared work item` };
|
|
145
147
|
if (it.state !== 'declared') return { ok: false, error: `${item} is ${it.state}, not waiting for a Builder` };
|
|
148
|
+
if (pausedOf(root).has(it.initiative_id)) return { ok: false, error: `${it.initiative_id} is paused, so the factory takes no new job of it. pmos cost resume ${it.initiative_id} starts its jobs again` };
|
|
146
149
|
const FL = require('./factory-fleet.js');
|
|
147
150
|
const wait = FL.waitingOn(it, all);
|
|
148
151
|
if (wait.length) return { ok: false, error: `${item} waits for ${wait.join(', ')}. It can be claimed once ${wait.length === 1 ? 'that item is' : 'those items are'} integrated` };
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*
|
|
12
12
|
* THE TRACE. <product state>/factory-traces.jsonl (pmos/state: runtime, gitignored, never a control-graph record). One line per Builder
|
|
13
13
|
* or reviewer run that named a work item (`pmos build claim|propose|open|policy|status <item>`):
|
|
14
|
-
* { at, kind: 'run', item, role, turns, tools: { Name: count }, files: [rel], model, input, cacheCreate, cacheRead, output, costUsd, ok }
|
|
14
|
+
* { at, kind: 'run', item, role, turns, tools: { Name: count }, files: [rel], model, input, cacheCreate, cacheRead, output, costUsd, ms, ok }
|
|
15
15
|
* tools are the tool NAMES the run called; files are the paths Write and Edit touched, relative to the item's worktree. The tokens and the
|
|
16
16
|
* cost come from lib/headless.js parseResult and usageOf, the same reads lib/run-tokens.js keeps. No line holds a prompt, an answer, a
|
|
17
17
|
* tool input, a command or a key. The server writes the line after the run ends, from the run's own stdout: the Builder's run gains no
|
|
@@ -105,6 +105,7 @@ function record(stateDir, { item, role = '', result = null, tracker: t = null, o
|
|
|
105
105
|
model: typeof r.model === 'string' ? r.model.slice(0, 80) : null,
|
|
106
106
|
input: num(tk.input), cacheCreate: num(tk.cacheCreate), cacheRead: num(tk.cacheRead), output: num(tk.output),
|
|
107
107
|
costUsd: Number.isFinite(r.costUsd) ? Math.round(r.costUsd * 10000) / 10000 : null,
|
|
108
|
+
ms: Number.isFinite(r.durationMs) && r.durationMs >= 0 ? Math.round(r.durationMs) : null, // the run's time: agent hours (lib/initiative-cost.js)
|
|
108
109
|
ok: ok == null ? null : !!ok,
|
|
109
110
|
});
|
|
110
111
|
}
|
|
@@ -93,6 +93,7 @@
|
|
|
93
93
|
{"id": "source", "audience": "agent", "status": "ga", "group": "Catch up", "name": "Stored tool reads", "say": "An agent session saves its read of a tool for the Briefing.", "cmd": "/source", "verb": "source"},
|
|
94
94
|
{"id": "refresh", "audience": "agent", "status": "ga", "group": "Catch up", "name": "Read only what changed", "say": "An agent session asks a tool what changed since the last read.", "cmd": "/refresh", "verb": "refresh"},
|
|
95
95
|
{"id": "lead", "audience": "agent", "status": "ga", "group": "Catch up", "name": "A popup's lead", "say": "PMOS writes a popup's short lead ahead, from stored reads.", "cmd": "/lead", "verb": "lead"},
|
|
96
|
+
{"id": "cost", "audience": "user", "status": "beta", "group": "What PMOS did", "name": "What the factory spent", "say": "Agent hours and spend per initiative and per merged pull request. Pause one that spends with no merge.", "cmd": "/spend", "verb": "cost", "place": "board", "since": "0.825.0"},
|
|
96
97
|
{"id": "propose", "audience": "agent", "status": "ga", "group": "What PMOS did", "name": "File a suggestion", "say": "A PMOS run files what it found under an initiative's ✦ for you to keep or drop.", "cmd": "/propose", "verb": "propose"},
|
|
97
98
|
{"id": "lab", "audience": "agent", "status": "ga", "group": "What PMOS did", "name": "The idle lab", "say": "What the idle lab's runs read and filed while you were away.", "cmd": "/lab", "verb": "lab"},
|
|
98
99
|
{"id": "metrics", "audience": "agent", "status": "ga", "group": "Your product", "name": "Metric drafts", "say": "A metric-draft run files a metric for you to keep or drop.", "cmd": "/metrics", "verb": "metrics"},
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* initiative-cost.js — what each initiative and each merged pull request cost the factory, and a pause for one that spends without a
|
|
3
|
+
* result (initiative initiative-cost, job #1906, idea A17; board BatchReleaseDS panel 21, agreed 2026-11-25). `pmos cost`.
|
|
4
|
+
*
|
|
5
|
+
* THE SOURCES, all the product's own, read-only here:
|
|
6
|
+
* traces <state>/factory-traces.jsonl (lib/factory-traces.js): one `run` line per Builder or reviewer run on a work item, with its
|
|
7
|
+
* tokens, its cost in dollars and (since this build) its time `ms`. An item `<initiative>.<n>` belongs to <initiative>.
|
|
8
|
+
* ledger <factory>/planning/work-items.jsonl: `integrated` or `shipped` is a merged item; `declared` carries its criterion.
|
|
9
|
+
* prs <state>/proposals.jsonl: a kept build ✦ wrote { op: 'pr', item, url }, the pull request PMOS opened for the item.
|
|
10
|
+
* THE ONE STORE this module writes: <state>/initiative-pause.jsonl, { at, by, ini, kind: 'pause' | 'resume', why }. The last line for an
|
|
11
|
+
* initiative wins. The UI (POST /api/initiative-cost/*), the ✦ (lib/routes-proposals.js group cost) and `pmos cost pause|resume` all write
|
|
12
|
+
* it through pause() and resume(), and lib/build-engine.js reads pausedOf().
|
|
13
|
+
*
|
|
14
|
+
* A PAUSE stops NEW jobs only: build-engine next() offers no declared item of a paused initiative and claim() refuses one. An item a
|
|
15
|
+
* Builder already holds keeps its claim, its worktree and its fix rounds, so running work finishes. Nothing here writes the work-item ledger.
|
|
16
|
+
*
|
|
17
|
+
* A STALL: the initiative's factory spent in the last STALL_DAYS days, and it has had no merge for STALL_DAYS days, counted from its last
|
|
18
|
+
* merge or, with none, from its first run. The proposal pass files ONE ✦ (group cost, type pause, class C: only the PM's ✓ pauses) per
|
|
19
|
+
* stall: its id carries the stall's start, so a ✕ or a ✓ is never asked again for the same stall. A ✦ whose initiative merged, stopped
|
|
20
|
+
* spending or was paused another way is dropped (zero is silence). Money is the Cost tab's alone: the ✦ title and why name no amount.
|
|
21
|
+
*
|
|
22
|
+
* costOf({ traces, ledger, prs, pauses, now }) PURE → { total: { costUsd, tokens, hours, runs }, rows: [row] }
|
|
23
|
+
* row { ini, runs, costUsd, tokens, hours, merged, prs: [{ item, title, costUsd, tokens, hours, url, mergedAt }], firstRunAt,
|
|
24
|
+
* lastRunAt, lastMergeAt, recentUsd (spent in the last STALL_DAYS), sinceUsd (spent since the stall's start), stall: { since } | null,
|
|
25
|
+
* paused }
|
|
26
|
+
* iniOf(item) · pausedOf(sd) → Set · pause(sd, ini, o) · resume(sd, ini, o) · readOf(root, { now }) → costOf over the repository's files
|
|
27
|
+
* proposePass(root, { now, stateDir? }) → { ok, filed: [id], dropped: [id] } never throws
|
|
28
|
+
* lines(C) · prLines(row) · run(argv, o) the CLI
|
|
29
|
+
* Nothing here calls a model or sends anything. */
|
|
30
|
+
const fs = require('fs');
|
|
31
|
+
const path = require('path');
|
|
32
|
+
|
|
33
|
+
const FILE = 'initiative-pause.jsonl';
|
|
34
|
+
const TAG = '[initiative-cost]';
|
|
35
|
+
const BY = 'agent:initiative-cost';
|
|
36
|
+
const DAY = 86400000;
|
|
37
|
+
const STALL_DAYS = 7;
|
|
38
|
+
const ITEM_RE = /^([a-z0-9][a-z0-9_-]*)\.[0-9]+$/;
|
|
39
|
+
const ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
|
|
40
|
+
|
|
41
|
+
const num = (v) => (Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : 0);
|
|
42
|
+
const tOf = (at) => { const t = Date.parse(at); return Number.isFinite(t) ? t : null; };
|
|
43
|
+
const r2 = (n) => Math.round(n * 100) / 100;
|
|
44
|
+
const r1 = (n) => Math.round(n * 10) / 10;
|
|
45
|
+
const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
46
|
+
const iniOf = (item) => { const m = ITEM_RE.exec(String(item || '')); return m ? m[1] : null; };
|
|
47
|
+
|
|
48
|
+
function readJsonl(file) {
|
|
49
|
+
let text = '';
|
|
50
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
|
|
51
|
+
const out = [];
|
|
52
|
+
for (const s of text.split('\n')) { if (!s.trim()) continue; try { const o = JSON.parse(s); if (o && typeof o === 'object') out.push(o); } catch { /* a torn line */ } }
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/* ── the pause store ── */
|
|
57
|
+
const pauseFile = (sd) => (sd ? path.join(sd, FILE) : null);
|
|
58
|
+
function pausesOf(sd) { return sd ? readJsonl(pauseFile(sd)) : []; }
|
|
59
|
+
/** PURE over the lines: the initiatives whose last line is a pause. */
|
|
60
|
+
function pausedSet(lines) {
|
|
61
|
+
const last = new Map();
|
|
62
|
+
for (const l of lines || []) if (l && ID_RE.test(String(l.ini || '')) && (l.kind === 'pause' || l.kind === 'resume')) last.set(l.ini, l.kind);
|
|
63
|
+
return new Set([...last].filter(([, k]) => k === 'pause').map(([i]) => i));
|
|
64
|
+
}
|
|
65
|
+
const pausedOf = (sd) => pausedSet(pausesOf(sd));
|
|
66
|
+
function write(sd, ini, kind, { by = 'pm', why = '', now = Date.now() } = {}) {
|
|
67
|
+
if (!sd) return { ok: false, error: 'this product has no state folder' };
|
|
68
|
+
if (!ID_RE.test(String(ini || ''))) return { ok: false, error: 'name an initiative' };
|
|
69
|
+
const on = pausedOf(sd).has(ini);
|
|
70
|
+
if (kind === 'pause' && on) return { ok: true, already: true, ini };
|
|
71
|
+
if (kind === 'resume' && !on) return { ok: true, already: true, ini };
|
|
72
|
+
const line = { at: new Date(now).toISOString(), by: one(by, 60) || 'pm', ini, kind, ...(why ? { why: one(why, 200) } : {}) };
|
|
73
|
+
try { fs.mkdirSync(sd, { recursive: true }); fs.appendFileSync(pauseFile(sd), JSON.stringify(line) + '\n'); } catch (e) { return { ok: false, error: one(e && e.message, 160) }; }
|
|
74
|
+
console.info(`${TAG} ${kind} ${ini}`);
|
|
75
|
+
return { ok: true, ini, line };
|
|
76
|
+
}
|
|
77
|
+
const pause = (sd, ini, o) => write(sd, ini, 'pause', o);
|
|
78
|
+
const resume = (sd, ini, o) => write(sd, ini, 'resume', o);
|
|
79
|
+
|
|
80
|
+
/* ── the fold ── */
|
|
81
|
+
/** PURE. prs: [{ item, url }]; pauses: the pause store's lines. */
|
|
82
|
+
function costOf({ traces = [], ledger = [], prs = [], pauses = [], now = Date.now() } = {}) {
|
|
83
|
+
const from = now - STALL_DAYS * DAY;
|
|
84
|
+
const mergedAt = new Map(), title = new Map(), urlOf = new Map();
|
|
85
|
+
for (const e of ledger || []) {
|
|
86
|
+
if (!e || typeof e.item_id !== 'string') continue;
|
|
87
|
+
if (e.event === 'declared' && e.criterion) title.set(e.item_id, one(e.criterion, 120));
|
|
88
|
+
const t = tOf(e.at);
|
|
89
|
+
if ((e.event === 'integrated' || e.event === 'shipped') && t != null && !mergedAt.has(e.item_id)) mergedAt.set(e.item_id, t);
|
|
90
|
+
}
|
|
91
|
+
for (const p of prs || []) if (p && p.item && p.url) urlOf.set(p.item, String(p.url));
|
|
92
|
+
const paused = pausedSet(pauses);
|
|
93
|
+
const by = new Map(), items = new Map();
|
|
94
|
+
const row = (ini) => { if (!by.has(ini)) by.set(ini, { ini, runs: 0, costUsd: 0, tokens: 0, ms: 0, firstRunAt: null, lastRunAt: null, runAts: [] }); return by.get(ini); };
|
|
95
|
+
for (const l of traces || []) {
|
|
96
|
+
if (!l || l.kind !== 'run') continue;
|
|
97
|
+
const ini = iniOf(l.item), t = tOf(l.at);
|
|
98
|
+
if (!ini || t == null || t > now) continue;
|
|
99
|
+
const x = row(ini), usd = num(l.costUsd), tk = num(l.input) + num(l.cacheCreate) + num(l.cacheRead) + num(l.output), ms = num(l.ms);
|
|
100
|
+
x.runs += 1; x.costUsd += usd; x.tokens += tk; x.ms += ms; x.runAts.push([t, usd]);
|
|
101
|
+
if (x.firstRunAt == null || t < x.firstRunAt) x.firstRunAt = t;
|
|
102
|
+
if (x.lastRunAt == null || t > x.lastRunAt) x.lastRunAt = t;
|
|
103
|
+
if (!items.has(l.item)) items.set(l.item, { item: l.item, costUsd: 0, tokens: 0, ms: 0 });
|
|
104
|
+
const it = items.get(l.item); it.costUsd += usd; it.tokens += tk; it.ms += ms;
|
|
105
|
+
}
|
|
106
|
+
const rows = [...by.values()].map((x) => {
|
|
107
|
+
const mine = [...items.values()].filter((it) => iniOf(it.item) === x.ini && mergedAt.has(it.item));
|
|
108
|
+
const merges = mine.map((it) => mergedAt.get(it.item)).filter((t) => t <= now);
|
|
109
|
+
const lastMergeAt = merges.length ? Math.max(...merges) : null;
|
|
110
|
+
const start = lastMergeAt != null ? lastMergeAt : x.firstRunAt;
|
|
111
|
+
const recentUsd = x.runAts.filter(([t]) => t >= from).reduce((s, [, u]) => s + u, 0);
|
|
112
|
+
const sinceUsd = x.runAts.filter(([t]) => lastMergeAt == null || t > lastMergeAt).reduce((s, [, u]) => s + u, 0);
|
|
113
|
+
const stalled = x.runAts.some(([t]) => t >= from) && start != null && now - start >= STALL_DAYS * DAY && (lastMergeAt == null || x.lastRunAt > lastMergeAt);
|
|
114
|
+
return {
|
|
115
|
+
ini: x.ini, runs: x.runs, costUsd: r2(x.costUsd), tokens: x.tokens, hours: r1(x.ms / 3600000), merged: mine.length,
|
|
116
|
+
prs: mine.sort((a, b) => mergedAt.get(b.item) - mergedAt.get(a.item)).map((it) => ({ item: it.item, title: title.get(it.item) || '', costUsd: r2(it.costUsd), tokens: it.tokens, hours: r1(it.ms / 3600000), url: urlOf.get(it.item) || '', mergedAt: new Date(mergedAt.get(it.item)).toISOString() })),
|
|
117
|
+
firstRunAt: new Date(x.firstRunAt).toISOString(), lastRunAt: new Date(x.lastRunAt).toISOString(), lastMergeAt: lastMergeAt == null ? null : new Date(lastMergeAt).toISOString(),
|
|
118
|
+
recentUsd: r2(recentUsd), sinceUsd: r2(sinceUsd), stall: stalled ? { since: new Date(start).toISOString() } : null, paused: paused.has(x.ini),
|
|
119
|
+
};
|
|
120
|
+
}).sort((a, b) => b.costUsd - a.costUsd || b.runs - a.runs || a.ini.localeCompare(b.ini));
|
|
121
|
+
const total = rows.reduce((s, r) => ({ costUsd: s.costUsd + r.costUsd, tokens: s.tokens + r.tokens, hours: s.hours + r.hours, runs: s.runs + r.runs }), { costUsd: 0, tokens: 0, hours: 0, runs: 0 });
|
|
122
|
+
return { total: { ...total, costUsd: r2(total.costUsd), hours: r1(total.hours) }, rows };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/* ── the repository's files ── */
|
|
126
|
+
const stateDirOf = (root, create = false) => { try { return require('./driver.js').stateDirOf(root, { create }); } catch { return null; } };
|
|
127
|
+
function prsOf(sd) {
|
|
128
|
+
const out = [];
|
|
129
|
+
for (const l of sd ? readJsonl(path.join(sd, 'proposals.jsonl')) : []) if (l.kind === 'keep' && Array.isArray(l.wrote)) for (const w of l.wrote) if (w && w.op === 'pr' && w.item && w.url) out.push({ item: w.item, url: w.url });
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
/** costOf over this repository's own files. An empty answer ({ rows: [] }) when no factory ran here. */
|
|
133
|
+
function readOf(root, { now = Date.now(), stateDir = null } = {}) {
|
|
134
|
+
const sd = stateDir || stateDirOf(root, false);
|
|
135
|
+
let dir = null; try { dir = require('./work-kind.js').factoryDir(root); } catch { dir = null; }
|
|
136
|
+
const ledger = dir ? readJsonl(path.join(dir, 'planning', 'work-items.jsonl')) : [];
|
|
137
|
+
const traces = sd ? readJsonl(path.join(sd, 'factory-traces.jsonl')) : [];
|
|
138
|
+
return costOf({ traces, ledger, prs: prsOf(sd), pauses: pausesOf(sd), now });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/* ── the ✦ ── */
|
|
142
|
+
const dayOf = (iso) => String(iso || '').slice(0, 10);
|
|
143
|
+
/** The ✦ for one stalled row. No amount of money in it (Totals only on the Cost tab). */
|
|
144
|
+
function proposalOf(r, now) {
|
|
145
|
+
const PR = require('./proposals.js');
|
|
146
|
+
const days = Math.floor((now - Date.parse(r.stall.since)) / DAY);
|
|
147
|
+
return {
|
|
148
|
+
kind: 'propose', ini: r.ini, board: '', run: 'initiative-cost', id: PR.idOf(r.ini, 'cost', 'pause', dayOf(r.stall.since)), group: 'cost', type: 'pause', section: 'check',
|
|
149
|
+
title: `Pause ${r.ini}'s new jobs?`,
|
|
150
|
+
why: one(`The factory has run agents on ${r.ini} for ${days} days with no merge${r.lastMergeAt ? ` since ${dayOf(r.lastMergeAt)}` : ''}. A pause stops new jobs; the work it holds now finishes, and Undo starts them again.`, 300),
|
|
151
|
+
sources: [{ label: 'Factory run traces', ref: 'factory-traces.jsonl' }, { label: 'Work items', ref: 'planning/work-items.jsonl' }],
|
|
152
|
+
items: [{ id: r.ini, title: 'Pause new jobs' }],
|
|
153
|
+
data: { since: r.stall.since, lastMergeAt: r.lastMergeAt, runs: r.runs },
|
|
154
|
+
at: new Date(now).toISOString(),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/** The pause ✦ pass, run when Work reads the costs (lib/routes-factory-metrics.js). Never throws. */
|
|
158
|
+
function proposePass(root, { now = Date.now(), stateDir = null, env = process.env } = {}) {
|
|
159
|
+
try {
|
|
160
|
+
if (/^(off|0|false|no)$/i.test(String(env.PMOS_INITIATIVE_COST || ''))) return { ok: true, filed: [], dropped: [], why: 'PMOS_INITIATIVE_COST=off' };
|
|
161
|
+
const sd = stateDir || stateDirOf(root, false);
|
|
162
|
+
if (!sd) return { ok: true, filed: [], dropped: [] };
|
|
163
|
+
const PR = require('./proposals.js');
|
|
164
|
+
const C = readOf(root, { now, stateDir: sd });
|
|
165
|
+
if (!C.rows.length) return { ok: true, filed: [], dropped: [] };
|
|
166
|
+
const F = PR.read(sd), kept = new Set(); for (const k of F.kept) if (!F.undone.has(k.batch)) for (const id of k.ids) kept.add(id);
|
|
167
|
+
const want = new Map(C.rows.filter((r) => r.stall && !r.paused).map((r) => [PR.idOf(r.ini, 'cost', 'pause', dayOf(r.stall.since)), r]));
|
|
168
|
+
const dropped = [], filed = [];
|
|
169
|
+
for (const p of F.props.values()) {
|
|
170
|
+
if (p.group !== 'cost' || p.type !== 'pause' || kept.has(p.id) || F.drops.has(PR.sigOf(p)) || want.has(p.id)) continue;
|
|
171
|
+
PR.append(sd, { by: BY }, { kind: 'drop', ini: p.ini, sig: PR.sigOf(p), id: p.id, group: 'cost', type: 'pause', why: 'it merged, stopped spending or was paused' });
|
|
172
|
+
dropped.push(p.id);
|
|
173
|
+
}
|
|
174
|
+
for (const [id, r] of want) {
|
|
175
|
+
if (F.props.has(id)) continue; // one ✦ per stall: open, kept or dropped, never filed again
|
|
176
|
+
PR.append(sd, { by: BY }, proposalOf(r, now));
|
|
177
|
+
filed.push(id);
|
|
178
|
+
}
|
|
179
|
+
if (filed.length || dropped.length) console.info(`${TAG} proposals filed=${filed.length} dropped=${dropped.length}`);
|
|
180
|
+
return { ok: true, filed, dropped };
|
|
181
|
+
} catch (e) { return { ok: false, filed: [], dropped: [], why: one(e && e.message, 160) }; }
|
|
182
|
+
}
|
|
183
|
+
/** The Cost tab's ✕ "Keep going" and its pause: the stall's open ✦ is answered, so it does not ask again. → the ids dropped */
|
|
184
|
+
function answer(sd, ini, why, { by = 'pm' } = {}) {
|
|
185
|
+
const PR = require('./proposals.js'), F = PR.read(sd), out = [];
|
|
186
|
+
for (const p of F.props.values()) {
|
|
187
|
+
if (p.group !== 'cost' || p.ini !== ini || F.drops.has(PR.sigOf(p))) continue;
|
|
188
|
+
PR.append(sd, { by }, { kind: 'drop', ini, sig: PR.sigOf(p), id: p.id, group: 'cost', type: 'pause', why: one(why, 120) });
|
|
189
|
+
out.push(p.id);
|
|
190
|
+
}
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/* ── the CLI ── */
|
|
195
|
+
const usd = (n) => '$' + (n >= 100 ? Math.round(n) : n.toFixed(2));
|
|
196
|
+
const hrs = (h) => (h > 0 ? `${h} h` : 'no time logged');
|
|
197
|
+
const result = (r) => (r.stall ? `0 merged in ${STALL_DAYS} days` : r.merged ? `${r.merged} PR${r.merged === 1 ? '' : 's'} merged` : 'nothing merged yet');
|
|
198
|
+
/** PURE. */
|
|
199
|
+
function lines(C) {
|
|
200
|
+
if (!C.rows.length) return ['No factory run on any initiative here yet.'];
|
|
201
|
+
const out = [`Factory cost by initiative: ${usd(C.total.costUsd)} in all, ${C.total.runs} run${C.total.runs === 1 ? '' : 's'}.`];
|
|
202
|
+
for (const r of C.rows) out.push(` ${r.ini}: ${hrs(r.hours)} · ${usd(r.costUsd)} · ${result(r)}${r.paused ? ' · paused' : r.stall ? ` · pause it? pmos cost pause ${r.ini}` : ''}`);
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
/** PURE. One initiative's merged pull requests. */
|
|
206
|
+
function prLines(r) {
|
|
207
|
+
if (!r) return ['No factory run on that initiative.'];
|
|
208
|
+
const out = [`${r.ini}: ${hrs(r.hours)} · ${usd(r.costUsd)} · ${r.tokens} tokens · ${result(r)}${r.paused ? ' · paused' : ''}`];
|
|
209
|
+
for (const p of r.prs) out.push(` ${p.item}${p.title ? ' ' + p.title : ''}: ${hrs(p.hours)} · ${usd(p.costUsd)} · ${p.tokens} tokens${p.url ? ' · ' + p.url : ''}`);
|
|
210
|
+
if (!r.prs.length) out.push(' No pull request merged yet.');
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const COMMANDS = { cost: ['show', 'pause', 'resume'] };
|
|
215
|
+
const USAGE = [
|
|
216
|
+
'usage: pmos cost [<initiative>] [--json] | pmos cost pause|resume <initiative> — what the factory spent per initiative and merged pull request',
|
|
217
|
+
' pmos cost [--json] each initiative: agent hours, spend and what merged',
|
|
218
|
+
' pmos cost <initiative> [--json] its merged pull requests, each with its own cost',
|
|
219
|
+
' pmos cost pause <initiative> the factory takes no new job of it; work it holds now finishes',
|
|
220
|
+
' pmos cost resume <initiative> the factory takes its jobs again',
|
|
221
|
+
];
|
|
222
|
+
function repoOf(cwd) {
|
|
223
|
+
let d = path.resolve(cwd);
|
|
224
|
+
for (;;) { try { if (fs.existsSync(path.join(d, '.git'))) return d; } catch { /* look further up */ } const up = path.dirname(d); if (up === d) return path.resolve(cwd); d = up; }
|
|
225
|
+
}
|
|
226
|
+
function run(argv, o = {}) {
|
|
227
|
+
const say = o.say || ((s) => console.log(s)), now = o.now || Date.now();
|
|
228
|
+
const args = argv[0] === 'cost' ? argv.slice(1) : argv.slice();
|
|
229
|
+
const pos = [], flags = {};
|
|
230
|
+
for (let i = 0; i < args.length; i++) { const a = args[i]; if (a === '--root') flags.root = args[++i]; else if (a === '--json') flags.json = true; else pos.push(a); }
|
|
231
|
+
if (pos[0] === 'help' || pos[0] === '--help') { USAGE.forEach((l) => say(l)); return 0; }
|
|
232
|
+
const root = path.resolve(flags.root || o.root || repoOf(o.cwd || process.cwd()));
|
|
233
|
+
const sd = o.stateDir || stateDirOf(root, pos[0] === 'pause' || pos[0] === 'resume');
|
|
234
|
+
if (pos[0] === 'pause' || pos[0] === 'resume') {
|
|
235
|
+
const ini = pos[1];
|
|
236
|
+
if (!ini || !ID_RE.test(ini)) { say(`✗ name an initiative: pmos cost ${pos[0]} <initiative>`); return 2; }
|
|
237
|
+
const r = (pos[0] === 'pause' ? pause : resume)(sd, ini, { by: 'pm:cli', now, why: pos[0] === 'pause' ? 'pmos cost pause' : '' });
|
|
238
|
+
if (!r.ok) { say('✗ ' + r.error); return 1; }
|
|
239
|
+
if (pos[0] === 'pause') try { answer(sd, ini, 'paused with pmos cost pause', { by: 'pm:cli' }); } catch { /* no ✦ to answer */ }
|
|
240
|
+
if (flags.json) { say(JSON.stringify({ ok: true, ini, paused: pos[0] === 'pause', already: !!r.already })); return 0; }
|
|
241
|
+
say(r.already ? `${ini} was already ${pos[0] === 'pause' ? 'paused' : 'running'}.` : pos[0] === 'pause' ? `✓ Paused ${ini}'s new jobs. Work it holds now finishes. pmos cost resume ${ini} undoes it.` : `✓ ${ini}'s jobs run again.`);
|
|
242
|
+
return 0;
|
|
243
|
+
}
|
|
244
|
+
const C = readOf(root, { now, stateDir: sd });
|
|
245
|
+
try { require('./use-log.js').record(sd || root, [{ kind: 'use', page: 'premium-board', control: 'costCli', device: 'desk' }], now); } catch { /* a count, never a reason to fail */ }
|
|
246
|
+
console.info(`${TAG} rows=${C.rows.length} stalled=${C.rows.filter((r) => r.stall).length}`);
|
|
247
|
+
const ini = pos[0] && pos[0] !== 'show' ? pos[0] : null;
|
|
248
|
+
if (ini) {
|
|
249
|
+
const r = C.rows.find((x) => x.ini === ini) || null;
|
|
250
|
+
if (flags.json) { say(JSON.stringify({ ok: true, row: r })); return 0; }
|
|
251
|
+
prLines(r).forEach((l) => say(l));
|
|
252
|
+
return 0;
|
|
253
|
+
}
|
|
254
|
+
if (flags.json) { say(JSON.stringify({ ok: true, ...C })); return 0; }
|
|
255
|
+
lines(C).forEach((l) => say(l));
|
|
256
|
+
return 0;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
module.exports = { FILE, TAG, STALL_DAYS, iniOf, costOf, pausedSet, pausedOf, pause, resume, readOf, proposalOf, proposePass, answer, lines, prLines, run, COMMANDS, USAGE };
|
|
@@ -167,6 +167,9 @@ const VERBS = Object.freeze({
|
|
|
167
167
|
tradeoff: Object.freeze({ module: 'tradeoff-cli.js', run: null, guide: 'cli.md',
|
|
168
168
|
help: 'pmos tradeoff [list|show|keep|undo|count] — two close items on the Roadmap side by side, and the reason you kept one first (pmos tradeoff help)' }),
|
|
169
169
|
// Not a pm-os-absorb verb (run: null): initiative next-hire-draft (job #1876, A75) added it through the same table.
|
|
170
|
+
// Not a pm-os-absorb verb (run: null): initiative initiative-cost (job #1906, A17) added it through the same table.
|
|
171
|
+
cost: Object.freeze({ module: 'initiative-cost.js', run: null, guide: 'cli.md',
|
|
172
|
+
help: 'pmos cost [<initiative>] | pmos cost pause|resume <initiative> — what the factory spent per initiative and merged pull request, and its pause (pmos cost help)' }),
|
|
170
173
|
// Not a pm-os-absorb verb (run: null): initiative starter-goals (job #1916, A84) added it through the same table.
|
|
171
174
|
goals: Object.freeze({ module: 'goals-cli.js', run: null, guide: 'cli.md',
|
|
172
175
|
help: 'pmos goals [starter|draft|keep <n>|drop <n>|undo] — starter goals PMOS drafts from your own product, each with its source; keep one and it becomes a goal (pmos goals help)' }),
|
|
@@ -12,6 +12,13 @@
|
|
|
12
12
|
* The factory floor per product as the Driver saved it after its last run (lib/factory-floor.js load). It reads one file per product and
|
|
13
13
|
* folds nothing, so the Factory page opens in 200 ms or less. snapshot is null while no run has saved one: a read never computes or writes.
|
|
14
14
|
* ws: one workspace (404 when unknown); without it, every workspace.
|
|
15
|
+
*
|
|
16
|
+
* GET /api/initiative-cost?ws → { ok, products: [{ ws, name, total, rows }] } (initiative initiative-cost, A17; lib/initiative-cost.js)
|
|
17
|
+
* What the factory spent per initiative and per merged pull request, and which initiatives are stalled or paused. Zero is silence: a
|
|
18
|
+
* product where no factory ran is left out, so Work shows no Cost tab. It reads two small files per product and writes nothing.
|
|
19
|
+
* POST /api/initiative-cost/pause|resume|keep { ws, ini } → { ok, ini, paused } page press only (pm-guard requirePagePress)
|
|
20
|
+
* pause: the factory takes no new job of the initiative (work it holds finishes), and the stall's ✦ is answered. resume: Undo.
|
|
21
|
+
* keep: "Keep going", the stall's ✦ is answered and nothing pauses. The same store as `pmos cost pause|resume`.
|
|
15
22
|
*/
|
|
16
23
|
const FT = require('./factory-traces.js');
|
|
17
24
|
|
|
@@ -45,8 +52,54 @@ function floorFor(ctx, { ws = '' } = {}) {
|
|
|
45
52
|
return { status: 200, body: { ok: true, products } };
|
|
46
53
|
}
|
|
47
54
|
|
|
55
|
+
const PASS_AT = new Map(), PASS_EVERY = 30 * 60 * 1000;
|
|
56
|
+
function costFor(ctx, { ws = '', now = Date.now() } = {}) {
|
|
57
|
+
let list;
|
|
58
|
+
if (ws) {
|
|
59
|
+
const w = ctx.getWs(ws);
|
|
60
|
+
if (!w || w.id !== ws) return bad(404, 'no such workspace');
|
|
61
|
+
list = [w];
|
|
62
|
+
} else list = (ctx.workspaceList ? ctx.workspaceList() : []).filter((w) => w && w.root && !w.linked);
|
|
63
|
+
const IC = require('./initiative-cost.js'), products = [];
|
|
64
|
+
for (const w of list) {
|
|
65
|
+
let C = null;
|
|
66
|
+
const sd = (ctx.stateDirFor && ctx.stateDirFor(w)) || null;
|
|
67
|
+
// the pause ✦ (no model): filed when Work reads the costs, at most once per half hour per product
|
|
68
|
+
if (now - (PASS_AT.get(w.root) || 0) >= PASS_EVERY) { PASS_AT.set(w.root, now); try { IC.proposePass(w.root, { now, stateDir: sd }); } catch { /* the read still answers */ } }
|
|
69
|
+
try { C = IC.readOf(w.root, { now, stateDir: sd }); } catch { C = null; }
|
|
70
|
+
if (C && C.rows.length) products.push({ ws: w.id, name: w.name || w.id, ...C });
|
|
71
|
+
}
|
|
72
|
+
return { status: 200, body: { ok: true, products } };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function costPost(req, url, ctx) {
|
|
76
|
+
const sub = url.pathname.replace(/^\/api\/initiative-cost\/?/, '');
|
|
77
|
+
if (!['pause', 'resume', 'keep'].includes(sub)) return bad(404, 'no such cost route');
|
|
78
|
+
if (req.method !== 'POST') return bad(405, 'POST only');
|
|
79
|
+
const read = await ctx.readJson(req);
|
|
80
|
+
if (!read.ok || !read.body || typeof read.body !== 'object') return bad(400, 'the body must be a JSON object');
|
|
81
|
+
const g = require('./pm-guard.js').requirePagePress(req, read.body);
|
|
82
|
+
if (!g.ok) return bad(g.status, g.error);
|
|
83
|
+
const ini = typeof read.body.ini === 'string' ? read.body.ini : '';
|
|
84
|
+
if (!/^[a-z0-9][a-z0-9._-]*$/.test(ini)) return bad(400, 'ini must name an initiative');
|
|
85
|
+
const w = ctx.getWs(typeof read.body.ws === 'string' && read.body.ws ? read.body.ws : null);
|
|
86
|
+
if (!w || (read.body.ws && w.id !== read.body.ws)) return bad(404, 'no such workspace');
|
|
87
|
+
const IC = require('./initiative-cost.js'), sd = (ctx.stateDirFor && ctx.stateDirFor(w)) || require('./driver.js').stateDirOf(w.root, { create: true });
|
|
88
|
+
const by = (g.actor && g.actor.by) || 'pm';
|
|
89
|
+
if (sub === 'keep') { IC.answer(sd, ini, 'keep going', { by }); return { status: 200, body: { ok: true, ini, paused: IC.pausedOf(sd).has(ini) } }; }
|
|
90
|
+
const r = (sub === 'pause' ? IC.pause : IC.resume)(sd, ini, { by, why: sub === 'pause' ? 'Work › Cost' : 'Undo' });
|
|
91
|
+
if (!r.ok) return bad(400, r.error);
|
|
92
|
+
if (sub === 'pause') IC.answer(sd, ini, 'paused from Work › Cost', { by });
|
|
93
|
+
return { status: 200, body: { ok: true, ini, paused: sub === 'pause' } };
|
|
94
|
+
}
|
|
95
|
+
|
|
48
96
|
async function handle(req, res, url, ctx) {
|
|
49
97
|
const send = (r) => { ctx.json(res, r.body, r.status); return true; };
|
|
98
|
+
if (url.pathname === '/api/initiative-cost') {
|
|
99
|
+
if (req.method !== 'GET') return send(bad(405, 'GET only'));
|
|
100
|
+
return send(costFor(ctx, { ws: String(url.searchParams.get('ws') || '') }));
|
|
101
|
+
}
|
|
102
|
+
if (url.pathname.startsWith('/api/initiative-cost/')) return send(await costPost(req, url, ctx));
|
|
50
103
|
if (url.pathname === '/api/factory') {
|
|
51
104
|
if (req.method !== 'GET') return send(bad(405, 'GET only'));
|
|
52
105
|
return send(floorFor(ctx, { ws: String(url.searchParams.get('ws') || '') }));
|
|
@@ -59,4 +112,4 @@ async function handle(req, res, url, ctx) {
|
|
|
59
112
|
return send(metricsFor(ctx, { ws: String(url.searchParams.get('ws') || ''), days }));
|
|
60
113
|
}
|
|
61
114
|
|
|
62
|
-
module.exports = { prefixes: ['/api/factory/metrics', '/api/factory'], handle, metricsFor, floorFor };
|
|
115
|
+
module.exports = { prefixes: ['/api/factory/metrics', '/api/factory', '/api/initiative-cost'], handle, metricsFor, floorFor, costFor };
|
|
@@ -157,6 +157,7 @@ function undoCore(ctx, p, g, id) {
|
|
|
157
157
|
// a new experiment the ✦ made goes from every list (the Board's own Delete: the record file stays, a restore brings it back)
|
|
158
158
|
else if (w.op === 'created') { r = RB.writeAs(ctx, '/api/boards/ini-delete', { ws: p.w.id, board: p.board.id, id: w.id }, g); }
|
|
159
159
|
else if (w.op === 'round') { const LR = require('./live-round.js'); LR.cancel(w.round); if (w.proposal) LR.dropCard(dir, w.proposal); back++; continue; } // a live round: its runs stop and its card goes
|
|
160
|
+
else if (w.op === 'pause') { const r2 = require('./initiative-cost.js').resume(dir, w.ini || k.ini, { by: (g.actor && g.actor.by) || 'pm', why: 'Undo' }); if (r2.ok) back++; else kept++; continue; } // initiative-cost: Undo starts its jobs again
|
|
160
161
|
else if (w.op === 'pr') { const r2 = require('./build-engine.js').close(p.w.root, w.item, { url: w.url }); if (r2.ok) back++; else kept++; continue; } // D108: Undo closes the pull request (the branch stays)
|
|
161
162
|
else if (w.op === 'verdict') {
|
|
162
163
|
// the PM's Undo of a verdict PMOS recorded by itself: the check is taken back (the outcome is due again, and Your move asks the PM),
|
|
@@ -383,6 +384,12 @@ function applyOne(ctx, p, g, f, ini, x, choices, outbox) {
|
|
|
383
384
|
const pol = r.policy || null, guard = pol ? { verdict: pol.verdict, rules: (pol.reasons || []).map((y) => String(y.rule || '')).filter(Boolean).slice(0, 12), detail: String(pol.why || '').slice(0, 300) } : null;
|
|
384
385
|
if (r.ok) add({ op: 'pr', item: d.item, branch: d.branch, url: r.url || '', ...(guard ? { guard } : {}) });
|
|
385
386
|
else x.failed = r.error;
|
|
387
|
+
} else if (x.group === 'cost') {
|
|
388
|
+
// a stall: the factory spent 7 days on the initiative with no merge (lib/initiative-cost.js, A17). Class C: only the PM's ✓ reaches
|
|
389
|
+
// here. It pauses the initiative's NEW factory jobs; an item a Builder holds finishes. Undo starts them again
|
|
390
|
+
const r = require('./initiative-cost.js').pause(dirOf(ctx, p.w), ini, { by: (g.actor && g.actor.by) || 'pm', why: 'the ✦ pause proposal' });
|
|
391
|
+
if (r.ok && !r.already) add({ op: 'pause', ini });
|
|
392
|
+
else if (!r.ok) x.failed = r.error;
|
|
386
393
|
} else if (x.group === 'harness') {
|
|
387
394
|
// a failure the factory repeated (lib/factory-lessons.js). Class C: only the PM's ✓ reaches here. It adds a task for the PM with the
|
|
388
395
|
// evidence; the harness itself changes only through the PM's own reviewed pull request
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pmos-workspace",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.843.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "pmos-workspace",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.843.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@anthropic-ai/sdk": "^1.3.0",
|
package/workspace/package.json
CHANGED
|
@@ -350,3 +350,6 @@ textarea.bk-rvl-ed, .bk-rvl textarea.bd { resize: vertical; min-height: 180px; }
|
|
|
350
350
|
.fx-sheet .fx-fold summary { cursor: pointer; padding: 6px 0; font-size: var(--fs-meta); color: var(--muted); }
|
|
351
351
|
.fx-sheet .ff-undo { all: unset; box-sizing: border-box; display: inline-grid; place-items: center; width: 28px; height: 28px; border-radius: var(--radius-md); cursor: pointer; }
|
|
352
352
|
.fx-sheet .ff-undo:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
|
353
|
+
/* Work › Cost (initiative-cost, A17): a stalled initiative's result, and the ✦ line under the table */
|
|
354
|
+
.ic-alert { color: var(--alert); }
|
|
355
|
+
.ic-ask { margin-top: var(--space-8); }
|
|
@@ -26,6 +26,7 @@ import * as TWV from './team-waits.js'; // team-waits (A364): Work › Depende
|
|
|
26
26
|
import * as TSV from './team-slips.js'; // team-slips (A15): Upstream on Work › Dependencies, other teams' slips (GET /api/team-slips)
|
|
27
27
|
import * as LV from './line-view.js'; // quiet-rows slice B: the Line tab, every initiative by station (GET /api/line)
|
|
28
28
|
import * as FV from './factory.js'; // Work › Factory (factory-page-ui): the stations and the work they make, from GET /api/factory
|
|
29
|
+
import * as IC from './initiative-cost.js'; // Work › Cost (initiative-cost, A17): what the factory spent per initiative, from GET /api/initiative-cost
|
|
29
30
|
import * as LB from './list-balance.js'; // the balance meter under the Backlog header (bet A448, board BalanceDS) // quiet-rows slice B: the Line tab, every initiative by station (GET /api/line)
|
|
30
31
|
import * as BD from './bd-backlog-ds.js'; // the Backlog from the system's parts (WorkBacklogDS) // the sprint overview while "This sprint" is on (initiative sprint-overview)
|
|
31
32
|
|
|
@@ -73,10 +74,11 @@ export function tabOf() {
|
|
|
73
74
|
if (q === 'sprint') return 'sp';
|
|
74
75
|
if (q === 'line') return 'ln';
|
|
75
76
|
if (q === 'factory') return 'fx';
|
|
77
|
+
if (q === 'cost') return 'co';
|
|
76
78
|
if (q === 'deps') return 'dp';
|
|
77
79
|
if (q === 'initiatives') return 'ini';
|
|
78
80
|
const v = (get(KEY, {}) || {})[scopeKey()];
|
|
79
|
-
return v === 'bk' || v === 'sp' || v === 'ln' || v === 'fx' || v === 'dp' ? v : 'ini';
|
|
81
|
+
return v === 'bk' || v === 'sp' || v === 'ln' || v === 'fx' || v === 'dp' || v === 'co' ? v : 'ini';
|
|
80
82
|
}
|
|
81
83
|
/** Is a task tab (Backlog or This sprint) the view now? */
|
|
82
84
|
export const on = () => tabOf() === 'bk' || tabOf() === 'sp';
|
|
@@ -86,6 +88,8 @@ export const lineOn = () => tabOf() === 'ln';
|
|
|
86
88
|
export const factoryOn = () => tabOf() === 'fx';
|
|
87
89
|
/** Is the Dependencies tab the view now? (team-waits) */
|
|
88
90
|
export const depsOn = () => tabOf() === 'dp';
|
|
91
|
+
/** Is the Cost tab the view now? (initiative-cost) */
|
|
92
|
+
export const costOn = () => tabOf() === 'co';
|
|
89
93
|
function setOn(v) {
|
|
90
94
|
v = v === true ? 'bk' : v === false ? 'ini' : v;
|
|
91
95
|
const m = get(KEY, {}) || {}; m[scopeKey()] = v; put(KEY, m);
|
|
@@ -137,7 +141,8 @@ export async function load() {
|
|
|
137
141
|
// the Line (quiet-rows-line) is a five-column table for a desk; a phone keeps its three tabs (Today's dashed line is desk-only too)
|
|
138
142
|
// the Factory (factory-page-ui) sits beside Line, a desk's too: its tiles are a row of five
|
|
139
143
|
// Dependencies (team-waits) is a desk tab as well: a phone keeps its three
|
|
140
|
-
|
|
144
|
+
// the Cost tab (initiative-cost) shows on a desk only while some factory spent on the pick (zero is silence)
|
|
145
|
+
export const tabNames = (phone, n, cost = false) => [['ini', 'Initiatives'], ...(phone ? [] : [['ln', 'Line'], ['fx', 'Factory']]), ['bk', 'Backlog' + (phone && n > 0 ? ` <span class="bk-swn">${Number(n)}</span>` : '')], ['sp', phone ? 'Sprint' : 'This sprint'], ...(phone ? [] : [['dp', 'Dependencies']]), ...(!phone && cost ? [['co', 'Cost']] : [])];
|
|
141
146
|
const phoneNow = () => typeof matchMedia === 'function' && matchMedia('(max-width: 760px)').matches;
|
|
142
147
|
function drawSwitch() {
|
|
143
148
|
if (!sw) return;
|
|
@@ -145,22 +150,45 @@ function drawSwitch() {
|
|
|
145
150
|
// one Tabs part for the three (WorkDS); no count on a desk tab: Where it stands says what matters (say it once).
|
|
146
151
|
// A phone (PhoneWorkDS, job 1540) has no Where it stands over the Backlog, so its tab carries the count, and the short name "Sprint"
|
|
147
152
|
const ph = phoneNow();
|
|
148
|
-
sw.innerHTML = tabNames(ph, ph && DATA ? backlogOf().length : 0).map(([k, n]) => tb(k, n)).join('');
|
|
153
|
+
sw.innerHTML = tabNames(ph, ph && DATA ? backlogOf().length : 0, IC.hasSpend(costScoped()) || t === 'co').map(([k, n]) => tb(k, n)).join('');
|
|
149
154
|
}
|
|
150
155
|
function apply() {
|
|
151
|
-
const bk = on(), ln = lineOn(), fx = factoryOn(), dp = depsOn();
|
|
156
|
+
const bk = on(), ln = lineOn(), fx = factoryOn(), dp = depsOn(), co = costOn();
|
|
152
157
|
if (tabOf() === 'sp') CHIPS.add('sprint');
|
|
153
158
|
document.body.classList.toggle('sp-on', tabOf() === 'sp');
|
|
154
|
-
document.body.classList.toggle('bk-on', bk || ln || fx || dp);
|
|
155
|
-
if (host) host.hidden = !(bk || ln || fx || dp);
|
|
159
|
+
document.body.classList.toggle('bk-on', bk || ln || fx || dp || co);
|
|
160
|
+
if (host) host.hidden = !(bk || ln || fx || dp || co);
|
|
156
161
|
drawSwitch();
|
|
157
162
|
if (ln) { closeAll(); drawLine(); return; }
|
|
158
163
|
if (fx) { closeAll(); drawFactory(); return; }
|
|
159
164
|
if (dp) { closeAll(); drawDeps(); return; }
|
|
165
|
+
if (co) { closeAll(); drawCost(); return; }
|
|
160
166
|
if (bk) { if (!DATA || scopeKey() !== lastScope) { lastScope = scopeKey(); host.innerHTML = '<p class="bk-wait">Reading the tasks…</p>'; load(); } else draw(); }
|
|
161
167
|
else closeAll();
|
|
162
168
|
}
|
|
163
169
|
|
|
170
|
+
/* ── the Cost tab (initiative-cost, board BatchReleaseDS panel 21) ── what the factory spent per initiative, from GET /api/initiative-cost ── */
|
|
171
|
+
const CO = { used: false, undone: new Set() };
|
|
172
|
+
/** The products of the pick, as the Cost read has them. */
|
|
173
|
+
function costScoped() {
|
|
174
|
+
const got = IC.cached() || [];
|
|
175
|
+
if (!A) return got;
|
|
176
|
+
const ws = new Set(A.scope().map((x) => x.ws || ''));
|
|
177
|
+
return ws.has('') ? got : got.filter((p) => ws.has(p.ws));
|
|
178
|
+
}
|
|
179
|
+
function drawCost() {
|
|
180
|
+
if (!host) return;
|
|
181
|
+
if (!CO.used) { CO.used = true; noteUse('costOpen'); console.info('[initiative-cost] cost tab opened'); }
|
|
182
|
+
if (!IC.cached()) { host.innerHTML = '<p class="bk-wait">Reading the cost…</p>'; IC.load().then(() => { if (costOn()) drawCost(); }); return; }
|
|
183
|
+
host.innerHTML = IC.tabHtml(costScoped(), { undone: CO.undone });
|
|
184
|
+
IC.load().then(() => { if (costOn()) host.innerHTML = IC.tabHtml(costScoped(), { undone: CO.undone }); }); // a read older than a minute comes again
|
|
185
|
+
}
|
|
186
|
+
/** A press in the Cost tab: Pause (with Undo), Keep going, Resume, or a name (opens the initiative). true when it was one. */
|
|
187
|
+
function costPress(e) {
|
|
188
|
+
if (!costOn()) return false;
|
|
189
|
+
return IC.press(e, { post: (u, b) => AP().post(u, b).catch(() => null), say: (m, undo) => (A.say ? A.say(m, undo) : null), redraw: () => { if (costOn()) drawCost(); }, open: (id, ws) => (A.openIni ? A.openIni(id, ws) : null), undone: CO.undone });
|
|
190
|
+
}
|
|
191
|
+
|
|
164
192
|
/* ── the Line tab (quiet-rows slice B, board QuietLine) ── every live initiative of the pick by station, from GET /api/line ── */
|
|
165
193
|
const LN = { tab: '', got: null, key: '', used: false };
|
|
166
194
|
async function readLine() {
|
|
@@ -914,7 +942,8 @@ export function sync(api) {
|
|
|
914
942
|
sw.addEventListener('click', (e) => { const b = e.target.closest('[data-bksw]'); if (b) setOn(b.dataset.bksw); });
|
|
915
943
|
host = document.createElement('div'); host.id = 'bkBody'; host.className = 'bk-host'; host.hidden = true;
|
|
916
944
|
ib.insertAdjacentElement('afterend', host);
|
|
917
|
-
host.addEventListener('click', (e) => { if (linePress(e) || factoryPress(e) || depsPress(e)) return; press(e); });
|
|
945
|
+
host.addEventListener('click', (e) => { if (linePress(e) || factoryPress(e) || depsPress(e) || costPress(e)) return; press(e); });
|
|
946
|
+
IC.load().then(() => drawSwitch()); // the Cost tab shows only when some factory spent (initiative-cost)
|
|
918
947
|
host.addEventListener('change', (e) => { if (e.target.closest('[data-bkck]')) press(e); });
|
|
919
948
|
host.addEventListener('keydown', (e) => { const c = e.target.closest('[data-bkcap]'); if (c && e.key === 'Enter') { e.preventDefault(); capture(c); } });
|
|
920
949
|
dragWire();
|
|
@@ -38,6 +38,7 @@ import * as IF from './inline-fields.js'; // a task's sprint and priority, set
|
|
|
38
38
|
import * as SD from './star-draft.js'; // a ✦ draft runs as a PMOS background job and lands on its line (star-buttons-act-directly A7)
|
|
39
39
|
import * as CAP from './pop-cap.js'; // five actions at most: Ask PMOS and the toolbar's four, the rest under ⋯ (popup-cap, idea A498)
|
|
40
40
|
import { noteUse } from './use-log.js';
|
|
41
|
+
import * as IC from './initiative-cost.js'; // ⋯ › Cost (initiative-cost, A17): the factory's spend per merged pull request, in a sheet
|
|
41
42
|
import * as BVD from './built-vs-design.js'; // the built screen beside its design, its circles, Accept and Send back (built-vs-design, A380)
|
|
42
43
|
import * as STMAP from './story-map.js'; // a new bet's story map with the Release 1 line (initiative story-map, A419)
|
|
43
44
|
import * as TLY from './three-layouts.js'; // three layouts for a new screen, pick one (initiative three-layouts, A317)
|
|
@@ -1762,12 +1763,24 @@ async function addArt(x, h) {
|
|
|
1762
1763
|
* every part of the old page, as a drill-in, and every suggestion. body: the popup body the host drew into (it carries the wired handlers). */
|
|
1763
1764
|
export function moreItems(x, h, body) {
|
|
1764
1765
|
// under the popup cap (PopupCapDS) Plan, View and Jira come first; View holds Every part
|
|
1765
|
-
const cap = capItems(body, h), out = cap.concat(artItems(body));
|
|
1766
|
+
const cap = capItems(body, h), out = cap.concat(artItems(body), costItems(body));
|
|
1766
1767
|
if (h.allParts && !cap.some((it) => it.label === 'Every part')) out.push({ label: 'Every part', on: () => h.allParts() });
|
|
1767
1768
|
if (h.props) out.push({ label: 'Everything PMOS suggests', on: () => h.props() });
|
|
1768
1769
|
return out.length ? out.concat({ sep: true }) : out;
|
|
1769
1770
|
}
|
|
1770
1771
|
|
|
1772
|
+
/** ⋯ › Cost (initiative-cost, A17): what the factory spent on this initiative, one row per merged pull request. Only when a factory ran on it
|
|
1773
|
+
* (zero is silence); the read is Work's (pm/initiative-cost.js load), so the first ⋯ may come before it and the next one has it. Money
|
|
1774
|
+
* shows in the sheet only, never on the popup itself. */
|
|
1775
|
+
function costItems(body) {
|
|
1776
|
+
if (RO || !body || !body.__pwx || !body.querySelector || !body.querySelector('.pw.pwd')) return [];
|
|
1777
|
+
const r = body.__pwx.r(); if (!r || !r.id) return [];
|
|
1778
|
+
IC.load();
|
|
1779
|
+
const row = IC.rowOf(r.ws || '', r.id);
|
|
1780
|
+
if (!row) return [];
|
|
1781
|
+
return [{ label: 'Cost', on: () => import('./primitives.js').then((P) => { const el = document.createElement('div'); el.innerHTML = IC.iniHtml(row); P.sheet({ title: 'Cost', sub: r.title || r.id, body: [el], attrs: { 'data-ic-sheet': r.id } }); }) }];
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1771
1784
|
/** The Artefacts section of ⋯ (artefacts-in-more-menu): read when ⋯ opens, so an artefact just added is there. The presses are the ones the
|
|
1772
1785
|
* side card had: open full screen with Back, add, and the ✦ merge goes to the chat. */
|
|
1773
1786
|
function artItems(body) {
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/* pm/initiative-cost.js — Work › Cost and the initiative's ⋯ › Cost (initiative initiative-cost, job #1906, idea A17; board BatchReleaseDS
|
|
2
|
+
* panel 21 on the main canvas, agreed 2026-11-25). What the factory spent per initiative and per merged pull request, from
|
|
3
|
+
* GET /api/initiative-cost (lib/initiative-cost.js, the same store as `pmos cost`).
|
|
4
|
+
* Pure parts first, so Node imports them (initiative-cost.test.js); the page parts touch the DOM only when called.
|
|
5
|
+
*
|
|
6
|
+
* hasSpend(products) → true when some factory spent: Work shows the Cost tab only then (zero is silence)
|
|
7
|
+
* rowsOf(products) → [row] every product's rows, each with its ws and product name, most spend first
|
|
8
|
+
* tabHtml(products, { undone }) → the Cost tab: the table (Initiative, Agent hours, Spend, Result) and one ✦ line per stalled initiative
|
|
9
|
+
* with icon-only Pause and Keep going; a paused one has a Resume button
|
|
10
|
+
* iniHtml(row) → the ⋯ › Cost sheet: one row per merged pull request, with its own cost
|
|
11
|
+
* money(n) · hoursText(h) · resultText(row)
|
|
12
|
+
* load({ force }) → Promise<products> · rowOf(ws, ini) → row | null the page's one read, kept a minute
|
|
13
|
+
* press(e, { post, say, redraw }) → true when the press was a Cost button
|
|
14
|
+
*
|
|
15
|
+
* Money shows here only (Totals only on the Cost tab; no money on other pages). The words say PMOS. Every button is an icon with its
|
|
16
|
+
* aria-label. Text from records goes through esc(). */
|
|
17
|
+
import { pmGet } from './http.js';
|
|
18
|
+
export const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
19
|
+
const SV = (d, cls = '') => `<svg class="pm-ic${cls ? ' ' + cls : ''}" width="16" height="16" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${d}"/></svg>`;
|
|
20
|
+
const IC = {
|
|
21
|
+
star: 'M12 3l1.8 5.4L19 10.2l-5.2 1.8L12 17.4l-1.8-5.4L5 10.2l5.2-1.8z',
|
|
22
|
+
pause: 'M8 5v14M16 5v14',
|
|
23
|
+
keep: 'M6 6l12 12M18 6L6 18',
|
|
24
|
+
play: 'M7 5l12 7-12 7z',
|
|
25
|
+
link: 'M14 4h6v6M20 4l-9 9M18 14v6H4V6h6',
|
|
26
|
+
};
|
|
27
|
+
const STALL_DAYS = 7;
|
|
28
|
+
|
|
29
|
+
export function money(n) { const v = Number(n) || 0; return '$' + (v >= 100 ? Math.round(v) : v >= 10 ? Math.round(v) : v.toFixed(2)); }
|
|
30
|
+
export function hoursText(h) { const v = Number(h) || 0; return v > 0 ? (v >= 10 ? Math.round(v) : v) + ' h' : '—'; }
|
|
31
|
+
export function resultText(r) {
|
|
32
|
+
if (r.stall) return `0 merged in ${STALL_DAYS} days`;
|
|
33
|
+
if (r.merged) return r.merged + (r.merged === 1 ? ' PR merged' : ' PRs merged');
|
|
34
|
+
return 'Nothing merged yet';
|
|
35
|
+
}
|
|
36
|
+
export function rowsOf(products) {
|
|
37
|
+
const out = [];
|
|
38
|
+
for (const p of Array.isArray(products) ? products : []) for (const r of (p && p.rows) || []) out.push({ ...r, ws: p.ws || '', product: p.name || p.ws || '' });
|
|
39
|
+
return out.sort((a, b) => b.costUsd - a.costUsd || a.ini.localeCompare(b.ini));
|
|
40
|
+
}
|
|
41
|
+
export const hasSpend = (products) => rowsOf(products).some((r) => r.runs > 0);
|
|
42
|
+
|
|
43
|
+
const btn = (attrs, label, d) => `<button type="button" class="pm-btn" ${attrs} aria-label="${esc(label)}" title="${esc(label)}">${SV(d)}</button>`;
|
|
44
|
+
const keyOf = (r) => esc((r.ws || '') + '|' + r.ini);
|
|
45
|
+
const dataOf = (r) => `data-ic-ws="${esc(r.ws || '')}" data-ic-ini="${esc(r.ini)}"`;
|
|
46
|
+
|
|
47
|
+
/** The Cost tab. o.undone: keys (ws|ini) the PM answered on this page, so their ✦ line goes at once. */
|
|
48
|
+
export function tabHtml(products, o = {}) {
|
|
49
|
+
const rows = rowsOf(products), many = new Set(rows.map((r) => r.ws)).size > 1, gone = o.undone || new Set();
|
|
50
|
+
if (!rows.length) return '<section class="pm-block ic-cost" aria-label="Cost"><p class="pm-meta">No factory has run on an initiative here yet.</p></section>';
|
|
51
|
+
const th = (t) => `<th scope="col">${esc(t)}</th>`;
|
|
52
|
+
const body = rows.map((r) => {
|
|
53
|
+
const res = r.paused ? `<span class="pm-badge">Paused</span>` : r.stall ? `<span class="ic-alert">${esc(resultText(r))}</span>` : esc(resultText(r));
|
|
54
|
+
const name = `<button type="button" class="pw-lk" data-ic-open ${dataOf(r)}>${esc(r.ini)}</button>${many ? ` <span class="pm-meta">${esc(r.product)}</span>` : ''}`;
|
|
55
|
+
const resume = r.paused ? ' ' + btn(`data-ic-resume ${dataOf(r)}`, `Resume ${r.ini}'s jobs`, IC.play) : '';
|
|
56
|
+
return `<tr data-ic-row="${keyOf(r)}"><td>${name}</td><td>${esc(hoursText(r.hours))}</td><td>${esc(money(r.costUsd))}</td><td>${res}${resume}</td></tr>`;
|
|
57
|
+
}).join('');
|
|
58
|
+
const table = `<table class="pm-table ic-table"><thead><tr>${th('Initiative')}${th('Agent hours')}${th('Spend')}${th('Result')}</tr></thead><tbody>${body}</tbody></table>`;
|
|
59
|
+
const asks = rows.filter((r) => r.stall && !r.paused && !gone.has((r.ws || '') + '|' + r.ini)).map((r) => `<div class="ic-ask" data-ic-ask="${keyOf(r)}"><p class="pm-said">${SV(IC.star, 'pm-star')}<span>${esc(r.ini)} has spent ${esc(money(r.sinceUsd || r.recentUsd))} with no merge in ${STALL_DAYS} days. Pause its jobs?</span></p>`
|
|
60
|
+
+ `<div class="pm-row">${btn(`data-ic-pause ${dataOf(r)}`, `Pause ${r.ini}'s new jobs`, IC.pause)}${btn(`data-ic-keep ${dataOf(r)}`, 'Keep going', IC.keep)}</div></div>`).join('');
|
|
61
|
+
const total = rows.reduce((s, r) => s + (Number(r.costUsd) || 0), 0);
|
|
62
|
+
return `<section class="pm-block ic-cost" aria-label="Cost"><div class="pm-row ic-head"><h2 class="pm-h-sm">Cost</h2><span class="pm-meta">${esc(money(total))} in all</span></div>${table}${asks}</section>`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The initiative's ⋯ › Cost sheet: one row per merged pull request. */
|
|
66
|
+
export function iniHtml(r) {
|
|
67
|
+
if (!r) return '<p class="pm-meta">No factory has run on this initiative yet.</p>';
|
|
68
|
+
const th = (t) => `<th scope="col">${esc(t)}</th>`;
|
|
69
|
+
const head = `<p class="pm-meta">${esc(hoursText(r.hours))} · ${esc(money(r.costUsd))} · ${esc(String(r.tokens || 0))} tokens · ${esc(resultText(r))}${r.paused ? ' · Paused' : ''}</p>`;
|
|
70
|
+
if (!r.prs || !r.prs.length) return head + '<p class="pm-meta">No pull request merged yet.</p>';
|
|
71
|
+
const body = r.prs.map((p) => `<tr><td>${esc(p.title || p.item)}${p.url ? ' ' + `<a class="pm-btn" href="${esc(p.url)}" target="_blank" rel="noopener" aria-label="Open the pull request" title="Open the pull request">${SV(IC.link)}</a>` : ''}</td><td>${esc(hoursText(p.hours))}</td><td>${esc(money(p.costUsd))}</td><td>${esc(String(p.tokens || 0))}</td></tr>`).join('');
|
|
72
|
+
return head + `<table class="pm-table ic-table"><thead><tr>${th('Pull request')}${th('Agent hours')}${th('Spend')}${th('Tokens')}</tr></thead><tbody>${body}</tbody></table>`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/* ── the page: one read, kept a minute ── */
|
|
76
|
+
const S = { got: null, at: 0, inflight: null };
|
|
77
|
+
export function load({ force = false } = {}) {
|
|
78
|
+
if (!force && S.got && Date.now() - S.at < 60000) return Promise.resolve(S.got);
|
|
79
|
+
if (S.inflight) return S.inflight;
|
|
80
|
+
S.inflight = pmGet('/api/initiative-cost').catch(() => null)
|
|
81
|
+
.then((j) => { S.got = j && j.ok ? j.products || [] : (S.got || []); S.at = Date.now(); S.inflight = null; return S.got; });
|
|
82
|
+
return S.inflight;
|
|
83
|
+
}
|
|
84
|
+
export const cached = () => S.got;
|
|
85
|
+
export function rowOf(ws, ini) { return rowsOf(S.got || []).find((r) => r.ini === ini && (!ws || !r.ws || r.ws === ws)) || null; }
|
|
86
|
+
|
|
87
|
+
/** A press on the Cost tab. post(path, body) → Promise<{ ok }>; say(msg, undo?) the page's toast; redraw() after a change. */
|
|
88
|
+
export function press(e, { post, say, redraw, open, undone } = {}) {
|
|
89
|
+
const b = e.target.closest('[data-ic-pause],[data-ic-keep],[data-ic-resume],[data-ic-open]');
|
|
90
|
+
if (!b || b.disabled) return false;
|
|
91
|
+
const d = b.dataset, body = { ws: d.icWs || undefined, ini: d.icIni };
|
|
92
|
+
if ('icOpen' in d) { if (open) open(d.icIni, d.icWs); return true; }
|
|
93
|
+
const act = 'icPause' in d ? 'pause' : 'icKeep' in d ? 'keep' : 'resume';
|
|
94
|
+
b.disabled = true;
|
|
95
|
+
post('/api/initiative-cost/' + act, body).then((r) => {
|
|
96
|
+
if (!r || !r.ok) { b.disabled = false; if (say) say((r && r.error) || 'That did not save. Try again in a moment.'); return; }
|
|
97
|
+
if (undone && act !== 'resume') undone.add((d.icWs || '') + '|' + d.icIni);
|
|
98
|
+
const again = () => post('/api/initiative-cost/resume', body).then(() => load({ force: true }).then(() => redraw && redraw()));
|
|
99
|
+
if (say) say(act === 'pause' ? `Paused ${d.icIni}'s new jobs. Running work finishes.` : act === 'keep' ? `${d.icIni} keeps going.` : `${d.icIni}'s jobs run again.`, act === 'pause' ? again : undefined);
|
|
100
|
+
return load({ force: true }).then(() => redraw && redraw());
|
|
101
|
+
});
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_comment": "What each initiative and merged pull request cost (initiative initiative-cost, done test C1-C7, N1-N3): the pure fold, the stall ✦, the pause in build-engine next and claim, pmos cost, the route in process and the Cost tab's HTML, on a scratch product with the vendored work-item ledger. No server, browser, model or network.",
|
|
3
|
+
"modules": [
|
|
4
|
+
"initiative-cost.test.js"
|
|
5
|
+
],
|
|
6
|
+
"seconds": {
|
|
7
|
+
"initiative-cost.test.js": 2
|
|
8
|
+
}
|
|
9
|
+
}
|