create-pmos 0.31.0 → 0.32.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.
@@ -0,0 +1,321 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* sink.js — the ONE place the append-only ledger discipline lives.
4
+ *
5
+ * ── WHY THIS FILE EXISTS ────────────────────────────────────────────────────────────────────────
6
+ * `record-eval.js` was PMOS's first validated writer. Three independent passes found four defects in
7
+ * it, and all four were fixed IN THAT FILE:
8
+ *
9
+ * 1. the sink was a caller-supplied allowlist -> a caller could name its own destination
10
+ * 2. the file was opened before validation -> N refused writes leaked N descriptors to EMFILE
11
+ * 3. a refused write still created the sink -> refusing to write left the file behind
12
+ * 4. the symlink check was a path-level stat -> a hardlink walked straight through it
13
+ *
14
+ * Two writers built afterwards inherited the fixes BY HAND, and each inheritance read as evidence
15
+ * that the pattern was holding. It was not holding — it was propagating FORWARD ONLY. The two
16
+ * writers that already existed when the defects were found were never revisited, because the process
17
+ * asks "does the new thing follow the rule?" and never "where else does this rule already live?"
18
+ *
19
+ * Measured by attempted write on 2026-08-04:
20
+ *
21
+ * scripts/work-item.js -> wrote 198 bytes through a symlink into a decoy
22
+ * scripts/verify-queue.js -> the same, AND wrote 202 bytes into a fresh tmpdir, because its
23
+ * allowlist compared `path.basename` alone. A basename is not a
24
+ * location; every directory on disk has one.
25
+ *
26
+ * Both are merged, PM-accepted, and load-bearing for D65 steps 1 and 2. So the discipline moves here
27
+ * and the writers call it. One wrong place that every assertion points at beats five where three
28
+ * happen to be right.
29
+ *
30
+ * ── THE RULE, STATED ONCE ───────────────────────────────────────────────────────────────────────
31
+ * Resolve before allowing. Validate before opening. Write to the descriptor that was vetted.
32
+ *
33
+ * The third clause is the one that looks redundant and is not. A path checked and then re-opened by
34
+ * path is two operations on two objects: whatever was approved may not be what gets written. The fd
35
+ * IS the approval, so it is what the caller must be handed.
36
+ */
37
+
38
+ const fs = require('fs');
39
+ const path = require('path');
40
+
41
+ /**
42
+ * THE `ForbiddenWrite`. One class, exported, re-exported by every writer that uses this guard.
43
+ *
44
+ * There were five of these — one per writer that had a guard at all — and that is not a cosmetic duplication. Callers and
45
+ * assertions tell "refused on purpose" from "crashed" with `instanceof`, so a guard throwing its own
46
+ * private copy makes every one of those checks silently false: `scripts/tests/work-item.sh` reported
47
+ * `threw ForbiddenWrite, want ForbiddenWrite` on seventeen assertions the moment this module started
48
+ * throwing a second class with the same name. A refusal nobody can recognise as a refusal is not one.
49
+ *
50
+ * `detail` is always set (null when absent) rather than conditionally attached, because a property
51
+ * that sometimes exists is a second shape for callers to handle.
52
+ */
53
+ class ForbiddenWrite extends Error {
54
+ constructor(message, detail) {
55
+ super(message);
56
+ this.name = 'ForbiddenWrite';
57
+ this.detail = detail || null;
58
+ }
59
+ }
60
+
61
+ /** Resolve a path through its real directory. Kept separate so the sink and the target are compared
62
+ * the same way — comparing a resolved target against an unresolved sink is a mismatch by
63
+ * construction, and would refuse every legitimate write on a machine where /tmp is a symlink. */
64
+ function resolveThrough(p) {
65
+ return path.join(fs.realpathSync(path.dirname(path.resolve(p))), path.basename(p));
66
+ }
67
+
68
+ /**
69
+ * Build a guard bound to ONE sink.
70
+ *
71
+ * @param {object} spec
72
+ * @param {string} spec.sink absolute path of the only file this guard will ever open.
73
+ * @param {string} spec.what noun for error messages, e.g. 'work-item events'.
74
+ * @returns {{ open: function, sinkPath: function, __setSinkForTests: function }}
75
+ *
76
+ * The sink is a CONSTRUCTION-TIME constant, never an argument to `open`. That is defect 1 of the
77
+ * original four, and re-admitting it as "just a parameter" is how it would come back.
78
+ */
79
+ function createSinkGuard(spec) {
80
+ if (!spec || typeof spec.sink !== 'string' || !spec.sink) {
81
+ throw new ForbiddenWrite('a sink guard needs a declared `sink` path — refused (fail-closed)');
82
+ }
83
+ const what = spec.what || 'records';
84
+ const declared = spec.sink;
85
+ let overrideForTests = null;
86
+
87
+ /* A seam, not a door. Gated so it cannot be reached in a production process even if something
88
+ * calls it — the point of A4 is that no code path lets a caller choose the destination. */
89
+ function __setSinkForTests(p) {
90
+ /* An explicit allowed set. `!process.env.PMOS_TEST` treats the STRING '0' as truthy, so
91
+ * PMOS_TEST=0 — the natural way an operator turns test mode OFF — OPENED the production sink
92
+ * override instead of closing it. A flag whose "off" value means "on" is worse than no flag. */
93
+ const on = (v) => v === '1' || v === 'true' || v === 'yes';
94
+ if (process.env.NODE_ENV !== 'test' && !on(process.env.PMOS_TEST)) {
95
+ throw new ForbiddenWrite('__setSinkForTests is a test seam — set NODE_ENV=test or PMOS_TEST=1 to use it');
96
+ }
97
+ overrideForTests = p;
98
+ }
99
+
100
+ const sinkPath = () => overrideForTests || declared;
101
+
102
+ /**
103
+ * Pre-flight: validate the record and confirm the target RESOLVES to the sink — without opening
104
+ * anything. For callers that want to ask "would this be permitted?" without a side effect.
105
+ *
106
+ * NOT AUTHORITATIVE, and the gap is deliberate rather than an oversight. Whether the sink is a
107
+ * symlink or carries a second hard link cannot be established without a descriptor, and a `lstat`
108
+ * here would answer about a path that may differ from the file eventually opened — which is the
109
+ * check-then-write race this module exists to close. `open` is the authority; this is a courtesy.
110
+ * The suite asserts the difference: a symlinked sink passes `check` and is refused by `open`.
111
+ */
112
+ function check(targetPath, validate) {
113
+ if (typeof targetPath !== 'string' || !targetPath) {
114
+ throw new ForbiddenWrite(`no target path supplied for ${what} — refused (fail-closed)`);
115
+ }
116
+ if (typeof validate === 'function') {
117
+ const v = validate();
118
+ if (!v || !v.ok) {
119
+ const errs = (v && v.errors) || ['invalid'];
120
+ throw new ForbiddenWrite(`invalid ${what} — refused: ${errs.join('; ')}`, { errors: errs });
121
+ }
122
+ }
123
+ let resolved;
124
+ try { resolved = resolveThrough(targetPath); }
125
+ catch { throw new ForbiddenWrite(`the sink directory does not resolve for '${targetPath}' — refused (fail-closed)`); }
126
+ let sinkResolved = sinkPath();
127
+ try { sinkResolved = resolveThrough(sinkPath()); } catch { /* not created yet */ }
128
+ if (resolved !== sinkResolved) {
129
+ throw new ForbiddenWrite(
130
+ `${what} are written only to ${sinkResolved}; '${targetPath}' resolves to '${resolved}'`,
131
+ { targetPath, resolved, sink: sinkResolved });
132
+ }
133
+ return true;
134
+ }
135
+
136
+ /**
137
+ * Vet `targetPath` against the declared sink and return a descriptor open for append.
138
+ *
139
+ * The caller MUST close it. Everything that can refuse, refuses before the file is opened, so a
140
+ * refusal creates nothing and leaks nothing.
141
+ *
142
+ * @param {string} targetPath where the caller believes it is writing.
143
+ * @param {function} [validate] returns { ok, errors } — runs BEFORE the open (defects 2 and 3).
144
+ * @returns {number} a vetted file descriptor.
145
+ */
146
+ function open(targetPath, validate) {
147
+ if (typeof targetPath !== 'string' || !targetPath) {
148
+ throw new ForbiddenWrite(`no target path supplied for ${what} — refused (fail-closed)`);
149
+ }
150
+
151
+ /* BEFORE the open. Ordering is the whole of defects 2 and 3: validating after opening leaks a
152
+ * descriptor per refusal, and O_CREAT means the refused write has already made the file. */
153
+ if (typeof validate === 'function') {
154
+ const v = validate();
155
+ if (!v || !v.ok) {
156
+ const errs = (v && v.errors) || ['invalid'];
157
+ throw new ForbiddenWrite(`invalid ${what} — refused: ${errs.join('; ')}`, { errors: errs });
158
+ }
159
+ }
160
+
161
+ let resolved;
162
+ try {
163
+ resolved = resolveThrough(targetPath);
164
+ } catch {
165
+ throw new ForbiddenWrite(`the sink directory does not resolve for '${targetPath}' — refused (fail-closed)`);
166
+ }
167
+ let sinkResolved = sinkPath();
168
+ try { sinkResolved = resolveThrough(sinkPath()); } catch { /* not created yet — compare literally */ }
169
+
170
+ /* A RESOLVED comparison, not a basename one. `verify-queue.js` compared basenames and therefore
171
+ * accepted every directory on disk that happened to contain the right filename. */
172
+ if (resolved !== sinkResolved) {
173
+ throw new ForbiddenWrite(
174
+ `${what} are written only to ${sinkResolved}; '${targetPath}' resolves to '${resolved}'`,
175
+ { targetPath, resolved, sink: sinkResolved });
176
+ }
177
+
178
+ let fd;
179
+ try {
180
+ fd = fs.openSync(
181
+ resolved,
182
+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_APPEND
183
+ | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK,
184
+ 0o644);
185
+ } catch (e) {
186
+ /* O_NOFOLLOW turns "the sink is a symlink" into ELOOP here rather than a silent write to
187
+ * wherever it pointed. That is defect 4, and it is refused at open rather than by a stat that
188
+ * a hardlink does not answer.
189
+ *
190
+ * O_NONBLOCK is not about performance. Opening a FIFO for writing BLOCKS until a reader
191
+ * arrives, so a named pipe left at the sink path hangs the writer forever — found by the
192
+ * assertion below, which hung this suite past its timeout instead of failing. A refusal that
193
+ * never returns is worse than a wrong answer: nothing reports it and nothing times it out.
194
+ * With O_NONBLOCK the same case returns ENXIO immediately and lands in the refusal path, and
195
+ * on a regular file the flag does nothing at all. */
196
+ throw new ForbiddenWrite(
197
+ `cannot open the ${what} ledger at '${targetPath}' safely (${e.code || e.message}) — refused (fail-closed)`,
198
+ { code: e.code });
199
+ }
200
+
201
+ try {
202
+ /* fstat on the FD, not stat on the path: for the FINAL component this genuinely closes the
203
+ * check-then-open race — an independent pass swapped the target inside the resolve→open window
204
+ * with perfect timing and got ELOOP, nlink=2 and a refusal every time.
205
+ *
206
+ * It does NOT cover the PARENT directory. `resolveThrough` realpaths the directory and
207
+ * `openSync` then re-walks that resolved path, so a local process able to rename the sink's
208
+ * parent and drop a directory symlink in its place inside that window can redirect the append
209
+ * — measured, 195 bytes into a foreign directory. That needs a concurrently-racing local
210
+ * attacker with write access to the parent, a strictly larger capability than the symlink
211
+ * defect this module was built to fix, so it is stated rather than claimed away. Closing it
212
+ * properly needs openat-style descent, which Node does not expose. The header's "the fd IS the
213
+ * approval" is true of the file, not of the path walked to reach it. */
214
+ const st = fs.fstatSync(fd);
215
+ if (!st.isFile()) {
216
+ throw new ForbiddenWrite(`'${targetPath}' is not a regular file — refused (fail-closed)`);
217
+ }
218
+ if (st.nlink !== 1) {
219
+ throw new ForbiddenWrite(
220
+ `'${targetPath}' has ${st.nlink} hard links; a ledger with a second name is not one this ` +
221
+ 'writer controls — refused (fail-closed)', { nlink: st.nlink });
222
+ }
223
+ } catch (e) {
224
+ fs.closeSync(fd);
225
+ throw e;
226
+ }
227
+
228
+ return fd;
229
+ }
230
+
231
+ /**
232
+ * The whole write, start to finish: vet, append one JSON line, close. Callers should prefer this
233
+ * over `open` — it is the shape that cannot forget to close, and every existing writer's append is
234
+ * exactly one line.
235
+ */
236
+ function appendLine(targetPath, record, validate) {
237
+ const fd = open(targetPath, validate);
238
+ const line = JSON.stringify(record) + '\n';
239
+ const want = Buffer.byteLength(line);
240
+ try {
241
+ /* THE RETURN VALUE IS NOT OPTIONAL. This was `fs.writeSync(fd, line)` with the result
242
+ * discarded, which reports a SHORT WRITE as success. Forced on a 64K tmpfs: a normal-shaped
243
+ * record returned true having appended a 3901-byte fragment with no trailing newline, and the
244
+ * next append CONCATENATED onto it — so one ENOSPC destroys two records and leaves a single
245
+ * line that no reader can parse. This is the append-only system of record, every reader
246
+ * JSON.parses line by line, and all six writers route through this one call.
247
+ *
248
+ * Loop, because a partial write is not necessarily an error — then verify the total. A torn
249
+ * tail is worse than a refused write, so if the bytes did not all land, say so loudly rather
250
+ * than returning true over a corrupted ledger. */
251
+ /* The size BEFORE this append, taken from the vetted fd. This is what makes the failure path a
252
+ * real refusal instead of a report: if the write tears, the file is truncated back to here and
253
+ * the ledger is left exactly as it was found. `nlink === 1` was already proven above, so no
254
+ * other name for this file exists and the rollback cannot reach anyone else's data. */
255
+ const before = fs.fstatSync(fd).size;
256
+ const buf = Buffer.from(line, 'utf8');
257
+ let written = 0;
258
+ let cause = null;
259
+ try {
260
+ while (written < want) {
261
+ const n = fs.writeSync(fd, buf, written, want - written);
262
+ if (!(n > 0)) break; // no progress: stop rather than spin
263
+ written += n;
264
+ }
265
+ } catch (e) {
266
+ /* ENOSPC does NOT arrive as a short write. Measured on a full tmpfs: the first writeSync
267
+ * short-writes 376 of 440 bytes with no error and the SECOND one throws — so a version that
268
+ * only checked `written !== want` never reached its own error path, and a raw Error escaped
269
+ * with name 'Error'. Everything in this repo tells a deliberate refusal from a crash with
270
+ * `instanceof ForbiddenWrite` (workspace/test.js:1772 checks e.name), so an unwrapped throw
271
+ * on the worst outcome this module has is the one place that signal must not be missing. */
272
+ cause = e;
273
+ }
274
+
275
+ if (cause || written !== want) {
276
+ /* THE ROLLBACK MUST NOT DESTROY SOMEONE ELSE'S RECORD, and the first version did.
277
+ *
278
+ * It called ftruncateSync(fd, before) unconditionally. `before` was measured at the top of
279
+ * this function, so ANY append by another process in between — a complete, successful,
280
+ * returned-true append — was inside the range being truncated away. Measured by an
281
+ * independent pass across 5 of 5 rounds: records whose write returned `true` were missing
282
+ * from disk afterwards, and the ledger was NUL-padded. A rollback that eats a committed
283
+ * record is worse than the torn line it was added to prevent.
284
+ *
285
+ * O_APPEND makes the arithmetic decidable: our bytes are the last `written` of the file if
286
+ * and only if nobody else appended. So truncate ONLY when the file is exactly the size our
287
+ * own write would have made it. Otherwise the tail is not ours to remove, and the honest
288
+ * outcome is to say the ledger is torn rather than to fix it by deleting a stranger's data. */
289
+ let rolledBack = false;
290
+ let intervened = false;
291
+ try {
292
+ const now = fs.fstatSync(fd).size;
293
+ if (now === before + written) { fs.ftruncateSync(fd, before); rolledBack = true; }
294
+ else intervened = true; // another writer appended; the tail is not ours
295
+ } catch { /* reported below */ }
296
+
297
+ const detail = { written, want, before, rolledBack, intervened, code: cause && cause.code };
298
+ throw new ForbiddenWrite(
299
+ `partial append to the ${what} ledger: ${written} of ${want} bytes landed` +
300
+ (cause ? ` (${cause.code || cause.message})` : '') + '. ' +
301
+ (rolledBack
302
+ ? 'The ledger was truncated back to its pre-write size, so nothing was written and the ' +
303
+ 'next append will not concatenate onto a fragment.'
304
+ : intervened
305
+ ? 'NOT ROLLED BACK ON PURPOSE — another writer appended while this write was failing, ' +
306
+ 'so the bytes at the end of the file are not this one\'s to remove. The ledger holds ' +
307
+ 'a torn fragment that must be repaired by hand; truncating it here would have ' +
308
+ 'deleted a record that committed successfully.'
309
+ : 'THE ROLLBACK ALSO FAILED — the ledger now ends in a torn line with no trailing ' +
310
+ 'newline, and the next append WILL concatenate onto it, destroying a second record. ' +
311
+ 'Repair it by hand before writing again.'),
312
+ detail);
313
+ }
314
+ } finally { fs.closeSync(fd); }
315
+ return true;
316
+ }
317
+
318
+ return { check, open, appendLine, sinkPath, __setSinkForTests };
319
+ }
320
+
321
+ module.exports = { createSinkGuard, ForbiddenWrite, resolveThrough };
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "private": true,
5
- "description": "PMOS Terminal Workspace \u2014 local companion hosting real PTYs beside the library and gates (D62)",
5
+ "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
7
7
  "bin": {
8
8
  "pmos": "bin/pmos.js"
@@ -29,7 +29,7 @@
29
29
  "playwright-core": "^1.61.1",
30
30
  "ws": "^8.18.0"
31
31
  },
