create-pmos 0.433.0 → 0.435.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 (89) 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/briefing-premium-insights-test.js +63 -58
  7. package/workspace/changelog.json +24 -0
  8. package/workspace/fixtures/ready-reports.js +145 -0
  9. package/workspace/guide/index.md +2 -0
  10. package/workspace/guide/metric-drafts.md +21 -1
  11. package/workspace/guide/ready-made-dashboards.md +62 -0
  12. package/workspace/guide/your-impact.md +58 -0
  13. package/workspace/impact-screens-test.js +149 -0
  14. package/workspace/intel-report-ui-test.js +1 -1
  15. package/workspace/intelligence-gaps-ui-test.js +13 -9
  16. package/workspace/lib/board-premium.js +1 -1
  17. package/workspace/lib/engine/outbox.js +1 -1
  18. package/workspace/lib/engine/records/index.js +11 -3
  19. package/workspace/lib/goal-status.js +199 -0
  20. package/workspace/lib/goal-watch.js +71 -0
  21. package/workspace/lib/headless.js +24 -2
  22. package/workspace/lib/impact-cli.js +72 -0
  23. package/workspace/lib/impact-runs.js +114 -0
  24. package/workspace/lib/impact.js +195 -0
  25. package/workspace/lib/insights-premium.js +43 -4
  26. package/workspace/lib/intel-report.js +36 -5
  27. package/workspace/lib/metric-draft-runs.js +33 -10
  28. package/workspace/lib/metric-drafts.js +118 -15
  29. package/workspace/lib/metric-read-runs.js +132 -0
  30. package/workspace/lib/metric-reads.js +129 -0
  31. package/workspace/lib/metrics-cli.js +100 -5
  32. package/workspace/lib/pmos-verbs.js +4 -1
  33. package/workspace/lib/ready-reports.js +616 -0
  34. package/workspace/lib/report-dashboards.js +5 -0
  35. package/workspace/lib/report-setups.js +16 -7
  36. package/workspace/lib/route-modules.js +4 -0
  37. package/workspace/lib/routes-board-premium.js +5 -0
  38. package/workspace/lib/routes-boards.js +1 -1
  39. package/workspace/lib/routes-goal-status.js +111 -0
  40. package/workspace/lib/routes-impact-views.js +58 -0
  41. package/workspace/lib/routes-impact.js +91 -0
  42. package/workspace/lib/routes-insights-premium.js +20 -0
  43. package/workspace/lib/routes-metric-drafts.js +55 -4
  44. package/workspace/lib/routes-ready-reports.js +455 -0
  45. package/workspace/lib/routes-records.js +2 -0
  46. package/workspace/lib/routes-report-setups.js +4 -3
  47. package/workspace/lib/settings-store.js +3 -0
  48. package/workspace/okr-goals-ui-test.js +175 -0
  49. package/workspace/package-lock.json +2 -2
  50. package/workspace/package.json +1 -1
  51. package/workspace/program-charter-test.js +11 -7
  52. package/workspace/program-panel-test.js +1 -1
  53. package/workspace/public/pm/bd-ini-panel.js +33 -8
  54. package/workspace/public/pm/bd-prog-panel.js +58 -10
  55. package/workspace/public/pm/cozy-adler.css +5 -0
  56. package/workspace/public/pm/cozy-adler.js +17 -9
  57. package/workspace/public/pm/cozy-insights.css +84 -0
  58. package/workspace/public/pm/cozy-settings.js +11 -1
  59. package/workspace/public/pm/cozy-viewer.js +2 -2
  60. package/workspace/public/pm/cozy-vw-rp.css +13 -0
  61. package/workspace/public/pm/dash-view.css +111 -0
  62. package/workspace/public/pm/dash-view.js +261 -0
  63. package/workspace/public/pm/home-app.js +87 -8
  64. package/workspace/public/pm/home-data.js +3 -2
  65. package/workspace/public/pm/home-impact.css +16 -0
  66. package/workspace/public/pm/home-impact.js +72 -0
  67. package/workspace/public/pm/home-ini.js +19 -1
  68. package/workspace/public/pm/home-today.js +4 -2
  69. package/workspace/public/pm/impact.css +37 -0
  70. package/workspace/public/pm/impact.js +201 -0
  71. package/workspace/public/pm/okr-list.js +249 -0
  72. package/workspace/public/pm/premium-insights.js +232 -240
  73. package/workspace/public/pm/premium-report-read.js +36 -5
  74. package/workspace/public/pm/premium-vw-mtg.js +4 -1
  75. package/workspace/public/pm/ready-lib.css +29 -0
  76. package/workspace/public/pm/ready-lib.js +62 -0
  77. package/workspace/public/premium-intelligence.html +3 -2
  78. package/workspace/public/premium.html +1 -0
  79. package/workspace/ready-dash-ui-test.js +227 -0
  80. package/workspace/server.js +58 -2
  81. package/workspace/skills/impact-detect.skill +46 -0
  82. package/workspace/skills/metric-read.skill +32 -0
  83. package/workspace/test-lists/batch17-ready-reports.json +9 -0
  84. package/workspace/test-lists/goal-watch.json +9 -0
  85. package/workspace/test-lists/impact-screens.json +5 -0
  86. package/workspace/test-lists/impact-ui.json +9 -0
  87. package/workspace/test-lists/impact.json +9 -0
  88. package/workspace/test-lists/okr-goals-ui.json +5 -0
  89. package/workspace/test-lists/ready-reports-ui.json +6 -0
@@ -8,6 +8,11 @@
8
8
  * scopeFilter(body, facts, scope, id, today, opts) the /api/c3-strategy body narrowed to a scope, plus delivery and range
9
9
  * validKey · readLayouts · writeLayout the layout store: <runtimeDir>/report-dashboards/layouts.json
10
10
  *
11
+ * RETIRED FOR THE PREMIUM PAGES (batch 17 item 1, lib/ready-reports.js): the ready-made dashboard of every program, product and initiative maps
12
+ * this library onto its blocks. North star and Quarter outcomes are the Goals block, Early signals is the ✦ line, Delivery against promise is
13
+ * Ships (a program's Milestones). Maturity by pillar, Bets and checkpoints and Synergy coverage are left out: not every scope has them, so they
14
+ * are not generic. This file stays for the console3 page that still reads it.
15
+ *
11
16
  * The layout store is the only I/O. It writes under the runtime directory the caller names, with a temp file and a rename, and never
12
17
  * touches the repository. Everything else reads values it is handed. */
13
18
  const fs = require('fs');
@@ -24,14 +24,16 @@
24
24
  *
25
25
  * THE LINES. Every line is { v: 1, ev, …, at, by? }. Who wrote a line is the call path (lib/actor.js), never an argument:
26
26
  * setup { id, name, purpose, audience, source: 'work'|'dashboard:<key>'|'intelligence:<scope>', output, schedule, sources[], sections[], learned_from, fixes[],
27
- * product, ws, last_run, def_sha, from?, storyline? } the PM pressed Set up. `from` is { ask } or { finding }.
27
+ * product, ws, last_run, def_sha, from?, storyline?, ready? } the PM pressed Set up. `from` is { ask } or { finding }.
28
+ * `ready` is { scope, kind }: a ready-made report of a program, product or initiative (batch 17 item 1, lib/ready-reports.js). Its
29
+ * drafting is lib/routes-ready-reports.js tick's, not this file's schedule
28
30
  * An Intelligence-sourced setup (batch 15 item 4, lib/intel-report.js) keeps the PM's storyline edits: { answer?, ask?: { text, who, by }, items?: [{ id, on }] }.
