create-pmos 0.748.0 → 0.750.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 (51) hide show
  1. package/package.json +51 -40
  2. package/payload/AGENTS.md +1 -0
  3. package/payload/KIT-VERSION +1 -1
  4. package/payload/planning/evals/eval-calibration.md +1 -1
  5. package/payload/planning/okrs/health-budgets.md +1 -1
  6. package/payload/state/discoveries.md +1 -1
  7. package/workspace/changelog.json +50 -0
  8. package/workspace/guide/backlog.md +13 -1
  9. package/workspace/guide/cli.md +13 -1
  10. package/workspace/guide/home.md +1 -1
  11. package/workspace/guide/layout.md +6 -6
  12. package/workspace/guide/programs.md +1 -0
  13. package/workspace/lib/idle-lab.js +16 -6
  14. package/workspace/lib/outcome-props.js +14 -4
  15. package/workspace/lib/outcomes-cli.js +44 -6
  16. package/workspace/lib/pmos-verbs.js +3 -0
  17. package/workspace/lib/proposals.js +12 -2
  18. package/workspace/lib/repeat-requests.js +123 -0
  19. package/workspace/lib/route-modules.js +1 -0
  20. package/workspace/lib/routes-intake.js +45 -2
  21. package/workspace/lib/routes-lab.js +19 -0
  22. package/workspace/lib/routes-proposals.js +13 -0
  23. package/workspace/lib/routes-standing-rules.js +44 -0
  24. package/workspace/lib/routes-your-move.js +7 -1
  25. package/workspace/lib/rules-cli.js +74 -0
  26. package/workspace/lib/smallest-test.js +200 -0
  27. package/workspace/lib/sprint-draft.js +24 -0
  28. package/workspace/lib/standing-rules.js +187 -0
  29. package/workspace/lib/tracker-cli.js +42 -1
  30. package/workspace/package-lock.json +2 -2
  31. package/workspace/package.json +1 -1
  32. package/workspace/premium-board-actions-test.js +2 -1
  33. package/workspace/public/pm/bd-asks.js +19 -5
  34. package/workspace/public/pm/bd-backlog-ds.js +58 -1
  35. package/workspace/public/pm/bd-backlog.js +14 -2
  36. package/workspace/public/pm/cozy-day-pick.js +34 -2
  37. package/workspace/public/pm/cozy-pop-work.js +13 -5
  38. package/workspace/public/pm/cozy-settings.js +6 -2
  39. package/workspace/public/pm/cozy-today-app.js +12 -6
  40. package/workspace/public/pm/cozy-today-model.js +88 -45
  41. package/workspace/public/pm/cozy-today-page.css +6 -0
  42. package/workspace/public/pm/cozy-today-view.js +72 -13
  43. package/workspace/public/pm/range-pick.css +1 -0
  44. package/workspace/public/pm/range-pick.js +21 -4
  45. package/workspace/public/pm/standing-rules-ui.js +100 -0
  46. package/workspace/task-card-test.js +16 -0
  47. package/workspace/test-lists/repeat-requests.json +9 -0
  48. package/workspace/test-lists/smallest-test.json +9 -0
  49. package/workspace/test-lists/sprint-draft.json +9 -0
  50. package/workspace/test-lists/standing-rules-list.json +9 -0
  51. package/workspace/test-lists/your-move-today.json +9 -0
@@ -13,6 +13,12 @@
13
13
  * pmos outcomes record <id> <worked|didnt-work|cant-tell> --evidence "<text>"
14
14
  * the PM's verdict on a check that is due (validated | refuted | inconclusive are the
15
15
  * same words), appended to the outcome ledger. Evidence is required.
16
+ * pmos outcomes test <id> --test "<text>" [--method data-count|fake-door|concierge|other] [--result planned|holds|fails|unclear] [--evidence "<text>"]
17
+ * the smallest test that could kill a bet before it is built (bet A472), and its result,
18
+ * appended to smallest_tests.jsonl. A result other than planned needs evidence. --test may be
19
+ * left out when the bet already has a named test.
20
+ * pmos outcomes tests [--count] [--json] the ranked bets with no smallest test, the tests waiting for a result, and the results;
21
+ * --count prints the number of bets with a result in the last 14 days (the health number).
16
22
  * every command: [--root <dir>] (default: this repository)
17
23
  *
18
24
  * The agent runs declare and record only after the PM said yes in the chat; the line names who wrote it (lib/actor.js). A verdict is the
@@ -21,15 +27,19 @@
21
27
  const path = require('path');
22
28
  const { execFileSync } = require('child_process');
23
29
  const O = require('./outcomes.js');
30
+ const ST = require('./smallest-test.js');
24
31
 
25
- const COMMANDS = { outcomes: ['list', 'propose', 'declare', 'record', 'live'] };
32
+ const COMMANDS = { outcomes: ['list', 'propose', 'declare', 'record', 'live', 'test', 'tests'] };
26
33
  const USAGE = [
27
- 'usage: pmos outcomes list|propose|declare|record|live — every initiative has an expected outcome and a date to check it',
34
+ 'usage: pmos outcomes list|propose|declare|record|live|test|tests — every initiative has an expected outcome and a date to check it',
28
35
  ' pmos outcomes list [--json] checks due, outcomes with no date, initiatives with no outcome; reads only',
29
36
  ' pmos outcomes propose [<id>] [--max <n>] [--json] PMOS\'s ✦ drafts from the PRD and the KR, each one cited',
30
37
  ' pmos outcomes declare <id> --metric "<text>" --horizon <YYYY-MM-DD> the PM said yes: write the outcome and its check date',
31
38
  ' pmos outcomes record <id> <worked|didnt-work|cant-tell> --evidence "<text>" the PM\'s verdict on a due check',
32
39
  ' pmos outcomes live --where <place> --version <v> the version a place runs now; a check measured there waits until it runs the shipped one',
40
+ ' pmos outcomes test <id> --test "<text>" [--method data-count|fake-door|concierge|other] [--result planned|holds|fails|unclear] [--evidence "<text>"]',
41
+ ' the smallest test that could kill a ranked bet, and what it showed',
42
+ ' pmos outcomes tests [--count] [--json] ranked bets with no test, tests waiting for a result, results; --count: results in 14 days',
33
43
  'Run it in the product\'s repository, or pass --root <dir>. Show each ✦ to the PM and write only after a yes.',
34
44
  ];
35
45
  const VERDICT = { worked: 'validated', validated: 'validated', 'didnt-work': 'refuted', "didn't-work": 'refuted', refuted: 'refuted', 'cant-tell': 'inconclusive', "can't-tell": 'inconclusive', inconclusive: 'inconclusive' };
@@ -40,7 +50,7 @@ function parse(args) {
40
50
  const a = args[i];
41
51
  if (!a.startsWith('--')) { pos.push(a); continue; }
42
52
  const k = a.slice(2);
43
- if (k === 'json') flags.json = true;
53
+ if (k === 'json' || k === 'count') flags[k] = true;
44
54
  else flags[k] = args[i + 1] !== undefined && !String(args[i + 1]).startsWith('--') ? args[++i] : '';
45
55
  }