32
- "//devDependencies": "design-parity's pixel axis only. Kept OUT of dependencies deliberately: `create-pmos workspace` installs this package with `npm install -g`, which takes dependencies and not devDependencies, so an adopter installing a local PM tool does not also install a screenshot differ. design-parity.js requires both optionally and degrades to text+style+geometry when they are absent, so the parity check still runs \u2014 it just stops measuring pixels, and says so.",
32
+ "//devDependencies": "design-parity's pixel axis only. Kept OUT of dependencies deliberately: `create-pmos workspace` installs this package with `npm install -g`, which takes dependencies and not devDependencies, so an adopter installing a local PM tool does not also install a screenshot differ. design-parity.js requires both optionally and degrades to text+style+geometry when they are absent, so the parity check still runs — it just stops measuring pixels, and says so.",
33
33
  "devDependencies": {
34
34
  "pixelmatch": "^7.1.0",
35
35
  "pngjs": "^7.0.0"
@@ -53,6 +53,10 @@
53
53
  opinion about what an .html file is would mean the endpoint and the pane disagreeing about the
54
54
  same document. Classic script (a UMD), like the three above. -->
55
55
  <script src="/lib/preview-kind.js"></script>
56
+ <!-- The newline normalizer behind the doc tab's `normalize` action (markdown-newlines). The same
57
+ file scripts/md-newlines.js requires, loaded here as window.MdNormalize, so the one-click
58
+ repair and the CI ratchet can never disagree about what a normalized document is. -->
59
+ <script src="/lib/md-normalize.js"></script>
56
60
  <link rel="preload" href="/vendor/ibm-plex-mono-500.woff2" as="font" type="font/woff2" crossorigin />
57
61
  </head>
58
62
  <body>
@@ -316,6 +316,7 @@ function diffBody(tab, raw, text, dirty) {
316
316
  /* ── per-tab state that is DOM, not data ───────────────────────────────────────────────────── */
317
317
 
318
318
  const boxes = new Map(); // tab id -> the persistent textarea for that tab
319
+ const normNote = new Map(); // tab id -> what the last `normalize` click did, in words
319
320
 
320
321
  function editBox(tab) {
321
322
  let ta = boxes.get(tab.id);
@@ -336,6 +337,7 @@ function editBox(tab) {
336
337
  /** Release what a closed doc tab held. Called by panel-tabs.js when the tab goes away. */
337
338
  export function disposeDoc(id) {
338
339
  boxes.delete(id);
340
+ normNote.delete(id);
339
341
  frames.delete(id);
340
342
  scrollers.delete(id);
341
343
  }
@@ -373,15 +375,44 @@ export function mountDoc(host, tab) {
373
375
  hover: 'border-color:var(--ring)',
374
376
  }, 'revert') : null;
375
377
 
378
+ /* ── normalize ────────────────────────────────────────────────────────────────────────────────
379
+ * The one-click half of markdown-newlines. It writes the normalized text into the BUFFER, never
380
+ * to disk: the pane goes dirty, `diff` shows exactly which lines were joined, and `save` is the
381
+ * existing write path with its existing refusal on a changed base. So a repair the PM did not
382
+ * want is one `revert` away, and no new way to write a file was added to get it.
383
+ *
384
+ * A document that is already normalized reports that and leaves the buffer alone — marking a
385
+ * clean file dirty for nothing is how a tool teaches you to ignore its dirty flag. */
386
+ const norm = typeof window !== 'undefined' ? window.MdNormalize : null;
387
+ const canNormalize = !!(norm && typeof norm.normalize === 'function')
388
+ && !isHtmlDoc(tab.path) && !isReference(tab.path) && !unread.has(tab.path);
389
+ const normBtn = canNormalize ? el('button', {
390
+ onClick: () => {
391
+ const r = norm.normalize(text);
392
+ normNote.set(tab.id, r.changed
393
+ ? r.joins + ' line(s) joined' + (r.blanks ? ', ' + r.blanks + ' blank inserted' : '')
394
+ : 'already normalized — every paragraph is one line');
395
+ if (!r.changed) { setState({}); return; }
396
+ setState((s) => ({ docEdits: { ...s.docEdits, [tab.path]: r.text } }));
397
+ },
398
+ style: 'margin-left:8px;font-family:var(--mono);font-size:10.5px;padding:4px 10px;min-height:26px;background:var(--secondary);border:1px solid var(--border);color:var(--muted-foreground)',
399
+ hover: 'border-color:var(--ring)',
400
+ title: 'Join hard-wrapped paragraphs into one line each — what a Jira issue, a Google Doc or any'
401
+ + ' plain-text destination needs. Writes the buffer, not the file: read it in diff, then save.',
402
+ }, 'normalize') : null;
403
+
376
404
  // The one place a real-mode refusal is reported: the same line that carries the dirty flag, so
377
- // a save that did not happen cannot read as one that did.
378
- const dirtyLabel = err ? 'not saved — ' + err : (dirty ? '● modified — unsaved' : 'saved on disk');
405
+ // a save that did not happen cannot read as one that did. The normalize note shares the line for
406
+ // the same reason — a repair that changed nothing must say so where the PM is already looking.
407
+ const note = normNote.get(tab.id);
408
+ const dirtyLabel = err ? 'not saved — ' + err
409
+ : (dirty ? '● modified — unsaved' : (note || 'saved on disk'));
379
410
  const dirtyColor = err ? 'var(--destructive)' : (dirty ? 'var(--warning)' : 'var(--muted-foreground)');
380
411
 
381
412
  const modeBar = el('div', {
382
413
  style: 'flex:none;display:flex;gap:2px;align-items:center;padding:6px 10px;border-bottom:1px solid var(--border);background:var(--background)',
383
414
  },
384
- modeBtns, saveBtn, revertBtn,
415
+ modeBtns, normBtn, saveBtn, revertBtn,
385
416
  el('span', { style: 'margin-left:auto;font-family:var(--mono);font-size:10px;color:' + dirtyColor }, iv(dirtyLabel)),
386
417
  );
387
418
 
@@ -61,6 +61,7 @@ function ensureSpawnHelperExecutable() {
61
61
  ensureSpawnHelperExecutable();
62
62
 
63
63
  const { checkSurface } = require('./lib/surface-contract');
64
+ const { createSinkGuard } = require('./lib/sink.js');
64
65
  const scheduleLogic = require('./lib/schedule-logic');
65
66
  const harness = require('./lib/harness-parse');
66
67
  const transcript = require('./lib/transcript-read');
@@ -3760,6 +3761,10 @@ async function handleRequest(req, res) {
3760
3761
  // /pm/ module graph below, and one front end is the point. A stray <script src="/app.js"> now
3761
3762
  // 404s loudly rather than silently resurrecting a second, diverging surface.
3762
3763
  if (p === '/lib/preview-kind.js') return serveFile(res, path.join(__dirname, 'lib', 'preview-kind.js'));
3764
+ // The newline normalizer the doc tab's `normalize` action runs, and the same file
3765
+ // scripts/md-newlines.js requires — one implementation, so the button and the gate can never
3766
+ // disagree about what a normalized document is (markdown-newlines).
3767
+ if (p === '/lib/md-normalize.js') return serveFile(res, path.join(__dirname, 'lib', 'md-normalize.js'));
3763
3768
  if (p === '/lib/layout.js') return serveFile(res, path.join(__dirname, 'lib', 'layout.js'));
3764
3769
  if (p === '/lib/mobile-nav.js') return serveFile(res, path.join(__dirname, 'lib', 'mobile-nav.js'));
3765
3770
  if (p === '/lib/session-state.js') return serveFile(res, path.join(__dirname, 'lib', 'session-state.js'));
@@ -4674,9 +4679,25 @@ async function handleRequest(req, res) {
4674
4679
  // A swallowed append + {ok:true} would light the gate green over a record that never landed —
4675
4680
  // exactly the false-green class D64 exists to delete. On write failure return HTTP 500 and
4676
4681
  // {ok:false}, and do NOT report success. The error text carries no header/secret content (D08).
4682
+ /* THROUGH THE GUARD, not a bare append.
4683
+ *
4684
+ * This was `fs.appendFileSync(sink, ...)`. An independent pass attacked it through this very
4685
+ * endpoint's write path: **42 bytes landed through a symlink and it returned {ok:true}**. And
4686
+ * 37 of 49 live acceptance rows carry a `workspace` key that only THIS endpoint writes — so the
4687
+ * guarded writer (scripts/record-acceptance.js) was the one nothing used, while the unguarded
4688
+ * one had written three quarters of the system of record.
4689
+ *
4690
+ * The guard is constructed per resolved sink rather than as one module constant, because the
4691
+ * acceptance ledger legitimately moves with the workspace — kit layout, or the install's own
4692
+ * state/ on fallback. The allowlist therefore degenerates here (target === declared by
4693
+ * construction) and that is stated rather than glossed: what this buys is O_NOFOLLOW, the
4694
+ * `nlink === 1` check, and the torn-append rollback, which is precisely the attack that landed.
4695
+ *
4696
+ * `pm_label` is NOT validated against record-acceptance.js's stricter schema: that writer
4697
+ * REQUIRES the label, this surface must not, and requiring it here would block the PM's click. */
4677
4698
  try {
4678
4699
  if (fallback) fs.mkdirSync(LEGACY_STATE, { recursive: true }); // the install's state/ may not exist yet
4679
- fs.appendFileSync(sink, JSON.stringify(rec) + '\n');
4700
+ createSinkGuard({ sink, what: 'PM acceptances' }).appendLine(sink, rec);
4680
4701
  } catch (e) {
4681
4702
  warnWriteFail('acceptances.jsonl (Acceptance Gate — system of record)', e);
4682
4703
  return json(res, { ok: false, error: 'could not record the acceptance — the file-mode system of record is unwritable; the decision was NOT saved', sink, fallback }, 500);