29
31
  * It is drafted like a dashboard-sourced one, by the tick in lib/routes-report-setups.js, from the live Intelligence model
30
32
  * change { id, …the fields that changed } the PM edited a recurring report
31
33
  * pause · resume · remove { id } a removed setup is a deleted TEMPLATE: its schedule stops, its documents stay
32
34
  * doc-discard { doc, path } the PM discarded an unissued draft (the file is deleted; this line keeps the record)
33
35
  * doc-archive { doc, archived } the PM archived (true) or brought back (false) an issued report. The file is never touched
34
- * drafted { id, slot, path } a dashboard-sourced setup made its document (this is its last run)
36
+ * drafted { id, slot, path, sha? } a dashboard-sourced setup made its document (this is its last run); sha: the git blob sha as drafted
35
37
  * ask-start { ask, text, ws } the PM typed a request in the Ask box
36
38
  * proposal { ask, proposal } the report-setup run filed ONE proposal (a second one revises it)
37
39
  * proposal-change { ask, text } the PM asked for a correction; a second run revises the same proposal
@@ -199,11 +201,17 @@ function checkProposal(input) {
199
201
  }
200
202
  }
201
203
  if (x.product != null && x.product !== '' && !oneLine(x.product, 80)) return { ok: false, error: 'product is one line of at most 80 characters' };
204
+ let ready = null;
205
+ if (x.ready != null) {
206
+ const RR = require('./ready-reports.js');
207
+ if (!isObj(x.ready) || !RR.parseScope(x.ready.scope) || !RR.KINDS.concat(['heads-up']).includes(x.ready.kind)) return { ok: false, error: 'ready is { scope: product | program:<id> | initiative:<id>, kind: weekly | checkpoint | did-it-work | heads-up }' };
208
+ ready = { scope: x.ready.scope, kind: x.ready.kind };
209
+ }
202
210
  const clean = (s) => String(s).replace(/["\\]/g, "'").trim();
203
211
  return { ok: true, proposal: {
204
212
  name: x.name.trim(), purpose: x.purpose.trim(), audience: clean(x.audience), source, output: x.output, schedule: sch.schedule,
205
213
  sources: sources.list, sections: sections.list.length ? sections.list : FRAME.slice(), learned_from: x.learned_from ? x.learned_from.trim() : null,
206
- fixes: fixes.list, found, ...(x.product ? { product: clean(x.product) } : {}), ...(storyline ? { storyline } : {}),
214
+ fixes: fixes.list, found, ...(x.product ? { product: clean(x.product) } : {}), ...(storyline ? { storyline } : {}), ...(ready ? { ready } : {}),
207
215
  } };
208
216
  }
209
217
 
@@ -231,7 +239,7 @@ function fold(lines) {
231
239
  st.setups.set(l.id, { id: l.id, name: l.name, purpose: l.purpose, audience: l.audience, source: l.source || 'work', output: l.output, schedule: l.schedule,
232
240
  sources: l.sources || [], sections: l.sections || FRAME.slice(), learned_from: l.learned_from || null, fixes: l.fixes || [], product: l.product || null,
233
241
  ws: l.ws || null, status: 'active', created_at: l.at, last_run: l.last_run || l.at, def_sha: l.def_sha || null, from: l.from || null, migrated: !!l.migrated, drafted: [],
234
- ...(isObj(l.storyline) ? { storyline: l.storyline } : {}) });
242
+ ...(isObj(l.storyline) ? { storyline: l.storyline } : {}), ...(isObj(l.ready) ? { ready: l.ready } : {}) });
235
243
  if (l.from && l.from.ask) st.asks.delete(l.from.ask);
236
244
  if (l.from && l.from.finding && st.findings.has(l.from.finding)) st.findings.get(l.from.finding).state = 'set-up';
237
245
  break;
@@ -247,7 +255,7 @@ function fold(lines) {
247
255
  case 'remove': { const s = st.setups.get(l.id); if (s) { st.removed.set(l.id, { ...s, status: 'removed', removed_at: l.at }); st.setups.delete(l.id); } break; }
248
256
  case 'doc-discard': if (typeof l.doc === 'string') { st.discarded.push({ doc: l.doc, path: l.path || null, at: l.at }); st.archived.delete(l.doc); } break;
249
257
  case 'doc-archive': if (typeof l.doc === 'string') { if (l.archived === false) st.archived.delete(l.doc); else st.archived.add(l.doc); } break;
250
- case 'drafted': { const s = st.setups.get(l.id); if (s) { s.last_run = l.at; s.drafted.push({ slot: l.slot, at: l.at, path: l.path || null }); } break; }
258
+ case 'drafted': { const s = st.setups.get(l.id); if (s) { s.last_run = l.at; s.drafted.push({ slot: l.slot, at: l.at, path: l.path || null, ...(typeof l.sha === 'string' ? { sha: l.sha } : {}) }); } break; }
251
259
  case 'ask-start':
252
260
  if (ASK_RE.test(String(l.ask || ''))) st.asks.set(l.ask, { id: l.ask, text: l.text, ws: l.ws || null, state: 'running', changed: false, proposal: null, error: null, started: l.at, changes: [] });
253
261
  break;
@@ -518,7 +526,7 @@ function setUp(root, input, opts = {}) {
518
526
  }
519
527
  append(file, { ev: 'setup', id, name: p.name, purpose: p.purpose, audience: p.audience, source: p.source, output: p.output, schedule: p.schedule, sources: p.sources,
520
528
  sections: p.sections, learned_from: p.learned_from, fixes: p.fixes, product: setup.product, ws: opts.wsId || null, last_run: lastRun, def_sha: def.sha,
521
- ...(from ? { from } : {}), ...(opts.migrated ? { migrated: true } : {}), ...(p.storyline ? { storyline: p.storyline } : {}) }, { now, by: opts.by });
529
+ ...(from ? { from } : {}), ...(opts.migrated ? { migrated: true } : {}), ...(p.storyline ? { storyline: p.storyline } : {}), ...(p.ready ? { ready: p.ready } : {}) }, { now, by: opts.by });
522
530
  const next = nextDraftAt(p.schedule, lastRun, now);