46
56
  return { pos, flags };
@@ -51,6 +61,7 @@ function repoRoot(cwd) {
51
61
  const wsIdOf = (root) => { try { return require('./driver.js').wsIdOf(root); } catch { return require('crypto').createHash('sha1').update(path.resolve(root)).digest('hex').slice(0, 10); } };
52
62
  const draftText = (p) => `✦ ${p.title}\n ${p.say}\n${p.claims.map((c) => ' · ' + c.text + ' [' + c.sources.map((s) => s.ref).join(', ') + ']').join('\n')}`
53
63
  + (p.data && p.data.kind === 'refuted' ? `\n It waits under the initiative's ✦ for the PM's ✓ (${O.NEXT_WORDS[p.data.next]}); a ✕ with a reason leaves it as it is.`
64
+ : p.data && p.data.kind === 'test' ? `\n Yes → pmos outcomes test ${p.data.initiative} --method ${p.data.method} --test ${JSON.stringify(p.data.test)}`
54
65
  : p.data && p.data.kind !== 'due' ? `\n Yes → pmos outcomes declare ${p.data.initiative} --metric ${JSON.stringify(p.data.metric)} --horizon ${p.data.horizon}`
55
66
  : p.data ? `\n Verdict → pmos outcomes record ${p.data.initiative} worked|didnt-work|cant-tell --evidence "<what shows it>"` : '');
56
67
 
@@ -60,7 +71,7 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
60
71
  if (!sub || ['help', '--help', '-h'].includes(sub)) { for (const l of USAGE) say(l); return sub ? 0 : 1; }
61
72
  if (!COMMANDS.outcomes.includes(sub)) { say(`unknown outcomes command "${sub}". Use one of: ${COMMANDS.outcomes.join(', ')}`); return 2; }
62
73
  const { pos, flags } = parse(args.slice(1));
63
- const allowed = { list: ['json', 'root'], propose: ['json', 'root', 'max'], declare: ['json', 'root', 'metric', 'horizon'], record: ['json', 'root', 'evidence'], live: ['json', 'root', 'where', 'version'] }[sub];
74
+ const allowed = { list: ['json', 'root'], propose: ['json', 'root', 'max'], declare: ['json', 'root', 'metric', 'horizon'], record: ['json', 'root', 'evidence'], live: ['json', 'root', 'where', 'version'], test: ['json', 'root', 'test', 'method', 'result', 'evidence'], tests: ['json', 'root', 'count'] }[sub];
64
75
  for (const k of Object.keys(flags)) if (!allowed.includes(k)) { say(`✗ --${k} is not an option of pmos outcomes ${sub}`); return 2; }
65
76
  const root = path.resolve(flags.root || repoRoot(cwd));
66
77
  const today = O.todayOf(now);
@@ -88,9 +99,10 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
88
99
  if (pos.length > 1) return fail('pmos outcomes propose takes at most one initiative id', 2);
89
100
  const max = flags.max === undefined ? 3 : Number(flags.max);
90
101
  if (!Number.isInteger(max) || max < 1 || max > 10) return fail('--max is a whole number from 1 to 10', 2);
91
- const S = O.scan(root, { today });
102
+ const S = ST.testScan(root, { today });
92
103
  if (pos[0] && !S.subjects.some((it) => it.id === pos[0])) return fail(`no initiative ${pos[0]} here (or it is stopped, or on a document lane)`);
93
- const { drafts, ask } = O.drafts(S, { only: pos[0] || null });
104
+ const D0 = O.drafts(S, { only: pos[0] || null }), ask = D0.ask;
105
+ const drafts = [...D0.drafts, ...ST.testDrafts(S, { only: pos[0] || null })]; // the smallest test before a build (bet A472) after the outcomes
94
106
  const askText = ask.length ? `${ask.length} with nothing to draft from (no success criteria in a PRD, no KR to cite): ask the PM what should change once each ships — ${ask.slice(0, 8).map((a) => a.id).join(', ')}${ask.length > 8 ? ', …' : ''}` : '';
95
107
  if (!drafts.length) { if (flags.json) say(JSON.stringify({ ok: true, drafts: [], ask })); else say(askText || 'Nothing to draft: every initiative here has its expected outcome and check date.'); return 0; }
96
108
  let AG = null; try { AG = require('./ai-guard.js'); } catch { AG = null; }
@@ -118,6 +130,22 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
118
130
  return 0;
119
131
  }
120
132
 
