create-pmos 0.569.0 → 0.570.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 +14 -14
- package/payload/AGENTS.md +11 -0
- 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/planning/work-items.jsonl +0 -0
- package/payload/scripts/lib/sink.js +321 -0
- package/payload/scripts/verify-work.js +149 -0
- package/payload/scripts/work-item.js +1460 -0
- package/payload/state/discoveries.md +1 -1
- package/workspace/changelog.json +13 -0
- package/workspace/guide/cli.md +26 -1
- package/workspace/guide/settings-and-switches.md +1 -0
- package/workspace/lib/agent-team.js +19 -4
- package/workspace/lib/autonomy.js +2 -1
- package/workspace/lib/build-cli.js +93 -0
- package/workspace/lib/build-engine.js +197 -0
- package/workspace/lib/headless.js +3 -1
- package/workspace/lib/pmos-verbs.js +3 -0
- package/workspace/lib/proposals.js +15 -4
- package/workspace/lib/routes-proposals.js +14 -3
- package/workspace/lib/team-cli.js +3 -1
- package/workspace/lib/team-runs.js +4 -0
- package/workspace/lib/verify-work-cli.js +4 -2
- package/workspace/lib/work-kind.js +12 -6
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/ini-props.js +3 -1
- package/workspace/test-lists/build-engine.json +9 -0
|
@@ -0,0 +1,1460 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* work-item.js — the factory's unit of execution (initiative `work-item-entity`, D65 build step 1).
|
|
3
|
+
*
|
|
4
|
+
* PURE, except for one deliberately narrow append in `appendEvent`. Given ledger lines and nothing
|
|
5
|
+
* else, `deriveItems` reports the current state of every work-item; given an event and a target
|
|
6
|
+
* path, `assertWritable` decides whether the factory is allowed to write it. No clock, no network,
|
|
7
|
+
* no spawning — so every rule below is testable without a factory, which is the point: the rules
|
|
8
|
+
* are the risky part.
|
|
9
|
+
*
|
|
10
|
+
* ── WHY STATE IS DERIVED AND NOT STORED (R1) ────────────────────────────────────────────────────
|
|
11
|
+
* The ladder refuses to carry a `stage:` field because "a status field nobody maintains is a board
|
|
12
|
+
* that lies" (workflow-state.js:21-29). A work-item carrying a writable `status` reintroduces that
|
|
13
|
+
* failure one layer down, at ~20 items/week instead of one initiative at a time. So the ledger holds
|
|
14
|
+
* EVENTS and this module folds them. A correction is a new line, never an edit — the same rule
|
|
15
|
+
* planning/runs/README.md already states for runs.
|
|
16
|
+
*
|
|
17
|
+
* ── WHY THE WRITE BOUNDARY IS AN ALLOWLIST (R5) ─────────────────────────────────────────────────
|
|
18
|
+
* D65(b) says the factory should inherit drive-guard.js's refusal "at a larger radius". The
|
|
19
|
+
* explain-surface pass commissioned for this initiative found that guard is (a) imported by nothing
|
|
20
|
+
* but workspace/test.js — the live acceptance writer at POST /api/gate appends directly and never
|
|
21
|
+
* calls it — and (b) bypassable seven ways: a depth cap of 8, a strict `v === true` that admits
|
|
22
|
+
* "true" and 1, JSON-stringified text defeating the key regex, PROMOTE/KILL unmatched by a regex
|
|
23
|
+
* requiring -D/-ED, nested `status` unchecked, a fail-open on assertWritable({}), and no coverage of
|
|
24
|
+
* parent_kr, evals.jsonl verdicts or DECISIONS.md.
|
|
25
|
+
*
|
|
26
|
+
* Every one of those is a case someone did not think of, which is the denylist's whole failure mode.
|
|
27
|
+
* So this is an ALLOWLIST: exactly one sink is permitted and everything else throws, including a
|
|
28
|
+
* request this module cannot parse. An allowlist's failure is a refused legitimate write — noisy,
|
|
29
|
+
* visible, fixable. A denylist's failure is a permitted illegitimate one, found only by the kind of
|
|
30
|
+
* adversarial reading that produced this file.
|
|
31
|
+
*
|
|
32
|
+
* ── THE BASENAME IDEA WAS WRONG, AND THIS IS WHERE IT WAS WRITTEN DOWN ──────────────────────────
|
|
33
|
+
* This header used to say: "the one idea worth carrying over from drive-guard: key the sink on
|
|
34
|
+
* `path.basename`, because every state sink in PMOS ends in the same basename whichever state root
|
|
35
|
+
* resolved it." That reasoning is what produced the defect, so it is corrected here rather than
|
|
36
|
+
* quietly deleted.
|
|
37
|
+
*
|
|
38
|
+
* A basename is not a location. Every directory on disk can hold a file called `work-items.jsonl`,
|
|
39
|
+
* and a symlink with that name points wherever it likes. Measured by attempted write on 2026-08-04,
|
|
40
|
+
* against this module as merged and PM-accepted: **198 bytes appended through a symlink into a
|
|
41
|
+
* decoy.** The allowlist was real; it just allowlisted the wrong noun.
|
|
42
|
+
*
|
|
43
|
+
* What actually holds is a RESOLVED path compared against one declared sink, `O_NOFOLLOW` at open,
|
|
44
|
+
* and `nlink === 1` on the descriptor — the discipline three independent passes converged on in
|
|
45
|
+
* record-eval.js, which this module predates and therefore never received. It now lives in
|
|
46
|
+
* scripts/lib/sink.js and is CALLED here, not copied; see that file for why one copy replaced six.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
const path = require('path');
|
|
50
|
+
const fs = require('fs');
|
|
51
|
+
const { createSinkGuard, ForbiddenWrite } = require('./lib/sink.js');
|
|
52
|
+
|
|
53
|
+
// ── The closed vocabularies (D65 clause (d)) ───────────────────────────────────────────────────
|
|
54
|
+
const ITEM_TYPES = Object.freeze([
|
|
55
|
+
'feature-slice', 'bugfix', 'chore-item', 'hotfix', 'migration', 'content-item', 'spike-item',
|
|
56
|
+
]);
|
|
57
|
+
const BLAST = Object.freeze(['low', 'medium', 'high']);
|
|
58
|
+
const EVENTS = Object.freeze([
|
|
59
|
+
'declared', 'claimed', 'released', 'verified', 'failed', 'integrated', 'shipped', 'withdrawn',
|
|
60
|
+
]);
|
|
61
|
+
/** How a machine decides the criterion. `none` is legal for ONE type — see requireCriterion. */
|
|
62
|
+
const CHECK_KINDS = Object.freeze(['test', 'assertion', 'rubric_dimension', 'none']);
|
|
63
|
+
|
|
64
|
+
/** The only type whose deliverable is a learning rather than a diff, so scoring it produces safe,
|
|
65
|
+
* uninformative work (D60(d), carried into D65(d)). Everything else owes a checkable criterion. */
|
|
66
|
+
const UNVERIFIED_TYPE = 'spike-item';
|
|
67
|
+
|
|
68
|
+
/** The gate's own id rule (.github/scripts/initiative-gate.sh), reused rather than re-invented: it
|
|
69
|
+
* excludes '/' and '.'-traversal, which is why the id can be interpolated into a path safely.
|
|
70
|
+
* A work-item id is `<initiative-id>.<ordinal>`, so the dot is a separator here, never traversal —
|
|
71
|
+
* hence the explicit two-part shape rather than a looser charset. */
|
|
72
|
+
const ITEM_ID_RE = /^[a-z0-9][a-z0-9_-]*\.[0-9]+$/;
|
|
73
|
+
const INITIATIVE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
|
|
74
|
+
/** D86 point 1: `declared` may name the plan item it materializes. The plan-items id format
|
|
75
|
+
* (workspace/lib/plan-items.js ID_RE): `<initiative>.<10 characters [0-9a-z]>`, parsed on its LAST dot. Whether
|
|
76
|
+
* the plan item exists is a ledger question, so scripts/check-work-items.js answers it, not this shape check. */
|
|
77
|
+
const PLAN_ITEM_RE = /^(.+)\.([0-9a-z]{10})$/;
|
|
78
|
+
|
|
79
|
+
/* THE ForbiddenWrite lives in scripts/lib/sink.js and is re-exported here unchanged. It used to be
|
|
80
|
+
* defined locally, and so did the same class in four other writers — five classes with one name.
|
|
81
|
+
* `instanceof` is how every assertion tells a deliberate refusal from a crash, so two classes make
|
|
82
|
+
* those checks quietly false; seventeen assertions in scripts/tests/work-item.sh went red with
|
|
83
|
+
* `threw ForbiddenWrite, want ForbiddenWrite` the moment a second one existed. */
|
|
84
|
+
|
|
85
|
+
// ── Validation (R2/R3) ─────────────────────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
function isPlainObject(v) {
|
|
88
|
+
return !!v && typeof v === 'object' && !Array.isArray(v);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Does this event line satisfy R2 (shape) and R3 (a checkable criterion)?
|
|
93
|
+
* Returns { ok, errors: string[] }. NEVER throws — the checker wants every error on a line, and the
|
|
94
|
+
* writer turns a non-ok result into a throw itself.
|
|
95
|
+
*
|
|
96
|
+
* `opts.initiativeExists` — optional (id) => boolean. When supplied, an event naming an initiative
|
|
97
|
+
* that does not exist is an error. The checker supplies it; unit tests mostly do not.
|
|
98
|
+
*/
|
|
99
|
+
function validateEvent(obj, opts) {
|
|
100
|
+
const o = opts || {};
|
|
101
|
+
const errors = [];
|
|
102
|
+
if (!isPlainObject(obj)) return { ok: false, errors: ['not a JSON object'] };
|
|
103
|
+
|
|
104
|
+
// -- required on every event -----------------------------------------------------------------
|
|
105
|
+
const itemId = obj.item_id;
|
|
106
|
+
if (typeof itemId !== 'string' || !itemId) errors.push('missing `item_id`');
|
|
107
|
+
else if (!ITEM_ID_RE.test(itemId)) errors.push(`\`item_id\` '${itemId}' is malformed (want <initiative-id>.<ordinal>, lowercase)`);
|
|
108
|
+
|
|
109
|
+
const initiativeId = obj.initiative_id;
|
|
110
|
+
if (typeof initiativeId !== 'string' || !initiativeId) errors.push('missing `initiative_id`');
|
|
111
|
+
else if (!INITIATIVE_ID_RE.test(initiativeId)) errors.push(`\`initiative_id\` '${initiativeId}' is malformed`);
|
|
112
|
+
else if (typeof itemId === 'string' && ITEM_ID_RE.test(itemId) && itemId.slice(0, itemId.lastIndexOf('.')) !== initiativeId) {
|
|
113
|
+
// The id carries its parent, so the two can disagree. A disagreement is a defect, not a
|
|
114
|
+
// preference for one of them — guessing which is right is how a ledger starts lying.
|
|
115
|
+
errors.push(`\`item_id\` '${itemId}' does not belong to \`initiative_id\` '${initiativeId}'`);
|
|
116
|
+
} else if (typeof o.initiativeExists === 'function' && !o.initiativeExists(initiativeId)) {
|
|
117
|
+
errors.push(`\`initiative_id\` '${initiativeId}' names no record in planning/initiatives/`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const event = obj.event;
|
|
121
|
+
if (typeof event !== 'string' || !event) errors.push('missing `event`');
|
|
122
|
+
else if (!EVENTS.includes(event)) errors.push(`\`event\` '${event}' is not one of ${EVENTS.join(' | ')}`);
|
|
123
|
+
|
|
124
|
+
if (typeof obj.at !== 'string' || !isIsoLike(obj.at)) errors.push('missing or malformed `at` (want ISO 8601)');
|
|
125
|
+
|
|
126
|
+
// -- required on `declared` ------------------------------------------------------------------
|
|
127
|
+
if (event === 'declared') {
|
|
128
|
+
if (!ITEM_TYPES.includes(obj.type)) errors.push(`\`type\` must be one of ${ITEM_TYPES.join(' | ')}`);
|
|
129
|
+
if (!BLAST.includes(obj.blast)) errors.push(`\`blast\` must be one of ${BLAST.join(' | ')}`);
|
|
130
|
+
errors.push(...criterionErrors(obj.criterion, obj.type));
|
|
131
|
+
/* OPTIONAL, and the only field D86 adds to this ledger. It joins a work item to one plan item; the factory
|
|
132
|
+
* never writes the planning ledgers, so this is the whole crossing (D65's materialization). */
|
|
133
|
+
if (obj.plan_item !== undefined) {
|
|
134
|
+
const m = typeof obj.plan_item === 'string' ? PLAN_ITEM_RE.exec(obj.plan_item) : null;
|
|
135
|
+
if (!m) errors.push(`\`plan_item\` must be a plan item id, <initiative>.<10 characters [0-9a-z]> — got ${JSON.stringify(obj.plan_item)}`);
|
|
136
|
+
else if (typeof initiativeId === 'string' && m[1] !== initiativeId) {
|
|
137
|
+
errors.push(`\`plan_item\` '${obj.plan_item}' belongs to '${m[1]}', not to \`initiative_id\` '${initiativeId}'`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
} else if (obj.plan_item !== undefined) {
|
|
141
|
+
errors.push('`plan_item` is written only on `declared` — it is fixed when the item is materialized');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// -- required on `claimed` -------------------------------------------------------------------
|
|
145
|
+
if (event === 'claimed') {
|
|
146
|
+
const c = obj.claim;
|
|
147
|
+
if (!isPlainObject(c)) errors.push('`claimed` needs `claim: { agent, expires_at }`');
|
|
148
|
+
else {
|
|
149
|
+
if (typeof c.agent !== 'string' || !c.agent) errors.push('`claim.agent` is required');
|
|
150
|
+
if (typeof c.expires_at !== 'string' || !isIsoLike(c.expires_at)) errors.push('`claim.expires_at` must be ISO 8601');
|
|
151
|
+
else if (typeof obj.at === 'string' && isIsoLike(obj.at) && !afterInstant(c.expires_at, obj.at)) {
|
|
152
|
+
/* INSTANTS, not text. This was `c.expires_at <= obj.at`, a lexicographic compare on two
|
|
153
|
+
* self-reported ISO strings — the residual of the very defect this step removed from the
|
|
154
|
+
* fold. It failed in BOTH directions once offsets differ: at='...T03:00:00Z' with
|
|
155
|
+
* expires_at='...T09:00:00+07:00' (= 02:00Z, an hour BEFORE `at`) passed the one rule this
|
|
156
|
+
* line exists to enforce, and a legitimate lease written '...T06:30:00-05:00' was rejected. */
|
|
157
|
+
errors.push('`claim.expires_at` is not after `at` — a claim that expires when it is made');
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// -- required where a verdict is being asserted ----------------------------------------------
|
|
163
|
+
if (event === 'verified' || event === 'failed' || event === 'shipped') {
|
|
164
|
+
if (obj.evidence === undefined || obj.evidence === null || obj.evidence === '') {
|
|
165
|
+
errors.push(`\`${event}\` must carry \`evidence\` — a verdict with no evidence is the gate-is-a-file failure`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return { ok: errors.length === 0, errors };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* R3 — a slice with no machine-checkable criterion is not a work-item.
|
|
174
|
+
* `check: none` is legal for exactly one type; for the other six it is a validation error, which is
|
|
175
|
+
* what makes D65's "fails decomposition" real rather than aspirational.
|
|
176
|
+
*/
|
|
177
|
+
function criterionErrors(criterion, type) {
|
|
178
|
+
if (!isPlainObject(criterion)) {
|
|
179
|
+
return ['`criterion` is required on `declared` — an item with no criterion cannot be verified, and a slice that cannot be given one fails decomposition (D65)'];
|
|
180
|
+
}
|
|
181
|
+
const errs = [];
|
|
182
|
+
if (typeof criterion.text !== 'string' || !criterion.text.trim()) errs.push('`criterion.text` is required');
|
|
183
|
+
if (!CHECK_KINDS.includes(criterion.check)) {
|
|
184
|
+
errs.push(`\`criterion.check\` must be one of ${CHECK_KINDS.join(' | ')}`);
|
|
185
|
+
return errs;
|
|
186
|
+
}
|
|
187
|
+
if (criterion.check === 'none' && type !== UNVERIFIED_TYPE) {
|
|
188
|
+
errs.push(`\`criterion.check: none\` is legal only for \`${UNVERIFIED_TYPE}\` — type '${type}' owes a checkable criterion`);
|
|
189
|
+
}
|
|
190
|
+
if (criterion.check !== 'none' && (typeof criterion.ref !== 'string' || !criterion.ref.trim())) {
|
|
191
|
+
// `test` names a test, `assertion` names a command, `rubric_dimension` names a dimension id.
|
|
192
|
+
// Without the ref the check kind is a label, not a check.
|
|
193
|
+
errs.push(`\`criterion.ref\` is required when check is '${criterion.check}' — name the test, command or dimension`);
|
|
194
|
+
}
|
|
195
|
+
return errs;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Deliberately loose: this is a shape check, not a calendar. `Date.parse` accepts too much on its
|
|
199
|
+
* own (it takes '2026' and 'Mon'), so the prefix is pinned and then parsed. */
|
|
200
|
+
/** Milliseconds for an ISO string, or NaN. One place, so "later" means the same thing everywhere. */
|
|
201
|
+
function instantOf(v) { return typeof v === 'string' ? Date.parse(v) : NaN; }
|
|
202
|
+
/** Is `a` strictly after `b`, as instants? Unparseable on either side is NOT "after" — fail closed. */
|
|
203
|
+
function afterInstant(a, b) {
|
|
204
|
+
const ma = instantOf(a), mb = instantOf(b);
|
|
205
|
+
return Number.isFinite(ma) && Number.isFinite(mb) && ma > mb;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function isIsoLike(s) {
|
|
209
|
+
return typeof s === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(s) && !Number.isNaN(Date.parse(s));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ── Derivation (R1/R4) ─────────────────────────────────────────────────────────────────────────
|
|
213
|
+
|
|
214
|
+
/** Which event wins when two share a timestamp is decided by file order, so the fold is total.
|
|
215
|
+
* Terminal states do not un-terminate: a `withdrawn` item is not re-opened by a stray later
|
|
216
|
+
* `claimed`, it records a defect instead.
|
|
217
|
+
*
|
|
218
|
+
* ── `shipped` IS NOT TERMINAL, AND D65(d) SAYS SO IN ITS OWN TEXT ───────────────────────────────
|
|
219
|
+
* Terminality was doing two unrelated jobs — *forbid a nonsense ordering* and *mark the end of an
|
|
220
|
+
* item's life* — and doing both badly. `shipped` did the first job wrongly: D65(d) specifies that
|
|
221
|
+
* for a `hotfix` **ship precedes integrate**, so the required order for an entire work-item type
|
|
222
|
+
* was recorded as an `after-terminal` defect, and the item's state became `determinable: false`.
|
|
223
|
+
* A pull request being open is not the end of anything either: it collects review comments, it
|
|
224
|
+
* fails CI, it gets more commits.
|
|
225
|
+
*
|
|
226
|
+
* Job one moves to ORDER, below, which knows the type. Job two stays here and stays with
|
|
227
|
+
* `withdrawn` alone: an abandoned item silently resurrected launders scope the PM dropped, and a
|
|
228
|
+
* new item id is the honest record of a decision reversed. */
|
|
229
|
+
const TERMINAL = Object.freeze(['withdrawn']);
|
|
230
|
+
|
|
231
|
+
/** ── THE BASE CHAIN, FOR THE FOUR NODES THE VOCABULARY CAN EXPRESS ──────────────────────────────
|
|
232
|
+
*
|
|
233
|
+
* D65(d)'s base chain is `claim → sandbox → warm context → [reproduce] → [plan] → build → verify →
|
|
234
|
+
* quality → [human review] → integrate → ship` — ELEVEN nodes, of which four have an event in the
|
|
235
|
+
* closed vocabulary and SEVEN have none. What is representable here is a quarter of the chain, and
|
|
236
|
+
* `UNSEEN_NODES` exists so the checker can say which seven it did not look at rather than let a
|
|
237
|
+
* green line read as *the chain ran*.
|
|
238
|
+
*
|
|
239
|
+
* `hotfix` is the reason this is per-type rather than one list: D65(d) puts `ship` BEFORE
|
|
240
|
+
* `integrate` for it, and the forward-port is a separate work-item. */
|
|
241
|
+
const CHAIN = Object.freeze({
|
|
242
|
+
hotfix: Object.freeze(['claimed', 'verified', 'shipped', 'integrated']),
|
|
243
|
+
DEFAULT: Object.freeze(['claimed', 'verified', 'integrated', 'shipped']),
|
|
244
|
+
});
|
|
245
|
+
const UNSEEN_NODES = Object.freeze(['sandbox', 'warm context', 'reproduce', 'plan', 'build', 'quality', 'human review']);
|
|
246
|
+
|
|
247
|
+
/** The chain for a type. `spike-item` is DERIVED from `UNVERIFIED_TYPE` rather than listed, because
|
|
248
|
+
* the first draft listed neither and fell through to DEFAULT — which requires `verified` before
|
|
249
|
+
* `integrated` for the one type this module itself declares unverified (`UNVERIFIED_TYPE`, above:
|
|
250
|
+
* *"the only type whose deliverable is a learning rather than a diff"*). The writer then REFUSED a
|
|
251
|
+
* spike's `integrated` and `shipped`. Two names for one rule, disagreeing: D60(d) and D65(d) both
|
|
252
|
+
* exempt a spike from verification, and the chain said otherwise. */
|
|
253
|
+
const chainFor = (type) => {
|
|
254
|
+
if (type === UNVERIFIED_TYPE) return CHAIN.DEFAULT.filter((e) => e !== 'verified');
|
|
255
|
+
return CHAIN[type] || CHAIN.DEFAULT;
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
/** Where an event sits in the chain. `failed` IS the verify node — its other outcome — so it sits at
|
|
259
|
+
* `verified`'s index in BOTH directions.
|
|
260
|
+
*
|
|
261
|
+
* The first draft let `failed` SATISFY `verified` while being absent from the chain itself, so it
|
|
262
|
+
* needed no predecessor: a `feature-slice` that was never claimed, whose only verify outcome was
|
|
263
|
+
* `failed`, reached `shipped` with the checker at exit 0 and `✓ every line is well-formed`. That is
|
|
264
|
+
* the baseline defect this rule was written to close, reproduced in two extra lines inside the rule
|
|
265
|
+
* — a skipped node becoming the sanctioned case in the check meant to stop it. */
|
|
266
|
+
const chainPos = (chain, event) => chain.indexOf(event === 'failed' ? 'verified' : event);
|
|
267
|
+
|
|
268
|
+
/* A node with TWO OUTCOMES is satisfied by its LATEST one, never by having once been reached.
|
|
269
|
+
*
|
|
270
|
+
* `verified` and `failed` are the two outcomes of one node. Membership in `history` answers *did this
|
|
271
|
+
* ever happen*, and that is the wrong question — it cannot be un-answered. An independent pass found
|
|
272
|
+
* the consequence: `declared → claimed → verified → failed → integrated → shipped` on a
|
|
273
|
+
* `feature-slice` folded clean, `state: shipped`, `✓ every line is well-formed`, EXIT=0. The slice's
|
|
274
|
+
* last word on its own verification was FAILURE and it shipped anyway.
|
|
275
|
+
*
|
|
276
|
+
* That is the same defect the comment at the call site says was closed — closed for
|
|
277
|
+
* `claimed → failed → shipped` (never verified at all) and left open for `verified → failed`
|
|
278
|
+
* (verified, then unverified). A rule fixed for the shape someone thought of and standing for the
|
|
279
|
+
* shape they did not: the recurring class in this repo, here inside the fix for its own baseline.
|
|
280
|
+
*
|
|
281
|
+
* Scanning BACKWARD is what makes re-verification work: `failed → verified` stands satisfied,
|
|
282
|
+
* because a slice that was fixed and re-verified is verified. Only the most recent outcome counts,
|
|
283
|
+
* in either direction. */
|
|
284
|
+
/* Every node whose standing can be REVOKED by a later event, and the event that revokes it.
|
|
285
|
+
*
|
|
286
|
+
* `verified` / `failed` is the pair the round-5 pass found. Round 6 found the identical shape one
|
|
287
|
+
* node over: `released` is the other outcome of the CLAIM node — the fold itself sets the item back
|
|
288
|
+
* to `declared` on it — so `declared → claimed → released → verified → integrated → shipped` walked
|
|
289
|
+
* clean through the real writer, six permitted appends, EXIT=0, `state: shipped`. The rule was fixed
|
|
290
|
+
* for the pair someone had in hand and left standing for the pair one node away, which is the same
|
|
291
|
+
* sentence this file has now written three times.
|
|
292
|
+
*
|
|
293
|
+
* It is a TABLE rather than two `if`s so the next pair is a row and not a rediscovery. */
|
|
294
|
+
const NEGATED_BY = Object.freeze({ verified: 'failed', claimed: 'released' });
|
|
295
|
+
|
|
296
|
+
/** Are these two events the two OPPOSITE outcomes of one node, in either order? Derived from
|
|
297
|
+
* `NEGATED_BY` rather than listed again, so a new pair is one row and not two edits. */
|
|
298
|
+
function opposedOutcomes(a, b) {
|
|
299
|
+
return NEGATED_BY[a] === b || NEGATED_BY[b] === a;
|
|
300
|
+
}
|
|
301
|
+
function standsSatisfied(history, need) {
|
|
302
|
+
const negator = NEGATED_BY[need];
|
|
303
|
+
if (!negator) return history.includes(need);
|
|
304
|
+
for (let i = history.length - 1; i >= 0; i -= 1) {
|
|
305
|
+
if (history[i] === need) return true;
|
|
306
|
+
if (history[i] === negator) return false;
|
|
307
|
+
}
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/* There is deliberately NO list of discard kinds here. The first draft had one, and its comment
|
|
312
|
+
* claimed it was derived; it was not, and a new fold defect kind escaped it silently. See
|
|
313
|
+
* `discardRefusal`, which folds twice and compares. */
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Fold ledger lines into current per-item state.
|
|
317
|
+
*
|
|
318
|
+
* @param {string[]|string} input raw lines (or the whole file body)
|
|
319
|
+
* @param {object} [opts] { initiativeExists?, now? }
|
|
320
|
+
* @returns {{ items: object[], defects: object[] }}
|
|
321
|
+
*
|
|
322
|
+
* R4's honesty rules, all four:
|
|
323
|
+
* - a line that does not parse is REPORTED, never guessed at (the torn-acceptance-row class);
|
|
324
|
+
* - an event naming an unknown item_id is a defect, NOT a silent create;
|
|
325
|
+
* - an expired claim derives as unclaimed, and expiry is measured against `opts.now` — a caller's
|
|
326
|
+
* clock passed IN, never read inside the fold — so the same `now` always folds to the same
|
|
327
|
+
* output, and with no `now` the lease's state is `unknown` rather than expired;
|
|
328
|
+
* - a state that cannot be determined says so, and never defaults to a happy value.
|
|
329
|
+
*
|
|
330
|
+
* THIS PARAGRAPH SAID THE OPPOSITE FOR THREE ROUNDS. It claimed expiry was measured against the
|
|
331
|
+
* ledger's own latest timestamp — the rule the code eighty lines below explicitly retracts, in a
|
|
332
|
+
* comment that explains why it does not measure time at all (a lease derived `claimed` ten hours
|
|
333
|
+
* past its `expires_at` because nothing had been appended since; one unrelated append expired it;
|
|
334
|
+
* one future-dated line expired every claim in the file). Two statements of one rule, inside one
|
|
335
|
+
* function, disagreeing — and the wrong one was the one a reader meets first. Sprint-contract
|
|
336
|
+
* criterion 25; it survived rounds 5, 6 and 7 because prose has no assertion attached to it by
|
|
337
|
+
* default. It has one now: see the suite's `deriveItems` docstring block.
|
|
338
|
+
*/
|
|
339
|
+
function deriveItems(input, opts) {
|
|
340
|
+
const o = opts || {};
|
|
341
|
+
const lines = Array.isArray(input) ? input : String(input == null ? '' : input).split('\n');
|
|
342
|
+
const defects = [];
|
|
343
|
+
const parsed = [];
|
|
344
|
+
|
|
345
|
+
for (let i = 0; i < lines.length; i++) {
|
|
346
|
+
const t = String(lines[i]).trim();
|
|
347
|
+
if (!t) continue;
|
|
348
|
+
let obj;
|
|
349
|
+
try { obj = JSON.parse(t); } catch (e) {
|
|
350
|
+
defects.push({ line: i + 1, kind: 'unparseable', detail: 'line is not JSON — reported, not guessed at' });
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const v = validateEvent(obj, o);
|
|
354
|
+
if (!v.ok) {
|
|
355
|
+
defects.push({ line: i + 1, kind: 'invalid', item_id: obj && obj.item_id, detail: v.errors.join('; ') });
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
parsed.push({ obj, idx: i });
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/* Sort by `at`, ties broken by original position, so the fold is a deterministic function of the
|
|
362
|
+
* ledger's BYTES.
|
|
363
|
+
*
|
|
364
|
+
* ~~two orderings of the same events derive identically~~ — **STRUCK 2026-08-06.** That was an
|
|
365
|
+
* overclaim and a round-6 pass measured the consequence: `verified` and `failed` at the SAME `at`
|
|
366
|
+
* give EXIT=1 with three defects in one file order and EXIT=0 with `✓ every line is well-formed`
|
|
367
|
+
* in the other. Same six events, opposite verdicts, decided by which line was written first.
|
|
368
|
+
*
|
|
369
|
+
* The tie-break is not the defect and is not being changed. A ledger is an APPEND-ONLY log, so
|
|
370
|
+
* line order is the real write order and is information, not noise — a fold that discarded it
|
|
371
|
+
* would be less faithful, not more. What was wrong is the sentence promising otherwise, and the
|
|
372
|
+
* silence: two events that occupy the same node with OPPOSITE outcomes at the same instant are
|
|
373
|
+
* genuinely undecidable from the record, and the concurrency debt makes that reachable rather than
|
|
374
|
+
* hypothetical. So the tie is now REPORTED (see the `simultaneous-outcomes` defect below) instead
|
|
375
|
+
* of being resolved by whichever process won a write race. */
|
|
376
|
+
/* BOTH arms compare instants. The '<' arm was converted and the '>' arm was left as a string
|
|
377
|
+
* compare, which makes the comparator NON-ANTISYMMETRIC: for '2026-08-04T05:00:00Z' and
|
|
378
|
+
* '2026-08-04T05:00:00+00:00' — the same instant, different text — it returns 1 in both
|
|
379
|
+
* directions, each saying the other should come first. ECMA-262 leaves a sort with an inconsistent
|
|
380
|
+
* comparator implementation-defined. It happened not to diverge in 31,600 randomized sorts only
|
|
381
|
+
* because V8's TimSort calls comparefn(higher-index, lower-index), the one direction in which the
|
|
382
|
+
* half-converted form is accidentally right — so the fold's determinism was resting on a V8
|
|
383
|
+
* implementation detail rather than on the comparator. */
|
|
384
|
+
parsed.sort((a, b) => {
|
|
385
|
+
const ia = instantOf(a.obj.at), ib = instantOf(b.obj.at);
|
|
386
|
+
if (ia < ib) return -1;
|
|
387
|
+
if (ia > ib) return 1;
|
|
388
|
+
return a.idx - b.idx; // same instant: ledger order decides, and it is a total order
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
/* A NODE DECIDED BY A WRITE RACE IS NOT DECIDED. Two events at the same instant, on the same item,
|
|
392
|
+
* that are the two OPPOSITE outcomes of one node (`verified`/`failed`, `claimed`/`released`) leave
|
|
393
|
+
* the fold with no basis in the record for choosing — only file position, which under the recorded
|
|
394
|
+
* concurrency debt is whichever process won. Reporting it costs one defect and a red gate; not
|
|
395
|
+
* reporting it means the gate's verdict flips on a coin nobody can see. */
|
|
396
|
+
{
|
|
397
|
+
/* EVERY event at an instant is compared against EVERY earlier one at that instant, not against
|
|
398
|
+
* the first one only.
|
|
399
|
+
*
|
|
400
|
+
* The first version kept ONE entry per `(item_id, instant)` and never replaced it, so a
|
|
401
|
+
* non-opposed event arriving first occupied the slot and hid the pair behind it. Measured by an
|
|
402
|
+
* independent pass: `claimed`, `verified` and `failed` all at one instant fold with ZERO
|
|
403
|
+
* defects, and the two write orders give `state: failed` with the ship refused, versus a fully
|
|
404
|
+
* shipped item — both at EXIT=0. That is round 6's finding closed for the exact two-line shape
|
|
405
|
+
* it named and standing for the shape one event away, which is this repository's most-repeated
|
|
406
|
+
* sentence.
|
|
407
|
+
*
|
|
408
|
+
* A list per key, checked pairwise, has no "first" to hide behind. */
|
|
409
|
+
const seen = new Map(); // `${item_id} ${instant}` -> [{event, line}, ...]
|
|
410
|
+
for (const p of parsed) {
|
|
411
|
+
const key = `${p.obj.item_id} ${instantOf(p.obj.at)}`;
|
|
412
|
+
const priors = seen.get(key) || [];
|
|
413
|
+
for (const prior of priors) {
|
|
414
|
+
if (!opposedOutcomes(prior.event, p.obj.event)) continue;
|
|
415
|
+
defects.push({
|
|
416
|
+
line: p.idx + 1, kind: 'simultaneous-outcomes', item_id: p.obj.item_id,
|
|
417
|
+
detail: `\`${prior.event}\` (line ${prior.line}) and \`${p.obj.event}\` share \`at\` ${p.obj.at} — `
|
|
418
|
+
+ 'they are the two outcomes of one node, so which one stands is decided by ledger position '
|
|
419
|
+
+ 'and nothing else. Re-record one with a distinct timestamp.',
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
priors.push({ event: p.obj.event, line: p.idx + 1 });
|
|
423
|
+
seen.set(key, priors);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/* THE CLOCK IS A PARAMETER (D65 step 3, B2/B3).
|
|
428
|
+
*
|
|
429
|
+
* This was the ledger's own latest `at`, and the reasoning above it was half right: a wall-clock
|
|
430
|
+
* read INSIDE the fold really would make derivation unreproducible, which is the property the
|
|
431
|
+
* append-only design buys. But the conclusion drawn from it — measure against the newest line —
|
|
432
|
+
* does not measure time at all. An independent pass observed a lease still deriving `claimed`
|
|
433
|
+
* TEN HOURS past its expires_at, because it was the newest line and nothing had been appended
|
|
434
|
+
* since. One unrelated append expires it; one future-dated line expires EVERY claim in the file.
|
|
435
|
+
*
|
|
436
|
+
* Taking `now` as a parameter keeps both properties: same `now` in, same answer out, and the
|
|
437
|
+
* caller supplies a real clock. `opts.now` is an ISO 8601 instant. */
|
|
438
|
+
const nowRaw = o.now;
|
|
439
|
+
const nowMs = typeof nowRaw === 'string' && isIsoLike(nowRaw) ? Date.parse(nowRaw) : null;
|
|
440
|
+
|
|
441
|
+
const byId = new Map();
|
|
442
|
+
for (const { obj, idx } of parsed) {
|
|
443
|
+
const id = obj.item_id;
|
|
444
|
+
if (obj.event === 'declared') {
|
|
445
|
+
if (byId.has(id)) {
|
|
446
|
+
defects.push({ line: idx + 1, kind: 'redeclared', item_id: id, detail: 'declared twice — the second is ignored and reported' });
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
byId.set(id, {
|
|
450
|
+
item_id: id,
|
|
451
|
+
initiative_id: obj.initiative_id,
|
|
452
|
+
type: obj.type,
|
|
453
|
+
blast: obj.blast,
|
|
454
|
+
criterion: obj.criterion,
|
|
455
|
+
...(obj.plan_item !== undefined ? { plan_item: obj.plan_item } : {}), // D86 point 1; absent stays absent
|
|
456
|
+
state: 'declared',
|
|
457
|
+
claim: null,
|
|
458
|
+
evidence: null,
|
|
459
|
+
history: [obj.event],
|
|
460
|
+
determinable: true,
|
|
461
|
+
});
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
const it = byId.get(id);
|
|
465
|
+
if (!it) {
|
|
466
|
+
// NOT a silent create. An event about an item nobody declared is exactly the case that, left
|
|
467
|
+
// to default, makes a ledger describe work that was never scoped.
|
|
468
|
+
defects.push({ line: idx + 1, kind: 'unknown-item', item_id: id, detail: `\`${obj.event}\` for an item that was never declared` });
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
if (TERMINAL.includes(it.state)) {
|
|
472
|
+
defects.push({ line: idx + 1, kind: 'after-terminal', item_id: id, detail: `\`${obj.event}\` after \`${it.state}\` — ignored and reported` });
|
|
473
|
+
it.determinable = false;
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/* ORDER, per type, over the four representable nodes.
|
|
478
|
+
*
|
|
479
|
+
* The switch below accepted every ordering, so the base chain was prose: measured on this very
|
|
480
|
+
* module before this change, a `feature-slice` ledger of `declared` then `shipped` — no
|
|
481
|
+
* `verified`, no `integrated` — folded clean and passed check-work-items.js with exit 0. A rule
|
|
482
|
+
* that accepts every ordering is not a rule.
|
|
483
|
+
*
|
|
484
|
+
* Two directions, because one of them was the whole reason `shipped` stopped being terminal:
|
|
485
|
+
* a `hotfix` with `shipped` before `integrated` is CORRECT (D65(d)), and a `feature-slice` with
|
|
486
|
+
* the same order is not. And absence counts: reaching a node without its predecessor is the
|
|
487
|
+
* likelier real defect than reaching one out of sequence. */
|
|
488
|
+
const chain = chainFor(it.type);
|
|
489
|
+
const pos = chainPos(chain, obj.event);
|
|
490
|
+
if (pos > 0) {
|
|
491
|
+
const need = chain[pos - 1];
|
|
492
|
+
/* `failed` OCCUPIES the verify node — it needs `claimed` before it — but it does NOT SATISFY
|
|
493
|
+
* verify for anything after it. The distinction is the whole point and the first draft got it
|
|
494
|
+
* backwards in one direction: mapping `failed → verified` in `reached` let
|
|
495
|
+
* `declared → claimed → failed → integrated → shipped` fold clean with zero defects. A slice
|
|
496
|
+
* whose only verification outcome was a FAILURE shipped, at exit 0. `chainPos` handles the
|
|
497
|
+
* position; `reached` must not launder the outcome. */
|
|
498
|
+
const satisfied = standsSatisfied(it.history, need);
|
|
499
|
+
if (!satisfied) {
|
|
500
|
+
defects.push({
|
|
501
|
+
line: idx + 1, kind: 'out-of-order', item_id: id,
|
|
502
|
+
detail: `\`${obj.event}\` before \`${need}\` on a \`${it.type}\` — D65(d)'s chain for this type is ${chain.join(' → ')}`,
|
|
503
|
+
});
|
|
504
|
+
it.determinable = false;
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
it.history.push(obj.event);
|
|
510
|
+
switch (obj.event) {
|
|
511
|
+
case 'claimed': it.state = 'claimed'; it.claim = obj.claim; break;
|
|
512
|
+
case 'released': it.state = 'declared'; it.claim = null; break;
|
|
513
|
+
case 'verified': it.state = 'verified'; it.claim = null; it.evidence = obj.evidence; break;
|
|
514
|
+
case 'failed': it.state = 'failed'; it.claim = null; it.evidence = obj.evidence; break;
|
|
515
|
+
case 'integrated':it.state = 'integrated'; it.claim = null; break;
|
|
516
|
+
case 'shipped': it.state = 'shipped'; it.claim = null; it.evidence = obj.evidence; break;
|
|
517
|
+
case 'withdrawn': it.state = 'withdrawn'; it.claim = null; break;
|
|
518
|
+
default: it.determinable = false; break;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/* An expired claim is not a claim — and an UNKNOWN one is not an unexpired one.
|
|
523
|
+
*
|
|
524
|
+
* Instants, via Date.parse, never strings: '2026-08-04T10:00:00+07:00' and '2026-08-04T03:00:00Z'
|
|
525
|
+
* are the same moment, and a string compare says the first is later. That is how an offset defeats
|
|
526
|
+
* a lease.
|
|
527
|
+
*
|
|
528
|
+
* With no `now`, the state is `unknown` and the item is NOT claimable-as-if-expired. A missing
|
|
529
|
+
* input silently becoming the permissive case is the defect class this repo has now produced six
|
|
530
|
+
* times, and expiry is the worst place for it: it would hand a held item to a second agent. */
|
|
531
|
+
for (const it of byId.values()) {
|
|
532
|
+
if (it.state !== 'claimed' || !it.claim) continue;
|
|
533
|
+
const expMs = Date.parse(it.claim.expires_at);
|
|
534
|
+
if (nowMs === null || Number.isNaN(expMs)) {
|
|
535
|
+
it.claim_expiry = 'unknown'; // callers MUST NOT read this as expired
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
it.claim_expiry = expMs <= nowMs ? 'expired' : 'live';
|
|
539
|
+
if (expMs <= nowMs) {
|
|
540
|
+
it.state = 'declared';
|
|
541
|
+
it.claim_expired = it.claim;
|
|
542
|
+
it.claim = null;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
return { items: [...byId.values()], defects };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// ── The write boundary (R5) ────────────────────────────────────────────────────────────────────
|
|
550
|
+
|
|
551
|
+
/** The ONLY sink the factory may append to.
|
|
552
|
+
*
|
|
553
|
+
* This was `path.basename(targetPath) !== PERMITTED_BASENAME` and nothing else, which is not a
|
|
554
|
+
* location check: every directory on disk can hold a file called `work-items.jsonl`, and a symlink
|
|
555
|
+
* named that pointed anywhere at all. Measured 2026-08-04 — this module appended 198 bytes through
|
|
556
|
+
* a symlink into a decoy. The resolved-path + O_NOFOLLOW + nlink discipline now lives in
|
|
557
|
+
* scripts/lib/sink.js and is called, not re-implemented; see that file for why all six writers
|
|
558
|
+
* share one copy. */
|
|
559
|
+
const PERMITTED_BASENAME = 'work-items.jsonl';
|
|
560
|
+
/* `planning/`, NOT `planning/runs/`. check-work-items.js:22 reads the former and it is where the
|
|
561
|
+
* live ledger is; drive-guard.js:120 allowlists the latter, a path that has never existed — a third
|
|
562
|
+
* disagreement about one file, and more evidence that guard is unmaintained (nothing imports it but
|
|
563
|
+
* its own suite). Recorded in bootstrap-debt.md rather than fixed here. */
|
|
564
|
+
const SINK = createSinkGuard({
|
|
565
|
+
sink: path.resolve(__dirname, '..', 'planning', PERMITTED_BASENAME),
|
|
566
|
+
what: 'work-item events',
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Throw unless this exact write is permitted. There is no return value to ignore: the refusal is
|
|
571
|
+
* the mechanism, not a flag a caller may drop (drive-plan's advisory `plan()` is the shape this
|
|
572
|
+
* deliberately avoids).
|
|
573
|
+
*
|
|
574
|
+
* FAILS CLOSED. A request this function cannot parse is refused, not permitted — the explain-surface
|
|
575
|
+
* pass measured `assertWritable({})` returning permitted in the predecessor, and that specific
|
|
576
|
+
* behaviour is what this signature exists not to reproduce.
|
|
577
|
+
*
|
|
578
|
+
* WHERE IT IS LOOSER THAN THE WRITER: exactly the three sink shapes in `CHECK_OPEN_GAP`, and that
|
|
579
|
+
* list is exported and asserted rather than described. See its docstring.
|
|
580
|
+
*
|
|
581
|
+
* ── WHAT IT COSTS TO CHECK FIRST, MEASURED AND STATED ──────────────────────────────────────────
|
|
582
|
+
*
|
|
583
|
+
* Roughly DOUBLE. On a 5,000-line ledger (~700 KB, 1,000 items × 5 events), 25 timed appends after
|
|
584
|
+
* a 3-append warm-up, three runs on one machine:
|
|
585
|
+
*
|
|
586
|
+
* appendEvent alone 59.2 · 59.2 · 66.4 ms/append
|
|
587
|
+
* assertWritable + appendEvent 123.7 · 116.0 · 118.5 ms/append → 1.78–2.09×
|
|
588
|
+
*
|
|
589
|
+
* The ratio is the durable number and the milliseconds are not: they are this machine's, and an
|
|
590
|
+
* earlier pass on different hardware recorded 116 → 181 ms (1.56×). Read the multiplier.
|
|
591
|
+
*
|
|
592
|
+
* ~2× is not overhead, it is the same work twice. `assertWritable` runs the FULL fold — it reads the
|
|
593
|
+
* whole ledger and derives every item, because "would the fold discard this?" cannot be answered
|
|
594
|
+
* without folding — and then `appendEvent` folds again under the lock. Nothing is cached between
|
|
595
|
+
* them ON PURPOSE: a cached answer is a check-then-write race with extra steps, and the writer must
|
|
596
|
+
* re-decide under the lock or its decision is about a ledger that may no longer exist.
|
|
597
|
+
*
|
|
598
|
+
* SO DO NOT CALL BOTH IN A HOT LOOP. `appendEvent` is the authority and it throws — a caller that
|
|
599
|
+
* simply appends and handles `ForbiddenWrite` pays 1× and gets a stronger guarantee, because its
|
|
600
|
+
* decision is made under the lock. The predicate is for callers that must ask before acting (a UI
|
|
601
|
+
* disabling a button, a planner costing a batch), and for them one extra fold is the right price.
|
|
602
|
+
*/
|
|
603
|
+
function assertWritable(request) {
|
|
604
|
+
if (!isPlainObject(request)) {
|
|
605
|
+
throw new ForbiddenWrite('write request is not an object — refused (fail-closed)', { request: typeof request });
|
|
606
|
+
}
|
|
607
|
+
const { targetPath, event } = request;
|
|
608
|
+
if (typeof targetPath !== 'string' || !targetPath) {
|
|
609
|
+
throw new ForbiddenWrite('write request has no `targetPath` — refused (fail-closed)');
|
|
610
|
+
}
|
|
611
|
+
/* Delegated, not re-implemented — scripts/lib/sink.js owns the discipline for all six writers.
|
|
612
|
+
* `check` validates and compares RESOLVED paths (the basename comparison this replaced accepted
|
|
613
|
+
* every directory on disk). It deliberately does NOT open, because this function is used as a
|
|
614
|
+
* predicate and a predicate that creates its subject is not one. The link checks need a
|
|
615
|
+
* descriptor, so `appendEvent` is the authority; see sink.js `check` for why that gap is real. */
|
|
616
|
+
/* THE SAME EXISTENCE DEFAULT `appendEvent` USES. Without it this predicate PERMITTED exactly the
|
|
617
|
+
* append `appendEvent` refuses — an event naming an initiative that does not exist — because the
|
|
618
|
+
* default was applied in one of the two places the rule lives. A documented, exported "is this
|
|
619
|
+
* write allowed?" that disagrees with the writer is worse than no predicate: a caller checks it,
|
|
620
|
+
* gets `true`, and is refused a line later. */
|
|
621
|
+
const o = request.opts || {};
|
|
622
|
+
const supplied = typeof o.initiativeExists === 'function' ? o.initiativeExists : defaultInitiativeExists;
|
|
623
|
+
const opts = Object.assign({}, o, { initiativeExists: supplied });
|
|
624
|
+
SINK.check(targetPath, () => validateEvent(event, opts));
|
|
625
|
+
|
|
626
|
+
/* AND THE LEDGER-CONTEXT REFUSAL, WHICH IS THE OTHER HALF OF WHAT `appendEvent` REFUSES.
|
|
627
|
+
*
|
|
628
|
+
* Round 4 closed this predicate's disagreement with the writer for the `initiativeExists` half and
|
|
629
|
+
* a round-5 pass found the general case still open: `assertWritable` PERMITTED an undeclared item's
|
|
630
|
+
* `verified` that `appendEvent` throws on — under a suite section titled *"the exported predicate
|
|
631
|
+
* agrees with the writer it speaks for"*. Fixing one instance of a rule and leaving the class is
|
|
632
|
+
* the defect this repo keeps finding; here it was found inside the fix for its own first instance.
|
|
633
|
+
*
|
|
634
|
+
* `validateEvent` answers *is this event well-formed* from the event alone. `discardRefusal`
|
|
635
|
+
* answers *would the fold throw this away* — which needs the ledger, and is exactly the question
|
|
636
|
+
* that makes the two disagree. Running it here is what makes the predicate's name true.
|
|
637
|
+
*
|
|
638
|
+
* WHAT THIS PREDICATE STILL CANNOT PROMISE, stated because a caller will otherwise read `true` as
|
|
639
|
+
* a guarantee: it does not hold the lock, so between `assertWritable` returning and the caller
|
|
640
|
+
* appending, another writer may land an event that changes the answer. It is a predicate, not a
|
|
641
|
+
* reservation. `appendEvent` re-checks under the lock and remains the authority — a caller that
|
|
642
|
+
* needs the decision to hold must call `appendEvent` and handle its throw, not consult this first. */
|
|
643
|
+
/* THE SAME LEDGER RULES THE WRITER APPLIES — from the same function, not a second copy.
|
|
644
|
+
*
|
|
645
|
+
* This one predicate has now disagreed with `appendEvent` in three consecutive rounds. Round 4:
|
|
646
|
+
* it did not apply the `initiativeExists` default. Round 5: it did not run `discardRefusal`.
|
|
647
|
+
* Round 6: it did not run `claimRefusal`, so it said YES to a second agent stealing a live-held
|
|
648
|
+
* claim that the writer refuses deterministically. Each round fixed the instance in front of it
|
|
649
|
+
* and the next round found the next instance — the unit of attention was the instance and the unit
|
|
650
|
+
* of the defect is the rule.
|
|
651
|
+
*
|
|
652
|
+
* So the two now call ONE function. There is no list here to fall out of step, and a refusal added
|
|
653
|
+
* to `ledgerRefusal` reaches both by construction rather than by someone remembering. */
|
|
654
|
+
const refusal = ledgerRefusal(targetPath, event, opts);
|
|
655
|
+
if (refusal) throw new ForbiddenWrite(refusal, { item_id: event && event.item_id });
|
|
656
|
+
return true;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Every ledger-context rule, in one place, for the two callers that must agree.
|
|
661
|
+
*
|
|
662
|
+
* Returns the first refusal message, or null if the append is permitted. It reads the ledger and so
|
|
663
|
+
* cannot live in `validateEvent`, which answers form alone and must hold in a vendored kit with no
|
|
664
|
+
* repository to resolve against (B12).
|
|
665
|
+
*
|
|
666
|
+
* WHAT IT STILL CANNOT PROMISE, stated because a caller will otherwise read `null` as a guarantee:
|
|
667
|
+
* `assertWritable` calls this WITHOUT the lock, so between the answer and the caller's append another
|
|
668
|
+
* writer may change it. It is a predicate, not a reservation. `appendEvent` calls it INSIDE the lock
|
|
669
|
+
* for claim events and remains the authority.
|
|
670
|
+
*/
|
|
671
|
+
function ledgerRefusal(sinkPath, event, opts) {
|
|
672
|
+
const ahead = futureRefusal(event, opts);
|
|
673
|
+
if (ahead) return `post-dated append refused — ${ahead}`;
|
|
674
|
+
const unranked = dispatchRefusal(event, opts);
|
|
675
|
+
if (unranked) return `dispatch refused — ${unranked}`;
|
|
676
|
+
if (CLAIM_EVENTS.includes(event && event.event)) {
|
|
677
|
+
const claimBlocked = claimRefusal(sinkPath, event, opts);
|
|
678
|
+
if (claimBlocked) return `claim refused — ${claimBlocked}`;
|
|
679
|
+
}
|
|
680
|
+
const discarded = discardRefusal(sinkPath, event, opts);
|
|
681
|
+
if (discarded) return `the fold would discard this append — ${discarded}`;
|
|
682
|
+
return null;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/* ── CLAIM EXCLUSIVITY (D65 step 3) ────────────────────────────────────────────────────────────
|
|
686
|
+
*
|
|
687
|
+
* An independent explain-surface pass measured that a second agent's `claimed` on a held item
|
|
688
|
+
* VALIDATES, is PERMITTED, is APPENDED — `appendEvent` never opened the file for reading — and
|
|
689
|
+
* leaves the checker exiting 0 over the double-claimed result. Agent B simply won.
|
|
690
|
+
*
|
|
691
|
+
* Reading the ledger and then appending is a TOCTOU: two agents both read "unclaimed" and both
|
|
692
|
+
* append, and the append itself being byte-atomic does not help, because the RACE IS IN THE DECISION.
|
|
693
|
+
* So the decision is serialized by an O_EXCL lock file, which is atomic on one filesystem — the only
|
|
694
|
+
* competitor the PRD scopes for. Two hosts would need re-deciding; that is recorded, not assumed.
|
|
695
|
+
*
|
|
696
|
+
* The lock covers the whole ledger rather than one item. At the PM's stated intake the contention is
|
|
697
|
+
* nil, and a per-item lock buys nothing but more ways to be wrong.
|
|
698
|
+
*/
|
|
699
|
+
const LOCK_STALE_MS = 60_000;
|
|
700
|
+
|
|
701
|
+
/** The writer's clock. Real by default; overridable ONLY under the same gate as the sink seam.
|
|
702
|
+
*
|
|
703
|
+
* `opts.now` is deliberately ignored here. A caller may pass it to `deriveItems` — that fold is
|
|
704
|
+
* pure and answers "what did this ledger look like at time T", which is a legitimate question. It
|
|
705
|
+
* may NOT decide whether someone else's lease has expired. */
|
|
706
|
+
let CLOCK_OVERRIDE_FOR_TESTS = null;
|
|
707
|
+
function __setClockForTests(iso) {
|
|
708
|
+
/* The same truthiness set sink.js uses. Three gates on one env var disagreeing about what 'on'
|
|
709
|
+
* means is a suite that fails for a reason nobody connects to the flag. */
|
|
710
|
+
const on = (v) => v === '1' || v === 'true' || v === 'yes';
|
|
711
|
+
if (process.env.NODE_ENV !== 'test' && !on(process.env.PMOS_TEST)) {
|
|
712
|
+
throw new ForbiddenWrite('__setClockForTests is a test seam — set NODE_ENV=test or PMOS_TEST=1 to use it');
|
|
713
|
+
}
|
|
714
|
+
CLOCK_OVERRIDE_FOR_TESTS = iso;
|
|
715
|
+
}
|
|
716
|
+
function writerNow() { return CLOCK_OVERRIDE_FOR_TESTS || new Date().toISOString(); }
|
|
717
|
+
|
|
718
|
+
/* HOW FAR AHEAD OF THE WRITER'S CLOCK AN EVENT MAY CLAIM TO HAVE HAPPENED.
|
|
719
|
+
*
|
|
720
|
+
* Generous, because the cost of the two errors is not symmetric: a refused legitimate append is
|
|
721
|
+
* noisy and fixable, and a permitted post-dated one silently decides an item's state forever. Five
|
|
722
|
+
* minutes covers ordinary clock skew between two machines writing the same ledger; it does not cover
|
|
723
|
+
* 2099. */
|
|
724
|
+
const FUTURE_SKEW_MS = 5 * 60 * 1000;
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Would this event claim to have happened in the future?
|
|
728
|
+
*
|
|
729
|
+
* WHY THIS EXISTS, AND WHY IT IS A WRITE-TIME RULE RATHER THAN A VALIDATION RULE.
|
|
730
|
+
*
|
|
731
|
+
* The chain rule decides a node's standing by its LATEST outcome, and "latest" is decided by `at` —
|
|
732
|
+
* which until now was a caller-supplied string checked only for ISO shape. An independent pass drove
|
|
733
|
+
* the consequence through the real writer in three permitted appends: post-date `verified`,
|
|
734
|
+
* `integrated` and `shipped` to 2099 and a slice whose real verification outcome was FAILURE reaches
|
|
735
|
+
* `state: shipped`, `✓ every line is well-formed`, EXIT=0. Worse, it is unrecoverable — a genuine
|
|
736
|
+
* present-dated `failed` afterwards lands and changes nothing, because it sorts before the forgery.
|
|
737
|
+
* The assertion named *"a later failure revokes an earlier pass"* was defeated by one unauthenticated
|
|
738
|
+
* field revoking the revocation.
|
|
739
|
+
*
|
|
740
|
+
* It belongs at WRITE time, not in `validateEvent`, for the reason B12 gives about form and
|
|
741
|
+
* resolution: `validateEvent` must hold in a vendored kit reading an old ledger, where every `at` is
|
|
742
|
+
* legitimately in the past of nothing and there may be no meaningful clock. A historical ledger is
|
|
743
|
+
* not invalid. An APPEND claiming the future is.
|
|
744
|
+
*
|
|
745
|
+
* `claimRefusal` already names this class — *"the winner is decided by a self-reported string"* — and
|
|
746
|
+
* applied the writer's own clock to lease expiry only. This applies it to the event's own timestamp,
|
|
747
|
+
* which is what the ordering rule actually reads.
|
|
748
|
+
*/
|
|
749
|
+
function futureRefusal(event, opts) {
|
|
750
|
+
const at = event && event.at;
|
|
751
|
+
if (typeof at !== 'string') return null; // shape is validateEvent's job; it has already refused
|
|
752
|
+
const t = Date.parse(at);
|
|
753
|
+
if (Number.isNaN(t)) return null;
|
|
754
|
+
/* THE WRITER'S OWN CLOCK, NEVER THE CALLER'S — and this line read `opts.now` for one round.
|
|
755
|
+
*
|
|
756
|
+
* `writerNow`'s docstring forty lines up says `opts.now` "may NOT decide whether someone else's
|
|
757
|
+
* lease has expired", and `claimRefusal`'s comment records an independent pass taking a live-held
|
|
758
|
+
* item by passing `now: '2099-01-01'`, concluding: *the defect is the WRITER deferring to the
|
|
759
|
+
* caller about what time it is.* This guard — written to stop a post-dated append — deferred to the
|
|
760
|
+
* caller about what time it is, in the same commit, one function over. Round 6's exact 2099 walk
|
|
761
|
+
* reproduced verbatim with one extra field, and removing the offending clause reddened no
|
|
762
|
+
* assertion, which is what a defect looks like from the suite's side.
|
|
763
|
+
*
|
|
764
|
+
* `writerNow()` is overridable only through `__setClockForTests`, which is gated on NODE_ENV=test
|
|
765
|
+
* or PMOS_TEST — the same gate as the sink seam. A caller cannot reach it through an options bag. */
|
|
766
|
+
const now = Date.parse(writerNow());
|
|
767
|
+
if (Number.isNaN(now)) return null;
|
|
768
|
+
if (t - now <= FUTURE_SKEW_MS) return null;
|
|
769
|
+
return `\`at\` ${at} is ${Math.round((t - now) / 60000)} minutes ahead of the writer's clock `
|
|
770
|
+
+ `(${new Date(now).toISOString()}), beyond the ${FUTURE_SKEW_MS / 60000}-minute skew allowance. `
|
|
771
|
+
+ 'The chain rule decides a node\'s standing by the LATEST outcome, so a post-dated event decides '
|
|
772
|
+
+ 'it permanently and cannot be corrected by a later honest one.';
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** Thrown when the LOCK could not be taken — never when a rule refused the write.
|
|
776
|
+
*
|
|
777
|
+
* Both used to be `ForbiddenWrite`, so a caller could not tell *the ledger says no* from *try
|
|
778
|
+
* again in a moment*, and the second is retryable while the first never is. An independent pass
|
|
779
|
+
* measured 3 of 8 concurrent writers refused on a 5,000-line ledger with a message
|
|
780
|
+
* indistinguishable by class from a policy refusal — and D65's factory graph is "N in parallel,
|
|
781
|
+
* ticks in hours", so that is the load this has to survive rather than an unusual one. */
|
|
782
|
+
class LockUnavailable extends Error {
|
|
783
|
+
constructor(detail) {
|
|
784
|
+
super(`work-item ledger lock unavailable — ${detail}. This is a CONTENTION failure, not a refusal: the write was never adjudicated and retrying is correct.`);
|
|
785
|
+
this.name = 'LockUnavailable';
|
|
786
|
+
this.retryable = true;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/* Budget, not attempts. The old loop was 100 tries × a 10 ms busy spin ≈ a 1 s ceiling, while one
|
|
791
|
+
* append costs ~112 ms on a 5,000-line ledger — so a handful of concurrent writers exhausted it and
|
|
792
|
+
* were refused for being ordinary. The wait is now a real deadline with exponential backoff and
|
|
793
|
+
* jitter, and it SLEEPS rather than spinning: a busy-wait under contention burns the CPU the holder
|
|
794
|
+
* needs to finish, which makes the queue it is waiting on slower. */
|
|
795
|
+
/* STRICTLY GREATER THAN `LOCK_STALE_MS`, and the ordering is the requirement rather than the
|
|
796
|
+
* numbers. At 30 s against a 60 s stale threshold the reclaim branch was unreachable inside a single
|
|
797
|
+
* call, so a crashed holder became a hard 30 s stall and then a throw — a NEW hang, introduced by
|
|
798
|
+
* the fix for a denial of service. A waiter must be able to outlive the staleness it is waiting on,
|
|
799
|
+
* or the recovery path exists only for a caller that retries. Asserted by name in the suite. */
|
|
800
|
+
const LOCK_WAIT_MS = LOCK_STALE_MS + 10000;
|
|
801
|
+
|
|
802
|
+
/** A real sleep, not a spin. `while (Date.now() < until) {}` burns the CPU the lock holder needs to
|
|
803
|
+
* finish, so a busy-wait under contention makes the queue it is waiting on slower — the classic
|
|
804
|
+
* way a fairness problem becomes a throughput problem. `Atomics.wait` blocks this thread and
|
|
805
|
+
* nothing else. */
|
|
806
|
+
function sleepSync(ms) {
|
|
807
|
+
try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }
|
|
808
|
+
catch { const until = Date.now() + ms; while (Date.now() < until) { /* last resort */ } }
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
function acquireLock(ledgerPath) {
|
|
812
|
+
const lockPath = ledgerPath + '.lock';
|
|
813
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
814
|
+
let backoff = 2;
|
|
815
|
+
let waited = 0;
|
|
816
|
+
let unlinkFailure = null;
|
|
817
|
+
for (;;) {
|
|
818
|
+
try {
|
|
819
|
+
const fd = fs.openSync(lockPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o644);
|
|
820
|
+
fs.writeSync(fd, String(process.pid));
|
|
821
|
+
fs.closeSync(fd);
|
|
822
|
+
return lockPath;
|
|
823
|
+
} catch (e) {
|
|
824
|
+
if (e.code !== 'EEXIST') throw new ForbiddenWrite(`cannot lock the work-item ledger (${e.code || e.message}) — refused (fail-closed)`);
|
|
825
|
+
/* A holder that died leaves the lock behind, and a deadlock is not safer than a race — it is
|
|
826
|
+
* the same outage with a better excuse. Age it out, but only well past any real hold. */
|
|
827
|
+
let age = 0;
|
|
828
|
+
try { age = Date.now() - fs.statSync(lockPath).mtimeMs; } catch { age = 0; }
|
|
829
|
+
if (age > LOCK_STALE_MS) {
|
|
830
|
+
/* `continue` only on an ACTUAL reclaim. Unconditional, this branch ran before both the
|
|
831
|
+
* deadline check and the sleep — so a stale lock that cannot be unlinked (a root-owned
|
|
832
|
+
* leftover in a container, a directory wearing the lock's name; O_EXCL reports EEXIST
|
|
833
|
+
* either way) was attempt 3's unbounded 100%-CPU spin, recorded in the revert note below
|
|
834
|
+
* and still live on this path. When the unlink fails AND the file persists, fall through:
|
|
835
|
+
* the waiter sleeps like any other, and the deadline converts it into a typed, retryable
|
|
836
|
+
* refusal instead of a process that never returns. */
|
|
837
|
+
let gone = true;
|
|
838
|
+
try { fs.unlinkSync(lockPath); }
|
|
839
|
+
catch (ue) { gone = !fs.existsSync(lockPath); /* gone anyway = another waiter won */ if (!gone) unlinkFailure = ue.code || ue.message; }
|
|
840
|
+
if (gone) continue;
|
|
841
|
+
}
|
|
842
|
+
if (Date.now() >= deadline) {
|
|
843
|
+
throw new LockUnavailable(unlinkFailure
|
|
844
|
+
? `waited ${waited} ms on a STALE lock that cannot be removed (unlink: ${unlinkFailure}) — ${lockPath} needs a hand: delete it or fix its ownership`
|
|
845
|
+
: `waited ${waited} ms for a holder that did not finish (stale threshold ${LOCK_STALE_MS} ms)`);
|
|
846
|
+
}
|
|
847
|
+
/* Jittered, so N writers released together do not collide again in lockstep. */
|
|
848
|
+
const nap = Math.min(backoff, 250) + 1 + (process.pid % 7);
|
|
849
|
+
sleepSync(nap);
|
|
850
|
+
waited += nap;
|
|
851
|
+
backoff = Math.min(backoff * 2, 250);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
const releaseLock = (lockPath) => { try { fs.unlinkSync(lockPath); } catch { /* already gone */ } };
|
|
857
|
+
|
|
858
|
+
/** Read the ledger this write is bound for and refuse a claim on a live, differently-held item.
|
|
859
|
+
* The ledger is read from the TARGET, never from a caller-supplied snapshot — a caller-supplied
|
|
860
|
+
* view of the world is the same defect class as a caller-supplied sink. */
|
|
861
|
+
/** Events that CHANGE WHO HOLDS AN ITEM, and therefore must be excluded against the live claim.
|
|
862
|
+
*
|
|
863
|
+
* This was `claimed` alone, and the gap was not subtle: `released` ends a claim, so a non-holder
|
|
864
|
+
* took a live-held item in two permitted appends — `released`, which no refusal path looked at, and
|
|
865
|
+
* then `claimed`, which now saw a free item and allowed it. An independent pass ran it against a
|
|
866
|
+
* lease held by agentA until 2099: both appends landed, zero defects reported, the derived holder
|
|
867
|
+
* was agentB, and the checker was clean. The module header said "everything else appends
|
|
868
|
+
* unserialized — only claims race", and the PRD is titled "a claim nobody can steal"; both were
|
|
869
|
+
* broader than what the code enforced.
|
|
870
|
+
*
|
|
871
|
+
* A release is a claim event in every way that matters — same holder question, same lock. What is
|
|
872
|
+
* NOT here is deliberate: `verified`, `failed`, `shipped` and the rest report on the work, not on
|
|
873
|
+
* who holds it, and serializing them would buy nothing and cost every append a lock. */
|
|
874
|
+
const CLAIM_EVENTS = Object.freeze(['claimed', 'released']);
|
|
875
|
+
|
|
876
|
+
function claimRefusal(targetPath, event, opts) {
|
|
877
|
+
const o = opts || {};
|
|
878
|
+
let raw = '';
|
|
879
|
+
raw = readLedgerSafely(targetPath); // same rule, same reason — one reader, not two
|
|
880
|
+
if (!raw) return null; // no ledger yet: nothing is held
|
|
881
|
+
/* THE CLOCK IS THE WRITER'S, NOT THE CALLER'S.
|
|
882
|
+
*
|
|
883
|
+
* This read `{ now: o.now }`, which made the exclusion's decision input a caller-supplied,
|
|
884
|
+
* unauthenticated parameter — and A1 already forbids a caller-supplied ledger snapshot for exactly
|
|
885
|
+
* this reason. The clock is the other half of that snapshot. Measured by an independent pass:
|
|
886
|
+
* agent B took a live-held item by passing `now: '2099-01-01'`. No race, no privilege, one field;
|
|
887
|
+
* 147 bytes landed and at the honest clock the derived holder was B. That is this initiative's own
|
|
888
|
+
* Problem statement — "the winner is decided by a self-reported string" — relocated from `at` to
|
|
889
|
+
* `now`, and success criterion 2 blocks the post-dated `at` while the isomorphic post-dated `now`
|
|
890
|
+
* succeeded. Under real concurrency with a two-day skew between racers, races ended with
|
|
891
|
+
* TWO live claims and both processes reporting success.
|
|
892
|
+
*
|
|
893
|
+
* `deriveItems` stays PURE and keeps taking `now` as a parameter — that is what makes the fold
|
|
894
|
+
* deterministic and testable, and it is not the defect. The defect is the WRITER deferring to the
|
|
895
|
+
* caller about what time it is. The writer reads the real clock; the test seam below is gated the
|
|
896
|
+
* same way the sink override is, so a test can still pin it without production being able to. */
|
|
897
|
+
// `writerNow()` takes NO argument — the call sites used to pass the options bag, which read as
|
|
898
|
+
// the caller's opts feeding the clock and invited the next editor to make that true. See the
|
|
899
|
+
// docstring on writerNow: the caller may never decide what time it is.
|
|
900
|
+
const { items } = deriveItems(raw, { now: writerNow() });
|
|
901
|
+
const held = items.find((i) => i.item_id === event.item_id);
|
|
902
|
+
if (!held || held.state !== 'claimed' || !held.claim) return null;
|
|
903
|
+
|
|
904
|
+
/* UNKNOWN is not expired. With no `now` the lease's state cannot be established, and handing the
|
|
905
|
+
* item over on that basis is exactly the substitution this step exists to remove. */
|
|
906
|
+
/* THE HOLDER'S OWN RENEWAL IS DECIDED FIRST, and the order was wrong.
|
|
907
|
+
*
|
|
908
|
+
* The unknown-clock refusal used to run before this, so with no usable clock the agent that HOLDS
|
|
909
|
+
* the lease was refused its own renewal — and, in the sandbox module, refused removal of its own
|
|
910
|
+
* worktree. "An agent loses work by continuing to do it" is the exact anchor-0 condition the
|
|
911
|
+
* renewal permit exists to prevent, produced by the guard written to protect it.
|
|
912
|
+
*
|
|
913
|
+
* A holder does not need to know whether its lease has expired: it holds it either way, and
|
|
914
|
+
* renewing is the one action that is safe under every clock state. */
|
|
915
|
+
if (event.claim && event.claim.agent === held.claim.agent) return null;
|
|
916
|
+
|
|
917
|
+
/* A RELEASE BY A NON-HOLDER IS A THEFT IN ONE MORE STEP. The holder's own release took the branch
|
|
918
|
+
* above; anything reaching here is a different agent ending someone else's lease. `agent` is
|
|
919
|
+
* self-reported — nothing in this system authenticates one — so this refuses the CHEAP route, not
|
|
920
|
+
* every route. That limit is stated rather than papered over: an agent willing to claim it is
|
|
921
|
+
* agentA is not stopped by anything here, and D65(h) is what would stop it. */
|
|
922
|
+
if (event.event === 'released') {
|
|
923
|
+
const who = (event.claim && event.claim.agent) || (event.released_by) || 'an unnamed agent';
|
|
924
|
+
if (held.claim_expiry === 'live' || held.claim_expiry === 'unknown') {
|
|
925
|
+
return `'${event.item_id}' is held by '${held.claim.agent}'` +
|
|
926
|
+
(held.claim_expiry === 'live' ? ` until ${held.claim.expires_at}` : ' on a lease that cannot be shown to have expired') +
|
|
927
|
+
` — '${who}' may not release it. A release by a non-holder is a claim transfer in two steps.`;
|
|
928
|
+
}
|
|
929
|
+
return null;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
if (held.claim_expiry === 'unknown') {
|
|
933
|
+
return `'${event.item_id}' is claimed by '${held.claim.agent}' and the lease cannot be shown to ` +
|
|
934
|
+
'have expired — refused rather than assumed free';
|
|
935
|
+
}
|
|
936
|
+
if (held.claim_expiry !== 'live') return null;
|
|
937
|
+
return `'${event.item_id}' is held by '${held.claim.agent}' until ${held.claim.expires_at} — ` +
|
|
938
|
+
`'${event.claim && event.claim.agent}' may not take it. Wait for release or expiry.`;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/** The single permitted mutation in this module. Appends one validated event line through the
|
|
942
|
+
* guard — validate before open, O_NOFOLLOW, `nlink === 1`, and the write goes to the descriptor
|
|
943
|
+
* that was vetted rather than to a path re-opened afterwards.
|
|
944
|
+
*
|
|
945
|
+
* A CLAIM EVENT — `claimed` or `released`, the two that change who holds an item — additionally
|
|
946
|
+
* takes the ledger lock, so the read-then-decide window is closed rather than narrowed. Everything
|
|
947
|
+
* else appends unserialized.
|
|
948
|
+
*
|
|
949
|
+
* This said "only claims race" while the set was `claimed` alone, which was the sentence and the
|
|
950
|
+
* bug in one place: a non-holder appended `released` unserialized and unrefused, then claimed the
|
|
951
|
+
* now-free item. See CLAIM_EVENTS. */
|
|
952
|
+
/** Read the ledger the way sink.js opens it, and for the same reason.
|
|
953
|
+
*
|
|
954
|
+
* `fs.readFileSync(path)` on a FIFO BLOCKS FOREVER waiting for a writer. This module already knew
|
|
955
|
+
* that — `workspace/lib/sink.js` opens with `O_NONBLOCK` precisely because a FIFO planted at the
|
|
956
|
+
* sink path once hung this suite past its timeout. The first draft of `wouldBeDiscarded` read the
|
|
957
|
+
* raw caller-supplied path with a plain `readFileSync`, BEFORE the sink guard had resolved or
|
|
958
|
+
* vetted anything, and hung the suite at the very assertion that plants one. I reintroduced the
|
|
959
|
+
* defect the guard exists for, one function away from the guard.
|
|
960
|
+
*
|
|
961
|
+
* So: open non-blocking, refuse to follow a symlink, `fstat` it, and treat anything that is not a
|
|
962
|
+
* regular file as *no ledger* rather than as something to read. A caller who planted a FIFO gets
|
|
963
|
+
* the same answer as a caller with no ledger at all — and the write that follows is still
|
|
964
|
+
* adjudicated by the sink guard, which is where refusing that path belongs. */
|
|
965
|
+
function readLedgerSafely(p) {
|
|
966
|
+
let fd = null;
|
|
967
|
+
try {
|
|
968
|
+
fd = fs.openSync(p, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | (fs.constants.O_NOFOLLOW || 0));
|
|
969
|
+
if (!fs.fstatSync(fd).isFile()) return ''; // a FIFO, a device, a directory — not a ledger
|
|
970
|
+
return fs.readFileSync(fd, 'utf8');
|
|
971
|
+
} catch (e) {
|
|
972
|
+
/* ── A READ FAILURE IS NOT AN EMPTY LEDGER. ──────────────────────────────────────────────────
|
|
973
|
+
*
|
|
974
|
+
* This collapsed every failure into `''`, and both callers read `''` as *nothing is here* — so
|
|
975
|
+
* every fold-derived refusal FAILED OPEN. Measured on a 566 MB ledger, past Node's string
|
|
976
|
+
* limit: the read returned length 0, and a second `declared` for an already-declared item was
|
|
977
|
+
* PERMITTED. A permitted append that produces a defect is the exact property this module
|
|
978
|
+
* exists to hold.
|
|
979
|
+
*
|
|
980
|
+
* A missing file genuinely is an empty ledger and stays `''`. Anything else — too large,
|
|
981
|
+
* permission denied, EIO — is a ledger this process cannot read, and refusing is the only
|
|
982
|
+
* honest answer: it is precisely the case where "I saw nothing" and "there is nothing" differ. */
|
|
983
|
+
if (e && e.code === 'ENOENT') return '';
|
|
984
|
+
throw new ForbiddenWrite(
|
|
985
|
+
`the work-item ledger could not be read (${e && e.code ? e.code : e && e.message}) — refused rather than treated as empty, `
|
|
986
|
+
+ 'because a fold over a ledger this process cannot see would permit anything it contradicts');
|
|
987
|
+
} finally {
|
|
988
|
+
if (fd !== null) { try { fs.closeSync(fd); } catch { /* already gone */ } }
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/** ── WOULD THE FOLD THROW THIS AWAY? DERIVED BY COMPARING TWO FOLDS. ────────────────────────────
|
|
993
|
+
*
|
|
994
|
+
* `validateEvent` is handed one event and no ledger context, so it permitted appends the fold then
|
|
995
|
+
* discarded — measured before this build: `appendEvent` PERMITTED a `verified` for an item nobody
|
|
996
|
+
* declared, and `deriveItems` returned `items: []` with an `unknown-item` defect. The writer could
|
|
997
|
+
* produce a state no reader can resolve.
|
|
998
|
+
*
|
|
999
|
+
* THE FIRST DRAFT OF THIS CHECK WAS WRONG IN TWO WAYS, AND AN INDEPENDENT PASS PROVED BOTH.
|
|
1000
|
+
*
|
|
1001
|
+
* (a) It classified defects against a LIST of kinds while its own comment claimed the list was
|
|
1002
|
+
* derived. Adding a new defect kind to `deriveItems` left the suite green and the writer
|
|
1003
|
+
* immediately permitted an append the fold discarded. There is no list now: the question is
|
|
1004
|
+
* answered by folding twice and comparing, so a defect kind added tomorrow is covered by
|
|
1005
|
+
* construction rather than by an edit nobody remembers to make.
|
|
1006
|
+
*
|
|
1007
|
+
* (b) It looked only at defects on the CANDIDATE'S OWN LINE (`d.line === after.length`) — and
|
|
1008
|
+
* `deriveItems` SORTS BY `at` before folding, so a backdated event lands somewhere else
|
|
1009
|
+
* entirely and the damage it does lands on OTHER lines. Measured: on a clean
|
|
1010
|
+
* `declared → claimed → verified → integrated → shipped` ledger, appending a `withdrawn`
|
|
1011
|
+
* backdated before `integrated` was PERMITTED, and the fold then reported `after-terminal` on
|
|
1012
|
+
* two later lines with `determinable: false`. A backdated second `declared` was permitted the
|
|
1013
|
+
* same way and silently rewrote the item's `type`, flipping which ordering chain applies.
|
|
1014
|
+
*
|
|
1015
|
+
* So the property is stated over the WHOLE FOLD, in three parts, none of them a list:
|
|
1016
|
+
* 1. the append introduces no defect anywhere that was not there before;
|
|
1017
|
+
* 2. the event actually lands — it appears in its item's history, or it is the `declared` that
|
|
1018
|
+
* creates the item;
|
|
1019
|
+
* 3. no item that was determinable stops being determinable.
|
|
1020
|
+
* Any of the three failing means the fold would throw this away, whatever the fold calls it. */
|
|
1021
|
+
/** Build the existence oracle for a given repository root. ONE implementation, two callers.
|
|
1022
|
+
*
|
|
1023
|
+
* ── WHY THIS IS A FACTORY AND NOT TWO SIMILAR FUNCTIONS ────────────────────────────────────────
|
|
1024
|
+
*
|
|
1025
|
+
* Round 4 made the writer look where the gate looks and the two still disagreed, because they were
|
|
1026
|
+
* written separately and asked the question differently: the writer used `statSync().isFile()`, the
|
|
1027
|
+
* gate listed the directory and kept every name ending `.md`. A DIRECTORY named `<id>.md` — which
|
|
1028
|
+
* `mkdir` creates as easily as a file — made the gate say YES and the writer say NO. The direction
|
|
1029
|
+
* is fail-safe (the writer refuses what the gate would accept, never the reverse), which is why it
|
|
1030
|
+
* was a MEDIUM and not a HIGH. It is still two answers to one question, and this repo has now
|
|
1031
|
+
* watched four rounds of exactly that shape: the unit of attention was the instance, and the unit
|
|
1032
|
+
* of the defect is the rule.
|
|
1033
|
+
*
|
|
1034
|
+
* So there is no second implementation left to drift. Both callers get the SAME closure over a
|
|
1035
|
+
* different root, and a change to what counts as a record reaches both by construction.
|
|
1036
|
+
*
|
|
1037
|
+
* The root is a parameter rather than a cwd read: the writer is called from a CLI, from a suite
|
|
1038
|
+
* with a `mkdtemp` cwd, and from the workspace, and a cwd-relative lookup would answer differently
|
|
1039
|
+
* in each — which is the original defect, relocated.
|
|
1040
|
+
*
|
|
1041
|
+
* @param {string} rootDir repository root; the records live at `<rootDir>/planning/initiatives/`.
|
|
1042
|
+
* @returns {(id: string) => boolean}
|
|
1043
|
+
*/
|
|
1044
|
+
/**
|
|
1045
|
+
* THE THREE SINK SHAPES `assertWritable` PERMITS AND `appendEvent` REFUSES — named, exported and
|
|
1046
|
+
* asserted, because a divergence recorded only in a comment is a divergence nobody measures.
|
|
1047
|
+
*
|
|
1048
|
+
* `assertWritable` is a predicate, and a predicate that opens its subject is not one: opening
|
|
1049
|
+
* creates the file, and re-resolving between the check and the open is the check-then-write race
|
|
1050
|
+
* `sink.js` exists to close. So the link and file-type facts — which need a DESCRIPTOR, not a path —
|
|
1051
|
+
* belong to `appendEvent`, which holds the lock and is the authority.
|
|
1052
|
+
*
|
|
1053
|
+
* The direction is the safe one and that is the entire reason this is an exemption rather than a
|
|
1054
|
+
* defect: the predicate is never STRICTER than the writer, only looser. A caller told `true` may
|
|
1055
|
+
* still be refused a line later, which is annoying; a caller told `false` that the writer would have
|
|
1056
|
+
* accepted would be a predicate nobody could trust. A 1,096-trial differential fuzz across every
|
|
1057
|
+
* (shape × event × ledger-state) combination found these three and nothing else.
|
|
1058
|
+
*
|
|
1059
|
+
* A change here is a deliberate act: closing one of these means deleting its row, and the suite goes
|
|
1060
|
+
* red until it does. Adding a fourth without naming it goes red the same way.
|
|
1061
|
+
*
|
|
1062
|
+
* Each row is checked by `scripts/tests/work-item.sh` in both directions — `check` PERMITS it,
|
|
1063
|
+
* `open` REFUSES it — so the list cannot quietly become fiction.
|
|
1064
|
+
*/
|
|
1065
|
+
const CHECK_OPEN_GAP = Object.freeze([
|
|
1066
|
+
Object.freeze({
|
|
1067
|
+
shape: 'fifo',
|
|
1068
|
+
why: 'a named pipe is a file type, and file type needs `fstat` on an open descriptor. Opening a FIFO to find out BLOCKS until a writer appears, which is how the gate once hung forever.',
|
|
1069
|
+
}),
|
|
1070
|
+
Object.freeze({
|
|
1071
|
+
shape: 'directory',
|
|
1072
|
+
why: 'a `stat` on the path would answer, but about a path that may not be the thing eventually opened. `open` gets EISDIR from the descriptor it actually holds.',
|
|
1073
|
+
}),
|
|
1074
|
+
Object.freeze({
|
|
1075
|
+
shape: 'hardlink',
|
|
1076
|
+
why: 'link count lives in the inode. `st_nlink > 1` is only trustworthy read from the descriptor being written to — a path-level stat is exactly the window a swap exploits.',
|
|
1077
|
+
}),
|
|
1078
|
+
]);
|
|
1079
|
+
|
|
1080
|
+
/* WHERE THE RECORDS ARE (launch simulation W7, kit-factory-builder). In PMOS-self this file sits in scripts/ and the records in
|
|
1081
|
+
* planning/initiatives/. In a kit (create-pmos) it sits in pmos/scripts/, and the records are in pmos/state/initiatives/ (the
|
|
1082
|
+
* engine's layout, workflow-state.js layout()). The kit has no planning/initiatives/, so the state folder is read only then. */
|
|
1083
|
+
function recordsDir(rootDir) {
|
|
1084
|
+
const self = path.join(rootDir, 'planning', 'initiatives');
|
|
1085
|
+
const kit = path.join(rootDir, 'state', 'initiatives');
|
|
1086
|
+
const isDir = (d) => { try { return fs.statSync(d).isDirectory(); } catch { return false; } };
|
|
1087
|
+
return !isDir(self) && isDir(kit) ? kit : self;
|
|
1088
|
+
}
|
|
1089
|
+
function makeInitiativeExists(rootDir) {
|
|
1090
|
+
return (id) => {
|
|
1091
|
+
if (typeof id !== 'string' || !id) return false;
|
|
1092
|
+
/* A traversal in `id` would reach outside the records directory, so the resolved path is
|
|
1093
|
+
* required to sit directly inside it. `..` is not a record name and never resolves to one. */
|
|
1094
|
+
const dir = recordsDir(rootDir);
|
|
1095
|
+
const file = path.join(dir, `${id}.md`);
|
|
1096
|
+
if (path.dirname(file) !== dir) return false;
|
|
1097
|
+
try { return fs.statSync(file).isFile(); }
|
|
1098
|
+
catch { return false; }
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/* ── DISPATCH REQUIRES A RANK ON THE ROADMAP (PRD R24 as amended by D105, map-spec X27) ───────────────
|
|
1103
|
+
*
|
|
1104
|
+
* A `declared` line is a dispatch: it puts work in the factory. For a FEATURE anchored to a KR, the
|
|
1105
|
+
* initiative must be ranked on the Roadmap: Prioritize's output (D105 retired Now / Next / Later, and with
|
|
1106
|
+
* them "starts only from Now"). A chore, an incident or a health-anchored initiative is not held to it
|
|
1107
|
+
* (R24: "for KR-anchored features only").
|
|
1108
|
+
*
|
|
1109
|
+
* The rank is read with a MINIMAL parse of the placements ledger: is there a `ranked` line, or an old
|
|
1110
|
+
* `placed` line at any horizon, for the initiative that is not a proposal? It does not require
|
|
1111
|
+
* workspace/lib/placements.js, because this file is a scripts/ writer that must run where the workspace is not
|
|
1112
|
+
* installed. The guard FAILS CLOSED on a forged line: a line without the writer's envelope (v 1, a
|
|
1113
|
+
* 12-character eid, via ui or cli) is skipped. An old `placed` line keeps counting, so an initiative the PM
|
|
1114
|
+
* placed before D105 is not held back. With no such line the answer is false: day one's activity order is a
|
|
1115
|
+
* guess, not a rank, so the first dispatch waits for someone to rank the initiative.
|
|
1116
|
+
*
|
|
1117
|
+
* A record that cannot be read gives no answer here: the existence check refuses a missing record, and a
|
|
1118
|
+
* test that names a fixture initiative (`demo`) supplies `initiativeExists` and no record. Both readers
|
|
1119
|
+
* can be replaced by a FUNCTION in opts (`recordOf`, `rankedOf`), the same rule as `initiativeExists`. */
|
|
1120
|
+
function frontmatterOf(text) {
|
|
1121
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(String(text || ''));
|
|
1122
|
+
if (!m) return null;
|
|
1123
|
+
const out = {};
|
|
1124
|
+
for (const line of m[1].split(/\r?\n/)) {
|
|
1125
|
+
const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line);
|
|
1126
|
+
if (kv) out[kv[1]] = kv[2].replace(/^(['"])(.*)\1$/, '$2').trim();
|
|
1127
|
+
}
|
|
1128
|
+
return out;
|
|
1129
|
+
}
|
|
1130
|
+
function makeRecordOf(rootDir) {
|
|
1131
|
+
const exists = makeInitiativeExists(rootDir);
|
|
1132
|
+
return (id) => {
|
|
1133
|
+
if (!exists(id)) return null;
|
|
1134
|
+
try { return frontmatterOf(fs.readFileSync(path.join(recordsDir(rootDir), `${id}.md`), 'utf8')); }
|
|
1135
|
+
catch { return null; }
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
/* The placements ledger is one per repository, in the MAIN working tree (workspace/lib/plan-ledgers.js), so a
|
|
1139
|
+
* dispatch from a linked worktree reads the rank the PM set in the main tree. The same filesystem-only walk
|
|
1140
|
+
* as workspace/lib/plan-tree.js mainTree, restated because this file may not require workspace/lib. */
|
|
1141
|
+
function mainTreeOf(root) {
|
|
1142
|
+
try {
|
|
1143
|
+
const dotgit = path.join(root, '.git');
|
|
1144
|
+
if (fs.statSync(dotgit).isDirectory()) return root;
|
|
1145
|
+
const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dotgit, 'utf8'));
|
|
1146
|
+
if (!m) return root;
|
|
1147
|
+
const gitdir = path.resolve(root, m[1].trim());
|
|
1148
|
+
const common = path.resolve(gitdir, fs.readFileSync(path.join(gitdir, 'commondir'), 'utf8').trim());
|
|
1149
|
+
if (path.basename(common) !== '.git') return root;
|
|
1150
|
+
const main = path.dirname(common);
|
|
1151
|
+
return fs.statSync(path.join(main, '.git')).isDirectory() ? main : root;
|
|
1152
|
+
} catch { return root; }
|
|
1153
|
+
}
|
|
1154
|
+
const PLACED_EID = /^[0-9a-z]{12}$/;
|
|
1155
|
+
const PLACED_VIA = new Set(['ui', 'cli']);
|
|
1156
|
+
const RANK_EVENTS = new Set(['ranked', 'placed']); // `placed` = a line written before D105, at any horizon
|
|
1157
|
+
/** (id) → true when a line ranked the initiative on the Roadmap (see the block comment above), else false. */
|
|
1158
|
+
function makeRankedOf(rootDir) {
|
|
1159
|
+
return (id) => {
|
|
1160
|
+
let text = '';
|
|
1161
|
+
// PMOS-self: planning/runs/; a kit: pmos/state/ (this file's root is pmos/ there, the engine's runsDir)
|
|
1162
|
+
try { text = fs.readFileSync(path.join(mainTreeOf(rootDir), 'planning', 'runs', 'placements.jsonl'), 'utf8'); }
|
|
1163
|
+
catch { try { text = fs.readFileSync(path.join(rootDir, 'state', 'placements.jsonl'), 'utf8'); } catch { return false; } }
|
|
1164
|
+
for (const raw of text.split('\n')) {
|
|
1165
|
+
if (!raw.trim()) continue;
|
|
1166
|
+
let r;
|
|
1167
|
+
try { r = JSON.parse(raw); } catch { continue; }
|
|
1168
|
+
if (!isPlainObject(r) || !RANK_EVENTS.has(r.ev) || r.initiative !== id || r.proposed === true) continue;
|
|
1169
|
+
if (r.v !== 1 || typeof r.eid !== 'string' || !PLACED_EID.test(r.eid) || !PLACED_VIA.has(r.via)) continue;
|
|
1170
|
+
if (typeof r.at !== 'string' || Number.isNaN(Date.parse(r.at))) continue;
|
|
1171
|
+
return true;
|
|
1172
|
+
}
|
|
1173
|
+
return false;
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
const defaultRecordOf = makeRecordOf(path.join(__dirname, '..'));
|
|
1177
|
+
const defaultRankedOf = makeRankedOf(path.join(__dirname, '..'));
|
|
1178
|
+
|
|
1179
|
+
/** null when this event may be dispatched; otherwise the reason, for the refusal. */
|
|
1180
|
+
function dispatchRefusal(event, opts) {
|
|
1181
|
+
if (!isPlainObject(event) || event.event !== 'declared' || typeof event.initiative_id !== 'string') return null;
|
|
1182
|
+
const o = opts || {};
|
|
1183
|
+
const recordOf = typeof o.recordOf === 'function' ? o.recordOf : defaultRecordOf;
|
|
1184
|
+
const rankedOf = typeof o.rankedOf === 'function' ? o.rankedOf : defaultRankedOf;
|
|
1185
|
+
const fm = recordOf(event.initiative_id);
|
|
1186
|
+
if (!fm) return null;
|
|
1187
|
+
const lane = String(fm.lane || '').trim() || 'feature';
|
|
1188
|
+
const anchor = String(fm.parent_kr || '').trim().split(/\s/)[0];
|
|
1189
|
+
if (lane !== 'feature' || !anchor || anchor.startsWith('health:')) return null;
|
|
1190
|
+
if (rankedOf(event.initiative_id) === true) return null;
|
|
1191
|
+
return `'${event.initiative_id}' is a feature anchored to ${anchor}, and it is not ranked on the Roadmap yet. `
|
|
1192
|
+
+ 'Factory work for a KR-anchored feature starts only once it is ranked (Prioritize, PRD R24 as amended by D105). '
|
|
1193
|
+
+ `Rank it with \`pmos initiative top ${event.initiative_id}\` (or up, down, bottom, after), then dispatch again.`;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
/** The DEFAULT the writer folds with, so that the writer and the gate answer the same question.
|
|
1197
|
+
*
|
|
1198
|
+
* `deriveItems`' discard set depends on `opts.initiativeExists`. The CI gate always supplies it;
|
|
1199
|
+
* the writer supplied it only if a caller happened to pass one — so an append naming an initiative
|
|
1200
|
+
* that does not exist was PERMITTED (211 bytes on disk) and `check-work-items.js` then reported
|
|
1201
|
+
* `✗ 1 defect (invalid)`, `0 item(s) derived`, exit 1. B4's property — "no append the writer
|
|
1202
|
+
* permits may be one the fold discards" — was false against the only fold that runs in CI, because
|
|
1203
|
+
* the two folds were not asking the same question. A caller may still pass its own; absent one, the
|
|
1204
|
+
* writer looks where the gate looks, through the same function the gate uses. */
|
|
1205
|
+
const defaultInitiativeExists = makeInitiativeExists(path.join(__dirname, '..'));
|
|
1206
|
+
|
|
1207
|
+
function discardRefusal(sinkPath, event, opts) {
|
|
1208
|
+
const raw = readLedgerSafely(sinkPath);
|
|
1209
|
+
|
|
1210
|
+
/* ── A TORN TAIL IS REFUSED, NOT MODELLED AWAY. ────────────────────────────────────────────────
|
|
1211
|
+
*
|
|
1212
|
+
* `before.concat(line)` assumes the file ends on a line boundary. `workspace/lib/sink.js` documents
|
|
1213
|
+
* a reachable torn tail it deliberately does NOT roll back — "the ledger holds a torn fragment
|
|
1214
|
+
* that must be repaired by hand". Measured against this module: with a fragment and no trailing
|
|
1215
|
+
* newline, a valid `claimed` was PERMITTED and concatenated INTO the fragment; the folded history
|
|
1216
|
+
* came back `["declared"]` and the `claimed` was gone. The writer permitted an append the fold
|
|
1217
|
+
* discarded — this module's entire thesis, falsified by a missing byte.
|
|
1218
|
+
*
|
|
1219
|
+
* Refused rather than repaired: appending a newline to fix it would be this writer editing history
|
|
1220
|
+
* it did not write, and the fragment may be half of a record whose other half matters. */
|
|
1221
|
+
if (raw.length && !raw.endsWith('\n')) {
|
|
1222
|
+
return 'the ledger does not end on a line boundary — a torn tail is present and this append would '
|
|
1223
|
+
+ 'concatenate into it. Repair the last line by hand (sink.js does not roll one back).';
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
const before = raw.split('\n').filter((l) => l.trim());
|
|
1227
|
+
const after = before.concat(JSON.stringify(event));
|
|
1228
|
+
/* `Object.assign(defaults, opts)` let a PRESENT key win even when it is not a function:
|
|
1229
|
+
* `{initiativeExists: undefined}`, `null` and `'yes'` each disabled the check and landed 224 bytes
|
|
1230
|
+
* the gate then reports as a defect. A default that any caller can turn off by naming it wrongly
|
|
1231
|
+
* is not a default. Only a FUNCTION overrides. */
|
|
1232
|
+
const supplied = opts && typeof opts.initiativeExists === 'function' ? opts.initiativeExists : defaultInitiativeExists;
|
|
1233
|
+
const o = Object.assign({}, opts, { initiativeExists: supplied, now: writerNow() });
|
|
1234
|
+
const b = deriveItems(before, o);
|
|
1235
|
+
const a = deriveItems(after, o);
|
|
1236
|
+
|
|
1237
|
+
/* ── SETS, NOT COUNTS. ─────────────────────────────────────────────────────────────────────────
|
|
1238
|
+
*
|
|
1239
|
+
* This compared `a.defects.length > b.defects.length`, so an append that REMOVED one defect could
|
|
1240
|
+
* add another for free. Proved against the real module: on a ledger of orphan `withdrawn` +
|
|
1241
|
+
* `shipped` (two `unknown-item`), a backdated `declared` was PERMITTED — it resolved both orphans
|
|
1242
|
+
* and introduced a fresh `after-terminal`, leaving `determinable: false`. The count did not move;
|
|
1243
|
+
* the ledger got worse. The comment beside it already said "introduces no defect ANYWHERE that was
|
|
1244
|
+
* not there before", which is a set statement, and the code was arithmetic. */
|
|
1245
|
+
const sig = (d) => `${d.kind}\u0000${d.item_id || ''}\u0000${d.detail || ''}`;
|
|
1246
|
+
const had = new Map();
|
|
1247
|
+
for (const d of b.defects) had.set(sig(d), (had.get(sig(d)) || 0) + 1);
|
|
1248
|
+
for (const d of a.defects) {
|
|
1249
|
+
const k = sig(d);
|
|
1250
|
+
const n = had.get(k) || 0;
|
|
1251
|
+
if (n === 0) return `the fold would report a new defect (${d.kind}): ${d.detail}`;
|
|
1252
|
+
had.set(k, n - 1);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
/* 2 — did it land? An event the fold silently ignores is a write the ledger did not record. */
|
|
1256
|
+
const id = String(event.item_id);
|
|
1257
|
+
const itemAfter = a.items.find((i) => i.item_id === id);
|
|
1258
|
+
if (!itemAfter) return `the fold does not produce item '${id}' after this append — the event would be ignored`;
|
|
1259
|
+
if (event.event !== 'declared') {
|
|
1260
|
+
const itemBefore = b.items.find((i) => i.item_id === id);
|
|
1261
|
+
const grew = (itemAfter.history || []).length === ((itemBefore && itemBefore.history) || []).length + 1;
|
|
1262
|
+
if (!grew) return `\`${event.event}\` does not appear in '${id}''s folded history — the fold would ignore it`;
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
/* 3 — nothing that could be read back stops being readable. */
|
|
1266
|
+
for (const wasOk of b.items.filter((i) => i.determinable)) {
|
|
1267
|
+
const now = a.items.find((i) => i.item_id === wasOk.item_id);
|
|
1268
|
+
if (now && !now.determinable) return `this append makes '${wasOk.item_id}' undeterminable`;
|
|
1269
|
+
}
|
|
1270
|
+
return null;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
function appendEvent(targetPath, event, opts) {
|
|
1274
|
+
/* ── EVERY APPEND TAKES THE LOCK NOW, AND THE READ HAPPENS ON THE VETTED SINK PATH. ─────────────
|
|
1275
|
+
*
|
|
1276
|
+
* Two findings from an independent pass, and the first was a comment broader than its code.
|
|
1277
|
+
*
|
|
1278
|
+
* (a) The first draft said the discard check "answers *is this event coherent with history*, which
|
|
1279
|
+
* a concurrent append cannot make false — only a concurrent CLAIM can, and claims still take
|
|
1280
|
+
* the lock." False. Non-claim appends took no lock at all, and two barrier-synchronised
|
|
1281
|
+
* processes appending `withdrawn` and `shipped` were BOTH permitted in 20 of 20 races (re-measured
|
|
1282
|
+
* 2026-08-06 from a `declared -> claimed -> verified -> integrated` seed), ending
|
|
1283
|
+
* `after-terminal` with `determinable: false`. Any decision that reads history has to be
|
|
1284
|
+
* serialized against anything that writes history, and that is now every event.
|
|
1285
|
+
*
|
|
1286
|
+
* (b) The check read the RAW caller-supplied path, from inside the callback `sink.js` runs BEFORE
|
|
1287
|
+
* it resolves or allowlists anything. Closing the FIFO hang there opened a slower one: a
|
|
1288
|
+
* 600 MB file took 15.7 s and a 3 GB file 82.9 s to return nothing, on a path the guard would
|
|
1289
|
+
* have refused in microseconds. Worse, it was a READ ORACLE — appending against an arbitrary
|
|
1290
|
+
* path echoed a field from that file back in the refusal message, in place of the allowlist
|
|
1291
|
+
* refusal that should have fired. The read is on `SINK.sinkPath()` now, after the guard has
|
|
1292
|
+
* approved it, so an unallowlisted path is refused before anything is opened.
|
|
1293
|
+
*
|
|
1294
|
+
* The hard-won half of the ordering is unchanged and is what it has always been: the lock is taken
|
|
1295
|
+
* LAST, on the RESOLVED sink path the guard approved, never on what the caller typed — `:552`'s
|
|
1296
|
+
* comment records what happened the one time that was wrong. The order is now, precisely:
|
|
1297
|
+
* validate → guard-check (resolve + allowlist) → lock → read + fold-compare → append.
|
|
1298
|
+
*/
|
|
1299
|
+
const v = validateEvent(event, opts);
|
|
1300
|
+
if (!v.ok) throw new ForbiddenWrite(`invalid work-item event — refused: ${v.errors.join('; ')}`, { errors: v.errors });
|
|
1301
|
+
|
|
1302
|
+
SINK.check(targetPath, () => v); // resolves + allowlists; throws before anything is created
|
|
1303
|
+
const sinkPath = SINK.sinkPath();
|
|
1304
|
+
|
|
1305
|
+
/* ── LOCKING IS CLAIM-ONLY AGAIN. I REVERTED MY OWN CHANGE. ────────────────────────────────────
|
|
1306
|
+
*
|
|
1307
|
+
* An independent pass found that two concurrent NON-claim appends could both be permitted, and
|
|
1308
|
+
* that race is REAL and is not fixed here. Re-measured 2026-08-06 over 20 barrier-synchronised
|
|
1309
|
+
* rounds per shape: `verified` vs `failed` from a `declared -> claimed` seed lands BOTH 20/20;
|
|
1310
|
+
* `withdrawn` vs `shipped` from `declared -> claimed -> verified -> integrated` lands both 20/20;
|
|
1311
|
+
* from a bare `declared` neither shape lands both, because `shipped` is refused out of order for an
|
|
1312
|
+
* unrelated reason. The rate depends entirely on the seeded prior state, which is why the figure
|
|
1313
|
+
* originally recorded here (8 of 20) reproduced in no configuration and is struck in
|
|
1314
|
+
* bootstrap-debt.md. What follows is why the fix is not in this commit.
|
|
1315
|
+
*
|
|
1316
|
+
* Widening the lock to every append was attempted three times and produced three new defects, each
|
|
1317
|
+
* found by the next independent pass and each worse than the race it was closing:
|
|
1318
|
+
*
|
|
1319
|
+
* 1. A DENIAL OF SERVICE. 3 of 8 concurrent writers on a 5,000-line ledger were refused with a
|
|
1320
|
+
* class indistinguishable from a policy refusal — and D65's factory graph is "N in parallel".
|
|
1321
|
+
* 2. A HANG. Raising the budget to 30 s against a 60 s staleness made the reclaim branch
|
|
1322
|
+
* unreachable inside a call, so a crashed holder became a hard 30 s stall and then a throw.
|
|
1323
|
+
* 3. AN INFINITE SPIN AND DETERMINISTIC LOCK THEFT. Ordering the budget above the staleness put
|
|
1324
|
+
* the deadline check after the reclaim `continue`, so an unlinkable stale lock span forever
|
|
1325
|
+
* (measured: no return in 100 s); and with nothing refreshing the mtime, every waiter now
|
|
1326
|
+
* steals from any holder that runs longer than 60 s (measured: a 68 s holder had its lock
|
|
1327
|
+
* unlinked at 60.1 s while it was still working).
|
|
1328
|
+
*
|
|
1329
|
+
* A mutex whose stale-reclaim, ownership and budget interact this badly wants a rewrite with a
|
|
1330
|
+
* different mechanism — an ownership token, a refreshed heartbeat, a bounded wait that cannot be
|
|
1331
|
+
* bypassed by any branch — and that is a piece of work with its own spec, not a paragraph inside a
|
|
1332
|
+
* ledger-integrity chore. Reverting to the merged, tested, claim-only behaviour restores a known
|
|
1333
|
+
* state; leaving my third attempt in place would ship an infinite spin to close a race that is
|
|
1334
|
+
* bounded, recorded and — in one of its two shapes — reported.
|
|
1335
|
+
*
|
|
1336
|
+
* THE RACE IS RECORDED, NOT HIDDEN: bootstrap-debt.md carries it with the re-measured table and the
|
|
1337
|
+
* reproduction. ~~and `check-work-items.js` reports the resulting defect if it ever lands.~~ THAT
|
|
1338
|
+
* CLAIM IS FALSE AND IS STRUCK (2026-08-06): the gate reports the `withdrawn`/`shipped` shape on
|
|
1339
|
+
* 20 of 20 races and is SILENT on `verified`/`failed` on 20 of 20, printing `every line is
|
|
1340
|
+
* well-formed`. Its silence there is correct — a verify followed by a failed verify is a legal
|
|
1341
|
+
* sequence, so what the race destroys is not in the record to check. A round-6 pass found this
|
|
1342
|
+
* sentence surviving here verbatim in the same commit that struck it in the debt register, which is
|
|
1343
|
+
* the two-places-one-rule defect inside the correction of a two-places-one-rule defect. */
|
|
1344
|
+
const lock = CLAIM_EVENTS.includes(event.event) ? acquireLock(sinkPath) : null;
|
|
1345
|
+
try {
|
|
1346
|
+
const refusal = ledgerRefusal(sinkPath, event, opts);
|
|
1347
|
+
if (refusal) throw new ForbiddenWrite(refusal, { item_id: event.item_id });
|
|
1348
|
+
return SINK.appendLine(targetPath, event, () => v);
|
|
1349
|
+
} finally { if (lock) releaseLock(lock); }
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
module.exports = {
|
|
1353
|
+
ITEM_TYPES, BLAST, EVENTS, CHECK_KINDS, UNVERIFIED_TYPE,
|
|
1354
|
+
ITEM_ID_RE, INITIATIVE_ID_RE, PLAN_ITEM_RE, PERMITTED_BASENAME,
|
|
1355
|
+
dispatchRefusal, makeRecordOf, makeRankedOf,
|
|
1356
|
+
ForbiddenWrite, LockUnavailable, LOCK_WAIT_MS, LOCK_STALE_MS, defaultInitiativeExists, makeInitiativeExists, CHECK_OPEN_GAP,
|
|
1357
|
+
validateEvent, criterionErrors, deriveItems, assertWritable, appendEvent, claimRefusal, CLAIM_EVENTS,
|
|
1358
|
+
TERMINAL, CHAIN, UNSEEN_NODES, chainFor, chainPos, discardRefusal, readLedgerSafely,
|
|
1359
|
+
/* Exported so the suite can assert the revocation table is DERIVED — an assertion that retyped
|
|
1360
|
+
* the pairs would agree with itself and not with the code. */
|
|
1361
|
+
NEGATED_BY, standsSatisfied, opposedOutcomes, futureRefusal, ledgerRefusal, FUTURE_SKEW_MS,
|
|
1362
|
+
/* Test seam, gated inside sink.js behind NODE_ENV=test || PMOS_TEST. Exported so the suite can
|
|
1363
|
+
* point the sink at a scratch dir and attack the LINK checks — without it every attack is
|
|
1364
|
+
* refused for being in the wrong directory, which proves nothing about symlinks. */
|
|
1365
|
+
__setSinkForTests: SINK.__setSinkForTests,
|
|
1366
|
+
__setClockForTests,
|
|
1367
|
+
/* Exported so work-item-sandbox.js reads the SAME clock. Two modules deciding the present
|
|
1368
|
+
* separately is how one of them ends up trusting a caller for it. */
|
|
1369
|
+
writerNow,
|
|
1370
|
+
};
|
|
1371
|
+
|
|
1372
|
+
/* ── THE CLI A BUILD THREAD USES (initiative loop-telemetry) ────────────────────────────────────────────────────────────
|
|
1373
|
+
*
|
|
1374
|
+
* node scripts/work-item.js declare <initiative> --type <t> --blast <low|medium|high> --criterion "<text>" \
|
|
1375
|
+
* --check <test|assertion|rubric_dimension|none> --ref "<suite or file>" [--plan-item <id>] [--agent <who>] [--hours N]
|
|
1376
|
+
* node scripts/work-item.js verify <item> --evidence "<what passed>"
|
|
1377
|
+
* node scripts/work-item.js claim <item> [--agent <who>] [--hours N] (W7: the kit's Builder claims an item PMOS declared)
|
|
1378
|
+
* node scripts/work-item.js show [<initiative>] [--json]
|
|
1379
|
+
*
|
|
1380
|
+
* `declare … --no-claim` appends `declared` only, so the item waits for a Builder (`pmos build claim`).
|
|
1381
|
+
* `declare` appends `declared` and then `claimed` (a lease of --hours, default 72, for --agent, default the session id), and
|
|
1382
|
+
* prints the trailer line for the PR body: `Work-Item: <id>`. `verify` appends `verified` once the criterion's check passed.
|
|
1383
|
+
* After the PR merges, `verify-work.js` (or `pmos verify-work`) finds the line in the squash commit and appends `integrated`.
|
|
1384
|
+
* Every append goes through appendEvent, so every rule above still decides; a refusal prints its reason and exits 1. */
|
|
1385
|
+
function cliMain(argv) {
|
|
1386
|
+
const opt = (k) => { const i = argv.indexOf(k); return i !== -1 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : undefined; };
|
|
1387
|
+
const [verb, target] = argv;
|
|
1388
|
+
const ledger = path.join(__dirname, '..', 'planning', 'work-items.jsonl');
|
|
1389
|
+
const read = () => { try { return readLedgerSafely(ledger); } catch (e) { if (e && e.code === 'ENOENT') return ''; throw e; } };
|
|
1390
|
+
const usage = () => {
|
|
1391
|
+
console.log('usage: node scripts/work-item.js declare <initiative> --type <t> --blast <b> --criterion "<text>" --check <kind> --ref "<ref>" [--plan-item <id>] [--agent <who>] [--hours N]');
|
|
1392
|
+
console.log(' node scripts/work-item.js verify <item> --evidence "<what passed>"');
|
|
1393
|
+
console.log(' node scripts/work-item.js claim <item> [--agent <who>] [--hours N]');
|
|
1394
|
+
console.log(' node scripts/work-item.js show [<initiative>] [--json]');
|
|
1395
|
+
return 2;
|
|
1396
|
+
};
|
|
1397
|
+
const append = (ev) => {
|
|
1398
|
+
try { appendEvent(ledger, ev); return true; } catch (e) {
|
|
1399
|
+
if (!(e instanceof ForbiddenWrite)) throw e;
|
|
1400
|
+
console.log(`✗ ${ev.item_id}: ${ev.event} not written — ${e.message}`);
|
|
1401
|
+
return false;
|
|
1402
|
+
}
|
|
1403
|
+
};
|
|
1404
|
+
if (verb === 'declare') {
|
|
1405
|
+
if (!target || !INITIATIVE_ID_RE.test(target)) return usage();
|
|
1406
|
+
const { items } = deriveItems(read(), { now: writerNow() });
|
|
1407
|
+
let n = 1;
|
|
1408
|
+
const taken = new Set(items.map((it) => it.item_id));
|
|
1409
|
+
while (taken.has(`${target}.${n}`)) n++;
|
|
1410
|
+
const id = `${target}.${n}`;
|
|
1411
|
+
const at = writerNow();
|
|
1412
|
+
const criterion = { text: opt('--criterion') || '', check: opt('--check') || 'test', ref: opt('--ref') || '' };
|
|
1413
|
+
const declared = { item_id: id, initiative_id: target, event: 'declared', at, type: opt('--type') || 'feature-slice', blast: opt('--blast') || 'low', criterion,
|
|
1414
|
+
...(opt('--plan-item') ? { plan_item: opt('--plan-item') } : {}) };
|
|
1415
|
+
if (!append(declared)) return 1;
|
|
1416
|
+
if (argv.includes('--no-claim')) {
|
|
1417
|
+
console.log(`✓ ${id} declared → planning/work-items.jsonl (not claimed; a Builder claims it)`);
|
|
1418
|
+
return 0;
|
|
1419
|
+
}
|
|
1420
|
+
const hours = Math.max(1, Math.min(24 * 14, Number(opt('--hours')) || 72));
|
|
1421
|
+
const agent = opt('--agent') || (process.env.CLAUDE_CODE_SESSION_ID ? `agent:${process.env.CLAUDE_CODE_SESSION_ID}` : 'agent');
|
|
1422
|
+
const claimAt = writerNow();
|
|
1423
|
+
const claimed = { item_id: id, initiative_id: target, event: 'claimed', at: claimAt, claim: { agent, expires_at: new Date(Date.parse(claimAt) + hours * 3600000).toISOString() } };
|
|
1424
|
+
if (!append(claimed)) { console.log(` ${id} is declared but not claimed.`); return 1; }
|
|
1425
|
+
console.log(`✓ ${id} declared and claimed by ${agent} for ${hours} h → planning/work-items.jsonl`);
|
|
1426
|
+
console.log('Put this line in the PR body:');
|
|
1427
|
+
console.log(`Work-Item: ${id}`);
|
|
1428
|
+
return 0;
|
|
1429
|
+
}
|
|
1430
|
+
if (verb === 'verify') {
|
|
1431
|
+
const evidence = opt('--evidence');
|
|
1432
|
+
if (!target || !ITEM_ID_RE.test(target) || !evidence) return usage();
|
|
1433
|
+
const ev = { item_id: target, initiative_id: target.slice(0, target.lastIndexOf('.')), event: 'verified', at: writerNow(), evidence };
|
|
1434
|
+
if (!append(ev)) return 1;
|
|
1435
|
+
console.log(`✓ ${target} verified (${evidence})`);
|
|
1436
|
+
return 0;
|
|
1437
|
+
}
|
|
1438
|
+
if (verb === 'claim') {
|
|
1439
|
+
if (!target || !ITEM_ID_RE.test(target)) return usage();
|
|
1440
|
+
const hours = Math.max(1, Math.min(24 * 14, Number(opt('--hours')) || 72));
|
|
1441
|
+
const agent = opt('--agent') || (process.env.CLAUDE_CODE_SESSION_ID ? `agent:${process.env.CLAUDE_CODE_SESSION_ID}` : 'agent');
|
|
1442
|
+
const at = writerNow();
|
|
1443
|
+
const ev = { item_id: target, initiative_id: target.slice(0, target.lastIndexOf('.')), event: 'claimed', at, claim: { agent, expires_at: new Date(Date.parse(at) + hours * 3600000).toISOString() } };
|
|
1444
|
+
if (!append(ev)) return 1;
|
|
1445
|
+
console.log(`✓ ${target} claimed by ${agent} for ${hours} h`);
|
|
1446
|
+
return 0;
|
|
1447
|
+
}
|
|
1448
|
+
if (verb === 'show') {
|
|
1449
|
+
const { items } = deriveItems(read(), { now: writerNow() });
|
|
1450
|
+
const shown = items.filter((it) => !target || (target !== '--json' && it.initiative_id === target) || target === '--json');
|
|
1451
|
+
if (argv.includes('--json')) { console.log(JSON.stringify(shown)); return 0; }
|
|
1452
|
+
for (const it of shown) console.log(`${it.item_id} ${it.state} ${(it.history || []).join(' → ')}`);
|
|
1453
|
+
if (!shown.length) console.log('no work items' + (target ? ` for ${target}` : ''));
|
|
1454
|
+
return 0;
|
|
1455
|
+
}
|
|
1456
|
+
return usage();
|
|
1457
|
+
}
|
|
1458
|
+
module.exports.cliMain = cliMain;
|
|
1459
|
+
|
|
1460
|
+
if (require.main === module) process.exitCode = cliMain(process.argv.slice(2));
|