create-pmos 0.538.0 → 0.540.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +39 -39
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/workspace/changelog.json +38 -0
- package/workspace/guide/agent-capabilities.md +9 -5
- package/workspace/guide/agents-act.md +68 -0
- package/workspace/guide/index.md +2 -1
- package/workspace/guide/initiative-driver.md +16 -7
- package/workspace/guide/settings.md +1 -1
- package/workspace/guide/today.md +8 -4
- package/workspace/guide/workflows.md +14 -12
- package/workspace/ini-workflow-test.js +1 -1
- package/workspace/lib/agent-inbox.js +2 -2
- package/workspace/lib/ai-cli.js +12 -1
- package/workspace/lib/ai-guard.js +16 -6
- package/workspace/lib/auto-keep.js +33 -0
- package/workspace/lib/autonomy-cli.js +53 -0
- package/workspace/lib/autonomy.js +234 -0
- package/workspace/lib/bg-queue.js +2 -1
- package/workspace/lib/driver-cli.js +26 -10
- package/workspace/lib/driver-decide.js +76 -8
- package/workspace/lib/driver.js +15 -4
- package/workspace/lib/goal-loop.js +221 -0
- package/workspace/lib/headless.js +75 -1
- package/workspace/lib/job-graph.js +5 -0
- package/workspace/lib/loop-cli.js +84 -0
- package/workspace/lib/pm-lines-needs.js +3 -0
- package/workspace/lib/pmos-verbs.js +6 -1
- package/workspace/lib/route-modules.js +1 -0
- package/workspace/lib/routes-autonomy.js +95 -0
- package/workspace/lib/routes-proposals.js +101 -46
- package/workspace/lib/run-tokens.js +70 -0
- package/workspace/lib/stage-tools.js +11 -1
- package/workspace/lib/today-cli.js +57 -4
- package/workspace/lib/today.js +2 -8
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/cozy-news.js +1 -1
- package/workspace/public/pm/cozy-onboard.js +2 -2
- package/workspace/public/pm/cozy-settings.js +42 -11
- package/workspace/public/pm/home-app.js +10 -1
- package/workspace/public/pm/home-around.js +2 -2
- package/workspace/public/pm/ini-wf.js +3 -3
- package/workspace/public/pm/wf-page.css +26 -15
- package/workspace/public/pm/wf-page.js +96 -72
- package/workspace/public/premium-workflows.html +8 -23
- package/workspace/replaced-tests.json +17 -0
- package/workspace/server.js +33 -16
- package/workspace/test-lists/full-autonomy.json +11 -0
- package/workspace/test-run.js +3 -0
- package/workspace/workflows-setup-test.js +50 -50
|
@@ -7,13 +7,16 @@
|
|
|
7
7
|
*
|
|
8
8
|
* THE PROPOSAL (the only thing a job may file):
|
|
9
9
|
* { id, title, say, confidence: 'high'|'medium'|'low'|'none',
|
|
10
|
-
* claims: [{ text, sources: [{ label, ref, quote }] }], data
|
|
10
|
+
* claims: [{ text, sources: [{ label, ref, quote }] }], data?, cls?: 'A'|'B'|'C' }
|
|
11
|
+
* cls (D106): A reversible upkeep, B reversible judgment, C seen by others or not reversible. Absent is C.
|
|
11
12
|
* ref is `path:line` relative to the repository root, or `state:<file>:line` for a ledger in the job's state folder. Other refs
|
|
12
13
|
* (`jira:KEY`, a URL) are kept as context but are unverified. confidence 'none' is "no record": claims may be empty, and that is a
|
|
13
14
|
* valid, complete answer.
|
|
14
15
|
*
|
|
15
16
|
* THE RULES (check):
|
|
16
|
-
* propose-only a key named write, apply, ops, patch, send, command or exec anywhere in the proposal rejects it
|
|
17
|
+
* propose-only a key named write, apply, ops, patch, send, command or exec anywhere in the proposal rejects it, with ONE exception
|
|
18
|
+
* (D106): a class A or B proposal may carry `data.apply`, the change the job applies by itself with Undo. A class C
|
|
19
|
+
* proposal (or one with no class) with any write key is still dropped, and so is a write key anywhere but data.apply
|
|
17
20
|
* every claim at least 1 verified source: the quote (12+ characters) is found within ±2 lines of ref, case and spacing ignored
|
|
18
21
|
* honest 'high' needs 2 or more distinct verified refs; 'none' must have no claims
|
|
19
22
|
* bounded at most `max` proposals per run (default 3); the rest are dropped, in the order given
|
|
@@ -46,6 +49,7 @@ const QUOTE_MIN = 12;
|
|
|
46
49
|
const NEAR = 2;
|
|
47
50
|
const CONF = ['high', 'medium', 'low', 'none'];
|
|
48
51
|
const WRITE_KEYS = new Set(['write', 'apply', 'ops', 'patch', 'send', 'command', 'exec']);
|
|
52
|
+
const CLASSES = ['A', 'B', 'C'];
|
|
49
53
|
const JOB_ID = /^[a-z][a-z0-9-]{1,40}$/;
|
|
50
54
|
const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/;
|
|
51
55
|
|
|
@@ -129,8 +133,13 @@ function writeKey(v, depth = 0) {
|
|
|
129
133
|
function check(p, { root, stateDir, cache = new Map() } = {}) {
|
|
130
134
|
const errors = [];
|
|
131
135
|
if (!p || typeof p !== 'object' || Array.isArray(p)) return { ok: false, p: null, errors: ['a proposal must be an object'] };
|
|
132
|
-
const
|
|
133
|
-
if (
|
|
136
|
+
const cls = p.cls == null ? 'C' : String(p.cls);
|
|
137
|
+
if (!CLASSES.includes(cls)) errors.push('cls is A, B or C');
|
|
138
|
+
// D106: only a class A or B proposal may carry data.apply; nothing inside data.apply may name a send, a command or an exec
|
|
139
|
+
const applyOk = (cls === 'A' || cls === 'B') && p.data && typeof p.data === 'object' && !Array.isArray(p.data) && p.data.apply && typeof p.data.apply === 'object';
|
|
140
|
+
const scan = applyOk ? { ...p, data: Object.fromEntries(Object.entries(p.data).filter(([k]) => k !== 'apply')) } : p;
|
|
141
|
+
const wk = writeKey(scan) || (applyOk ? ['send', 'command', 'exec'].find((k) => JSON.stringify(p.data.apply).includes(`"${k}"`)) : null);
|
|
142
|
+
if (wk) errors.push(`propose-only: the key "${wk}" names a write${cls === 'C' ? ' (class C stays propose-only)' : ''}`);
|
|
134
143
|
const id = String(p.id || '').trim();
|
|
135
144
|
if (!ID.test(id)) errors.push('id is missing or has characters other than letters, digits and . _ : -');
|
|
136
145
|
const title = one(p.title, 200), say = one(p.say, 1200);
|
|
@@ -168,7 +177,7 @@ function check(p, { root, stateDir, cache = new Map() } = {}) {
|
|
|
168
177
|
if (confidence === 'high' && verifiedRefs.size < 2) errors.push('confidence high needs 2 or more distinct verified sources');
|
|
169
178
|
const data = p.data && typeof p.data === 'object' && !Array.isArray(p.data) ? p.data : undefined;
|
|
170
179
|
if (errors.length) return { ok: false, p: null, errors };
|
|
171
|
-
return { ok: true, p: { id, title, say, confidence, claims, ...(data ? { data } : {}) }, errors: [] };
|
|
180
|
+
return { ok: true, p: { id, title, say, confidence, claims, ...(data ? { data } : {}), ...(p.cls != null ? { cls } : {}) }, errors: [] };
|
|
172
181
|
}
|
|
173
182
|
|
|
174
183
|
/* ── audit ───────────────────────────────────────────────────────────────────────────────── */
|
|
@@ -232,7 +241,8 @@ function negatives(p) {
|
|
|
232
241
|
{ const q = clone(); first(q).quote = 'this sentence was never written anywhere in the sources ' + Date.now(); out.push({ name: 'a fabricated quote is dropped', p: q }); }
|
|
233
242
|
{ const q = clone(); q.claims[0].sources = []; out.push({ name: 'a claim with no source is dropped', p: q }); }
|
|
234
243
|
{ const q = clone(); first(q).ref = '../../etc/passwd:1'; out.push({ name: 'a ref outside the repository is dropped', p: q }); }
|
|
235
|
-
{ const q = clone(); q.data = { ...(q.data || {}), apply: { op: 'set' } }; out.push({ name: 'a write key is dropped', p: q }); }
|
|
244
|
+
{ const q = clone(); q.cls = 'C'; q.data = { ...(q.data || {}), apply: { op: 'set' } }; out.push({ name: 'a class C proposal with a write key is dropped', p: q }); }
|
|
245
|
+
{ const q = clone(); q.cls = 'B'; q.send = { to: 'someone' }; out.push({ name: 'a write key outside data.apply is dropped, whatever the class', p: q }); }
|
|
236
246
|
return out;
|
|
237
247
|
}
|
|
238
248
|
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* auto-keep.js — the ✦ half of D106 ("Full autonomy now"): after the proposal runs, every open class A or B ✦ proposal of a lead
|
|
3
|
+
* workspace is applied by itself, one batch each, with Undo (lib/routes-proposals.js autoKeep, lib/autonomy.js). A workspace is
|
|
4
|
+
* read again only when its proposals ledger changed. `pmos ai off` and PMOS_AUTONOMY=off stop it (autonomy.killed).
|
|
5
|
+
*
|
|
6
|
+
* create({ workspaces, isLead, stateDirFor, proposalCtx, settingsDir, env?, warn? }) → { tick() }
|
|
7
|
+
*/
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
|
|
11
|
+
function create({ workspaces, isLead, stateDirFor, proposalCtx, settingsDir, env = process.env, warn = () => {} }) {
|
|
12
|
+
const seen = new Map();
|
|
13
|
+
const mtimeOf = (dir) => { try { return fs.statSync(path.join(dir, 'proposals.jsonl')).mtimeMs; } catch { return null; } };
|
|
14
|
+
function tick() {
|
|
15
|
+
if (require('./autonomy.js').killed({ env, settingsDir: settingsDir() })) return;
|
|
16
|
+
const D = require('./driver.js');
|
|
17
|
+
const RP = require('./routes-proposals.js');
|
|
18
|
+
for (const w of workspaces()) {
|
|
19
|
+
try {
|
|
20
|
+
if (!isLead(w)) continue;
|
|
21
|
+
const dir = stateDirFor(w); if (!dir) continue;
|
|
22
|
+
const mt = mtimeOf(dir);
|
|
23
|
+
if (mt == null || seen.get(w.id) === mt) continue;
|
|
24
|
+
const state = D.fold(D.readLines(D.ledgerFile(D.stateDirOf(w.root) || dir)));
|
|
25
|
+
RP.autoKeep(proposalCtx(), w, { modeOf: (board) => D.modeOf(state, board) });
|
|
26
|
+
seen.set(w.id, mtimeOf(dir));
|
|
27
|
+
} catch (e) { warn('auto keep tick', e); }
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return { tick };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { create };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* autonomy-cli.js — `pmos autonomy`: what agents do by themselves (D106, lib/autonomy.js).
|
|
3
|
+
*
|
|
4
|
+
* pmos autonomy status [--json] [--root <dir>] the changes applied by agents in the last 14 days, and the jobs back to propose
|
|
5
|
+
* pmos autonomy restore <job> [--product <ws>] end a job's demotion early (PM or agent, D98)
|
|
6
|
+
*
|
|
7
|
+
* Undo a change on its page, or with `pmos driver undo <proposal>` for a Driver change. Exit codes: 0 done, 1 refused, 2 usage. */
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const { execFileSync } = require('child_process');
|
|
10
|
+
const A = require('./autonomy.js');
|
|
11
|
+
const D = require('./driver.js');
|
|
12
|
+
const actorLib = require('./actor.js');
|
|
13
|
+
|
|
14
|
+
const COMMANDS = { autonomy: ['status', 'restore'] };
|
|
15
|
+
const USAGE = [
|
|
16
|
+
'usage: pmos autonomy status|restore — what agents do by themselves (class A and B, with Undo)',
|
|
17
|
+
' pmos autonomy status [--json] the changes agents applied in the last 14 days, and the jobs back to propose',
|
|
18
|
+
' pmos autonomy restore <job> [--product <ws>] end a job\'s demotion early',
|
|
19
|
+
'Class C (a message to a person, a Jira move others see, a merge into a product repository, a delete, spend) always waits for you.',
|
|
20
|
+
];
|
|
21
|
+
const flag = (args, k) => { const i = args.indexOf('--' + k); return i >= 0 ? (args[i + 1] === undefined || args[i + 1].startsWith('--') ? true : args[i + 1]) : undefined; };
|
|
22
|
+
function repoRoot(cwd) { try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; } catch { return cwd; } }
|
|
23
|
+
|
|
24
|
+
function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), env = process.env, isTTY, now } = {}) {
|
|
25
|
+
const args = argv[0] === 'autonomy' ? argv.slice(1) : argv.slice();
|
|
26
|
+
const verb = args[0];
|
|
27
|
+
if (!verb || ['help', '--help', '-h'].includes(verb)) { for (const l of USAGE) say(l); return verb ? 0 : 1; }
|
|
28
|
+
if (!COMMANDS.autonomy.includes(verb)) { say(`unknown autonomy command "${verb}" — one of ${COMMANDS.autonomy.join(', ')}`); return 2; }
|
|
29
|
+
const root = typeof flag(args, 'root') === 'string' ? path.resolve(cwd, flag(args, 'root')) : repoRoot(cwd);
|
|
30
|
+
const dir = D.stateDirOf(root);
|
|
31
|
+
if (!dir) { say('✗ this repository has no PMOS state folder (pmos/state, state or .pmos)'); return 1; }
|
|
32
|
+
if (verb === 'status') {
|
|
33
|
+
const done = A.done(dir, { now }), notices = A.notices(dir, { now });
|
|
34
|
+
const killed = A.killed({ env, settingsDir: require('./state-root.js').defaultRoot({ env }) });
|
|
35
|
+
if (flag(args, 'json')) { say(JSON.stringify({ ok: true, on: !killed, why: killed, done, demoted: notices })); return 0; }
|
|
36
|
+
say(killed ? `Agents act by themselves: off (${killed})` : 'Agents act by themselves: on (class A and B, with Undo for 14 days)');
|
|
37
|
+
for (const n of notices) say(` back to propose until ${n.until.slice(0, 10)}: ${n.job} — ${n.why}`);
|
|
38
|
+
if (!done.length) say(' nothing applied by an agent in the last 14 days');
|
|
39
|
+
for (const a of done) say(` ${a.at.slice(0, 16).replace('T', ' ')} · ${a.job} · class ${a.cls || '?'} · ${a.ref} — ${a.title}`);
|
|
40
|
+
return 0;
|
|
41
|
+
}
|
|
42
|
+
const job = args[1] && !args[1].startsWith('--') ? args[1] : null;
|
|
43
|
+
if (!job) { say('usage: pmos autonomy restore <job> [--product <ws>]'); return 2; }
|
|
44
|
+
const a = actorLib.fromCli({ isTTY: isTTY === undefined ? !!(process.stdin.isTTY && process.stdout.isTTY) : isTTY, env });
|
|
45
|
+
if (!actorLib.isPm(a) && !actorLib.isAgent(a)) { say('✗ only the PM or an agent session can restore a job'); return 1; }
|
|
46
|
+
const p = flag(args, 'product');
|
|
47
|
+
const r = A.restore(dir, { job, product: typeof p === 'string' ? p : null }, a, { now });
|
|
48
|
+
if (!r.ok) { say('✗ ' + r.error); return 1; }
|
|
49
|
+
say(`✓ ${job} applies by itself again`);
|
|
50
|
+
return 0;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = { run, COMMANDS, USAGE };
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* autonomy.js — what an agent may do by itself, and the safety net under it (D106, "Full autonomy now", PM wawan 2026-11-08).
|
|
3
|
+
*
|
|
4
|
+
* THE THREE CLASSES. Every change an agent proposes has one class:
|
|
5
|
+
* A reversible upkeep with one right answer: tidy names, dates moved by evidence, a note → applied at once, with Undo
|
|
6
|
+
* B reversible judgment: a problem statement, evidence, an outcome, a description, a task, a grill
|
|
7
|
+
* fix, what was found elsewhere → applied at once, with Undo
|
|
8
|
+
* C seen by others or not reversible: a message to a person, a Jira move others see, a stage move
|
|
9
|
+
* on a board others read, a merge into a product repository, a delete, spend → stays a proposal (one daily press)
|
|
10
|
+
* A change with no Undo writer is never applied by itself, whatever its class ("no Undo, no auto"): it waits like C.
|
|
11
|
+
*
|
|
12
|
+
* THE LEDGER: <state folder>/autonomy.jsonl, append-only, THIS FILE IS ITS ONE WRITER. One line per event { v: 1, at, ev, ... }:
|
|
13
|
+
* applied { job, product, ref, title, cls } an agent applied a change by itself (ref: the proposal id or the ✦ batch)
|
|
14
|
+
* setback { job, product, ref?, kind } kind: undo (the PM pressed Undo) · revert (a revert of the change) ·
|
|
15
|
+
* verifier-fail (the T4 verifier failed it; counts like an Undo)
|
|
16
|
+
* demote { job, product, until, why } the job falls back to propose for this product until `until`
|
|
17
|
+
* seen { job, product, until } Home said so once; it does not say it again for this demotion
|
|
18
|
+
* A job is `driver:<what>` for the Initiative Driver and `propose:<group>` for a ✦ group. A product is the workspace id.
|
|
19
|
+
*
|
|
20
|
+
* AUTOMATIC DEMOTION (a safety net, not a gate). A job on a product falls back to propose for 7 days when:
|
|
21
|
+
* - its last two applied changes were both undone (two Undos in a row), or
|
|
22
|
+
* - one of its changes was reverted, or
|
|
23
|
+
* - over the last 7 days at least 4 changes were applied and more than 30% of them were undone (the D106 tripwire).
|
|
24
|
+
* A verifier FAIL counts as an Undo. The demotion ends by itself; `pmos autonomy restore <job>` ends it early (PM or agent, D98).
|
|
25
|
+
*
|
|
26
|
+
* CLASSES · DRIVER_CLASS · PROPOSAL_CLASS · DEMOTE_DAYS · UNDO_DAYS · RATE_LIMIT · RATE_MIN
|
|
27
|
+
* classOfDriver(what) · classOfProposal(p) → 'A' | 'B' | 'C'
|
|
28
|
+
* file(stateDir) · read(stateDir) → lines · fold(lines, { now }) → state the ledger
|
|
29
|
+
* recordApplied(stateDir, { job, product, ref, title, cls }, { now })
|
|
30
|
+
* recordSetback(stateDir, { job, product, ref?, kind }, { now }) → { demoted: null | { until, why } } the hook T4 calls on a FAIL
|
|
31
|
+
* decide({ stateDir, job, product, cls, mode, undoable, now, env, settingsDir }) → { apply: bool, why } killed() first
|
|
32
|
+
* autoFor(cls, { stateDir?, job?, product?, undoable? }) → bool for callers with no mode: does `cls` apply by itself now
|
|
33
|
+
* killed({ env, settingsDir }) → null | reason PMOS_AUTONOMY=off or `pmos ai off` stops every auto apply
|
|
34
|
+
* demotedNow(state, job, product, now) → null | { until, why }
|
|
35
|
+
* notices(stateDir, { now }) → [{ job, product, until, why }] demotions Home has not said yet; markSeen(stateDir, n, { now })
|
|
36
|
+
* done(stateDir, { now, days }) → [applied line, newest first] the applied changes of the last 14 days that are not undone
|
|
37
|
+
* restore(stateDir, { job, product }, actor, { now })
|
|
38
|
+
*/
|
|
39
|
+
const fs = require('fs');
|
|
40
|
+
const path = require('path');
|
|
41
|
+
|
|
42
|
+
const LEDGER = 'autonomy.jsonl';
|
|
43
|
+
const CLASSES = Object.freeze(['A', 'B', 'C']);
|
|
44
|
+
const DAY = 86400000;
|
|
45
|
+
const DEMOTE_DAYS = 7;
|
|
46
|
+
const UNDO_DAYS = 14;
|
|
47
|
+
const RATE_DAYS = 7;
|
|
48
|
+
const RATE_LIMIT = 0.3;
|
|
49
|
+
const RATE_MIN = 4;
|
|
50
|
+
const KINDS = Object.freeze(['undo', 'revert', 'verifier-fail']);
|
|
51
|
+
const EVENTS = Object.freeze(['applied', 'setback', 'demote', 'seen', 'restore']);
|
|
52
|
+
const JOB_RE = /^(driver|propose|ai|goal):[a-z0-9][a-z0-9-]{0,40}$/;
|
|
53
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
54
|
+
const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
55
|
+
|
|
56
|
+
/* The Initiative Driver's kinds (lib/driver.js WHATS). */
|
|
57
|
+
const DRIVER_CLASS = Object.freeze({
|
|
58
|
+
note: 'A',
|
|
59
|
+
problem: 'B', evidence: 'B', sizing: 'B', assumption: 'B', stakeholders: 'B', overlap: 'B', doc: 'B', 'next-step': 'B',
|
|
60
|
+
move: 'C', // a stage move shows on boards others read (D103) and can move a Jira ticket (D100)
|
|
61
|
+
'follow-up': 'C', // a message to a person
|
|
62
|
+
});
|
|
63
|
+
/* The ✦ groups (lib/proposals.js). `status` turns C when an item is a Jira ticket: its state is Jira's, seen by others (D100). */
|
|
64
|
+
const PROPOSAL_CLASS = Object.freeze({
|
|
65
|
+
names: 'A', dates: 'A',
|
|
66
|
+
description: 'B', outcome: 'B', found: 'B', status: 'B', grill: 'B', links: 'B', prototyped: 'B', improved: 'B', scanned: 'B',
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const classOfDriver = (what) => DRIVER_CLASS[what] || 'C';
|
|
70
|
+
function classOfProposal(p) {
|
|
71
|
+
if (!isObj(p)) return 'C';
|
|
72
|
+
const c = PROPOSAL_CLASS[p.group] || 'C';
|
|
73
|
+
if (p.group === 'status' && (p.items || []).some((x) => x && x.jira)) return 'C';
|
|
74
|
+
// a maybe, or a duplicate already in another initiative (type link, or an item with `other`), is a question for the PM, not a change
|
|
75
|
+
// found type stage moves the initiative's stage: a stage move is C (as the Driver's `move`)
|
|
76
|
+
if (p.group === 'found' && (p.type === 'stage' || p.type === 'maybe' || p.type === 'link' || (p.items || []).some((x) => x && x.other))) return 'C';
|
|
77
|
+
return c;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/* ── the ledger ── */
|
|
81
|
+
const file = (stateDir) => (stateDir ? path.join(stateDir, LEDGER) : null);
|
|
82
|
+
function read(stateDir) {
|
|
83
|
+
const f = file(stateDir);
|
|
84
|
+
if (!f) return [];
|
|
85
|
+
let text = '';
|
|
86
|
+
try { text = fs.readFileSync(f, 'utf8'); } catch { return []; }
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const raw of text.split('\n')) {
|
|
89
|
+
if (!raw.trim()) continue;
|
|
90
|
+
try { const l = JSON.parse(raw); if (isObj(l) && EVENTS.includes(l.ev)) out.push(l); } catch { /* a torn line is skipped */ }
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
function append(stateDir, line, { now } = {}) {
|
|
95
|
+
const f = file(stateDir);
|
|
96
|
+
if (!f) return null;
|
|
97
|
+
const out = { v: 1, at: new Date(now == null ? Date.now() : now).toISOString(), ...line };
|
|
98
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
99
|
+
fs.appendFileSync(f, JSON.stringify(out) + '\n');
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const keyOf = (job, product) => `${job}|${product || '*'}`;
|
|
104
|
+
|
|
105
|
+
/** The state of the ledger: per job and product, the applied changes (each with undone or not), the setbacks and the demotion. */
|
|
106
|
+
function fold(lines) {
|
|
107
|
+
const jobs = new Map();
|
|
108
|
+
const applied = new Map(); // ref -> applied entry
|
|
109
|
+
const get = (job, product) => { const k = keyOf(job, product); if (!jobs.has(k)) jobs.set(k, { job, product: product || null, applied: [], setbacks: [], demote: null, seen: null }); return jobs.get(k); };
|
|
110
|
+
for (const l of lines || []) {
|
|
111
|
+
if (!isObj(l) || typeof l.job !== 'string') continue;
|
|
112
|
+
const j = get(l.job, l.product);
|
|
113
|
+
if (l.ev === 'applied') {
|
|
114
|
+
const a = { ref: l.ref || null, title: l.title || '', cls: l.cls || null, job: l.job, product: l.product || null, at: l.at, undone: false, undoneAt: null };
|
|
115
|
+
j.applied.push(a);
|
|
116
|
+
if (a.ref) applied.set(a.ref, a);
|
|
117
|
+
} else if (l.ev === 'setback') {
|
|
118
|
+
j.setbacks.push({ kind: l.kind, ref: l.ref || null, at: l.at });
|
|
119
|
+
const a = l.ref ? applied.get(l.ref) : null;
|
|
120
|
+
if (a && (l.kind === 'undo' || l.kind === 'verifier-fail' || l.kind === 'revert')) { a.undone = true; a.undoneAt = l.at; }
|
|
121
|
+
} else if (l.ev === 'demote') j.demote = { until: l.until, why: l.why || '', at: l.at };
|
|
122
|
+
else if (l.ev === 'seen') j.seen = l.until || null;
|
|
123
|
+
else if (l.ev === 'restore') j.demote = null;
|
|
124
|
+
}
|
|
125
|
+
return { jobs, applied };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function demotedNow(state, job, product, now) {
|
|
129
|
+
const t = now == null ? Date.now() : now;
|
|
130
|
+
for (const k of [keyOf(job, product), keyOf(job, null)]) {
|
|
131
|
+
const j = state.jobs.get(k);
|
|
132
|
+
if (j && j.demote && Date.parse(j.demote.until) > t) return { until: j.demote.until, why: j.demote.why };
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Should this job on this product be demoted now, and why? Pure. */
|
|
138
|
+
function trip(j, now) {
|
|
139
|
+
const last = j.setbacks[j.setbacks.length - 1];
|
|
140
|
+
if (last && last.kind === 'revert') return 'one of its changes was reverted';
|
|
141
|
+
const done = j.applied.slice(-2);
|
|
142
|
+
if (done.length === 2 && done.every((a) => a.undone)) return 'its last two changes were undone';
|
|
143
|
+
const since = now - RATE_DAYS * DAY;
|
|
144
|
+
const week = j.applied.filter((a) => Date.parse(a.at) >= since);
|
|
145
|
+
const undone = week.filter((a) => a.undone).length;
|
|
146
|
+
if (week.length >= RATE_MIN && undone / week.length > RATE_LIMIT) return `${undone} of its ${week.length} changes this week were undone`;
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function recordApplied(stateDir, { job, product, ref, title, cls }, { now } = {}) {
|
|
151
|
+
if (!JOB_RE.test(String(job || ''))) return null;
|
|
152
|
+
return append(stateDir, { ev: 'applied', job, product: product || null, ref: ref ? one(ref, 120) : null, title: one(title, 200), cls: CLASSES.includes(cls) ? cls : null }, { now });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** THE HOOK for an Undo, a revert or a verifier FAIL. Writes the setback and, when it trips, the demotion. */
|
|
156
|
+
function recordSetback(stateDir, { job, product, ref = null, kind }, { now } = {}) {
|
|
157
|
+
if (!JOB_RE.test(String(job || '')) || !KINDS.includes(kind)) return { demoted: null, error: 'job is driver:|propose:|ai:|goal:<name>; kind is undo, revert or verifier-fail' };
|
|
158
|
+
const t = now == null ? Date.now() : now;
|
|
159
|
+
append(stateDir, { ev: 'setback', job, product: product || null, ...(ref ? { ref: one(ref, 120) } : {}), kind }, { now: t });
|
|
160
|
+
const state = fold(read(stateDir));
|
|
161
|
+
if (demotedNow(state, job, product, t)) return { demoted: null };
|
|
162
|
+
const j = state.jobs.get(keyOf(job, product));
|
|
163
|
+
const why = j ? trip(j, t) : null;
|
|
164
|
+
if (!why) return { demoted: null };
|
|
165
|
+
const until = new Date(t + DEMOTE_DAYS * DAY).toISOString();
|
|
166
|
+
append(stateDir, { ev: 'demote', job, product: product || null, until, why }, { now: t });
|
|
167
|
+
return { demoted: { until, why } };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** May the agent apply this change by itself now? mode: the Driver's mode for the board ('auto' applies; any other mode proposes). */
|
|
171
|
+
/** The stop switches (D106 tripwire): PMOS_AUTONOMY=off, or `pmos ai off` (PMOS_AI=off, Settings ai.on false). null or the reason. */
|
|
172
|
+
function killed({ env = process.env, settingsDir = null } = {}) {
|
|
173
|
+
if (/^(off|0|false|no)$/i.test(String((env || {}).PMOS_AUTONOMY || '').trim())) return 'agents act by themselves no more (PMOS_AUTONOMY=off)';
|
|
174
|
+
try { const why = require('./ai-guard.js').off(null, { env, settingsDir }); if (why) return why; } catch { /* no guard: nothing stops it */ }
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function decide({ stateDir, job, product, cls, mode = 'auto', undoable = true, now, env = process.env, settingsDir = null } = {}) {
|
|
179
|
+
const k = killed({ env, settingsDir });
|
|
180
|
+
if (k) return { apply: false, why: k };
|
|
181
|
+
if (mode !== 'auto') return { apply: false, why: `the mode is ${mode}` };
|
|
182
|
+
if (cls === 'C' || !CLASSES.includes(cls)) return { apply: false, why: 'class C: seen by others or not reversible, so it waits for the daily press' };
|
|
183
|
+
if (!undoable) return { apply: false, why: 'no Undo for this change, so it waits' };
|
|
184
|
+
const d = demotedNow(fold(read(stateDir)), job, product, now);
|
|
185
|
+
if (d) return { apply: false, why: `back to propose until ${d.until.slice(0, 10)}: ${d.why}` };
|
|
186
|
+
return { apply: true, why: `class ${cls}: applied with Undo` };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** For a caller with no mode of its own (a role agent, an AI job): does class `cls` apply by itself now? With `stateDir` and `job`
|
|
190
|
+
* the demotion of that job counts too. Class C never does. */
|
|
191
|
+
function autoFor(cls, { stateDir = null, job = null, product = null, undoable = true, now, env = process.env, settingsDir = null } = {}) {
|
|
192
|
+
if (!stateDir || !job) return !killed({ env, settingsDir }) && (cls === 'A' || cls === 'B') && !!undoable;
|
|
193
|
+
return decide({ stateDir, job, product, cls, mode: 'auto', undoable, now, env, settingsDir }).apply;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function notices(stateDir, { now } = {}) {
|
|
197
|
+
const t = now == null ? Date.now() : now;
|
|
198
|
+
const out = [];
|
|
199
|
+
for (const j of fold(read(stateDir)).jobs.values()) {
|
|
200
|
+
if (!j.demote || Date.parse(j.demote.until) <= t || j.seen === j.demote.until) continue;
|
|
201
|
+
out.push({ job: j.job, product: j.product, until: j.demote.until, why: j.demote.why });
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
const markSeen = (stateDir, n, { now } = {}) => append(stateDir, { ev: 'seen', job: n.job, product: n.product || null, until: n.until }, { now });
|
|
206
|
+
|
|
207
|
+
/** The Done group: what agents applied by themselves in the last `days` days and nobody undid, newest first. */
|
|
208
|
+
function done(stateDir, { now, days = UNDO_DAYS } = {}) {
|
|
209
|
+
const t = now == null ? Date.now() : now;
|
|
210
|
+
const since = t - days * DAY;
|
|
211
|
+
const out = [];
|
|
212
|
+
for (const j of fold(read(stateDir)).jobs.values()) for (const a of j.applied) if (!a.undone && Date.parse(a.at) >= since) out.push(a);
|
|
213
|
+
return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** May this applied change still be undone (within 14 days, not undone yet)? */
|
|
217
|
+
function undoOpen(stateDir, ref, { now } = {}) {
|
|
218
|
+
const a = fold(read(stateDir)).applied.get(ref);
|
|
219
|
+
if (!a) return { ok: false, error: 'no change was applied by an agent under that id' };
|
|
220
|
+
if (a.undone) return { ok: false, error: 'that change is undone already' };
|
|
221
|
+
if ((now == null ? Date.now() : now) - Date.parse(a.at) > UNDO_DAYS * DAY) return { ok: false, error: `Undo is open for ${UNDO_DAYS} days after a change; this one is older` };
|
|
222
|
+
return { ok: true, applied: a };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function restore(stateDir, { job, product }, actor, { now } = {}) {
|
|
226
|
+
if (!JOB_RE.test(String(job || ''))) return { ok: false, error: 'job is driver:|propose:|ai:|goal:<name>' };
|
|
227
|
+
append(stateDir, { ev: 'restore', job, product: product || null, by: (actor && actor.by) || null }, { now });
|
|
228
|
+
return { ok: true };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
module.exports = {
|
|
232
|
+
LEDGER, CLASSES, DRIVER_CLASS, PROPOSAL_CLASS, DEMOTE_DAYS, UNDO_DAYS, RATE_LIMIT, RATE_MIN, KINDS,
|
|
233
|
+
classOfDriver, classOfProposal, killed, autoFor, file, read, fold, recordApplied, recordSetback, decide, demotedNow, notices, markSeen, done, undoOpen, restore,
|
|
234
|
+
};
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* held, so step 1 has no tick here. It is in the table so the Lab can list it.
|
|
15
15
|
* 2 due what is due at a set time: schedules, the morning brief and the day check, the day plan, the data refresh, report
|
|
16
16
|
* schedules, Git sync
|
|
17
|
-
* 3 driver the Initiative Driver
|
|
17
|
+
* 3 driver the Initiative Driver, and the rounds of the long-running goals (D106, lib/goal-loop.js)
|
|
18
18
|
* 4 deep the deep drafts: core documents, Your impact, metric drafts and reads, proposals, grill, the report finder, the
|
|
19
19
|
* report design and structure checks, milestone reviews, the forecast, the role agents (lib/team-runs.js), the verifier after merge
|
|
20
20
|
* 5 idle the idle lab and the slow reads: the Horizon scan (its daily run waits for the first idle stretch of the day), then the idle
|
|
@@ -67,6 +67,7 @@ const JOBS = Object.freeze([
|
|
|
67
67
|
{ id: 'reports', step: 2, label: 'Report schedules' },
|
|
68
68
|
{ id: 'sync', step: 2, label: 'Git sync', ai: false },
|
|
69
69
|
{ id: 'driver', step: 3, label: 'Initiative Driver' },
|
|
70
|
+
{ id: 'goal-loops', step: 3, label: 'Goal loops' }, // D106: the rounds of a long-running goal (lib/goal-loop.js)
|
|
70
71
|
{ id: 'finder', step: 4, label: 'Report finder' },
|
|
71
72
|
{ id: 'coredocs', step: 4, label: 'Core documents' },
|
|
72
73
|
{ id: 'milestones', step: 4, label: 'Milestone reviews' },
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
* pmos driver return <proposal> --note "<what to change>" PM only: send back; the note wakes a run
|
|
9
9
|
* pmos driver drop <proposal> [--note "<why>"] PM only
|
|
10
10
|
* pmos driver pause|resume <initiative|work> <id> PM only
|
|
11
|
-
* pmos driver
|
|
11
|
+
* pmos driver undo <proposal> PM or agent (D98): Undo of a kept proposal, within 14 days (D106)
|
|
12
|
+
* pmos driver mode <off|shadow|approve|auto> [--board <id>] PM only; with no --board it sets every board. auto is the default (D106)
|
|
12
13
|
* every command: [--json] [--root <dir>]
|
|
13
14
|
*
|
|
14
15
|
* Who wrote a line is the call path (lib/actor.js), never an argument. `keep` goes through lib/pm-guard.js requirePmCli, which
|
|
@@ -27,19 +28,20 @@ const decideLib = require('./driver-decide.js');
|
|
|
27
28
|
const stageTools = require('./stage-tools.js');
|
|
28
29
|
const stateRoot = require('./state-root.js');
|
|
29
30
|
|
|
30
|
-
const COMMANDS = { driver: ['propose', 'status', 'keep', 'return', 'drop', 'pause', 'resume', 'mode'] };
|
|
31
|
+
const COMMANDS = { driver: ['propose', 'status', 'keep', 'return', 'drop', 'undo', 'pause', 'resume', 'mode'] };
|
|
31
32
|
const USAGE = [
|
|
32
|
-
'usage: pmos driver propose|status|keep|return|drop|pause|resume|mode — the Initiative Driver',
|
|
33
|
+
'usage: pmos driver propose|status|keep|return|drop|undo|pause|resume|mode — the Initiative Driver',
|
|
33
34
|
' pmos driver propose <initiative|work> <id> --what <what> (--file <json|md> | --data "<text>") --why "<one line>" [--source label=ref …] [--confidence 0..1] [--recommended "<what you suggest>"] [--reversible true|false] [--effort S|M|L]',
|
|
34
35
|
' what: problem, evidence, sizing, assumption, stakeholders, move, note, doc, overlap (initiative) · next-step, follow-up, note (Work task)',
|
|
35
36
|
' pmos driver status <initiative|work> <id>',
|
|
36
37
|
' pmos driver keep <proposal> PM only',
|
|
37
38
|
' pmos driver return <proposal> --note "<what to change>" PM only',
|
|
38
39
|
' pmos driver drop <proposal> [--note "<why>"] PM only',
|
|
40
|
+
' pmos driver undo <proposal> PM or agent: Undo of a kept proposal (14 days)',
|
|
39
41
|
' pmos driver pause|resume <initiative|work> <id> PM only',
|
|
40
|
-
' pmos driver mode <off|shadow|approve> [--board <id>]
|
|
42
|
+
' pmos driver mode <off|shadow|approve|auto> [--board <id>] PM only (auto, the default: class A and B apply at once with Undo)',
|
|
41
43
|
' every command: [--json] [--root <dir>]',
|
|
42
|
-
'Every claim in a proposal carries a pointer (--source label=ref). The driver sends nothing
|
|
44
|
+
'Every claim in a proposal carries a pointer (--source label=ref). The driver sends nothing. In auto mode (D106) a class A or B proposal is applied at once, with Undo; a class C one (a stage move, a follow-up) waits for the PM.',
|
|
43
45
|
];
|
|
44
46
|
const BOOL = new Set(['json', 'help']);
|
|
45
47
|
const VALUE = new Set(['what', 'file', 'data', 'why', 'source', 'ws', 'note', 'board', 'root', 'confidence', 'recommended', 'reversible', 'effort']);
|
|
@@ -113,6 +115,8 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
|
|
|
113
115
|
if (!pos[0] || !pos[1]) { say(`usage: pmos driver ${verb} <initiative|work> <id>`); return false; }
|
|
114
116
|
return true;
|
|
115
117
|
};
|
|
118
|
+
const ctxOf = () => ({ stageFile: path.join(stateDir, stageTools.LEDGER), itemsDir: path.join(stateRoot.defaultRoot(), 'pm-items'), root,
|
|
119
|
+
correctionsFile: path.join(stateRoot.defaultRoot(), 'corrections.jsonl'), settingsDir: stateRoot.defaultRoot() });
|
|
116
120
|
const pmOnly = (act) => {
|
|
117
121
|
const a = actorLib.fromCli(who);
|
|
118
122
|
// D98: an agent session may do it too; the ledger line carries its own `by`.
|
|
@@ -157,7 +161,10 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
|
|
|
157
161
|
const token = actorLib.isAgent(actor) && actor.by !== 'agent:unknown' ? actor.by.slice('agent:'.length) : null;
|
|
158
162
|
const id = D.newId('p');
|
|
159
163
|
const line = D.append(file, { ev: 'proposal', id, ...c.proposal, run: D.runOfSession(state, token), by: actor.by }, { now });
|
|
160
|
-
|
|
164
|
+
// D106: in auto mode a class A or B proposal is applied at once, through the same Keep, with Undo; anything else waits for the PM
|
|
165
|
+
const a = await decideLib.autoApply({ file, proposal: id, actor, ctx: ctxOf(), now, stateDir, product: ws });
|
|
166
|
+
if (a.applied) return done({ filed: true, applied: true, id, class: a.cls, proposal: { ...line, by: actorLib.pageName(line.by) } }, `✓ applied ${id}: ${c.proposal.what} for ${c.proposal.target.kind} ${c.proposal.target.id} (class ${a.cls}). Undo: pmos driver undo ${id}`);
|
|
167
|
+
return done({ filed: true, applied: false, why: a.why, id, proposal: { ...line, by: actorLib.pageName(line.by) } }, `✓ filed ${id}: ${c.proposal.what} for ${c.proposal.target.kind} ${c.proposal.target.id}. It waits for the PM (${a.why}).`);
|
|
161
168
|
}
|
|
162
169
|
|
|
163
170
|
if (verb === 'status') {
|
|
@@ -195,13 +202,22 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
|
|
|
195
202
|
if (!file) return noState();
|
|
196
203
|
const p = D.fold(D.readLines(file)).proposals.get(pid);
|
|
197
204
|
if (p && verb === 'keep' && p.what === 'move') return fail('keep a move on the workspace page: the board move route checks the stage and its warnings');
|
|
198
|
-
const
|
|
199
|
-
correctionsFile: path.join(stateRoot.defaultRoot(), 'corrections.jsonl') };
|
|
200
|
-
const r = await decideLib.decide(verb, { file, proposal: pid, note: flags.note, actor, ctx, now });
|
|
205
|
+
const r = await decideLib.decide(verb, { file, proposal: pid, note: flags.note, actor, ctx: ctxOf(), now });
|
|
201
206
|
if (!r.ok) return fail(r.error);
|
|
202
207
|
return done({ proposal: pid, state: r.proposal.state, wrote: r.wrote }, `✓ ${pid} ${r.proposal.state}${r.wrote ? ` (written to the ${r.wrote} record as you)` : ''}`);
|
|
203
208
|
}
|
|
204
209
|
|
|
210
|
+
if (verb === 'undo') {
|
|
211
|
+
const pid = pos[0];
|
|
212
|
+
if (!pid) { say('usage: pmos driver undo <proposal>'); return 2; }
|
|
213
|
+
const g = pmOnly('undo a kept proposal');
|
|
214
|
+
if (!g.ok) return fail(g.error);
|
|
215
|
+
if (!file) return noState();
|
|
216
|
+
const r = await decideLib.undo({ file, proposal: pid, actor: g.actor, ctx: ctxOf(), now, stateDir, product: ws });
|
|
217
|
+
if (!r.ok) return fail(r.error);
|
|
218
|
+
return done({ proposal: pid, state: 'undone', back: r.back, demoted: r.demoted }, `✓ ${pid} undone${r.back ? '' : ' (the record changed since, so it keeps that change)'}${r.demoted ? `. This job is back to propose until ${r.demoted.until.slice(0, 10)}: ${r.demoted.why}` : ''}`);
|
|
219
|
+
}
|
|
220
|
+
|
|
205
221
|
if (verb === 'pause' || verb === 'resume') {
|
|
206
222
|
if (!needTarget()) return 2;
|
|
207
223
|
const g = pmOnly(`${verb} the driver`);
|
|
@@ -214,7 +230,7 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
|
|
|
214
230
|
|
|
215
231
|
// mode
|
|
216
232
|
const mode = pos[0];
|
|
217
|
-
if (!mode) { say('usage: pmos driver mode <off|shadow|approve> [--board <id>]'); return 2; }
|
|
233
|
+
if (!mode) { say('usage: pmos driver mode <off|shadow|approve|auto> [--board <id>]'); return 2; }
|
|
218
234
|
const g = pmOnly('set the driver mode');
|
|
219
235
|
if (!g.ok) return fail(g.error);
|
|
220
236
|
if (!file) return noState();
|
|
@@ -6,7 +6,12 @@
|
|
|
6
6
|
* decide(verb, { file, proposal, note, actor, ctx, now }) → Promise of { ok, proposal, wrote } | { ok: false, status, error }
|
|
7
7
|
* verb: keep | return | drop. ctx: { stageFile, itemsDir, move(proposal) → { status, body }, correctionsFile?, root? }
|
|
8
8
|
* setPause(file, verb, target, actor, { now }) verb: pause | resume
|
|
9
|
-
* setMode(file, board, mode, actor, { now }) mode: off | shadow | approve; board '*' is every board
|
|
9
|
+
* setMode(file, board, mode, actor, { now }) mode: off | shadow | approve | auto; board '*' is every board
|
|
10
|
+
* autoApply({ file, proposal, actor, ctx, now, stateDir, product, mode }) → { applied: bool, why, … } D106: an agent applies a class A
|
|
11
|
+
* or B proposal by itself, through the same Keep, with Undo. Class C, a demoted job and a kind with no Undo stay open for the PM
|
|
12
|
+
* undo({ file, proposal, actor, ctx, now, stateDir, product }) → { ok, back } | { ok: false, status, error } D106: Undo of a kept
|
|
13
|
+
* proposal, within 14 days. Its record write goes back unless the record changed since; it counts as a correction (the north
|
|
14
|
+
* star) and as a setback of its job (lib/autonomy.js), which may demote the job
|
|
10
15
|
*
|
|
11
16
|
* The caller has already proved the actor is the PM (pm-guard requirePagePress on a route, lib/actor.js on the CLI). These
|
|
12
17
|
* functions still refuse a non-PM actor: a run cannot keep its own proposals.
|
|
@@ -39,8 +44,9 @@ async function writeRecord(p, actor, ctx, now) {
|
|
|
39
44
|
if (!ctx.stageFile) return refuse(409, 'this repository has no state folder to keep the problem statement in');
|
|
40
45
|
const c = stageTools.checkData('problem', { text: p.data && p.data.text });
|
|
41
46
|
if (!c.ok) return refuse(400, c.error);
|
|
47
|
+
const before = (stageTools.readLedger(ctx.stageFile).get(p.target.id) || new Map()).get('problem');
|
|
42
48
|
stageTools.appendTool(ctx.stageFile, { initiative: p.target.id, tool: 'problem', data: c.data }, actor, { now });
|
|
43
|
-
return { ok: true, wrote: 'problem' };
|
|
49
|
+
return { ok: true, wrote: 'problem', undo: { op: 'problem', from: before ? before.data : null, to: c.data } };
|
|
44
50
|
}
|
|
45
51
|
if (p.what === 'move') {
|
|
46
52
|
if (typeof ctx.move !== 'function') return refuse(409, 'a move is kept from the workspace page');
|
|
@@ -66,12 +72,16 @@ async function writeRecord(p, actor, ctx, now) {
|
|
|
66
72
|
if (!r.ok) return refuse(400, r.error);
|
|
67
73
|
pmItems.appendEvent(paths.steps, r.event, new Date(now));
|
|
68
74
|
if (p.data.due) pmItems.appendEvent(paths.items, { event: 'edited', id: p.target.id, fields: { due: p.data.due } }, new Date(now));
|
|
69
|
-
return { ok: true, wrote: 'next-step' };
|
|
75
|
+
return { ok: true, wrote: 'next-step', undo: { op: 'next-step', step: id, ...(p.data.due ? { due: { from: item.due || '', to: p.data.due } } : {}) } };
|
|
70
76
|
}
|
|
71
77
|
return { ok: true, wrote: null };
|
|
72
78
|
}
|
|
73
79
|
|
|
74
|
-
|
|
80
|
+
/* D106 "no Undo, no auto": the kinds whose Keep has an Undo. A decision-only kind (evidence, sizing, …) is undone in the ledger alone.
|
|
81
|
+
* `doc` issues a document and `move` moves a stage: neither has an Undo writer, so neither is applied by itself. */
|
|
82
|
+
const UNDOABLE = new Set(['problem', 'next-step', 'evidence', 'sizing', 'assumption', 'stakeholders', 'note', 'overlap']);
|
|
83
|
+
|
|
84
|
+
async function decide(verb, { file, proposal, note, actor, ctx = {}, now, auto = false } = {}) {
|
|
75
85
|
if (!['keep', 'return', 'drop'].includes(verb)) return refuse(500, `driver: ${JSON.stringify(verb)} is not a decision`);
|
|
76
86
|
if (!isPm(actor)) return refuse(403, 'only the PM can keep, send back or drop a driver proposal');
|
|
77
87
|
if (!file) return refuse(409, 'this repository has no state folder for the driver');
|
|
@@ -83,13 +93,13 @@ async function decide(verb, { file, proposal, note, actor, ctx = {}, now } = {})
|
|
|
83
93
|
const text = typeof note === 'string' ? note.trim() : '';
|
|
84
94
|
if (text.length > 500 || /[\r\n]/.test(text)) return refuse(400, 'the note is one line of at most 500 characters');
|
|
85
95
|
if (verb === 'return' && !text) return refuse(400, 'say what to change: sending a proposal back needs a note');
|
|
86
|
-
let wrote = null; let warnings = [];
|
|
96
|
+
let wrote = null; let warnings = []; let undoInfo = null;
|
|
87
97
|
if (verb === 'keep') {
|
|
88
98
|
const w = await writeRecord(p, actor, ctx, t);
|
|
89
99
|
if (!w.ok) return w;
|
|
90
|
-
wrote = w.wrote; warnings = w.warnings || [];
|
|
100
|
+
wrote = w.wrote; warnings = w.warnings || []; undoInfo = w.undo || null;
|
|
91
101
|
}
|
|
92
|
-
D.append(file, { ev: verb, proposal: p.id, ...(text ? { note: text } : {}), by: actor.by }, { now: t });
|
|
102
|
+
D.append(file, { ev: verb, proposal: p.id, ...(text ? { note: text } : {}), ...(verb === 'keep' && auto ? { auto: true } : {}), ...(undoInfo ? { undo: undoInfo } : {}), by: actor.by }, { now: t });
|
|
93
103
|
if (verb !== 'keep') {
|
|
94
104
|
D.append(file, { ev: 'correction', proposal: p.id, run: p.run, kind: verb, by: actor.by }, { now: t });
|
|
95
105
|
if (ctx.correctionsFile) {
|
|
@@ -104,6 +114,64 @@ async function decide(verb, { file, proposal, note, actor, ctx = {}, now } = {})
|
|
|
104
114
|
return { ok: true, proposal: D.fold(D.readLines(file)).proposals.get(p.id), wrote, warnings };
|
|
105
115
|
}
|
|
106
116
|
|
|
117
|
+
const jobOf = (p) => `driver:${p.what}`;
|
|
118
|
+
|
|
119
|
+
/** D106: apply a proposal by itself when the rules allow it. Never throws; a refusal leaves the proposal open for the PM. */
|
|
120
|
+
async function autoApply({ file, proposal, actor, ctx = {}, now, stateDir, product = null, mode } = {}) {
|
|
121
|
+
const A = require('./autonomy.js');
|
|
122
|
+
try {
|
|
123
|
+
const state = D.fold(D.readLines(file));
|
|
124
|
+
const p = state.proposals.get(proposal);
|
|
125
|
+
if (!p || p.state !== 'open') return { applied: false, why: 'not open' };
|
|
126
|
+
const m = mode || D.modeOf(state, p.target.kind === 'work' ? 'work' : null);
|
|
127
|
+
const cls = A.classOfDriver(p.what);
|
|
128
|
+
const d = A.decide({ stateDir, job: jobOf(p), product, cls, mode: m, undoable: UNDOABLE.has(p.what), now, settingsDir: ctx.settingsDir || null });
|
|
129
|
+
if (!d.apply) return { applied: false, why: d.why, cls };
|
|
130
|
+
const r = await decide('keep', { file, proposal, actor, ctx, now, auto: true });
|
|
131
|
+
if (!r.ok) return { applied: false, why: r.error, cls };
|
|
132
|
+
A.recordApplied(stateDir, { job: jobOf(p), product, ref: p.id, title: `${p.what}: ${p.why}`, cls }, { now });
|
|
133
|
+
return { applied: true, why: d.why, cls, wrote: r.wrote };
|
|
134
|
+
} catch (e) { return { applied: false, why: 'the apply failed: ' + String((e && e.message) || e).slice(0, 160) }; }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** D106: Undo of a kept proposal. A record changed since keeps its change (Undo never overwrites a later edit). */
|
|
138
|
+
async function undo({ file, proposal, actor, ctx = {}, now, stateDir, product = null } = {}) {
|
|
139
|
+
if (!isPm(actor)) return refuse(403, 'only the PM or an agent session can undo');
|
|
140
|
+
if (!file) return refuse(409, 'this repository has no state folder for the driver');
|
|
141
|
+
const t = now == null ? Date.now() : now;
|
|
142
|
+
const p = D.fold(D.readLines(file)).proposals.get(proposal);
|
|
143
|
+
if (!p) return refuse(404, `no driver proposal ${String(proposal).slice(0, 40)}`);
|
|
144
|
+
if (p.state !== 'kept') return refuse(409, `the proposal is ${p.state}, so there is nothing to undo`);
|
|
145
|
+
if (p.decided_at && t - Date.parse(p.decided_at) > require('./autonomy.js').UNDO_DAYS * D.DAY) return refuse(409, 'Undo is open for 14 days after a change; this one is older');
|
|
146
|
+
if (!UNDOABLE.has(p.what)) return refuse(409, `a kept ${p.what} has no Undo`);
|
|
147
|
+
let back = true;
|
|
148
|
+
const u = p.undo || {};
|
|
149
|
+
if (p.what === 'problem' && u.op === 'problem' && ctx.stageFile) {
|
|
150
|
+
const now2 = (stageTools.readLedger(ctx.stageFile).get(p.target.id) || new Map()).get('problem');
|
|
151
|
+
if (!now2 || JSON.stringify(now2.data) !== JSON.stringify(u.to)) back = false; // edited since: it keeps its edit
|
|
152
|
+
else if (u.from) stageTools.appendTool(ctx.stageFile, { initiative: p.target.id, tool: 'problem', data: u.from }, actor, { now: t });
|
|
153
|
+
else stageTools.clearTool(ctx.stageFile, { initiative: p.target.id, tool: 'problem' }, actor, { now: t });
|
|
154
|
+
} else if (p.what === 'next-step' && u.op === 'next-step' && ctx.itemsDir) {
|
|
155
|
+
const paths = itemsPaths(ctx.itemsDir);
|
|
156
|
+
pmItems.appendEvent(paths.steps, { event: 'step_removed', id: u.step }, new Date(t));
|
|
157
|
+
if (u.due) {
|
|
158
|
+
const item = pmItems.fold(pmItems.readLines(paths.items)).find((i) => i.id === p.target.id);
|
|
159
|
+
if (item && (item.due || '') === u.due.to) pmItems.appendEvent(paths.items, { event: 'edited', id: p.target.id, fields: { due: u.due.from || null } }, new Date(t));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
D.append(file, { ev: 'undo', proposal: p.id, back, by: actor.by }, { now: t });
|
|
163
|
+
D.append(file, { ev: 'correction', proposal: p.id, run: p.run, kind: 'undo', by: actor.by }, { now: t });
|
|
164
|
+
if (ctx.correctionsFile) {
|
|
165
|
+
try {
|
|
166
|
+
fs.mkdirSync(path.dirname(ctx.correctionsFile), { recursive: true });
|
|
167
|
+
fs.appendFileSync(ctx.correctionsFile, JSON.stringify({ type: 'correction', kind: 'reject', reason: 'driver:undo', run: p.run, counted: true, at: new Date(t).toISOString(),
|
|
168
|
+
record: { kind: 'correction', run: p.run, reason: 'driver:undo', by: actorLib.isPm(actor) ? 'pm' : actor.by } }) + '\n');
|
|
169
|
+
} catch { /* the driver ledger already holds the correction */ }
|
|
170
|
+
}
|
|
171
|
+
const s = p.auto && stateDir ? require('./autonomy.js').recordSetback(stateDir, { job: jobOf(p), product, ref: p.id, kind: 'undo' }, { now: t }) : { demoted: null };
|
|
172
|
+
return { ok: true, back, demoted: s.demoted || null };
|
|
173
|
+
}
|
|
174
|
+
|
|
107
175
|
function setPause(file, verb, target, actor, { now } = {}) {
|
|
108
176
|
if (!['pause', 'resume'].includes(verb)) return refuse(500, `driver: ${JSON.stringify(verb)} is not pause or resume`);
|
|
109
177
|
if (!isPm(actor)) return refuse(403, 'only the PM can pause or resume the driver');
|
|
@@ -123,4 +191,4 @@ function setMode(file, board, mode, actor, { now } = {}) {
|
|
|
123
191
|
return { ok: true, board, mode };
|
|
124
192
|
}
|
|
125
193
|
|
|
126
|
-
module.exports = { decide, setPause, setMode, writeRecord };
|
|
194
|
+
module.exports = { decide, setPause, setMode, writeRecord, autoApply, undo, UNDOABLE };
|