133
+ if (sub === 'tests') {
134
+ if (pos.length) return fail('pmos outcomes tests takes no argument', 2);
135
+ const n = ST.testCount(root, { now });
136
+ if (flags.count) { say(flags.json ? JSON.stringify({ ok: true, ...n }) : `Bets with a smallest-test result in the last ${n.days} days:\n${n.results}`); return 0; }
137
+ const S = ST.testScan(root, { today });
138
+ const untested = S.untested.map((it) => ({ id: it.id, title: it.title }));
139
+ const waiting = ST.waitingTests(S);
140
+ const results = S.subjects.filter((it) => it.test && it.test.result !== 'planned').map((it) => ({ id: it.id, title: it.title, result: it.test.result, test: it.test.test, evidence: it.test.evidence || '', at: it.test.at }));
141
+ if (flags.json) { say(JSON.stringify({ ok: true, untested, waiting, results, count: n })); return 0; }
142
+ say(`${untested.length} ranked with no smallest test · ${waiting.length} waiting for a result · ${n.results} result${n.results === 1 ? '' : 's'} in the last ${n.days} days`);
143
+ if (untested.length) say('\nRanked, no smallest test yet (PMOS drafts one: pmos outcomes propose):\n' + untested.slice(0, 15).map((it) => ` ${it.id} — ${it.title}`).join('\n'));
144
+ if (waiting.length) say('\nWaiting for a result:\n' + waiting.map((w) => ` ${w.id} — ${ST.METHOD_WORDS[w.method] || 'a test'}: ${w.test}`).join('\n') + '\n Result → pmos outcomes test <id> --result holds|fails|unclear --evidence "<what it showed>"');
145
+ if (results.length) say('\nResults:\n' + results.slice(0, 15).map((r) => ` ${r.id} — ${ST.RESULT_WORDS[r.result]}: ${r.evidence}`).join('\n'));
146
+ return 0;
147
+ }
148
+
121
149
  if (sub === 'live') {
122
150
  if (pos.length) return fail('usage: pmos outcomes live --where <place> --version <version>', 2);
123
151
  const r = O.recordLive(root, { where: flags.where, version: flags.version, by: 'cli' }, { now });
@@ -131,6 +159,16 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
131
159
  const id = pos[0];
132
160
  const actor = require('./actor.js').fromCli({ isTTY: isTTY === undefined ? !!(process.stdin.isTTY && process.stdout.isTTY) : isTTY, env });
133
161
 
162
+ if (sub === 'test') {
163
+ if (!id || pos.length > 1) return fail('usage: pmos outcomes test <id> --test "<text>" [--method …] [--result planned|holds|fails|unclear] [--evidence "<text>"]', 2);
164
+ const r = ST.recordTest(root, { initiative: id, method: flags.method, test: flags.test, result: flags.result || 'planned', evidence: flags.evidence, by: actor.by, via: actor.via }, { now });
165
+ if (!r.ok) return fail(r.error, 2);
166
+ if (flags.json) { say(JSON.stringify({ ok: true, file: r.file, line: r.line })); return 0; }
167
+ say(`✓ ${id}: ${ST.METHOD_WORDS[r.line.method] || 'a test'} — ${r.line.test} · ${ST.RESULT_WORDS[r.line.result]}${r.line.evidence ? ': ' + r.line.evidence : ''} (${r.file}). Commit it to keep it.`);
168
+ if (r.line.result === 'fails') say(' The bet failed its smallest test. Stop it, or change it, before a build starts.');
169
+ return 0;
170
+ }
171
+
134
172
  if (sub === 'declare') {
135
173
  if (!id || pos.length > 1) return fail('usage: pmos outcomes declare <id> --metric "<text>" --horizon <YYYY-MM-DD>', 2);
136
174
  const r = require('./initiative-writer.js').setOutcome(root, id, { metric: flags.metric, horizon: flags.horizon }, { actor, today });
@@ -142,6 +142,9 @@ const VERBS = Object.freeze({
142
142
  // Not a pm-os-absorb verb (run: null): initiative try-what-shipped added it through the same table.
143
143
  try: Object.freeze({ module: 'try-it.js', run: null, guide: 'cli.md',
144
144
  help: 'pmos try [works|broken|note|undo|later|count] — the changes your recent updates brought, how to try each, and your answer (beta only; pmos try help)' }),
145
+ // Not a pm-os-absorb verb (run: null): initiative standing-rules-list (bet A470) added it through the same table.
146
+ rules: Object.freeze({ module: 'rules-cli.js', run: null, guide: 'cli.md',
147
+ help: 'pmos rules [edit|retire|restore|count] — the standing rules PMOS learned from your corrections: where each came from, times fired, last fired (pmos rules help)' }),
145
148
  // Not a pm-os-absorb verb (run: null): initiative three-line-why (bet A86) added it through the same table.
146
149
  why: Object.freeze({ module: 'why-cli.js', run: null, guide: 'cli.md',
147
150
  help: 'pmos why <initiative or task> | coverage — why the work exists in three lines: goal, problem, evidence, read from its records (pmos why help)' }),
@@ -18,7 +18,9 @@
18
18
  * outcome the expected outcome and its check date (D57; lib/outcomes.js, filed by lib/outcome-props.js): type new (no outcome yet) or date
19
19
  * (an outcome with no date). Type refuted (launch simulation W2): the check said it did not work, and PMOS recommends the next
20
20
  * step, data { next: kill | iterate | new, check, evidence, horizon (iterate) }; class C, so only the PM's ✓ does it. data { metric, horizon }; one item { id: 'outcome', title: the metric, due: the date }. Always section
21
- * 'check': its own ✓, never Keep all. ✓ writes the record's outcome_metric and outcome_horizon lines (lib/initiative-writer.js)
21
+ * 'check': its own ✓, never Keep all. ✓ writes the record's outcome_metric and outcome_horizon lines (lib/initiative-writer.js).
22
+ * Type test (bet A472): the smallest test that could kill a ranked bet, data { test, method }; ✓ records it as planned
23
+ * (lib/smallest-test.js recordTest), Undo takes it back.
22
24
  * description the record's own description (initiative-description-field; filed by lib/description-props.js): type new (none yet) or
23
25
  * enrich (the PRD says more). data { text, from? }; one item { id: 'description', title: the text cut }. Always section 'check'.
24
26
  * ✓ writes the record's description line (lib/initiative-writer.js setDescription)
@@ -86,7 +88,7 @@ const KINDS = new Set(['epoch', 'look', 'src', 'end', 'propose', 'drop', 'keep',
86
88
  const EXPIRE_DAYS = 14;
87
89
  const EXPIRE_WHY = 'No answer in 14 days, so I left it as it was.';
88
90
  const GROUPS = ['found', 'dates', 'status', 'names', 'outcome', 'description', 'build'];
89
- const TYPES = { found: ['stage', 'docs', 'tasks', 'link', 'maybe', 'unplaced'], dates: ['stage', 'task'], status: ['done'], names: ['tidy'], outcome: ['new', 'date', 'refuted', 'verdict', 'source'], description: ['new', 'enrich'], build: ['pr'] };
91
+ const TYPES = { found: ['stage', 'docs', 'tasks', 'link', 'maybe', 'unplaced'], dates: ['stage', 'task'], status: ['done'], names: ['tidy'], outcome: ['new', 'date', 'refuted', 'verdict', 'source', 'test'], description: ['new', 'enrich'], build: ['pr'] };
90
92
  const SOURCES = ['drive', 'docs', 'sheets', 'slides', 'jira', 'calendar', 'notes', 'mail', 'slack', 'confluence', 'chat', 'repo'];
91
93
  const SOURCE_NAMES = { drive: 'Drive and Slides', docs: 'Docs', sheets: 'Sheets', slides: 'Slides', jira: 'Jira', calendar: 'Calendar and meeting notes', notes: 'Meeting notes',
92
94
  mail: 'Gmail', slack: 'Slack', confluence: 'Confluence', chat: 'Chat', repo: 'This repository' };
@@ -195,6 +197,14 @@ function clean(group, type, input) {
195
197
  if (evidence.length < 12) return { error: 'data.evidence says what shows it, at least 12 characters' };
196
198
  if (!DAY_RE.test(str(d.horizon))) return { error: 'data.horizon is the check date it answers, YYYY-MM-DD' };
197
199
  Object.assign(data, { disposition: d.disposition, evidence, horizon: str(d.horizon) });
200
+ } else if (group === 'outcome' && type === 'test') {
201
+ // the smallest test that could kill a ranked bet before it is built (bet A472; lib/smallest-test.js). Class B: ✓ records it
202
+ // as planned in smallest_tests.jsonl (lib/smallest-test.js recordTest), Undo takes the line back (undoTest)
203
+ const d = isObj(input.data) ? input.data : {};
204
+ const test = one(d.test, 500);
205
+ if (test.length < 8) return { error: 'data.test says the test in a few words' };
206
+ if (!['data-count', 'fake-door', 'concierge', 'other'].includes(d.method)) return { error: 'data.method is data-count, fake-door, concierge or other' };
207
+ Object.assign(data, { test, method: d.method });
198
208
  } else if (group === 'outcome' && type === 'source') {
199
209
  // the one ask for a goal PMOS cannot read (lib/outcome-judge.js): class C, ✓ adds a task for the PM
200
210
  const d = isObj(input.data) ? input.data : {};
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+ /* repeat-requests.js — how many times an ask was asked before (bet A264, initiative repeat-request-count; proof T126, 2026-11-23).
3
+ *
4
+ * WHY. A PM decides whether to build a customer's or a stakeholder's special ask as a one-off without knowing it was asked before.
5
+ * Proof T126 found 22 of the latest 100 request tickets on a test product are two kinds that repeat (10 monitoring access requests,
6
+ * 12 ad hoc verification tickets), and nothing in PMOS counted them. Here PMOS counts the similar earlier requests of one ask: in the
7
+ * Jira reads it already stores, and in the board's earlier asks.
8
+ *
9
+ * similar(a, b) PURE → bool two word lists ask for the same thing
10
+ * ticketsOf(reads) PURE → [{ key, title, at }] stored readings, each key once, no epics
11
+ * countFor(line, pool, o) PURE → { count, jira, asks, examples: [{ ref, title, kind }], setting, say } say is '' at 0
12
+ * share(tickets) PURE → { tickets, repeating, pct } tickets with 2 or more similar others (the health number)
13
+ * poolOf(root) → [{ key, title, at }] the stored Jira tickets of a repository (cached by the files' times)
14
+ * askPool(asks, self, board) PURE → the board's earlier asks, any state, without the ask itself
15
+ * decorate(root, asks, all, board) → the asks, each with `repeats`
16
+ *
17
+ * THE MATCH. The words lib/tracker-match.js compares (lower case, no common words, no ticket keys, no numbers). Similar when the two
18
+ * share 2 or more words and at least half the words of the shorter one: "Grant Grafana monitoring access to ops" and "Monitoring access
19
+ * for finance" share "monitoring" and "access", half of the shorter. One shared word is never enough.
20
+ * THE LINE. 0 says nothing. 1: "Asked once before: …". 2 or more adds that others want it too, so build it once as a setting.
21
+ *
22
+ * BOUNDARY. No network and no write. It reads the stored Jira reads and the asks it is given.
23
+ */
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const TM = require('./tracker-match.js');
27
+
28
+ const LOG = '[repeat-requests]';
29
+ const EXAMPLES = 3;
30
+ const one = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1).trimEnd() + '…' : t; };
31
+
32
+ /** PURE. a, b: word lists (TM.tokens). */
33
+ function similar(a, b) {
34
+ const A = new Set(a), B = new Set(b);
35
+ if (A.size < 2 || B.size < 2) return false;
36
+ let n = 0; for (const w of A) if (B.has(w)) n++;
37
+ return n >= 2 && n / Math.min(A.size, B.size) >= 0.5;
38
+ }
39
+
40
+ /** PURE. reads: [{ src, snap: { tickets: Map } }] (lib/tracker-match.js storedReads). Each key once; an epic is a body of work, not a request. */
41
+ function ticketsOf(reads) {
42
+ const by = new Map();
43
+ for (const x of reads || []) {
44
+ for (const r of (x && x.snap && x.snap.tickets ? x.snap.tickets.values() : [])) {
45
+ if (!r || !r.key || by.has(r.key) || /^epic$/i.test(String(r.type || '')) || !String(r.summary || '').trim()) continue;
46
+ by.set(r.key, { key: r.key, title: String(r.summary), at: String(r.created || r.resolved || (r.sprint && r.sprint.start) || '') });
47
+ }
48
+ }
49
+ return [...by.values()];
50
+ }
51
+
52
+ /** PURE. The board's earlier asks, in any state, without the ask itself (and without asks of other boards when `board` is given). */
53
+ function askPool(asks, self, board) {
54
+ return (asks || []).filter((a) => a && a.id !== self && (!board || a.board === board) && String(a.line || '').trim())
55
+ .map((a) => ({ ask: a.id, title: String(a.line), at: String(a.at || ''), state: a.state || 'open' }));
56
+ }
57
+
58
+ /** PURE. The line a card shows for a count. '' at 0. */
59
+ function sayOf(r) {
60
+ if (!r || !r.count) return '';
61
+ const names = r.examples.map((x) => (x.kind === 'jira' ? x.ref + ' ' + one(x.title, 60) : 'an earlier ask "' + one(x.title, 60) + '"'));
62
+ const more = r.count - r.examples.length;
63
+ const list = names.join(', ') + (more > 0 ? ` and ${more} more` : '');
64
+ const head = r.count === 1 ? 'Asked once before: ' : `Asked ${r.count} times before: `;
65
+ return head + list + '.' + (r.setting ? ' Others want it too: build it once, as a setting others can use, not a one-off.' : '');
66
+ }
67
+
68
+ /** PURE. line: the ask. pool: { tickets: [{ key, title, at }], asks: [{ ask, title, at }] }. o.max: examples (3). */
69
+ function countFor(line, pool = {}, o = {}) {
70
+ const want = TM.tokens(line);
71
+ const hits = [];
72
+ for (const t of pool.tickets || []) if (similar(want, TM.tokens(t.title))) hits.push({ ref: t.key, title: t.title, kind: 'jira', at: t.at || '' });
73
+ for (const a of pool.asks || []) if (similar(want, TM.tokens(a.title))) hits.push({ ref: a.ask, title: a.title, kind: 'ask', at: a.at || '' });
74
+ hits.sort((a, b) => String(b.at).localeCompare(String(a.at)) || String(a.ref).localeCompare(String(b.ref)));
75
+ const r = { count: hits.length, jira: hits.filter((h) => h.kind === 'jira').length, asks: hits.filter((h) => h.kind === 'ask').length,
76
+ examples: hits.slice(0, o.max || EXAMPLES).map((h) => ({ ref: h.ref, title: one(h.title, 140), kind: h.kind })), setting: hits.length >= 2 };
77
+ r.say = sayOf(r);
78
+ return r;
79
+ }
80
+
81
+ /** PURE. The health number: the tickets that have 2 or more similar others, of all stored tickets. */
82
+ function share(tickets) {
83
+ const tok = (tickets || []).map((t) => TM.tokens(t.title));
84
+ let repeating = 0;
85
+ for (let i = 0; i < tok.length; i++) {
86
+ let n = 0;
87
+ for (let j = 0; j < tok.length && n < 2; j++) if (i !== j && similar(tok[i], tok[j])) n++;
88
+ if (n >= 2) repeating++;
89
+ }
90
+ return { tickets: tok.length, repeating, pct: tok.length ? Math.round((repeating / tok.length) * 100) : null };
91
+ }
92
+
93
+ /* ── the repository ── */
94
+ const cache = new Map(); // root → { sig, tickets }
95
+ /** The stored Jira tickets of a repository. Read again only when a stored read file changed (its name, size or time). */
96
+ function poolOf(root) {
97
+ let sig = '';
98
+ try {
99
+ const dir = require('./jira-tickets.js').jiraDir(root);
100
+ sig = fs.readdirSync(dir).filter((n) => n.endsWith('.md')).sort().map((n) => { const s = fs.statSync(path.join(dir, n)); return n + ':' + s.size + ':' + s.mtimeMs; }).join('|');
101
+ } catch { return []; }
102
+ const c = cache.get(root);
103
+ if (c && c.sig === sig) return c.tickets;
104
+ const tickets = ticketsOf(TM.storedReads(root));
105
+ cache.set(root, { sig, tickets });
106
+ return tickets;
107
+ }
108
+
109
+ /** The asks, each with its `repeats` (countFor). all: every ask of the board's ledger, any state. A failed read gives no count. */
110
+ function decorate(root, asks, all, board) {
111
+ let tickets = [];
112
+ try { tickets = poolOf(root); } catch { tickets = []; }
113
+ return (asks || []).map((a) => {
114
+ try { return { ...a, repeats: countFor(a.line, { tickets, asks: askPool(all, a.id, board || a.board) }) }; } catch { return a; }
115
+ });
116
+ }
117
+
118
+ /** One `[repeat-requests]` line (the health log of repeat-request-count). */
119
+ function log(fields) {
120
+ console.log(LOG + ' ' + Object.entries(fields).map(([k, v]) => `${k}=${v == null ? 'none' : typeof v === 'string' && /\s/.test(v) ? JSON.stringify(v) : v}`).join(' '));
121
+ }
122
+
123
+ module.exports = { LOG, EXAMPLES, similar, ticketsOf, askPool, countFor, sayOf, share, poolOf, decorate, log };
@@ -98,6 +98,7 @@ const MODULES = Object.freeze([
98
98
  'routes-proposals', // batch 12 items 2, 3 and 4: everything Claude proposes on an initiative, under its one ✦ (proposals.jsonl; page-press POST)
99
99
  'routes-autonomy', // D106: what agents did by themselves (the Done group, 14 days), its Undo, and the demotions Home says once (autonomy.jsonl)
100
100
  'routes-your-move', // workspace grill W3: Your move's overdue outcome verdicts (drafted from Jira) and the first key result with no reading (GET)
101
+ 'routes-standing-rules', // standing-rules-list (A470): the standing rules PMOS keeps, with edit, retire and bring back (memory + standing-rules.jsonl)
101
102
  'routes-lab', // idle lab (build U): Intelligence › Lab, the compare view, the specimen files and the Lab's own ✦ (idle-lab.jsonl; page-press POST)
102
103
  'routes-loose', // batch 13 item 3: Claude's clean-up of Home's "Not in an initiative" under the group's ✦ (loose-props/; page-press POST)
103
104
  'routes-workflows', // workflows-per-initiative (D99): the workflow library, save, copy, archive and the chat's draft (workflows.jsonl; page-press POST)
@@ -3,6 +3,9 @@
3
3
  * POST /api/intake/draft { line, acknowledged? } → { ok, draft } draft.kind and draft.kind_cue: the kind of work the name reads as
4
4
  * (lib/work-kind.js fromName; kind_cue '' when the name tells nothing,
5
5
  * and then the kind is the PM's role, setting work.role)
6
+ * ws (board, ask): draft.repeats, the similar earlier requests (repeat-request-count)
7
+ * POST /api/ask-repeats { ws, board? } → { ok, repeats: { <ask id>: { count, jira, asks, examples, setting, say } } } the open asks'
8
+ * similar earlier requests (repeat-request-count, lib/repeat-requests.js)
6
9
  * Drafts only. Creating the initiative stays with createInitiative, which refuses an unanchored create. */
7
10
  const path = require('path');
8
11
  const guard = require('./pm-guard.js');
@@ -12,9 +15,49 @@ const KS = require('./kind-scope.js');
12
15
 
13
16
  const ROOT = path.resolve(__dirname, '..', '..');
14
17
 
18
+ /** repeat-request-count (A264): how many times the line was asked before, in the workspace's stored Jira reads and its board's earlier
19
+ * asks (lib/repeat-requests.js). Only with `ws`; null when that workspace is not known or its reads fail. */
20
+ function repeatsOf(ctx, body) {
21
+ if (typeof body.ws !== 'string' || !body.ws || !ctx.getWs) return null;
22
+ try {
23
+ const w = ctx.getWs(body.ws);
24
+ if (!w || w.id !== body.ws || !w.root) return null;
25
+ const all = asksOf(ctx, w);
26
+ const RR = require('./repeat-requests.js');
27
+ const board = typeof body.board === 'string' && body.board ? body.board : null;
28
+ return RR.countFor(body.line, { tickets: RR.poolOf(w.root), asks: RR.askPool(all, typeof body.ask === 'string' ? body.ask : null, board) });
29
+ } catch { return null; }
30
+ }
31
+
32
+ /** POST /api/ask-repeats { ws, board } → { ok, repeats: { <ask id>: countFor result } } for the board's open asks (repeat-request-count). */
33
+ async function askRepeats(req, res, ctx) {
34
+ const got = await ctx.readJson(req);
35
+ if (!got.ok) { ctx.json(res, { ok: false, error: 'invalid JSON body' }, 400); return true; }
36
+ const body = got.body || {};
37
+ const g = guard.requirePagePress(req, body);
38
+ if (!g.ok) { ctx.json(res, { ok: false, error: g.error }, g.status); return true; }
39
+ const w = typeof body.ws === 'string' && body.ws && ctx.getWs ? ctx.getWs(body.ws) : null;
40
+ if (!w || w.id !== body.ws || !w.root) { ctx.json(res, { ok: false, error: 'ws names no registered workspace' }, 404); return true; }
41
+ const board = typeof body.board === 'string' && body.board ? body.board : null;
42
+ const RR = require('./repeat-requests.js');
43
+ const all = asksOf(ctx, w);
44
+ const open = all.filter((a) => a.state === 'open' && (!board || a.board === board));
45
+ const repeats = {};
46
+ for (const a of RR.decorate(w.root, open, all, null)) if (a.repeats) repeats[a.id] = a.repeats;
47
+ const n = Object.values(repeats).filter((r) => r.count > 0).length;
48
+ RR.log({ root: w.root, board: board || 'all', open: open.length, repeated: n });
49
+ ctx.json(res, { ok: true, repeats });
50
+ return true;
51
+ }
52
+ /** Every ask of a workspace's boards ledger, any state. [] when it cannot be read. */
53
+ function asksOf(ctx, w) {
54
+ try { const RB = require('./routes-boards.js'); return [...require(repoScript('boards.js')).fold(RB.readLedger(ctx, w)).asks.values()]; } catch { return []; }
55
+ }
56
+
15
57
  module.exports = {
16
- prefixes: ['/api/intake'],
58
+ prefixes: ['/api/intake', '/api/ask-repeats'],
17
59
  handle: async (req, res, url, ctx) => {
60
+ if (req.method === 'POST' && url.pathname === '/api/ask-repeats') return askRepeats(req, res, ctx);
18
61
  if (req.method !== 'POST' || url.pathname !== '/api/intake/draft') return false;
19
62
  const got = await ctx.readJson(req);
20
63
  if (!got.ok) { ctx.json(res, { ok: false, error: 'invalid JSON body' }, 400); return true; }
@@ -27,7 +70,7 @@ module.exports = {
27
70
  let role = 'product'; try { role = require('./settings-store.js').get(ctx.runtimeDir, 'work.role'); } catch { role = 'product'; }
28
71
  const k = KS.prePick(body.line, draft && draft.lane, role);
29
72
  if (!k.cue && k.kind !== 'product') console.log(KS.LOG + ' intake kind ' + k.kind + ' from the role');
30
- ctx.json(res, { ok: true, draft: { ...draft, kind: k.kind, kind_cue: k.cue } });
73
+ ctx.json(res, { ok: true, draft: { ...draft, kind: k.kind, kind_cue: k.cue, repeats: repeatsOf(ctx, body) } });
31
74
  return true;
32
75
  },
33
76
  };
@@ -13,6 +13,8 @@
13
13
  * POST /api/lab/keep { ws, id } → { ok, batch, said } ✓ on a Lab ✦: start keeps it and starts the initiative on its board
14
14
  * POST /api/lab/drop { ws, id, why? } → { ok, batch } ✕, with the PM's reason when given
15
15
  * POST /api/lab/undo { ws, batch } → { ok } Undo of a keep or a drop (a started initiative stays: close it on the Board)
16
+ * A `retire` ✦ (lib/standing-rules.js, bet A470) is filed on GET /api/lab once a month when standing rules have not fired in 30 days;
17
+ * its ✓ retires them (each memory entry leaves) and its Undo brings them back.
16
18
  * POST /api/lab/round { ws?, board?, ini, brief, base?, dirs?, propose? } → the live round (lib/live-round.js): `pmos lab round` starts one,
17
19
  * or with propose: true files its ✦ ask. No page press needed (D98); it writes no record.
18
20
  * Prototype by chatting (initiative live-round-iterative): the compare view of a live round carries its version's companions as data
@@ -120,6 +122,8 @@ const READS = {
120
122
  const w = wsOf(ctx, url.searchParams.get('ws')); if (!w) return fail(ctx, res, 404, 'no such workspace');
121
123
  const dir = dirOf(ctx, w); if (!dir) { ctx.json(res, { ok: true, lab: null }); return true; }
122
124
  const now = Date.now(), T = titles(w);
125
+ // the monthly ask on standing rules that have not fired in 30 days (lib/standing-rules.js): filed here, at most once in 30 days
126
+ require('./standing-rules.js').filePrompt(w.root, dir, { now });
123
127
  const lab = LAB.labOf({ P: PR.read(dir), L: LAB.read(dir), extra: others(ctx, w, dir, T, now), now, titleOf: (ini) => (T.get(ini) || {}).title || '' });
124
128
  ctx.json(res, { ok: true, lab });
125
129
  return true;
@@ -198,6 +202,15 @@ const WRITES = {
198
202
  if (!r.ok) return fail(ctx, res, 409, 'The rule was not saved: ' + r.error);
199
203
  wrote.push({ op: 'memory', text: p.title }); said = 'PMOS will follow this from now on.';
200
204
  }
205
+ if (p.type === 'retire') {
206
+ // the monthly ask on quiet standing rules (lib/standing-rules.js, bet A470): each named rule leaves memory; Undo brings it back
207
+ const by = humanOf(g.actor);
208
+ if (!by) return fail(ctx, res, 403, 'Only the PM retires a standing rule');
209
+ const SR = require('./standing-rules.js');
210
+ for (const id of (p.data && p.data.ids) || []) { const r = SR.retire(w.root, { id, by }); if (r.ok) wrote.push({ op: 'retire', id, text: r.rule.text }); }
211
+ SR.use(w.root, { op: 'keep', id: p.id, by });
212
+ said = wrote.length === 1 ? 'Retired 1 standing rule. Bring it back in Settings.' : 'Retired ' + wrote.length + ' standing rules. Bring them back in Settings.';
213
+ }
201
214
  const batch = PR.newBatch();
202
215
  LAB.append(dir, g.actor, { kind: 'keep', id: p.id, batch, wrote });
203
216
  ctx.json(res, { ok: true, batch, said });
@@ -210,6 +223,7 @@ const WRITES = {
210
223
  const batch = PR.newBatch();
211
224
  LAB.append(dir, g.actor, { kind: 'drop', id: p.id, batch, ...(why ? { why } : {}) });
212
225
  if (why) require('./corrections-memory.js').remember(w.root, { what: 'an idle-lab result', why, source: 'lab:' + p.id });
226
+ if (p.type === 'retire') require('./standing-rules.js').use(w.root, { op: 'drop', id: p.id, by: humanOf(g.actor) || undefined });
213
227
  ctx.json(res, { ok: true, batch });
214
228
  return true;
215
229
  },
@@ -222,6 +236,11 @@ const WRITES = {
222
236
  const r = ruleWrite(w.root, { op: 'remove', old: x.text, by: humanOf(g.actor) || 'agent:corrections' });
223
237
  if (!r.ok && !/no (?:entry|match)|not found/i.test(String(r.error))) return fail(ctx, res, 409, 'The rule was not removed: ' + r.error);
224
238
  }
239
+ // retired standing rules (the monthly ask): bring each back
240
+ for (const k of F.kept) if (k.batch === b) for (const x of k.wrote) if (x.op === 'retire' && x.text) {
241
+ const r = require('./standing-rules.js').restore(w.root, { id: x.text, by: humanOf(g.actor) || 'agent:standing-rules' });
242
+ if (!r.ok && !/no retired rule/.test(String(r.error))) return fail(ctx, res, 409, 'The rule was not brought back: ' + r.error);
243
+ }
225
244
  LAB.append(dir, g.actor, { kind: 'undo', batch: b });
226
245
  ctx.json(res, { ok: true });
227
246
  return true;
@@ -145,6 +145,7 @@ function undoCore(ctx, p, g, id) {
145
145
  for (const pid of k.ids) { const pp = F.props.get(pid); if (pp && pp.group === 'outcome' && pp.type === 'verdict') PR.append(dir, { by: 'pmos:outcomes' }, { kind: 'drop', ini: k.ini, sig: PR.sigOf(pp), id: pid, group: 'outcome', type: 'verdict' }); }
146
146
  continue;
147
147
  }
148
+ else if (w.op === 'test') { const r2 = require('./smallest-test.js').undoTest(p.w.root, { initiative: k.ini, at: w.at, by: (g.actor && g.actor.by) || 'pm', via: 'ui' }); if (r2.ok) back++; else kept++; continue; } // the smallest test (bet A472)
148
149
  else if (w.op === 'outcome') { const r2 = require('./initiative-writer.js').restoreOutcome(p.w.root, k.ini, w.from || {}, w.to || {}, { actor: g.actor }); if (r2.ok && !r2.kept) back++; else kept++; continue; } // a record edited since keeps its edit
149
150
  if (r && r.body && r.body.ok) back++; else kept++;
150
151
  }
@@ -368,6 +369,18 @@ function applyOne(ctx, p, g, f, ini, x, choices, outbox) {
368
369
  if (r.ok) add({ op: 'verdict', at: r.line.at, disposition: d.disposition, horizon: d.horizon });
369
370
  else x.failed = r.error;
370
371
  }
372
+ } else if (x.group === 'outcome' && x.type === 'test') {
373
+ // the smallest test before a build (bet A472; lib/smallest-test.js recordTest). Class B: ✓ records it as planned, Undo takes the line back.
374
+ // A bet that has a test already (recorded another way) keeps it: nothing is written.
375
+ const ST = require('./smallest-test.js'), d = x.data || {};
376
+ const S = ST.testScan(p.w.root), it = S.subjects.find((y) => y.id === ini);
377
+ if (!it) x.failed = 'This initiative is not here any more, or it is stopped.';
378
+ else if (!it.test) {
379
+ const by = g.actor && g.actor.by && g.actor.by !== 'agent:auto' ? g.actor.by : 'agent:outcomes';
380
+ const r = ST.recordTest(p.w.root, { initiative: ini, method: d.method, test: d.test, result: 'planned', by, via: (g.actor && g.actor.via) || 'ui' });
381
+ if (r.ok) add({ op: 'test', at: r.line.at });
382
+ else x.failed = r.error;
383
+ }
371
384
  } else if (x.group === 'outcome' && x.type === 'source') {
372
385
  // the one ask for a goal PMOS cannot read (lib/outcome-judge.js). Class C: only the PM's ✓ reaches here. It adds a task for the PM.
373
386
  const d = x.data || {}, title = `Connect the source of "${String(d.goal || 'the goal').slice(0, 80)}", or pick another number`.slice(0, 200);
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+ /* routes-standing-rules.js — the standing rules PMOS keeps for a product, read, edited and retired (bet A470; lib/standing-rules.js).
3
+ *
4
+ * GET /api/standing-rules?ws=<id> → { ok, rules, retired, quiet } Settings › How PMOS decides › Standing rules
5
+ * POST /api/standing-rules { ws, op: edit, id, text } → { ok, rule } new words for a rule (its source stays)
6
+ * POST /api/standing-rules { ws, op: retire | restore, id } → { ok, rule } take a rule out of every run, or bring a retired one back
7
+ *
8
+ * A POST from a page passes pm-guard requirePagePress; one with no Origin is the chat's agent (`pmos rules`, D98), which keeps its own name
9
+ * on the memory line. A product with no memory answers an empty list. Each use is one line in standing-rules.jsonl (the health number). */
10
+ const guard = require('./pm-guard.js');
11
+ const SR = require('./standing-rules.js');
12
+
13
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
14
+ const fail = (ctx, res, status, error) => { ctx.json(res, { ok: false, error }, status); return true; };
15
+ function wsOf(ctx, id) { let w = null; try { w = ctx.getWs(id || null); } catch { w = null; } return w && (!id || w.id === id) ? w : null; }
16
+ const humanOf = (actor) => { const by = String((actor && actor.by) || ''); return /^pm:[A-Za-z0-9_-]{1,40}$/.test(by) ? 'human:' + by.slice(3) : /^human:/.test(by) ? by : null; };
17
+
18
+ module.exports = {
19
+ prefixes: ['/api/standing-rules'],
20
+ handle: async (req, res, url, ctx) => {
21
+ if (url.pathname !== '/api/standing-rules') return fail(ctx, res, 404, 'not found');
22
+ if (req.method === 'GET') {
23
+ const w = wsOf(ctx, url.searchParams.get('ws')); if (!w) return fail(ctx, res, 404, 'no such workspace');
24
+ const L = SR.listOf(w.root);
25
+ if (url.searchParams.get('view') === '1') SR.use(w.root, { op: 'view' });
26
+ ctx.json(res, { ok: true, ...L });
27
+ return true;
28
+ }
29
+ if (req.method !== 'POST') return fail(ctx, res, 405, 'GET or POST only');
30
+ const got = await ctx.readJson(req);
31
+ if (!got.ok || !isObj(got.body)) return fail(ctx, res, 400, 'the body must be a JSON object');
32
+ const b = got.body;
33
+ let by;
34
+ if (req.headers.origin) { const g = guard.requirePagePress(req, b); if (!g.ok) return fail(ctx, res, g.status, g.error); by = humanOf(g.actor) || 'pm:page'; }
35
+ else by = /^(pm|agent):[\w.:-]{1,80}$/.test(String(b.by || '')) ? b.by : 'agent:cli';
36
+ const w = wsOf(ctx, typeof b.ws === 'string' && b.ws ? b.ws : null); if (!w) return fail(ctx, res, 404, 'no such workspace');
37
+ const id = typeof b.id === 'string' ? b.id : '';
38
+ const r = b.op === 'edit' ? SR.edit(w.root, { id, text: b.text, by }) : b.op === 'retire' ? SR.retire(w.root, { id, by })
39
+ : b.op === 'restore' ? SR.restore(w.root, { id, by }) : { ok: false, error: 'op is edit, retire or restore' };
40
+ if (!r.ok) return fail(ctx, res, /^op is/.test(r.error) || /needs its text/.test(r.error) ? 400 : 409, r.error);
41
+ ctx.json(res, r);
42
+ return true;
43
+ },
44
+ };
@@ -16,7 +16,8 @@
16
16
  * DONE (C2, board CsD): what an agent kept by itself in the last 14 days, one line per batch with its Undo (lib/done-feed.js).
17
17
  * QUESTIONS (act-alone-only-with-a-source): { day, questions: [lib/question-batch.js question], later } — the changes PMOS holds for want
18
18
  * of a source, one question per owner and initiative, the PM's first; the list is fixed for the day (one line in question-days.jsonl).
19
- * On the same card (dry-run-tickets-before-build): the dry-run gaps of drafted tickets and the outside sign-offs with no answer.
19
+ * On the same card (dry-run-tickets-before-build): the dry-run gaps of drafted tickets and the outside sign-offs with no answer, and (bet A472)
20
+ * each smallest test that was named and has no result yet.
20
21
  * DEFAULTS (default-decisions-with-a-deadline, lib/default-decisions.js): each question carries `default` ({ choice, due, n, say } | null),
21
22
  * `waits` (why it has no default | null), `waiting` (days on the list) and `cost` (A27: what the wait holds up | null). The read takes the
22
23
  * defaults due today (one batch each, with Undo in "PMOS did"), and `taken` lists them. A dry-run gap or a sign-off never defaults. */
@@ -103,6 +104,11 @@ function asksOf(root, now = Date.now()) {
103
104
  const title = (JT.recordFm(root, ini) || {}).title || ini;
104
105
  for (const g of JT.dryRunGaps(root, ini)) out.push({ ini, title, id: `dry:${ini}:${g.ticket}:${g.n}`, text: `Ticket ${g.ticket}: ${/[?.]$/.test(g.q) ? g.q : g.q + '?'}` });
105
106
  }
107
+ // smallest test first (bet A472): a ranked bet's test that was named and has no result yet; the chat records it (pmos outcomes test)
108
+ try {
109
+ const ST = require('./smallest-test.js');
110
+ for (const t of ST.waitingTestsOf(root)) out.push({ ini: t.id, title: t.title, id: `test:${t.id}:${t.at}`, text: `What did its smallest test show? ${t.test}` });
111
+ } catch { /* no tests to ask about */ }
106
112
  for (const p of SO.partsOf(SO.list(SO.fileOf(JT.stateDirOf(root)), { open: true }), now)) {
107
113
  out.push({ ini: p.ini, title: (JT.recordFm(root, p.ini) || {}).title || p.ini, id: p.id, text: p.text });
108
114
  }
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+ /* rules-cli.js — `pmos rules`: the standing rules PMOS keeps for this product, from the chat or a terminal (bet A470; lib/standing-rules.js).
3
+ *
4
+ * pmos rules [list] [--json] [--root <dir>] every standing rule, numbered: where it came from, times fired, last fired; then Retired
5
+ * pmos rules edit <n> --text "…" new words for rule n (its source stays)
6
+ * pmos rules retire <n> take rule n out of every run (Settings › How PMOS decides › Standing rules has Bring back)
7
+ * pmos rules restore <n> bring back retired rule n (the number in the Retired list)
8
+ * pmos rules count [--root <dir>] uses of the list in the last 7 days (the health number; last line)
9
+ *
10
+ * It writes the product's memory and standing-rules.jsonl directly, the same writer the page's route uses, so the page shows the change
11
+ * on its next read. The line it writes names the agent (D98). Exit codes: 0 done, 1 refused, 2 usage. */
12
+ const path = require('path');
13
+ const { execFileSync } = require('child_process');
14
+ const SR = require('./standing-rules.js');
15
+ const K = require('./correction-kinds.js');
16
+
17
+ const USAGE = [
18
+ 'pmos rules [list] [--json] the standing rules PMOS keeps for this product, numbered, then Retired',
19
+ 'pmos rules edit <n> --text "…" new words for rule n',
20
+ 'pmos rules retire <n> take rule n out of every run',
21
+ 'pmos rules restore <n> bring back retired rule n',
22
+ 'pmos rules count uses of the list in the last 7 days (last line)',
23
+ ' every command: [--root <dir>]',
24
+ ];
25
+ function repoRoot(cwd) {
26
+ try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; }
27
+ catch { return cwd; }
28
+ }
29
+ const day = (at) => String(at || '').slice(0, 10);
30
+
31
+ function run(argv, o = {}) {
32
+ const say = o.say || ((l) => process.stdout.write(l + '\n'));
33
+ const args = argv.slice(1), flags = {}, pos = [];
34
+ for (let i = 0; i < args.length; i++) {
35
+ const a = args[i];
36
+ if (a === '--root' || a === '--text' || a === '--by') flags[a.slice(2)] = args[++i];
37
+ else if (a === '--json') flags.json = true;
38
+ else pos.push(a);
39
+ }
40
+ const cmd = pos[0] || 'list';
41
+ if (cmd === 'help' || cmd === '--help') { USAGE.forEach((l) => say(l)); return 0; }
42
+ const root = path.resolve(flags.root || repoRoot(o.cwd || process.cwd()));
43
+ const by = /^(pm|agent):[\w.:-]{1,80}$/.test(String(flags.by || '')) ? flags.by : 'agent:cli';
44
+ const L = SR.listOf(root);
45
+ if (cmd === 'list') {
46
+ if (flags.json) { say(JSON.stringify(L)); return 0; }
47
+ if (!L.rules.length && !L.retired.length) { say('No standing rules yet. When you correct the same kind of thing 3 times, PMOS offers one in the Lab.'); return 0; }
48
+ L.rules.forEach((r, i) => {
49
+ say(`${i + 1}. ${r.text}`);
50
+ say(` from ${r.from.n} of your corrections${r.from.latest ? ', latest "' + r.from.latest + '"' : ''} · kept ${day(r.keptAt)} · fired ${r.fired} ${r.fired === 1 ? 'time' : 'times'}${r.lastFired ? ', last ' + day(r.lastFired) : ''}${r.quiet ? ' · not fired in 30 days' : ''}`);
51
+ });
52
+ if (L.retired.length) { say('Retired:'); L.retired.forEach((r, i) => say(` R${i + 1}. ${r.text} (retired ${day(r.at)})`)); }
53
+ return 0;
54
+ }
55
+ if (cmd === 'count') {
56
+ const n = SR.count(SR.readLines(K.stateDir(root)));
57
+ if (flags.json) say(JSON.stringify({ last7: n })); else say(String(n));
58
+ return 0;
59
+ }
60
+ if (!['edit', 'retire', 'restore'].includes(cmd)) { say(`✗ ${cmd} is not a command of pmos rules`); USAGE.forEach((l) => say(l)); return 2; }
61
+ const raw = String(pos[1] || '').replace(/^R/i, ''), n = Number(raw);
62
+ const pool = cmd === 'restore' ? L.retired : L.rules;
63
+ if (!Number.isInteger(n) || n < 1 || n > pool.length) { say(`✗ say which rule by its number in \`pmos rules\`${cmd === 'restore' ? ' (the R number under Retired)' : ''}`); return 2; }
64
+ const x = pool[n - 1];
65
+ if (cmd === 'edit' && !String(flags.text || '').trim()) { say('✗ pmos rules edit <n> --text "the new words"'); return 2; }
66
+ const r = cmd === 'edit' ? SR.edit(root, { id: x.id, text: flags.text, by }) : cmd === 'retire' ? SR.retire(root, { id: x.id, by }) : SR.restore(root, { id: x.text, by });
67
+ if (!r.ok) { say('✗ ' + r.error); return 1; }
68
+ const staged = r.staged ? ' It waits for your approval first.' : '';
69
+ say(cmd === 'edit' ? `✓ rule ${n} now reads: ${r.rule.text}.${staged}` : cmd === 'retire' ? `✓ retired: ${r.rule.text}. Bring it back with \`pmos rules restore\` or in Settings › How PMOS decides.${staged}`
70
+ : `✓ back: ${r.rule.text}. Every run reads it again.${staged}`);
71
+ return 0;
72
+ }
73
+
74
+ module.exports = { run, USAGE, COMMANDS: { rules: ['list', 'edit', 'retire', 'restore', 'count'] } };