523
531
  const folded = fold(readLines(file)).setups.get(id);
524
532
  return { ok: true, setup: folded, definition: def.path, first_draft: next ? { slot: localDay(next), at: next.toISOString(), day: next.getDay() } : null };
@@ -744,7 +752,8 @@ function writeDocument(root, setup, slot, markdown, { now, record = true } = {})
744
752
  const tmp = `${file}.tmp-${crypto.randomBytes(6).toString('hex')}`;
745
753
  try { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(tmp, markdown, { flag: 'wx' }); fs.renameSync(tmp, file); }
746
754
  catch (e) { try { fs.unlinkSync(tmp); } catch { /* not made */ } return refuse(500, 'could not write the document: ' + String((e && e.message) || e).slice(0, 160)); }
747
- if (record) append(ledgerFile(abs), { ev: 'drafted', id: setup.id, slot, path: rel }, { now });
755
+ // the blob sha of the file as drafted: an issue whose sha is the same was sent unchanged (lib/ready-reports.js trustOf)
756
+ if (record) append(ledgerFile(abs), { ev: 'drafted', id: setup.id, slot, path: rel, sha: issues.blobSha(Buffer.from(markdown)) }, { now });
748
757
  return { ok: true, path: rel };
749
758
  }
750
759
 
@@ -102,8 +102,12 @@ const MODULES = Object.freeze([
102
102
  'routes-report-structure', // report-structure: the structure step (turns, versions, Use this structure, sources and their checks, dry run) and the chart store (GET /api/charts)
103
103
  'routes-insight-moves', // batch 16 item 1: the ✓ and Undo of a drafted move on the Intelligence ✦ strip (insight-moves.jsonl; date, anchor, chase to the outbox)
104
104
  'routes-page-opens', // batch 16 item 1: the pages the PM opens, by day, local only (runtime page-opens.jsonl); drives the weekly report proposal
105
+ 'routes-ready-reports', // batch 17 item 1: the ready-made dashboard and reports of every program, product and initiative (ready-reports.jsonl; page-press POST)
105
106
  'routes-metric-drafts', // batch 15 item 1: the metrics Claude drafts unasked for a product, a program or an initiative; ✓ keep writes kr-metrics (metric-drafts.jsonl; page-press POST)
107
+ 'routes-impact', // batch 16 item 7: Your impact, private to the PM: the week, the log, the weekly check and its ✓/✕ (runtime impact/impact.jsonl; page-press POST)
108
+ 'routes-goal-status', // batch 16 item 6: the goals' one status from readings (product page), notify choice, recipe, Read now, test read, CSV readings
106
109
  'routes-refresh', // data-refresh-settings: Settings › Data refresh: what refreshes, when, the refresh log, Refresh now
110
+ 'routes-impact-views', // batch 16 item 7 (Your impact, Phase 4): the chapter card's read, a stage that closed this week (boards.jsonl; read-only)
107
111
  ]);
108
112
  const PM_DIR = path.join(__dirname, '..', 'public', 'pm');
109
113
  const MODULE_NAME = /^[a-z0-9][a-z0-9-]*\.js$/;
@@ -93,6 +93,11 @@ module.exports = {
93
93
  rows: listOf(rk, nw), columns: c ? c.columns : [], sprints: s || { source: 'none', sprints: [] }, docs: d, custom,
94
94
  items: its && its.body && its.body.ok !== false && Array.isArray(its.body.items) ? its.body.items : [], held: hd ? hd.rows : [], cancelled: cn ? cn.rows : [], archived: ar ? ar.rows : [], asks: ak ? ak.asks || [] : null,
95
95
  });
96
+ // every open initiative's anchor, not only the 100 rows listed (batch 17 item 1): Home's product card counts the goals as the ready-made
97
+ // dashboard counts them (lib/ready-reports.js anchorGoalsOf reads the same /api/boards/items rows)
98
+ const iniRows = its && its.body && Array.isArray(its.body.initiatives) ? its.body.initiatives : null;
99
+ if (iniRows) model.anchorRows = iniRows.filter((r) => r && r.anchor && !['done', 'cancelled'].includes(String(r.status || '').toLowerCase()) && !r.archived)
100
+ .map((r) => ({ id: r.id, title: r.title, status: r.status || null, late: r.status === 'late', anchor: r.anchor, kr: BoardPremium.krShort(r.anchor) }));
96
101
  // planned versus actual (batch 11 item 8): each row's drafts and saved plans, from task-plans.jsonl
