fwdloop 0.9.0 → 0.11.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/bin/fwdloop +15 -11
- package/package.json +1 -1
- package/src/ask.js +219 -8
- package/src/authoring.js +31 -5
- package/src/books.js +20 -0
- package/src/liveness.js +160 -0
- package/src/model-step.js +4 -3
- package/src/panel/data.js +468 -76
- package/src/panel/index.html +774 -205
- package/src/panel/lock.js +42 -0
- package/src/panel/resume.js +35 -4
- package/src/panel/server.js +261 -45
- package/src/provider.js +9 -1
- package/src/runner.js +112 -21
- package/types/ask.d.ts +82 -1
- package/types/authoring.d.ts +3 -2
- package/types/books.d.ts +19 -0
- package/types/liveness.d.ts +70 -0
- package/types/panel/data.d.ts +210 -20
- package/types/panel/lock.d.ts +21 -0
- package/types/panel/resume.d.ts +4 -0
- package/types/panel/server.d.ts +30 -2
- package/types/runner.d.ts +4 -3
package/bin/fwdloop
CHANGED
|
@@ -31,7 +31,9 @@ import { makeLiveModelStep } from '../src/model-step.js';
|
|
|
31
31
|
import { sendViaPrimitive } from '../src/send.js';
|
|
32
32
|
import { resolvePrimitives } from '../src/primitives.js';
|
|
33
33
|
import { checkKeyPreflight } from '../src/provider.js';
|
|
34
|
-
import {
|
|
34
|
+
import {
|
|
35
|
+
answerAsk, readAskEvidence, normalizeDecision, stripControl, withReopen,
|
|
36
|
+
} from '../src/ask.js';
|
|
35
37
|
import { panelMain } from '../src/panel/server.js';
|
|
36
38
|
import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
|
|
37
39
|
import { draftToDir, signDraft, SIGN_LINE, costText } from '../src/authoring.js';
|
|
@@ -288,7 +290,7 @@ function cmdInbox(rest) {
|
|
|
288
290
|
if (!askRead.ok) continue; // eslint-disable-line no-continue -- missing (or refused) ask.json: nothing to show
|
|
289
291
|
let ask;
|
|
290
292
|
try {
|
|
291
|
-
ask = JSON.parse(askRead.text);
|
|
293
|
+
ask = withReopen(runDir, JSON.parse(askRead.text)); // the effective deadline (a reopened ask's new one)
|
|
292
294
|
} catch (err) {
|
|
293
295
|
// A malformed/unparseable ask.json must never crash inbox — show it
|
|
294
296
|
// naming the run as unreadable and move on to the next one.
|
|
@@ -342,11 +344,11 @@ function cmdInbox(rest) {
|
|
|
342
344
|
continue;
|
|
343
345
|
}
|
|
344
346
|
if (row.status === 'legacy') {
|
|
345
|
-
process.stdout.write(`flow=${row.flow} run=${row.runId} [legacy (not answerable)] — ${row.question}\n`);
|
|
347
|
+
process.stdout.write(`flow=${row.flow} run=${row.runId} [legacy (not answerable)] — ${stripControl(row.question)}\n`);
|
|
346
348
|
continue;
|
|
347
349
|
}
|
|
348
350
|
const timeLeft = row.status === 'expired' ? 'expired' : `${Math.max(0, Math.round(row.timeLeftMs / 1000))}s left`;
|
|
349
|
-
process.stdout.write(`${row.askId} flow=${row.flow} run=${row.runId} [${row.status}] ${timeLeft} — ${row.question}\n`);
|
|
351
|
+
process.stdout.write(`${row.askId} flow=${row.flow} run=${row.runId} [${row.status}] ${timeLeft} — ${stripControl(row.question)}\n`);
|
|
350
352
|
}
|
|
351
353
|
}
|
|
352
354
|
|
|
@@ -381,13 +383,13 @@ function cmdShow(rest) {
|
|
|
381
383
|
}
|
|
382
384
|
let ask;
|
|
383
385
|
try {
|
|
384
|
-
ask = JSON.parse(askRead.text);
|
|
386
|
+
ask = withReopen(runDir, JSON.parse(askRead.text)); // the effective deadline (a reopened ask's new one)
|
|
385
387
|
} catch (err) {
|
|
386
388
|
fail(`show: ask.json for askId "${askId}" is not valid JSON — ${err.message}`);
|
|
387
389
|
return;
|
|
388
390
|
}
|
|
389
391
|
|
|
390
|
-
process.stdout.write(`question: ${ask.question}\n`);
|
|
392
|
+
process.stdout.write(`question: ${stripControl(ask.question)}\n`);
|
|
391
393
|
process.stdout.write(`expiresAt: ${ask.expiresAt}\n`);
|
|
392
394
|
|
|
393
395
|
const { draft, unjudged, why } = readAskEvidence(ask);
|
|
@@ -396,10 +398,10 @@ function cmdShow(rest) {
|
|
|
396
398
|
return;
|
|
397
399
|
}
|
|
398
400
|
process.stdout.write('\n--- artifact under review ---\n');
|
|
399
|
-
process.stdout.write(`${draft.text}\n`);
|
|
401
|
+
process.stdout.write(`${stripControl(draft.text)}\n`);
|
|
400
402
|
for (const item of unjudged) {
|
|
401
|
-
process.stdout.write(`\n--- unjudged: ${item.step} ---\n`);
|
|
402
|
-
process.stdout.write(`${item.text}\n`);
|
|
403
|
+
process.stdout.write(`\n--- unjudged: ${stripControl(item.step)} ---\n`);
|
|
404
|
+
process.stdout.write(`${stripControl(item.text)}\n`);
|
|
403
405
|
}
|
|
404
406
|
}
|
|
405
407
|
|
|
@@ -516,8 +518,10 @@ async function cmdResume(rest) {
|
|
|
516
518
|
// panel — M4a piece 2 + M4b (docs/wiki/the-module-ladder.md, "M4a — read-only
|
|
517
519
|
// panel" and "M4b — inputs"): `fwdloop panel [--port 4800] [--root <dir>]`.
|
|
518
520
|
// Reads are GET/HEAD; the only writes are POST /api/answer and POST
|
|
519
|
-
// /api/resume (src/panel/server.js), each gated by Origin/Host +
|
|
520
|
-
//
|
|
521
|
+
// /api/resume (src/panel/server.js), each gated by Origin/Host + the panel's
|
|
522
|
+
// cookie. `fwdloop panel` writes its token to a 0600 file ($XDG_RUNTIME_DIR/fwdloop/
|
|
523
|
+
// panel-<port>.token, else ~/.cache/fwdloop/; reused across restarts while that file is 0600) and prints `http://127.0.0.1:<port>/?t=<token>` —
|
|
524
|
+
// open that link (it sets the cookie); every request needs it. Bound to 127.0.0.1 only. Never picks
|
|
521
525
|
// a different port on collision — a taken port is a loud, non-zero-exit
|
|
522
526
|
// failure.
|
|
523
527
|
// ---------------------------------------------------------------------------
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fwdloop",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
package/src/ask.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
// not a second Checkpoint instance layered on top of the same file protocol.
|
|
18
18
|
|
|
19
19
|
import {
|
|
20
|
-
existsSync, mkdirSync, readFileSync, renameSync, writeFileSync,
|
|
20
|
+
existsSync, linkSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync,
|
|
21
21
|
} from 'node:fs';
|
|
22
22
|
import { join } from 'node:path';
|
|
23
23
|
import { createHash, randomUUID } from 'node:crypto';
|
|
@@ -25,6 +25,24 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
25
25
|
import { appendAudit } from './books.js';
|
|
26
26
|
import { readFileInside, resolveInside, readdirInside } from './flow.js';
|
|
27
27
|
|
|
28
|
+
/**
|
|
29
|
+
* M4c amendment 3: the ONE rule for "was this answer saved in time" — the
|
|
30
|
+
* answer's own saved time (`answeredAt`, written by `answerAsk`) against the
|
|
31
|
+
* ask's deadline, never the clock at the moment a resume restarts.
|
|
32
|
+
* on-time - answeredAt parses and is not after expiresAt
|
|
33
|
+
* late - answeredAt parses and is after expiresAt
|
|
34
|
+
* unreadable - answeredAt or expiresAt missing/unparseable: never on time
|
|
35
|
+
* @param {unknown} answeredAt
|
|
36
|
+
* @param {unknown} expiresAt
|
|
37
|
+
* @returns {'on-time'|'late'|'unreadable'}
|
|
38
|
+
*/
|
|
39
|
+
export function answerTiming(answeredAt, expiresAt) {
|
|
40
|
+
const a = typeof answeredAt === 'string' ? Date.parse(answeredAt) : NaN;
|
|
41
|
+
const e = typeof expiresAt === 'string' ? Date.parse(expiresAt) : NaN;
|
|
42
|
+
if (Number.isNaN(a) || Number.isNaN(e)) return 'unreadable';
|
|
43
|
+
return a > e ? 'late' : 'on-time';
|
|
44
|
+
}
|
|
45
|
+
|
|
28
46
|
/**
|
|
29
47
|
* M4b amendment 3 (SIGNED by hamr 2026-09-30): the ONE translation of a
|
|
30
48
|
* decision. The answer that was spelled `reject` is `redo`; `reject` is still
|
|
@@ -40,10 +58,25 @@ export function normalizeDecision(decision) {
|
|
|
40
58
|
return decision === 'reject' ? 'redo' : decision;
|
|
41
59
|
}
|
|
42
60
|
|
|
61
|
+
/** Terminal control codes out of text a model wrote, before it reaches a terminal: C0 (incl. ESC, which starts
|
|
62
|
+
* every CSI/OSC sequence), DEL and C1 (incl. the one-byte CSI, U+009B). Keeps \n and \t. A stripped ESC leaves the
|
|
63
|
+
* sequence's printable tail ("[2J") visible, which is inert. */
|
|
64
|
+
export function stripControl(text) {
|
|
65
|
+
// eslint-disable-next-line no-control-regex
|
|
66
|
+
return String(text).replace(/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g, '');
|
|
67
|
+
}
|
|
68
|
+
|
|
43
69
|
/** The one decision -> status table, used by `listArchivedAsks` here and by the panel's legacy-ask rows.
|
|
44
70
|
* Look it up with `normalizeDecision(decision)`. */
|
|
45
71
|
export const DECISION_STATUS = { accept: 'accepted', redo: 'redo', rerun: 'reran' };
|
|
46
72
|
|
|
73
|
+
/** The status for a decision word read from disk, or undefined for anything that is not one of the table's OWN
|
|
74
|
+
* entries ("constructor", "toString" and the rest of Object.prototype read as unrecognised). */
|
|
75
|
+
export function decisionStatus(decision) {
|
|
76
|
+
const word = normalizeDecision(decision);
|
|
77
|
+
return typeof word === 'string' && Object.hasOwn(DECISION_STATUS, word) ? DECISION_STATUS[word] : undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
47
80
|
function sleep(ms) {
|
|
48
81
|
return new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
49
82
|
}
|
|
@@ -244,9 +277,171 @@ export function sha256Hex(serialised) {
|
|
|
244
277
|
return createHash('sha256').update(Buffer.from(serialised, 'utf8')).digest('hex');
|
|
245
278
|
}
|
|
246
279
|
|
|
280
|
+
/**
|
|
281
|
+
* M4c-fix amendment 1 (a): why a saved `answer.json` is not a usable answer for the open ask `openAskId`, or `null`
|
|
282
|
+
* when it is usable. The resume refuses each of these by name before it consumes the file, so without a way aside
|
|
283
|
+
* the file would block every new answer (`answerAsk`'s exclusive create).
|
|
284
|
+
* @param {string} text the file's text @param {string} openAskId
|
|
285
|
+
* @returns {string|null}
|
|
286
|
+
*/
|
|
287
|
+
export function brokenAnswerWhy(text, openAskId) {
|
|
288
|
+
let a;
|
|
289
|
+
try { a = JSON.parse(text); } catch { return 'it is not valid JSON'; }
|
|
290
|
+
if (a === null || typeof a !== 'object' || Array.isArray(a)) return 'it is not a JSON object';
|
|
291
|
+
if (a.askId !== openAskId) return `it names another ask ("${a.askId}")`;
|
|
292
|
+
if (Number.isNaN(Date.parse(typeof a.answeredAt === 'string' ? a.answeredAt : ''))) return 'it carries no readable saved time';
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Move `answer.json` aside as a record: `answer.<askId>.<kind>.<n>.json`, `n` the first free number. Write-once:
|
|
298
|
+
* the new name is created with a hard link (`EEXIST` = taken, try the next), then the old name is removed — never
|
|
299
|
+
* a rename, which would overwrite; never a delete of the content. A symlinked `answer.json` is refused, not followed.
|
|
300
|
+
* @param {string} runDir @param {string} askId @param {'broken'|'late'} kind
|
|
301
|
+
* @returns {{ ok: true, name: string } | { ok: false, red: string }}
|
|
302
|
+
*/
|
|
303
|
+
export function setAsideAnswer(runDir, askId, kind) {
|
|
304
|
+
const resolved = resolveInside(runDir, 'answer.json');
|
|
305
|
+
if (!resolved.ok) return { ok: false, red: `answer.json cannot be set aside — ${'red' in resolved ? resolved.red : 'it is missing'}` };
|
|
306
|
+
for (let n = 1; n < 1000; n += 1) {
|
|
307
|
+
const name = `answer.${askId}.${kind}.${n}.json`;
|
|
308
|
+
try {
|
|
309
|
+
linkSync(resolved.full, join(runDir, name));
|
|
310
|
+
} catch (err) {
|
|
311
|
+
if (err.code === 'EEXIST') continue; // eslint-disable-line no-continue
|
|
312
|
+
return { ok: false, red: `answer.json could not be set aside — ${err.message}` };
|
|
313
|
+
}
|
|
314
|
+
try { unlinkSync(resolved.full); } catch { /* already moved by another process: the record exists either way */ }
|
|
315
|
+
return { ok: true, name };
|
|
316
|
+
}
|
|
317
|
+
return { ok: false, red: 'answer.json could not be set aside — no free record name' };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ---------------------------------------------------------------------------
|
|
321
|
+
// M4c-fix amendment 1 (b): an expired ask can be reopened — by a human only. A reopen never rewrites `ask.json`,
|
|
322
|
+
// `state.json` or the archive (nothing existing is rewritten): it is a new write-once record,
|
|
323
|
+
// `reopen.<askId>.<n>.json` (`wx`, `n` = the next free number), holding who/when/the new deadline. The deadline of
|
|
324
|
+
// an ask is read in ONE place, `effectiveExpiresAt`: the newest reopen record for that askId, else the ask's own
|
|
325
|
+
// `expiresAt`. Every reader of a deadline (answerAsk, the resume, the panel, the CLI) goes through it.
|
|
326
|
+
// ---------------------------------------------------------------------------
|
|
327
|
+
|
|
328
|
+
const REOPEN_RE = /^reopen\.(.+)\.(\d+)\.json$/;
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* The deadline an ask is judged against: the newest valid reopen record's `expiresAt`, else `original`.
|
|
332
|
+
* A record that is unreadable, names another ask, or holds no parseable `expiresAt` is ignored.
|
|
333
|
+
* @param {string} runDir @param {string} askId @param {string} original the ask's own `expiresAt`
|
|
334
|
+
* @returns {string}
|
|
335
|
+
*/
|
|
336
|
+
export function effectiveExpiresAt(runDir, askId, original) {
|
|
337
|
+
let best = null;
|
|
338
|
+
for (const name of readdirInside(runDir, '.')) {
|
|
339
|
+
const m = REOPEN_RE.exec(name);
|
|
340
|
+
if (!m || m[1] !== askId) continue; // eslint-disable-line no-continue
|
|
341
|
+
const n = Number(m[2]);
|
|
342
|
+
if (best && best.n >= n) continue; // eslint-disable-line no-continue
|
|
343
|
+
const r = readFileInside(runDir, name);
|
|
344
|
+
if (!r.ok) continue; // eslint-disable-line no-continue
|
|
345
|
+
let rec;
|
|
346
|
+
try { rec = JSON.parse(r.text); } catch { continue; } // eslint-disable-line no-continue
|
|
347
|
+
if (rec === null || typeof rec !== 'object' || rec.askId !== askId || typeof rec.expiresAt !== 'string' || Number.isNaN(Date.parse(rec.expiresAt))) continue; // eslint-disable-line no-continue
|
|
348
|
+
best = { n, expiresAt: rec.expiresAt };
|
|
349
|
+
}
|
|
350
|
+
return best ? best.expiresAt : original;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* An `ask.json`-shaped object as every reader should see it: `expiresAt` is the effective deadline, and `waitMs`
|
|
355
|
+
* is the signed wait the ask was parked with (its own `expiresAt` minus `askedAt`, written from the signed ttl),
|
|
356
|
+
* which a reopen repeats. `waitMs` is `null` when either time cannot be read.
|
|
357
|
+
* @param {string} runDir @param {any} ask
|
|
358
|
+
* @returns {any}
|
|
359
|
+
*/
|
|
360
|
+
export function withReopen(runDir, ask) {
|
|
361
|
+
if (ask === null || typeof ask !== 'object' || typeof ask.askId !== 'string') return ask;
|
|
362
|
+
const waitMs = Date.parse(ask.expiresAt) - Date.parse(ask.askedAt);
|
|
363
|
+
return {
|
|
364
|
+
...ask,
|
|
365
|
+
expiresAt: typeof ask.expiresAt === 'string' ? effectiveExpiresAt(runDir, ask.askId, ask.expiresAt) : ask.expiresAt,
|
|
366
|
+
waitMs: Number.isFinite(waitMs) && waitMs > 0 ? waitMs : null,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Reopen an expired ask: a fresh window of the same signed length, starting now, on the same ask (the same draft;
|
|
372
|
+
* nothing about the run changes). Human only — the caller names who (`by`); no runner, agent or resume path calls this.
|
|
373
|
+
* Refused, by name, when: there is no such open ask, its answer was already taken, it has not expired, or a saved
|
|
374
|
+
* answer made in time is waiting (that one is resumed, not reopened). A late or broken saved answer is moved aside
|
|
375
|
+
* as a record (`answer.<askId>.late.<n>.json`, never deleted). Two clicks race on the record's exclusive create:
|
|
376
|
+
* the loser is refused "already reopened", so a double click opens one window, not two.
|
|
377
|
+
* @param {{ runDir: string, askId: string, by: string, clock?: () => string }} opts
|
|
378
|
+
* @returns {{ ok: true, expiresAt: string, n: number, setAside: string|null } | { ok: false, red: string }}
|
|
379
|
+
*/
|
|
380
|
+
export function reopenAsk({
|
|
381
|
+
runDir, askId, by, clock,
|
|
382
|
+
}) {
|
|
383
|
+
const nowIso = (typeof clock === 'function' ? clock : () => new Date().toISOString())();
|
|
384
|
+
if (typeof runDir !== 'string' || runDir.length === 0) return { ok: false, red: 'reopenAsk: "runDir" must be a non-empty string' };
|
|
385
|
+
if (typeof askId !== 'string' || askId.length === 0) return { ok: false, red: 'reopenAsk: "askId" must be a non-empty string' };
|
|
386
|
+
if (typeof by !== 'string' || by.length === 0) return { ok: false, red: 'reopenAsk: "by" must name who reopened it' };
|
|
387
|
+
const askRead = readFileInside(runDir, 'ask.json');
|
|
388
|
+
if (!askRead.ok) return { ok: false, red: `reopenAsk: no open ask for run ${runDir}` };
|
|
389
|
+
let raw;
|
|
390
|
+
try { raw = JSON.parse(askRead.text); } catch (err) { return { ok: false, red: `reopenAsk: ask.json for run ${runDir} is not valid JSON — ${err.message}` }; }
|
|
391
|
+
if (raw === null || typeof raw !== 'object' || raw.askId !== askId) return { ok: false, red: `reopenAsk: askId "${askId}" is unknown for run ${runDir}` };
|
|
392
|
+
const ask = withReopen(runDir, raw);
|
|
393
|
+
if (Number.isNaN(Date.parse(ask.expiresAt))) return { ok: false, red: `reopenAsk: askId "${askId}" has an unparseable expiresAt — refusing` };
|
|
394
|
+
if (ask.waitMs === null) return { ok: false, red: `reopenAsk: askId "${askId}" carries no readable wait (askedAt/expiresAt) to repeat — refusing` };
|
|
395
|
+
if (existsSync(join(runDir, `answer.${askId}.consumed.json`))) return { ok: false, red: `reopenAsk: askId "${askId}" already answered for run ${runDir}` };
|
|
396
|
+
if (Date.parse(nowIso) <= Date.parse(ask.expiresAt)) return { ok: false, red: `reopenAsk: askId "${askId}" has not expired (it runs until ${ask.expiresAt})` };
|
|
397
|
+
const saved = readFileInside(runDir, 'answer.json');
|
|
398
|
+
let timing = null;
|
|
399
|
+
if (saved.ok) {
|
|
400
|
+
let a = null;
|
|
401
|
+
try { a = JSON.parse(saved.text); } catch { /* broken: set aside below */ }
|
|
402
|
+
timing = a !== null && typeof a === 'object' && a.askId === askId ? answerTiming(a.answeredAt, ask.expiresAt) : 'unreadable';
|
|
403
|
+
if (timing === 'on-time') return { ok: false, red: `reopenAsk: askId "${askId}" has an answer saved in time — resume it, it is not expired` };
|
|
404
|
+
}
|
|
405
|
+
// Amendment 3 (b): the stale answer is moved aside FIRST. If that fails nothing is written (no record, no audit
|
|
406
|
+
// row, the clock stays), so a stale answer can never count as fresh under a new deadline. If the record write then
|
|
407
|
+
// fails, the answer stays set aside: it was late or broken anyway, and the ask is simply still expired.
|
|
408
|
+
let setAside = null;
|
|
409
|
+
if (saved.ok) {
|
|
410
|
+
const moved = setAsideAnswer(runDir, askId, timing === 'late' ? 'late' : 'broken');
|
|
411
|
+
if (!moved.ok) return { ok: false, red: 'Could not clear the late answer; nothing was reopened.' };
|
|
412
|
+
setAside = moved.name;
|
|
413
|
+
}
|
|
414
|
+
// The record: write-once, keyed by askId and its number. The exclusive create is the one gate.
|
|
415
|
+
let n = 1;
|
|
416
|
+
for (const name of readdirInside(runDir, '.')) {
|
|
417
|
+
const m = REOPEN_RE.exec(name);
|
|
418
|
+
if (m && m[1] === askId) n = Math.max(n, Number(m[2]) + 1);
|
|
419
|
+
}
|
|
420
|
+
const expiresAt = new Date(Date.parse(nowIso) + ask.waitMs).toISOString();
|
|
421
|
+
const record = {
|
|
422
|
+
askId, n, by, at: nowIso, previousExpiresAt: ask.expiresAt, expiresAt, waitMs: ask.waitMs,
|
|
423
|
+
};
|
|
424
|
+
try {
|
|
425
|
+
writeFileSync(join(runDir, `reopen.${askId}.${n}.json`), JSON.stringify(record, null, 2), { flag: 'wx' });
|
|
426
|
+
} catch (err) {
|
|
427
|
+
if (err.code === 'EEXIST') return { ok: false, red: `reopenAsk: askId "${askId}" was already reopened (record ${n} exists)` };
|
|
428
|
+
return { ok: false, red: `reopenAsk: could not write the reopen record — ${err.message}` };
|
|
429
|
+
}
|
|
430
|
+
// The run's audit book names the reopen too (amendment 1 (b): "the audit records who reopened it and when"),
|
|
431
|
+
// through the one audit writer; a pure note (cost 0, no model), shaped like the stale-answer row.
|
|
432
|
+
appendAudit(runDir, {
|
|
433
|
+
step: 'ask', attempt: raw.attempt ?? null, class: null, verdict: 'ask-reopened',
|
|
434
|
+
gap: `reopened by ${by} at ${nowIso} (ask ${askId}); deadline ${ask.expiresAt} -> ${expiresAt}`,
|
|
435
|
+
usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: nowIso, tokens: null, tools: null, refused: [],
|
|
436
|
+
});
|
|
437
|
+
return {
|
|
438
|
+
ok: true, expiresAt, n, setAside,
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
247
442
|
/**
|
|
248
443
|
* @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
|
|
249
|
-
* @returns {{ ok: true } | { ok: false, red: string }}
|
|
444
|
+
* @returns {{ ok: true, setAside: string|null } | { ok: false, red: string }}
|
|
250
445
|
*/
|
|
251
446
|
export function answerAsk({
|
|
252
447
|
runDir, askId, decision: givenDecision, reason, clock,
|
|
@@ -292,8 +487,10 @@ export function answerAsk({
|
|
|
292
487
|
if (Number.isNaN(Date.parse(ask.expiresAt))) {
|
|
293
488
|
return { ok: false, red: `answerAsk: askId "${askId}" has an unparseable expiresAt "${ask.expiresAt}" for run ${runDir} — refusing rather than treating it as not-expired` };
|
|
294
489
|
}
|
|
295
|
-
|
|
296
|
-
|
|
490
|
+
// The deadline is the reopened one when the ask was reopened (`effectiveExpiresAt`, the one reader).
|
|
491
|
+
const expiresAt = effectiveExpiresAt(runDir, askId, ask.expiresAt);
|
|
492
|
+
if (Date.parse(nowIso) > Date.parse(expiresAt)) {
|
|
493
|
+
return { ok: false, red: `answerAsk: askId "${askId}" expired at ${expiresAt} for run ${runDir}` };
|
|
297
494
|
}
|
|
298
495
|
|
|
299
496
|
const answerPath = join(runDir, 'answer.json');
|
|
@@ -331,6 +528,18 @@ export function answerAsk({
|
|
|
331
528
|
// the exclusive gate (fails EEXIST if the file already exists), so there
|
|
332
529
|
// is no window between "is it answered" and "answer it" for a second
|
|
333
530
|
// caller to land in.
|
|
531
|
+
// M4c-fix amendment 1 (a): a saved answer that is broken (not JSON, not an object, names another ask, no readable
|
|
532
|
+
// time) would block this write for good — it is moved aside as a record first (never deleted). Only a broken one.
|
|
533
|
+
let setAside = null;
|
|
534
|
+
const savedRead = readFileInside(runDir, 'answer.json');
|
|
535
|
+
if (savedRead.ok) {
|
|
536
|
+
const why = brokenAnswerWhy(savedRead.text, askId);
|
|
537
|
+
if (why !== null) {
|
|
538
|
+
const moved = setAsideAnswer(runDir, askId, 'broken');
|
|
539
|
+
if (!moved.ok) return { ok: false, red: `answerAsk: askId "${askId}" — a broken saved answer (${why}) is in the way — ${moved.red}` };
|
|
540
|
+
setAside = moved.name;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
334
543
|
try {
|
|
335
544
|
writeFileSync(answerPath, JSON.stringify(payload, null, 2), { flag: 'wx' });
|
|
336
545
|
} catch (err) {
|
|
@@ -339,7 +548,7 @@ export function answerAsk({
|
|
|
339
548
|
}
|
|
340
549
|
return { ok: false, red: `answerAsk: could not write ${answerPath} — ${err.message}` };
|
|
341
550
|
}
|
|
342
|
-
return { ok: true };
|
|
551
|
+
return { ok: true, setAside };
|
|
343
552
|
}
|
|
344
553
|
|
|
345
554
|
// ---------------------------------------------------------------------------
|
|
@@ -520,7 +729,7 @@ export function listArchivedAsks(runDir) {
|
|
|
520
729
|
try {
|
|
521
730
|
parsed = JSON.parse(consumedRead.text);
|
|
522
731
|
answer = {
|
|
523
|
-
status:
|
|
732
|
+
status: decisionStatus(parsed.decision) ?? `unrecognised: ${parsed.decision}`,
|
|
524
733
|
answeredAt: parsed.answeredAt,
|
|
525
734
|
};
|
|
526
735
|
if (typeof parsed.reason === 'string') answer.reason = parsed.reason;
|
|
@@ -528,7 +737,7 @@ export function listArchivedAsks(runDir) {
|
|
|
528
737
|
answer = { status: 'open', why: `${join(runDir, consumedRelPath)} is not valid JSON — ${err.message}` };
|
|
529
738
|
}
|
|
530
739
|
} else if (typeof ask.expiresAt === 'string' && !Number.isNaN(Date.parse(ask.expiresAt))
|
|
531
|
-
&& Date.now() > Date.parse(ask.expiresAt)) {
|
|
740
|
+
&& Date.now() > Date.parse(effectiveExpiresAt(runDir, askId, ask.expiresAt))) {
|
|
532
741
|
answer = { status: 'expired' };
|
|
533
742
|
} else {
|
|
534
743
|
answer = { status: 'unanswered' };
|
|
@@ -538,9 +747,11 @@ export function listArchivedAsks(runDir) {
|
|
|
538
747
|
askId,
|
|
539
748
|
question: ask.question,
|
|
540
749
|
askedAt: ask.askedAt,
|
|
541
|
-
expiresAt: ask.expiresAt,
|
|
750
|
+
expiresAt: typeof ask.expiresAt === 'string' ? effectiveExpiresAt(runDir, askId, ask.expiresAt) : ask.expiresAt,
|
|
751
|
+
waitMs: withReopen(runDir, ask).waitMs ?? null,
|
|
542
752
|
evidence: readAskEvidence(ask),
|
|
543
753
|
answer,
|
|
754
|
+
...(typeof ask.emits === 'string' ? { emits: ask.emits } : {}),
|
|
544
755
|
});
|
|
545
756
|
}
|
|
546
757
|
|
package/src/authoring.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
import { createHash } from 'node:crypto';
|
|
17
17
|
import {
|
|
18
|
-
existsSync, mkdirSync, readFileSync, rmdirSync, writeFileSync,
|
|
18
|
+
existsSync, mkdirSync, readFileSync, realpathSync, rmdirSync, writeFileSync,
|
|
19
19
|
} from 'node:fs';
|
|
20
20
|
import path from 'node:path';
|
|
21
21
|
|
|
@@ -97,10 +97,13 @@ export const costText = (n, spendComplete = true) => {
|
|
|
97
97
|
const usd = costText;
|
|
98
98
|
|
|
99
99
|
/** Plain-text readout of what the human is about to sign. Pure. */
|
|
100
|
-
export function buildReadout({
|
|
100
|
+
export function buildReadout({
|
|
101
|
+
declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root,
|
|
102
|
+
}) {
|
|
101
103
|
const out = [];
|
|
102
104
|
out.push(`DRAFT READOUT — NOT SIGNED — flow "${name}"`, '');
|
|
103
105
|
out.push(`Drafted by: ${modelId ?? '?'} in ${rounds} round(s), cost ${usd(costUsd, spendComplete)}`);
|
|
106
|
+
if (typeof root === 'string') out.push(`Flows root: ${root} (the flow is written to <flows root>/${name} when you sign)`);
|
|
104
107
|
out.push(`Cap per run (signed by you in the prose): $${arbiter.capUsd}`, '');
|
|
105
108
|
out.push('INPUTS');
|
|
106
109
|
for (const s of arbiter.sources) {
|
|
@@ -128,6 +131,20 @@ export function buildReadout({ declaration, arbiter, lines, name, modelId, costU
|
|
|
128
131
|
return `${out.join('\n')}\n`;
|
|
129
132
|
}
|
|
130
133
|
|
|
134
|
+
/** realpath of a path that may not exist yet: the real path of its nearest existing ancestor plus the rest. */
|
|
135
|
+
function realpathOfNew(p) {
|
|
136
|
+
const rest = [];
|
|
137
|
+
let cur = path.resolve(p);
|
|
138
|
+
for (;;) {
|
|
139
|
+
try { return path.join(realpathSync(cur), ...rest.reverse()); } catch (e) {
|
|
140
|
+
const up = path.dirname(cur);
|
|
141
|
+
if (up === cur || e.code === 'EACCES') return path.resolve(p);
|
|
142
|
+
rest.push(path.basename(cur));
|
|
143
|
+
cur = up;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
131
148
|
/** Read the prose file. Refuses (a red, never a throw) on unreadable or blank. */
|
|
132
149
|
export function readProseFile(file) {
|
|
133
150
|
let text;
|
|
@@ -153,6 +170,13 @@ export async function draftToDir({
|
|
|
153
170
|
if (!nameCheck.ok) return refuse([nameCheck.red]);
|
|
154
171
|
if (typeof root !== 'string' || root === '') return refuse(['draft: --root <flows dir> is required']);
|
|
155
172
|
if (!(budgetUsd > 0)) return refuse(['draft: budget must be a positive number']);
|
|
173
|
+
// An unsigned draft folder inside the flows root would list as a flow in the panel and Inbox (checked by realpath, at use time).
|
|
174
|
+
const realRoot = realpathOfNew(root);
|
|
175
|
+
const realDir = realpathOfNew(dir);
|
|
176
|
+
const rel = path.relative(realRoot, realDir);
|
|
177
|
+
if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
|
|
178
|
+
return refuse([`draft: "${dir}" is inside the flows root "${root}" — an unsigned draft would show as a flow; use a --out outside the flows root`]);
|
|
179
|
+
}
|
|
156
180
|
const read = readProseFile(proseFile);
|
|
157
181
|
if (!read.ok) return refuse([String(read.red)]);
|
|
158
182
|
const prose = { text: String(read.text) };
|
|
@@ -164,6 +188,8 @@ export async function draftToDir({
|
|
|
164
188
|
}
|
|
165
189
|
const secrets = secretVar && env[secretVar] ? [env[secretVar]] : [];
|
|
166
190
|
if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
|
|
191
|
+
// Red messages can echo what a provider's error body echoed (a key): scrubbed like every file, before anything prints them.
|
|
192
|
+
const cleanReds = (reds) => (reds ?? []).map((r) => scrub(String(r), secrets));
|
|
167
193
|
// Claim the dir BEFORE the paid round (exclusive mkdir: a race or an existing path refuses at $0).
|
|
168
194
|
const exists = () => refuse([`draft: "${dir}" already exists — never overwritten, use a new dir`]);
|
|
169
195
|
if (existsSync(dir)) return exists();
|
|
@@ -179,7 +205,7 @@ export async function draftToDir({
|
|
|
179
205
|
});
|
|
180
206
|
if (result.stop === 'pre-flight') {
|
|
181
207
|
try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
|
|
182
|
-
return refuse(result.reds);
|
|
208
|
+
return refuse(cleanReds(result.reds));
|
|
183
209
|
}
|
|
184
210
|
|
|
185
211
|
// After a paid round: never a silent throw. The cost is returned so the caller prints it; the dir is claimed and stays.
|
|
@@ -203,7 +229,7 @@ export async function draftToDir({
|
|
|
203
229
|
const declarationText = scrub(dj(result.declaration), secrets);
|
|
204
230
|
const inputFactsText = scrub(dj(result.declaration.inputFacts), secrets);
|
|
205
231
|
const readoutText = scrub(buildReadout({
|
|
206
|
-
declaration: result.declaration, arbiter: parsed.arbiter, lines: parsed.lines, name, modelId: result.modelId, costUsd: result.costUsd, rounds: result.rounds, spendComplete: result.spendComplete,
|
|
232
|
+
declaration: result.declaration, arbiter: parsed.arbiter, lines: parsed.lines, name, modelId: result.modelId, costUsd: result.costUsd, rounds: result.rounds, spendComplete: result.spendComplete, root,
|
|
207
233
|
}), secrets);
|
|
208
234
|
files['declaration.json'] = declarationText;
|
|
209
235
|
files['input-facts.json'] = inputFactsText;
|
|
@@ -244,7 +270,7 @@ export async function draftToDir({
|
|
|
244
270
|
return paidFail(`write failed after the paid round (${e.code ?? e.message}); the draft dir is incomplete and never signable`);
|
|
245
271
|
}
|
|
246
272
|
return {
|
|
247
|
-
ok: result.ok, wrote: true, dir, hash, reds: result.reds, costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
|
|
273
|
+
ok: result.ok, wrote: true, dir, hash, reds: cleanReds(result.reds), costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
|
|
248
274
|
};
|
|
249
275
|
}
|
|
250
276
|
|
package/src/books.js
CHANGED
|
@@ -28,6 +28,26 @@ function appendLine(filePath, row) {
|
|
|
28
28
|
appendFileSync(filePath, `${JSON.stringify(row)}\n`);
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
/**
|
|
32
|
+
* M4c piece 1: the ONE writer of a run dir's `pids.jsonl` — append-only, never
|
|
33
|
+
* rewritten, not a book the arbiter reads. One row per process that works on
|
|
34
|
+
* the run (`src/liveness.js` `recordPid` builds the row).
|
|
35
|
+
* @param {string} runDir
|
|
36
|
+
* @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'}} row
|
|
37
|
+
*/
|
|
38
|
+
export function appendPidRow(runDir, row) {
|
|
39
|
+
appendLine(join(runDir, 'pids.jsonl'), row);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The one reader of `pids.jsonl` (same tolerant `readLines` every book uses).
|
|
44
|
+
* @param {string} runDir
|
|
45
|
+
* @returns {any[]}
|
|
46
|
+
*/
|
|
47
|
+
export function readPidRows(runDir) {
|
|
48
|
+
return readLines(runDir, 'pids.jsonl');
|
|
49
|
+
}
|
|
50
|
+
|
|
31
51
|
/**
|
|
32
52
|
* Raw read-back of one JSONL book, one writer's own sibling reader (M4a
|
|
33
53
|
* piece 2, docs/wiki/the-module-ladder.md M4a scope item 2: "one reader per
|