97
102
  try {
98
103
  const w = ctx.getWs ? ctx.getWs(pick.ws) : null, dir = w && ctx.stateDirFor ? ctx.stateDirFor(w) : null;
@@ -715,7 +715,7 @@ const READS = {
715
715
  const live = r.rows.filter((x) => !x.archived); // an archived initiative leaves every list and timeline (c3-initiative-lifecycle)
716
716
  seedRows(ctx, r.w, r.fr, r.board, live);
717
717
  ctx.json(res, { ok: true, ws: r.w.id, board: r.board.id, build: r.board.build, jira: r.board.jira, jiraProjects: r.board.jiraProjects, items: itemsOf(r.w, r.fr, r.board, live),
718
- initiatives: live.map((x) => ({ id: x.id, title: x.title, stage: x.stage, cat: x.cat, status: x.status, owner: x.owner, horizon: x.horizon, start: x.start, end: x.end, progress: x.progress, template: x.template, epics: x.epics,
718
+ initiatives: live.map((x) => ({ id: x.id, title: x.title, stage: x.stage, cat: x.cat, status: x.status, owner: x.owner, anchor: x.anchor || '', horizon: x.horizon, start: x.start, end: x.end, progress: x.progress, template: x.template, epics: x.epics,
719
719
  stages: (x.wfStages || []).map((st) => ({ key: st.key, name: st.name, milestone: !!st.milestone })) })) }); // the sections a task can sit in (the task Viewer's move icon)
720
720
  },
721
721
  '/api/boards/sprints': (ctx, res, url) => {
@@ -0,0 +1,111 @@
1
+ 'use strict';
2
+ /* routes-goal-status.js — the goals' readings and their watch (feedback batch 16 item 6, "Claude runs the OKRs"). The status is lib/goal-status.js,
3
+ * the reading ledger lib/metric-reads.js, the runs lib/metric-read-runs.js (ctx.metricReadRuns), the alerts and the standing fixes lib/goal-watch.js.
4
+ *
5
+ * GET /api/goal-status?ws=<id> → { ok, on, behind: [title], broken: [title], close: [title], none, dots: [{ id, title, dot }], line }
6
+ * the product page's Goals line: the same status as Intelligence's goal list, never initiative risk
7
+ * POST /api/goals/notify { ws, id, notify: push | intel | quiet } → { ok } the goal Viewer ⋯: how a broken limit reaches the PM
8
+ * POST /api/goal-status/recipe { ws, id, recipe: { connector, query, cadence } | null, close_band? } → { ok } how the goal is read, and its band
9
+ * POST /api/goal-status/read { ws, id? } → { ok, run, rids } Read now: one goal, or every goal with a recipe
10
+ * POST /api/goal-status/test { ws, rows: [draft row id] } → { ok, run, rids } a test read of drafted rows before the ✓ (no record is written)
11
+ * POST /api/goal-status/csv { ws, id, csv, source? } → { ok, added, skipped } the fallback: a CSV or sheet export's readings, via csv
12
+ *
13
+ * WHO WRITES. As lib/routes-metric-drafts.js: a POST with an agent session header is refused (403), and pm-guard requirePagePress checks the
14
+ * launch nonce and the page's origin. A record write goes through scripts/records (planning/records/kr-metrics.jsonl of the workspace). */
15
+ const guard = require('./pm-guard.js');
16
+ const GS = require('./goal-status.js');
17
+ const MR = require('./metric-reads.js');
18
+ const MD = require('./metric-drafts.js');
19
+ const GW = require('./goal-watch.js');
20
+ const { repoScript } = require('./repo-script.js');
21
+ const { recordsDirFor } = require('./records-dir.js');
22
+
23
+ const text = (v) => (typeof v === 'string' ? v : '');
24
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
25
+ const records = () => require(repoScript('records/index.js'));
26
+ const UI = () => require(repoScript('trust/ledger.js')).actorFrom({ ui: true });
27
+ const todayIso = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
28
+ const dirOf = (ctx, w) => { try { return ctx.stateDirFor ? ctx.stateDirFor(w) : null; } catch { return null; } };
29
+ const wsOf = (ctx, ws) => { let w = null; try { w = ctx.getWs(ws || null); } catch { w = null; } return ws && w && w.id !== ws ? null : w; };
30
+ /** The goals the product page shows: the product's own (North Star, key results, guardrails, budgets), not what Claude only watches and not a
31
+ * program's or an initiative's own measure. */
32
+ const PRODUCT_ROLES = new Set(['north-star', 'input', 'guardrail', 'kr']);
33
+ const liveRecords = (ctx, w) => records().list(recordsDirFor(ctx, w.id), 'kr-metrics').filter((r) => r && r.retired !== true);
34
+
35
+ function summaryFor(ctx, w, today) {
36
+ const goals = liveRecords(ctx, w).filter((r) => !r.role || PRODUCT_ROLES.has(r.role) || r.budget).map((r) => ({ id: r.rid, title: String(r.metric || r.rid), reading: GS.readingOf(r, today) }));
37
+ return GS.summaryOf(goals);
38
+ }
39
+
40
+ /** After readings landed: the alert check, the bell for a push, and the standing read fixes cleared (lib/goal-watch.js). */
41
+ function afterRead(ctx, w, rids, now = Date.now()) {
42
+ const dir = dirOf(ctx, w); if (!dir) return [];
43
+ return GW.afterRead({ dir, ws: w.id, records: liveRecords(ctx, w), rids, today: todayIso(), at: new Date(now).toISOString(),
44
+ tell: (rec, reading) => { if (ctx.tellGoalAlert) ctx.tellGoalAlert(w, rec, reading); } });
45
+ }
46
+
47
+ async function handle(req, res, url, ctx) {
48
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
49
+ if (url.pathname === '/api/goal-status') {
50
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
51
+ const w = wsOf(ctx, url.searchParams.get('ws'));
52
+ if (!w) return send(bad(404, 'no such workspace'));
53
+ try { return send({ status: 200, body: { ok: true, ...summaryFor(ctx, w, todayIso()) } }); } catch (e) { return send(bad(500, 'The goals could not be read: ' + String((e && e.message) || e).slice(0, 160))); }
54
+ }
55
+ const what = url.pathname === '/api/goals/notify' ? 'notify' : url.pathname.replace(/^\/api\/goal-status\/?/, '');
56
+ if (!['notify', 'recipe', 'read', 'test', 'csv'].includes(what)) return send(bad(404, 'no such goal-status route'));
57
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
58
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'Only the PM changes how a goal is read or told, from the page. A run files readings with pmos metrics reading.'));
59
+ const got = await ctx.readJson(req);
60
+ if (!got.ok) return send(bad(400, 'the body is not JSON'));
61
+ const body = got.body || {};
62
+ const g = guard.requirePagePress(req, body);
63
+ if (!g.ok) return send(bad(g.status, g.error));
64
+ const w = wsOf(ctx, text(body.ws));
65
+ if (!w) return send(bad(404, 'no such workspace'));
66
+ const root = recordsDirFor(ctx, w.id), id = text(body.id);
67
+ const rec = id ? liveRecords(ctx, w).find((r) => r.rid === id) : null;
68
+ const edit = (fields, why) => { let e; try { e = records().edit(root, 'kr-metrics', id, fields, UI(), why); } catch (x) { e = { ok: false, reasons: [String((x && x.message) || x).slice(0, 160)] }; } return e.ok ? { status: 200, body: { ok: true } } : bad(400, (e.reasons || []).join('; ')); };
69
+
70
+ if (what === 'notify') {
71
+ if (!rec) return send(bad(404, 'There is no such goal.'));
72
+ if (!['push', 'intel', 'quiet'].includes(body.notify)) return send(bad(400, 'notify is push, intel or quiet'));
73
+ return send(edit({ notify: body.notify }, 'How a broken limit reaches you'));
74
+ }
75
+ if (what === 'recipe') {
76
+ if (!rec) return send(bad(404, 'There is no such goal.'));
77
+ const set = {};
78
+ if (body.recipe === null) set.recipe = null;
79
+ else if (body.recipe !== undefined) { const r = MD.recipeOf(body.recipe); if (r.error) return send(bad(400, r.error)); set.recipe = r.recipe; }
80
+ if (body.close_band !== undefined) { const b = Number(body.close_band); if (!Number.isFinite(b) || b < 0) return send(bad(400, 'close_band is a number, 0 or more')); set.close_band = b; }
81
+ if (!Object.keys(set).length) return send(bad(400, 'Say the recipe or the close band.'));
82
+ return send(edit(set, 'How Claude reads this goal'));
83
+ }
84
+ if (what === 'read' || what === 'test') {
85
+ if (!ctx.metricReadRuns) return send(bad(503, 'Claude\'s runs are off on this server.'));
86
+ let rids;
87
+ if (what === 'test') {
88
+ rids = Array.isArray(body.rows) ? body.rows.filter((x) => typeof x === 'string').slice(0, 8) : [];
89
+ if (!rids.length) return send(bad(400, 'rows names the drafts to test-read.'));
90
+ } else rids = rec ? [rec.rid] : id ? [] : liveRecords(ctx, w).filter((r) => r.recipe && r.recipe.connector).map((r) => r.rid);
91
+ if (!rids.length) return send(bad(id ? 404 : 409, id ? 'There is no such goal.' : 'No goal has a way to be read yet.'));
92
+ const r = ctx.metricReadRuns.start({ ws: w.id, rids, why: what === 'test' ? 'test' : 'press' });
93
+ return send(r && r.ok ? { status: 200, body: { ok: true, run: r.run, rids: r.rids } } : bad(409, (r && r.error) || 'Claude could not start reading.'));
94
+ }
95
+ // csv: the fallback when no connector reads it
96
+ if (!rec) return send(bad(404, 'There is no such goal.'));
97
+ const p = MR.parseCsv(text(body.csv));
98
+ if (p.error) return send(bad(400, p.error));
99
+ const have = new Set((rec.readings || []).map((x) => String(x.at).slice(0, 10)));
100
+ const source = (text(body.source).replace(/\s+/g, ' ').trim() || 'CSV upload').slice(0, 120), readAt = new Date().toISOString();
101
+ let added = 0, skipped = 0;
102
+ for (const row of p.rows) {
103
+ if (have.has(row.at) || row.at > todayIso()) { skipped++; continue; }
104
+ const r = records().addReading(root, rec.rid, { at: row.at, value: row.value, source, via: 'csv', read_at: readAt }, UI(), 'Read from a file the PM gave');
105
+ if (r.ok) added++; else skipped++;
106
+ }
107
+ if (added) { try { afterRead(ctx, w, [rec.rid]); } catch { /* the readings stand */ } }
108
+ return send({ status: 200, body: { ok: true, added, skipped } });
109
+ }
110
+
111
+ module.exports = { prefixes: ['/api/goal-status', '/api/goals/notify'], handle, summaryFor, afterRead, PRODUCT_ROLES };
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+ /* routes-impact-views.js — what Your impact's chapter card reads (feedback batch 16 item 7, Phase 4; canvas GmP4Chapter). Read-only.
3
+ *
4
+ * GET /api/impact-views/chapter?ws=<id> → { ok, week, chapters: [{ ws, board, id, closed, now, at, then: { at, line } }] }
5
+ *
6
+ * A chapter is a stage that really closed this week: a PM's own `move` line in boards.jsonl (scripts/boards.js fold `moves`, via 'move')
7
+ * from one stage to another, at or after this week's Monday. "Then" is the initiative's first line on the board: the triage ask it was
8
+ * accepted from (its words and day), else its first move. The newest close per initiative wins. Without ws, every workspace is read.
9
+ * Home draws the card on a Friday only, and only while Your impact is on (pm/impact.js chapterHtml). Titles come from Home's own rows.
10
+ * The ledger behind Your impact (lib/impact.js, GET /api/impact/*) is another thread's; this file reads only the boards ledger and writes
11
+ * nothing. No number value is in the body (the Your impact rule): dates are ISO strings. */
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const { repoScript } = require('./repo-script.js');
15
+ const B = require(repoScript('boards.js'));
16
+
17
+ const ONE = (s, n) => String(s || '').replace(/\s+/g, ' ').trim().slice(0, n);
18
+ function lines(ctx, w) {
19
+ const d = ctx.stateDirFor ? ctx.stateDirFor(w) : null;
20
+ if (!d) return [];
21
+ try { return fs.readFileSync(path.join(d, 'boards.jsonl'), 'utf8').split('\n').filter(Boolean); } catch { return []; }
22
+ }
23
+ /** This week's Monday at 00:00, local time (Settings › Time › week start is the Board's; Your impact's weeks start on Monday). */
24
+ function monday(now) { const d = new Date(now); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() - ((d.getDay() + 6) % 7)); return d; }
25
+ const isoDay = (d) => d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
26
+
27
+ /** The chapters of one folded ledger. Pure: f is scripts/boards.js fold(); since a Date. */
28
+ function chaptersOf(f, since, ws) {
29
+ const first = new Map(), out = new Map();
30
+ for (const m of f.moves || []) {
31
+ if (!m || !m.id) continue;
32
+ if (!first.has(m.id) && m.at) first.set(m.id, { at: m.at, line: '' });
33
+ const at = Date.parse(m.at || '');
34
+ if (m.via !== 'move' || !m.from || !m.to || m.from === m.to || !(at >= since.getTime())) continue;
35
+ out.set(m.id, { ws, board: m.board || '', id: m.id, closed: ONE(m.from, 60), now: ONE(m.to, 60), at: m.at });
36
+ }
37
+ for (const a of (f.asks && f.asks.values ? f.asks.values() : [])) {
38
+ if (a && a.state === 'accepted' && a.initiative && a.line) first.set(a.initiative, { at: a.at || (first.get(a.initiative) || {}).at || null, line: ONE(a.line, 200) });
39
+ }
40
+ return [...out.values()].map((c) => ({ ...c, then: first.get(c.id) || { at: null, line: '' } }));
41
+ }
42
+
43
+ module.exports = {
44
+ prefixes: ['/api/impact-views'],
45
+ chaptersOf,
46
+ handle: async (req, res, url, ctx) => {
47
+ if (url.pathname !== '/api/impact-views/chapter') return false;
48
+ if (req.method !== 'GET') { ctx.json(res, { ok: false, error: 'GET only' }, 405); return true; }
49
+ const since = monday(Date.now()), wsId = url.searchParams.get('ws');
50
+ const list = ctx.workspaceList ? ctx.workspaceList() : [];
51
+ const ws = wsId ? [ctx.getWs ? ctx.getWs(wsId) : list.find((x) => x.id === wsId)].filter(Boolean) : list;
52
+ const chapters = [];
53
+ for (const w of ws) { let f; try { f = B.fold(lines(ctx, w)); } catch { continue; } chapters.push(...chaptersOf(f, since, w.id || '')); }
54
+ chapters.sort((a, b) => String(b.at).localeCompare(String(a.at)));
55
+ ctx.json(res, { ok: true, week: isoDay(since), chapters: chapters.slice(0, 10) });
56
+ return true;
57
+ },
58
+ };
@@ -0,0 +1,91 @@
1
+ 'use strict';
2
+ /* routes-impact.js — "Your impact" over HTTP (feedback batch 16 item 7; contract next16/briefs/7-impact-api.md). The fold is lib/impact.js;
3
+ * the daily run is lib/impact-runs.js. The ledger is the person's own, in the runtime folder (<runtime>/impact/impact.jsonl): outside every
4
+ * repository, so nobody else reads it. Nothing here sends anything.
5
+ *
6
+ * GET /api/impact/week?week=YYYY-MM-DD → { ok, on, live, first, week, from, to, label, grow, celebrate, quiet, items } Home's Adler, the Viewer
7
+ * GET /api/impact/weeks → { ok, on, live, weeks: [{ week, from, to, label, quiet, items }] } the log, newest first
8
+ * GET /api/impact/check → { ok, on, due, week, label, items, gate } the weekly check in Home's chat
9
+ * POST /api/impact/verdict { id, real } → { ok } ✓ (true) or ✕ (false) one row
10
+ * POST /api/impact/verdict-all { week } → { ok } ✓✓ every row of that week not checked yet
11
+ * POST /api/impact/undo { id } → { ok } the row back to not checked
12
+ * POST /api/impact/seen { ids } → { ok } read on a Phase 2 surface; ends its one celebration
13
+ * `ws` is accepted on every route and ignored: the ledger is per person, across products.
14
+ *
15
+ * THE SWITCH. Settings › General › Your impact (impact.on, lib/settings-store.js). Off: every GET answers { ok, on: false } and nothing else,
16
+ * every POST answers 409, and the daily run does not start.
17
+ *
18
+ * NO NUMBERS. No body carries a number value (impact-ui-test and impact.test.js check it): growth and the gate are words.
19
+ *
20
+ * WHO WRITES. As routes-metric-drafts.js: a POST that carries an agent session header is refused (403), and pm-guard requirePagePress
21
+ * checks the launch nonce and the page's origin. After a verdict, a change of the gate is written to the ledger with its rate. */
22
+ const guard = require('./pm-guard.js');
23
+ const IM = require('./impact.js');
24
+ const store = require('./settings-store.js');
25
+
26
+ const text = (v) => (typeof v === 'string' ? v : '');
27
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
28
+ const nowMs = (ctx) => { const t = Date.parse((ctx.env || process.env).PMOS_IMPACT_NOW || ''); return Number.isFinite(t) ? t : Date.now(); };
29
+ const isOn = (ctx) => { try { return store.get(ctx.runtimeDir, 'impact.on') !== false; } catch { return true; } };
30
+ const startOf = (ctx) => { try { return store.get(ctx.runtimeDir, 'time.weekStart') === 'sun' ? 'sun' : 'mon'; } catch { return 'mon'; } };
31
+ const optsOf = (ctx, extra) => ({ today: IM.dayOf(nowMs(ctx)), start: startOf(ctx), ...extra });
32
+
33
+ /** The gate after a verdict: written once each time it changes (the brief's "record the rate"). Open stays open. */
34
+ function noteGate(ctx, dir) {
35
+ const F = IM.read(dir), o = optsOf(ctx);
36
+ const g = IM.gateOf(F, IM.weekOf(o.today, o.start), o.start);
37
+ const was = F.gate ? F.gate.state : 'measuring';
38
+ if (g.state !== was && was !== 'open') IM.append(dir, null, { kind: 'gate', state: g.state, real: g.real, judged: g.judged, weeks: g.weeks }, new Date(nowMs(ctx)).toISOString());
39
+ }
40
+
41
+ async function handle(req, res, url, ctx) {
42
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
43
+ const what = url.pathname.replace(/^\/api\/impact\/?/, '');
44
+ const dir = IM.dirOf(ctx.runtimeDir);
45
+ if (['week', 'weeks', 'check'].includes(what)) {
46
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
47
+ if (!isOn(ctx)) return send({ status: 200, body: { ok: true, on: false } });
48
+ const F = dir ? IM.read(dir) : IM.fold([]);
49
+ const body = what === 'week' ? IM.weekView(F, optsOf(ctx, { week: url.searchParams.get('week') || '' }))
50
+ : what === 'weeks' ? IM.weeksView(F, optsOf(ctx)) : IM.checkView(F, optsOf(ctx));
51
+ return send({ status: 200, body: { ok: true, on: true, ...body } });
52
+ }
53
+ if (!['verdict', 'verdict-all', 'undo', 'seen'].includes(what)) return send(bad(404, 'no such impact route'));
54
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
55
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'Only you check your impact, from the page. Claude\'s run files items with pmos impact.'));
56
+ const rd = await ctx.readJson(req);
57
+ if (!rd.ok) return send(bad(400, 'the body is not JSON'));
58
+ const body = rd.body || {};
59
+ const g = guard.requirePagePress(req, body);
60
+ if (!g.ok) return send(bad(g.status, g.error));
61
+ if (!isOn(ctx)) return send(bad(409, 'Your impact is off in Settings.'));
62
+ if (!dir) return send(bad(409, 'There is no runtime folder.'));
63
+ const F = IM.read(dir), at = new Date(nowMs(ctx)).toISOString(), by = { by: 'pm' };
64
+
65
+ if (what === 'seen') {
66
+ const ids = (Array.isArray(body.ids) ? body.ids : []).map(String).filter((id) => { const it = F.items.get(id); return it && it.real === true && !it.read; }).slice(0, 100);
67
+ if (ids.length) IM.append(dir, by, { kind: 'seen', ids }, at);
68
+ return send({ status: 200, body: { ok: true } });
69
+ }
70
+ if (what === 'verdict-all') {
71
+ const week = text(body.week), o = optsOf(ctx);
72
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(week)) return send(bad(400, 'week is the first day of the week, YYYY-MM-DD'));
73
+ const open = [...F.items.values()].filter((it) => it.real === null && IM.weekOf(IM.dayOf(Date.parse(it.at)), o.start) === week);
74
+ for (const it of open) IM.append(dir, by, { kind: 'verdict', id: it.id, real: true }, at);
75
+ noteGate(ctx, dir);
76
+ return send({ status: 200, body: { ok: true } });
77
+ }
78
+ const id = text(body.id), it = F.items.get(id);
79
+ if (!it) return send(bad(404, 'There is no such item.'));
80
+ if (what === 'verdict') {
81
+ if (typeof body.real !== 'boolean') return send(bad(400, 'real is true (✓ real) or false (✕ not real)'));
82
+ IM.append(dir, by, { kind: 'verdict', id, real: body.real }, at);
83
+ } else {
84
+ if (it.real === null) return send(bad(409, 'This item is not checked yet.'));
85
+ IM.append(dir, by, { kind: 'undo', id }, at);
86
+ }
87
+ noteGate(ctx, dir);
88
+ return send({ status: 200, body: { ok: true } });
89
+ }
90
+
91
+ module.exports = { prefixes: ['/api/impact'], handle };
@@ -41,6 +41,8 @@ function leadsOf(ctx, ws, list) {
41
41
  }
42
42
  return out;
43
43
  }
44
+ /** The product's open drafts: the ✦ line's ✓✓ count (lib/metric-drafts.js). */
45
+ const openDrafts = (dir, ws) => { const MD = require('./metric-drafts.js'), S = MD.read(dir).scopes.get(MD.keyOf('product', ws)); return S ? [...S.rows.values()].filter((r) => r.state === 'open').length : 0; };
44
46
  const qs = (o) => '?' + Object.entries(o).filter(([, v]) => v != null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');
45
47
 
46
48
  module.exports = {
@@ -92,7 +94,18 @@ module.exports = {
92
94
  // premium-uncovered-features (IsMenus): the product picker says how many goals each product's workspace records; a workspace that cannot be read says none
93
95
  const counts = new Map();
94
96
  const goalsIn = (w) => { if (!counts.has(w)) { let n = null; try { n = w === ws ? outcomes.length : require(repoScript('records/index.js')).list(recordsDirFor(ctx, w), 'kr-metrics').length; } catch { n = null; } counts.set(w, n); } return counts.get(w) === null ? {} : { goals: counts.get(w) }; };
97
+ // batch 16 item 6 ("Claude runs the OKRs"): the reading ledger, each record's own history, and the product's open drafts
98
+ let watch = null, wdir = null;
99
+ if (pick) {
100
+ try {
101
+ wdir = ctx.stateDirFor ? ctx.stateDirFor(ctx.getWs(pick.ws)) : null;
102
+ const R = require(repoScript('records/index.js')), lines = R.readLines(R.fileOf(recordsDirFor(ctx, ws), 'kr-metrics')), GW = require('./goal-watch.js');
103
+ const history = Object.fromEntries(Object.keys(goalMeta).map((rid) => [rid, GW.historyOf(lines, rid)]));
104
+ watch = { reads: wdir ? require('./metric-reads.js').read(wdir) : null, history, drafts: wdir ? openDrafts(wdir, pick.ws) : 0 };
105
+ } catch { watch = null; }
106
+ }
95
107
  const model = Insights.build({
108
+ watch,
96
109
  now: Date.now(), board: pick ? { ws: pick.ws, id: pick.id, name: pick.name } : { ws, id: null, name: 'Intelligence' }, boards: all.map((x) => Object.assign({ ws: x.ws, id: x.id, name: x.name }, goalsIn(x.ws))),
97
110
  outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing, saved, mine,
98
111
  setups: setupsOk ? su.body : null, pinned, leads, archived, initiatives, goalMeta, ins, budgets,
@@ -105,6 +118,13 @@ module.exports = {
105
118
  require('./insight-moves.js').draftAll(model, { initiatives: initiatives || [], today: model.today, anchorOk: (t) => A.resolve(t).status === 'resolved', ledger: dir ? require('./insight-moves.js').read(dir) : new Map() });
106
119
  } catch { /* no move is drafted: the strip says the finding without a ✓ */ }
107
120
  }
121
+ // batch 16 item 6: the owner, chase and rollback-ticket fixes the goals call for now, filed standing (drafts only: nothing is sent)
122
+ if (wdir && pick) {
123
+ try {
124
+ const r = require('./goal-watch.js').syncFixes({ dir: wdir, ws: pick.ws, goals: model.goals, at: new Date().toISOString() });
125
+ if (r.filed || r.cleared) model.okr = Insights.okrOf(model, openDrafts(wdir, pick.ws));
126
+ } catch { /* the goals stand without the fixes */ }
127
+ }
108
128
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
109
129
  return true;
110
130
  } catch (e) { return fail((e && e.message) || e); }
@@ -6,6 +6,9 @@
6
6
  * GET /api/metric-drafts?ws=&scope=&id= → { ok, scope, id, title, when, run: { state: idle|running|ready|failed|off, step, reads },
7
7
  * rows, head, sub, src } rows [] and run.state idle when nothing is drafted
8
8
  * POST /api/metric-drafts/keep { ws, scope, id, row } → { ok, rid } ✓ one row: the record and, when now is known, one reading
9
+ * a fix row (batch 16 item 6): outcome, next-quarter add a record (the test read is its first reading); recipe,
10
+ * carry, owner edit the goal's record; chase, ticket → { ok, outbox } (nothing is sent until the PM's Send in the
11
+ * outbox); connect → { ok, open: 'settings:connectors', connector }
9
12
  * POST /api/metric-drafts/keep-all { ws, scope, id } → { ok, kept: n, failed } ✓ every open row
10
13
  * POST /api/metric-drafts/drop { ws, scope, id, row } → { ok } ✕
11
14
  * POST /api/metric-drafts/edit { ws, scope, id, row, name?, target?, source? } → { ok, row } the inline edit of an open row (batch 16 item 1)
@@ -99,7 +102,46 @@ async function handle(req, res, url, ctx) {
99
102
  }
100
103
  const s = S();
101
104
  const root = recordsDirFor(ctx, w.id), today = todayIso();
105
+ // batch 16 item 6: a fix row's ✓ (lib/metric-drafts.js FIXES). → { rid?, outbox?, open?, connector? } | { error }
106
+ const editRec = (rid, fields, why) => { let e; try { e = records().edit(root, 'kr-metrics', rid, fields, UI(), why); } catch (x) { e = { ok: false, reasons: [String((x && x.message) || x).slice(0, 160)] }; } return e.ok ? null : 'The goal could not be changed: ' + (e.reasons || []).join('; '); };
107
+ const toOutbox = (channel, recipient, subject, body) => {
108
+ if (!ctx.runtimeDir) return { error: 'This workspace has no outbox, so it could not be drafted.' };
109
+ try {
110
+ const e = require(repoScript('outbox.js')).draftOutbox({ channel, recipient, subject, body, origin: 'pm' });
111
+ const entry = { id: 'out-' + require('crypto').randomBytes(6).toString('hex'), ...e };
112
+ require('./outbox-store.js').appendEvent(ctx.runtimeDir, { event: 'queued', ...entry }, new Date());
113
+ return { id: entry.id };
114
+ } catch (x) { return { error: 'It could not go to the outbox: ' + String((x && x.message) || x).slice(0, 160) }; }
115
+ };
116
+ const keepFix = (row) => {
117
+ const k = row.kind, done = (extra) => { MD.append(dir, g.actor, { kind: 'keep', scope, id, row: row.id, rid: extra.rid || null, ...(extra.before ? { before: extra.before } : {}), ...(extra.outbox ? { outbox: extra.outbox } : {}) }, at()); const { before, ...out } = extra; return out; };
118
+ const cur = (rid) => (records().list(root, 'kr-metrics').find((r) => r.rid === rid) || null);
119
+ const beforeOf = (rid, keys) => { const c = cur(rid) || {}; return Object.fromEntries(keys.map((x) => [x, c[x] === undefined ? null : c[x]])); };
120
+ if (k === 'outcome' || k === 'next-quarter') {
121
+ const kf = MD.keepFields(scope, id, row.metric, { today });
122
+ if (kf.error) return { error: kf.error };
123
+ if (k === 'outcome') Object.assign(kf.fields, { kr: row.goal, was: row.old || '' });
124
+ if (row.recipe) kf.fields.recipe = row.recipe;
125
+ kf.fields.draft = row.id;
126
+ let r; try { r = records().add(root, 'kr-metrics', kf.fields, UI(), k === 'outcome' ? 'Kept the outcome Claude drafted for a project-shaped goal' : 'Kept next quarter\'s goal Claude drafted'); } catch (e) { return { error: 'The record could not be written: ' + String((e && e.message) || e).slice(0, 160) }; }
127
+ if (!r.ok) return { error: r.reasons.join('; ') };
128
+ // the test read (lib/metric-reads.js), else the reading it was drafted from, is the first reading, with its source
129
+ let test = null; try { const x = require('./metric-reads.js').read(dir).rids.get(row.id); test = x && x.test && x.test.ok ? x.test : null; } catch { test = null; }
130
+ const first = test ? { at: test.day, value: test.value, source: test.source, via: 'run', read_at: test.at } : kf.reading;
131
+ if (first) { try { records().addReading(root, r.rid, first, UI(), test ? 'The test read before you kept it' : 'The reading Claude drafted it from'); } catch { /* the record stands */ } }
132
+ return done({ rid: r.rid });
133
+ }
134
+ if (k === 'connect') return done({ open: 'settings:connectors', connector: row.connector });
135
+ const editKeep = (fields, why) => { if (!cur(row.goal)) return { error: 'The goal this fix repairs is not recorded any more.' }; const before = beforeOf(row.goal, Object.keys(fields)); const e = editRec(row.goal, fields, why); return e ? { error: e } : done({ rid: row.goal, before }); };
136
+ if (k === 'recipe') return editKeep({ recipe: row.recipe }, 'Kept how Claude reads this goal');
137
+ if (k === 'carry') return editKeep({ by: row.by, ...(typeof row.target === 'number' ? { target: row.target } : {}) }, 'Carried on to next quarter');
138
+ if (k === 'owner') return editKeep({ owner: row.owner.name, owner_from: row.owner.from }, 'Kept the owner Claude proposed');
139
+ if (k === 'chase') { const o = row.channel === 'jira-write' ? toOutbox('jira-write', row.epic, 'About ' + row.goal, row.body) : toOutbox('team-note', row.to, 'A note on ' + row.goal, row.body); return o.error ? o : done({ rid: row.goal, outbox: o.id }); }
140
+ if (k === 'ticket') { const o = toOutbox('jira-write', (row.ticket && row.ticket.project) || null, row.ticket.title, row.ticket.text); return o.error ? o : done({ rid: row.goal, outbox: o.id }); }
141
+ return { error: 'This draft cannot be kept.' };
142
+ };
102
143
  const keepOne = (row) => {
144
+ if (row.kind && row.kind !== 'metric') return keepFix(row);
103
145
  const k = MD.keepFields(scope, id, row, { today });
104
146
  if (k.error) return { error: k.error };
105
147
  let r;
@@ -113,7 +155,7 @@ async function handle(req, res, url, ctx) {
113
155
  const open = s ? [...s.rows.values()].filter((r) => r.state === 'open') : [];
114
156
  if (!open.length) return send(bad(409, 'There is nothing open to keep.'));
115
157
  let kept = 0; const failed = [];
116
- for (const row of open) { const r = keepOne(row); if (r.rid) kept++; else failed.push({ row: row.id, error: r.error }); }
158
+ for (const row of open) { const r = keepOne(row); if (!r.error) kept++; else failed.push({ row: row.id, error: r.error }); }
117
159
  return send(kept ? { status: 200, body: { ok: true, kept, failed } } : bad(400, failed[0].error));
118
160
  }
119
161
  const row = s && s.rows.get(text(body.row));
@@ -121,11 +163,13 @@ async function handle(req, res, url, ctx) {
121
163
  if (what === 'keep') {
122
164
  if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it already.' : 'You dropped it. Undo first.'));
123
165
  const r = keepOne(row);
124
- return send(r.rid ? { status: 200, body: { ok: true, rid: r.rid } } : bad(400, r.error));
166
+ if (r.error) return send(bad(400, r.error));
167
+ const out = { ok: true, rid: r.rid || null }; for (const k of ['outbox', 'open', 'connector']) if (r[k]) out[k] = r[k];
168
+ return send({ status: 200, body: out });
125
169
  }
126
170
  if (what === 'edit') {
127
171
  if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it. Undo it first, then edit.' : 'You dropped it. Undo first.'));
128
- const pick = {}; for (const k of ['name', 'target', 'source']) if (body[k] !== undefined) pick[k] = body[k];
172
+ const pick = {}; for (const k of ['name', 'target', 'source', 'text', 'body']) if (body[k] !== undefined) pick[k] = body[k];
129
173
  const e = MD.editOf(row, pick);
130
174
  if (e.error) return send(bad(400, e.error));
131
175
  if (Object.keys(e.set).length) MD.append(dir, g.actor, { kind: 'edit', scope, id, row: row.id, set: e.set }, at());
@@ -138,7 +182,14 @@ async function handle(req, res, url, ctx) {
138
182
  }
139
183
  // undo: a kept row's record is retired (readers skip it), a dropped row comes back
140
184
  if (row.state === 'open') return send(bad(409, 'There is nothing to undo.'));
141
- if (row.state === 'kept' && row.rid) {
185
+ if (row.state === 'kept' && row.before && row.rid) { // a fix that edited a goal: its fields go back
186
+ const back = {}; for (const [k, v] of Object.entries(row.before)) back[k] = v;
187
+ const e = editRec(row.rid, back, 'Undo of a kept fix');
188
+ if (e) return send(bad(400, e));
189
+ } else if (row.state === 'kept' && row.outbox) { // a chase or a ticket: out of the outbox, unless it was sent
190
+ const r = require('./routes-outbox.js').discard(req, { id: row.outbox }, ctx.runtimeDir);
191
+ if (r.status !== 200) return send(bad(r.status === 409 ? 409 : 400, (r.body && r.body.error) === 'a sent entry is a record and is not discarded' ? 'It was sent already, so it cannot be taken back.' : 'It could not be taken out of the outbox.'));
192
+ } else if (row.state === 'kept' && row.rid && (!row.kind || row.kind === 'metric' || row.kind === 'outcome' || row.kind === 'next-quarter')) {
142
193
  let e;
143
194
  try { e = records().edit(root, 'kr-metrics', row.rid, { retired: true }, UI(), 'Undo of a kept draft'); } catch (x) { e = { ok: false, reasons: [String((x && x.message) || x).slice(0, 160)] }; }
144
195
  if (!e.ok && !(e.reasons || []).some((m) => /no such record/.test(m))) return send(bad(400, 'The record could not be retired: ' + (e.reasons || []).join('; ')));