pi-durable-subagents 1.0.39 → 1.0.40
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/CHANGELOG.md +24 -0
- package/README.md +15 -1
- package/dist/agent/main/snapshots.js +63 -74
- package/dist/agent/main.js +17 -16
- package/dist/cli/control.js +1 -1
- package/dist/cli/restart.js +2 -2
- package/dist/kernel/cache.js +40 -0
- package/dist/kernel/journal.js +85 -11
- package/dist/orchestrator/reader-ledger.js +110 -0
- package/dist/orchestrator/snapshot.js +334 -34
- package/dist/orchestrator/store.js +9 -1
- package/dist/paths.js +6 -0
- package/dist/requests.js +2 -2
- package/dist/ui/data.js +150 -44
- package/dist/ui/index.js +14 -5
- package/dist/ui/session.js +18 -3
- package/package.json +1 -1
|
@@ -4,15 +4,17 @@ import { initiatorSummary, restartLine } from "./restart.js";
|
|
|
4
4
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { compileFanout } from "../compat/fanout.js";
|
|
7
|
-
import { readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
7
|
+
import { crc32, forgetJournalSnapshot, forgetJournalSnapshotsIf, journalAppends, readJournalRecord, readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
|
|
8
|
+
import { readCache, writeCache } from "../kernel/cache.js";
|
|
9
|
+
import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
|
|
10
|
+
import { JT, attentionEntries, isEntry } from "../types.js";
|
|
11
|
+
import {} from "./ledger.js";
|
|
12
|
+
import { readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
|
|
11
13
|
import { packageVersion } from "../version.js";
|
|
12
14
|
import { worktreeCalls, worktreeLabel } from "./executor/worktree.js";
|
|
13
15
|
import { leaseCalls, leaseLines, leaseState } from "../platform/lease.js";
|
|
14
16
|
import { labelsOf } from "../events/derive.js";
|
|
15
|
-
import { PENDING_NOTE } from "./notes.js";
|
|
17
|
+
import { PENDING_NOTE, generationRids, UNDELIVERED_FOLLOW_UP } from "./notes.js";
|
|
16
18
|
import { readStats } from "./stats.js";
|
|
17
19
|
/** A workflow has live work: it runs, or follow-ups opened on it after it finished have not ended yet. */
|
|
18
20
|
export function isLive(wf) {
|
|
@@ -48,7 +50,8 @@ export function plannedFromScript(source) {
|
|
|
48
50
|
const plannedByPath = new Map();
|
|
49
51
|
/** v12 §4: The current revision's planned total, read lazily from the pinned run body and cached (pins are immutable). */
|
|
50
52
|
function plannedTotal(home, wid, rev) {
|
|
51
|
-
const
|
|
53
|
+
const scripts = pathsOf(home, wid).scripts;
|
|
54
|
+
const path = scripts[rev] ??= join(pinnedDir(home, wid), rev === 1 ? "script.js" : join(`r${rev}`, "script.js"));
|
|
52
55
|
if (!plannedByPath.has(path)) {
|
|
53
56
|
try {
|
|
54
57
|
plannedByPath.set(path, plannedFromScript(readFileSync(path, "utf8")));
|
|
@@ -358,8 +361,217 @@ export function snapshotFromEntries(wid, entries) {
|
|
|
358
361
|
const FOLDS = 256; // workflows whose fold state is kept; pruned and long-idle ones fall out
|
|
359
362
|
const folds = new Map();
|
|
360
363
|
const derived = new WeakMap();
|
|
361
|
-
export function workflowSnapshot(home, wid) {
|
|
362
|
-
const
|
|
364
|
+
export function workflowSnapshot(home, wid, ledger) {
|
|
365
|
+
const wf = workflowDigest(home, wid, ledger).snapshot;
|
|
366
|
+
const planned = plannedTotal(home, wid, wf.rev);
|
|
367
|
+
return planned === undefined ? wf : { ...wf, planned };
|
|
368
|
+
}
|
|
369
|
+
/** P37: a generation opened by a send (possibly after the workflow finished) that has no seal yet is pending work. */
|
|
370
|
+
const opened = new WeakMap();
|
|
371
|
+
export function openGeneration(entries) {
|
|
372
|
+
const hit = opened.get(entries);
|
|
373
|
+
if (hit?.length === entries.length)
|
|
374
|
+
return hit.open;
|
|
375
|
+
// Sealed call ids end in `/<key>@<gen>`; collect every such suffix once instead of rescanning per generation.
|
|
376
|
+
const sealed = new Set();
|
|
377
|
+
for (const s of entries)
|
|
378
|
+
if (s.type === JT.sealed) {
|
|
379
|
+
const call = String(s.call);
|
|
380
|
+
for (let i = call.indexOf("/"); i >= 0; i = call.indexOf("/", i + 1))
|
|
381
|
+
sealed.add(call.slice(i));
|
|
382
|
+
}
|
|
383
|
+
const open = entries.some(g => g.type === "generation" && !sealed.has(`/${String(g.key)}@${String(g.gen)}`));
|
|
384
|
+
opened.set(entries, { length: entries.length, open });
|
|
385
|
+
return open;
|
|
386
|
+
}
|
|
387
|
+
const unresolvedByEntries = new WeakMap();
|
|
388
|
+
/** P15: The attention items of one immutable journal snapshot without an `attention-resolved`, computed once per snapshot. */
|
|
389
|
+
export function unresolvedAttention(entries) {
|
|
390
|
+
let items = unresolvedByEntries.get(entries);
|
|
391
|
+
if (items)
|
|
392
|
+
return items;
|
|
393
|
+
const done = new Set(entries.filter(e => e.type === JT.attentionResolved).map(e => `${e.id}\0${e.rev}`));
|
|
394
|
+
items = attentionEntries(entries).map(e => e.item).filter(item => !done.has(`${item.id}\0${item.rev}`));
|
|
395
|
+
unresolvedByEntries.set(entries, items);
|
|
396
|
+
return items;
|
|
397
|
+
}
|
|
398
|
+
// A settled workflow's digest is kept in memory and on disk (DSA_HOME/cache), keyed by the journal's inode and committed
|
|
399
|
+
// size: committed bytes never change (A1), so the same device, inode and size reduce to the same digest. Readers used to
|
|
400
|
+
// decode every historical journal at each pi start (hundreds of MB: seconds of pi's main thread and hundreds of MB
|
|
401
|
+
// per pi window) only to find them finished. The key also names this reduction's code, so a changed reducer reads its
|
|
402
|
+
// journals again instead of trusting digests an older one wrote.
|
|
403
|
+
const DIGEST_FORMAT = 2;
|
|
404
|
+
let digestCode;
|
|
405
|
+
function digestVersion() {
|
|
406
|
+
if (digestCode === undefined) {
|
|
407
|
+
try {
|
|
408
|
+
const ext = import.meta.url.endsWith(".ts") ? "ts" : "js";
|
|
409
|
+
digestCode = `${DIGEST_FORMAT}.${crc32(Buffer.concat([new URL(import.meta.url), ...[`../types.${ext}`, `./executor/worktree.${ext}`, `./notes.${ext}`].map(p => new URL(p, import.meta.url))].map(u => readFileSync(u))))}`;
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
digestCode = "";
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return digestCode;
|
|
416
|
+
}
|
|
417
|
+
const digests = new Map();
|
|
418
|
+
const FINAL_STATUS = new Set(["done", "failed", "stopped"]);
|
|
419
|
+
/** Post-seal/recovery work that can append without a new request must not enter a polling trust window. */
|
|
420
|
+
export function pendingRecovery(wid, entries) {
|
|
421
|
+
const start = entries.findLastIndex(e => e.type === "revised"), current = start < 0 ? entries : entries.slice(start);
|
|
422
|
+
const consumed = new Set(current.filter(e => e.type === "generation").flatMap(generationRids));
|
|
423
|
+
const retiredForwards = new Map(entries.filter(e => e.type === "forward-retired").map(e => [String(e.rid2), e]));
|
|
424
|
+
const delivered = new Set(entries.filter(e => e.type === "forward-delivered").map(e => String(e.rid2)));
|
|
425
|
+
// collectSealed repairs forwarding receipts of older revisions as well.
|
|
426
|
+
for (const e of entries)
|
|
427
|
+
if (e.type === "forward" && !retiredForwards.has(String(e.rid2)) && !delivered.has(String(e.rid2)))
|
|
428
|
+
return true;
|
|
429
|
+
for (const e of current)
|
|
430
|
+
if (e.type === "forward" && retiredForwards.get(String(e.rid2))?.reason === UNDELIVERED_FOLLOW_UP && !consumed.has(String(e.rid)))
|
|
431
|
+
return true;
|
|
432
|
+
const fenced = new Set(entries.filter(e => e.type === JT.fenced).map(e => e.exec));
|
|
433
|
+
const gates = new Set(entries.filter(e => e.type === "gate").map(e => e.id));
|
|
434
|
+
const cleaned = new Set(entries.filter(e => e.type === "wt-removed" || e.type === "wt-kept").map(e => e.call));
|
|
435
|
+
const seals = new Map(entries.filter(e => e.type === JT.sealed).map(e => [e.call, e]));
|
|
436
|
+
const attention = attentionEntries(entries), resolved = new Set(entries.filter(e => e.type === JT.attentionResolved).map(e => JSON.stringify([e.id, e.rev])));
|
|
437
|
+
const hasAttention = (id, rev) => attention.some(e => e.item.id === id && (rev === undefined || e.item.rev === rev));
|
|
438
|
+
// Engine.attention repairs completion notices, including on already-ended workflows after a crash.
|
|
439
|
+
if (current.some(e => e.type === JT.done) && !hasAttention(`finished:${wid}`, entries.filter(e => e.type === JT.done).length))
|
|
440
|
+
return true;
|
|
441
|
+
for (const e of entries) {
|
|
442
|
+
if (e.type === JT.exec && !fenced.has(e.exec))
|
|
443
|
+
return true;
|
|
444
|
+
if (e.type === "gate-intent" && !gates.has(e.id))
|
|
445
|
+
return true;
|
|
446
|
+
if (e.type === "wt-intent" && seals.get(e.call)?.result?.status === "ok" && !cleaned.has(e.call))
|
|
447
|
+
return true;
|
|
448
|
+
if (e.type === JT.sealed && e.result?.status === "unknown" && !hasAttention(`unknown:${String(e.call)}`))
|
|
449
|
+
return true;
|
|
450
|
+
if (e.type === "generation" && e.revision !== undefined) {
|
|
451
|
+
const call = `${wid}@${e.revision}/${String(e.key)}@${String(e.gen)}`;
|
|
452
|
+
if (seals.has(call) && !hasAttention(`finished:${call}`))
|
|
453
|
+
return true;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
// Retirement, fence repair, and cross-workflow conflict resolution can still close these items.
|
|
457
|
+
for (const { item } of attention)
|
|
458
|
+
if (!resolved.has(JSON.stringify([item.id, item.rev]))) {
|
|
459
|
+
if (item.id.startsWith("fence:") || item.kind === "conflict")
|
|
460
|
+
return true;
|
|
461
|
+
if (item.call && seals.has(item.call) && item.kind !== "finished" && item.id !== `unknown:${item.call}`)
|
|
462
|
+
return true;
|
|
463
|
+
}
|
|
464
|
+
return false;
|
|
465
|
+
}
|
|
466
|
+
function digestOf(wf, entries, complete) {
|
|
467
|
+
const settled = complete && FINAL_STATUS.has(wf.status) && !wf.active && !wf.followUps &&
|
|
468
|
+
entries.some(e => e.type === JT.done) && !openGeneration(entries) && !pendingRecovery(wf.wid, entries);
|
|
469
|
+
const tasks = Object.create(null);
|
|
470
|
+
if (settled)
|
|
471
|
+
for (const e of entries)
|
|
472
|
+
if (e.type === "call")
|
|
473
|
+
tasks[`${e.key}\0${e.gen}`] = String(e.spec?.task ?? "");
|
|
474
|
+
return settled ? { snapshot: wf, settled: { attention: structuredClone(unresolvedAttention(entries)), tasks } } : { snapshot: wf };
|
|
475
|
+
}
|
|
476
|
+
function storedDigest(home, wid, dev, ino, size) {
|
|
477
|
+
const stored = readCache(join(digestDir(home), `${wid}.json`));
|
|
478
|
+
const d = stored?.digest, wf = d?.snapshot;
|
|
479
|
+
if (!(digestVersion() && stored?.v === digestVersion() && stored.home === home && stored.dev === dev && stored.ino === ino && stored.size === size &&
|
|
480
|
+
d?.settled && Array.isArray(d.settled.attention) && d.settled.tasks && wf?.wid === wid && Array.isArray(wf.calls) &&
|
|
481
|
+
Array.isArray(wf.attention) && wf.counts && FINAL_STATUS.has(wf.status) && !wf.active && !wf.followUps))
|
|
482
|
+
return undefined;
|
|
483
|
+
// The reducer always sets pos with Number(e.pos); a missing position is NaN, which JSON represents as null.
|
|
484
|
+
for (const call of wf.calls)
|
|
485
|
+
if (call.pos === null)
|
|
486
|
+
call.pos = NaN;
|
|
487
|
+
return d;
|
|
488
|
+
}
|
|
489
|
+
/** Concurrent windows publish independently; an old writer's identity cannot pass a new journal's key. */
|
|
490
|
+
function storeDigest(home, wid, record, digest) {
|
|
491
|
+
const v = digestVersion();
|
|
492
|
+
if (v)
|
|
493
|
+
writeCache(join(digestDir(home), `${wid}.json`), { v, home, dev: record.dev, ino: record.ino, size: record.size, digest }, journalPath(home, wid));
|
|
494
|
+
}
|
|
495
|
+
// Path strings per workflow: joining them for every workflow on every UI refresh cost pi's main thread milliseconds.
|
|
496
|
+
const pathsByHome = new Map();
|
|
497
|
+
function pathsOf(home, wid) {
|
|
498
|
+
let byWid = pathsByHome.get(home);
|
|
499
|
+
if (!byWid)
|
|
500
|
+
pathsByHome.set(home, byWid = new Map());
|
|
501
|
+
let paths = byWid.get(wid);
|
|
502
|
+
if (!paths)
|
|
503
|
+
byWid.set(wid, paths = { journal: journalPath(home, wid), scripts: [] });
|
|
504
|
+
return paths;
|
|
505
|
+
}
|
|
506
|
+
/** Intake commits requests before applying their generation or revision, then decisions afterward. Recovery and
|
|
507
|
+
* late attention can also append without a fresh request: an unchanged ledger skips settled journal IO only for
|
|
508
|
+
* this bounded window. Local appends end it too; turn boundaries check immediately. */
|
|
509
|
+
export const SETTLED_RECHECK_MS = 5000;
|
|
510
|
+
/** P25: The current digest of one workflow, from its committed journal. With `ledger` (the orchestrator ledger's
|
|
511
|
+
* identity, see allWorkflows) a settled digest checked under the same ledger less than SETTLED_RECHECK_MS ago is
|
|
512
|
+
* reused without a stat. */
|
|
513
|
+
export function workflowDigest(home, wid, ledger) {
|
|
514
|
+
const path = pathsOf(home, wid).journal, memo = digests.get(path), now = Date.now();
|
|
515
|
+
if (memo?.digest.settled)
|
|
516
|
+
releasable.add(path);
|
|
517
|
+
if (ledger !== undefined && memo?.digest.settled && memo.ledger === ledger && memo.appends === journalAppends() && now >= memo.checked && now - memo.checked < SETTLED_RECHECK_MS)
|
|
518
|
+
return memo.digest;
|
|
519
|
+
let dev, ino, size;
|
|
520
|
+
try {
|
|
521
|
+
({ dev, ino, size } = statSync(path));
|
|
522
|
+
}
|
|
523
|
+
catch (error) {
|
|
524
|
+
if (error.code !== "ENOENT")
|
|
525
|
+
throw error;
|
|
526
|
+
}
|
|
527
|
+
if (memo && memo.dev === dev && memo.ino === ino && memo.size === size) {
|
|
528
|
+
memo.ledger = ledger;
|
|
529
|
+
memo.checked = now;
|
|
530
|
+
memo.appends = journalAppends();
|
|
531
|
+
return memo.digest;
|
|
532
|
+
}
|
|
533
|
+
if (dev !== undefined && ino !== undefined && size !== undefined && !memo) {
|
|
534
|
+
const stored = storedDigest(home, wid, dev, ino, size);
|
|
535
|
+
if (stored) {
|
|
536
|
+
digests.set(path, { dev, ino, size, digest: stored, checked: now, ledger, appends: journalAppends() });
|
|
537
|
+
releasable.add(path);
|
|
538
|
+
return stored;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
const record = readJournalRecord(path), entries = record?.entries ?? [];
|
|
542
|
+
const digest = digestOf(foldSnapshot(path, wid, entries), entries, !!record && record.length === record.size);
|
|
543
|
+
if (!record) {
|
|
544
|
+
digests.delete(path);
|
|
545
|
+
return digest;
|
|
546
|
+
}
|
|
547
|
+
digests.set(path, { dev: record.dev, ino: record.ino, size: record.size, digest, checked: now, ledger, appends: journalAppends() });
|
|
548
|
+
if (digest.settled) {
|
|
549
|
+
storeDigest(home, wid, record, digest);
|
|
550
|
+
releasable.add(path);
|
|
551
|
+
}
|
|
552
|
+
return digest;
|
|
553
|
+
}
|
|
554
|
+
/** Last journal identity check of the current digest. Reuse never renews this timestamp. */
|
|
555
|
+
export function workflowDigestChecked(home, wid) {
|
|
556
|
+
return digests.get(pathsOf(home, wid).journal)?.checked ?? -Infinity;
|
|
557
|
+
}
|
|
558
|
+
/** The digest is all a poller reads of a settled workflow: its entries and fold state need not stay in memory. Pollers
|
|
559
|
+
* (allWorkflows, the main agent's workflows) release them after a pass; a one-off reader that compares journal
|
|
560
|
+
* snapshots by identity around a digest (describe) keeps them. */
|
|
561
|
+
const releasable = new Set();
|
|
562
|
+
/** Explicit one-off readers may load settled history between polling passes. */
|
|
563
|
+
export function releaseLoadedSettledJournals() {
|
|
564
|
+
forgetJournalSnapshotsIf(path => !!digests.get(path)?.digest.settled);
|
|
565
|
+
}
|
|
566
|
+
export function releaseSettledJournals() {
|
|
567
|
+
for (const path of releasable) {
|
|
568
|
+
forgetJournalSnapshot(path);
|
|
569
|
+
folds.delete(path);
|
|
570
|
+
}
|
|
571
|
+
releasable.clear();
|
|
572
|
+
}
|
|
573
|
+
function foldSnapshot(path, wid, entries) {
|
|
574
|
+
const hit = derived.get(entries);
|
|
363
575
|
let wf;
|
|
364
576
|
if (hit?.wid === wid)
|
|
365
577
|
wf = hit.snapshot;
|
|
@@ -393,12 +605,11 @@ export function workflowSnapshot(home, wid) {
|
|
|
393
605
|
else
|
|
394
606
|
folds.delete(path);
|
|
395
607
|
}
|
|
396
|
-
|
|
397
|
-
return planned === undefined ? wf : { ...wf, planned };
|
|
608
|
+
return wf;
|
|
398
609
|
}
|
|
399
610
|
/** Ops: wids archived by `prune` (orchestrator ledger `pruned{wid}`); they no longer exist for any reader. */
|
|
400
611
|
function prunedIds(home) {
|
|
401
|
-
return
|
|
612
|
+
return readerLedger(home).state.pruned;
|
|
402
613
|
}
|
|
403
614
|
const ledgerIndexes = new WeakMap();
|
|
404
615
|
export function ledgerIndex(ledger) {
|
|
@@ -471,8 +682,24 @@ function workflowIds(home) {
|
|
|
471
682
|
throw error;
|
|
472
683
|
}
|
|
473
684
|
const pruned = prunedIds(home);
|
|
685
|
+
forgetRemovedWorkflows(home, wids, pruned);
|
|
474
686
|
return wids.filter(wid => !pruned.has(wid));
|
|
475
687
|
}
|
|
688
|
+
function forgetRemovedWorkflows(home, names, pruned) {
|
|
689
|
+
const paths = pathsByHome.get(home), present = new Set(names);
|
|
690
|
+
if (paths)
|
|
691
|
+
for (const [wid, p] of paths)
|
|
692
|
+
if (pruned.has(wid) || !present.has(wid)) {
|
|
693
|
+
digests.delete(p.journal);
|
|
694
|
+
folds.delete(p.journal);
|
|
695
|
+
forgetJournalSnapshot(p.journal);
|
|
696
|
+
firstOrigins.delete(p.journal);
|
|
697
|
+
for (const script of p.scripts)
|
|
698
|
+
if (script)
|
|
699
|
+
plannedByPath.delete(script);
|
|
700
|
+
paths.delete(wid);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
476
703
|
/** Drain: the one hold rule. drain/undrain entries apply to every workflow (no scope), one session's (`origin`) or one
|
|
477
704
|
* workflow (`wid`). A workflow is held when the newest entry that applies to it is a drain recorded after it was created. */
|
|
478
705
|
export function holdOf(ledger, wid, origin) {
|
|
@@ -491,10 +718,10 @@ export function heldIn(ledger) {
|
|
|
491
718
|
}
|
|
492
719
|
/** Drain: the workflows a drain (stop-all, a quit pi) holds until resume, and since when. */
|
|
493
720
|
export function heldWorkflows(home) {
|
|
494
|
-
const
|
|
721
|
+
const ix = readerLedger(home).state;
|
|
495
722
|
const origin = (wid) => ix.created.get(wid)?.origin;
|
|
496
|
-
const hold = (wid) =>
|
|
497
|
-
const since = ix.lastDrain
|
|
723
|
+
const hold = (wid) => readerHold(ix, wid, origin(wid));
|
|
724
|
+
const since = ix.lastDrain?.ts;
|
|
498
725
|
return { ...(since !== undefined ? { since } : {}), held: wid => hold(wid) !== undefined, labels: wid => ix.labels.get(wid), session: wid => ix.sessions.get(wid) };
|
|
499
726
|
}
|
|
500
727
|
/** The origin of a workflow's `wf-created`, the first entry of its journal, for a workflow the ledger does not attribute
|
|
@@ -557,14 +784,63 @@ export function labelsText(labels, width = 60) {
|
|
|
557
784
|
const text = Object.entries(labels).map(([k, v]) => `${k}=${v}`).join(" ").replace(/\s+/g, " ");
|
|
558
785
|
return text ? `[${clip(text, Math.max(1, width - 3))}]` : "";
|
|
559
786
|
}
|
|
787
|
+
const decorated = new WeakMap();
|
|
560
788
|
/** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
|
|
561
789
|
export function allWorkflows(home) {
|
|
562
790
|
return snapshotsOf(home, workflowIds(home));
|
|
563
791
|
}
|
|
792
|
+
export function ledgerIdentity(record) {
|
|
793
|
+
return record ? `${record.dev}:${record.ino}:${record.size}` : "";
|
|
794
|
+
}
|
|
795
|
+
function snapshotWithLedger(home, wid, ix, mark) {
|
|
796
|
+
const pendingRevision = (ix.revisions.get(wid) ?? 0) > (digests.get(pathsOf(home, wid).journal)?.digest.snapshot.rev ?? 0);
|
|
797
|
+
const base = workflowDigest(home, wid, pendingRevision ? undefined : mark).snapshot, planned = plannedTotal(home, wid, base.rev), l = ix.labels.get(wid), s = ix.sessions.get(wid);
|
|
798
|
+
const paused = isLive(base) && !!readerHold(ix, wid, ix.created.get(wid)?.origin), hit = decorated.get(base);
|
|
799
|
+
if (hit && hit.planned === planned && hit.labels === l && hit.session === s && hit.paused === paused)
|
|
800
|
+
return hit.wf;
|
|
801
|
+
const planned1 = planned === undefined ? base : { ...base, planned }, labelled1 = labelled(planned1, l, s);
|
|
802
|
+
const wf = paused ? { ...labelled1, paused: true } : labelled1;
|
|
803
|
+
decorated.set(base, { planned, labels: l, session: s, paused, wf });
|
|
804
|
+
return wf;
|
|
805
|
+
}
|
|
564
806
|
function snapshotsOf(home, wids) {
|
|
565
|
-
const
|
|
566
|
-
|
|
807
|
+
const record = readerLedger(home), mark = readerLedgerIdentity(record);
|
|
808
|
+
try {
|
|
809
|
+
return wids.sort().reverse().map(wid => snapshotWithLedger(home, wid, record.state, mark));
|
|
810
|
+
}
|
|
811
|
+
finally {
|
|
812
|
+
releaseSettledJournals();
|
|
813
|
+
}
|
|
567
814
|
}
|
|
815
|
+
/** Directory effects follow committed create-intent/pruned entries (Store.create/materialize, Engine.prune).
|
|
816
|
+
* Check identity first for the fast path; if a scan is needed, read the attributing ledger AFTER listing w/. */
|
|
817
|
+
const listings = new Map();
|
|
818
|
+
export function readerWorkflowListing(home, fresh = false) {
|
|
819
|
+
let record = readerLedger(home);
|
|
820
|
+
const memo = listings.get(home), now = Date.now();
|
|
821
|
+
if (!fresh && memo && memo.mark === readerLedgerIdentity(record) && now >= memo.checked && now - memo.checked < SETTLED_RECHECK_MS)
|
|
822
|
+
return { record, names: memo.names, checked: memo.checked };
|
|
823
|
+
let names;
|
|
824
|
+
try {
|
|
825
|
+
names = readdirSync(join(home, "w"));
|
|
826
|
+
}
|
|
827
|
+
catch (error) {
|
|
828
|
+
if (error.code !== "ENOENT")
|
|
829
|
+
throw error;
|
|
830
|
+
names = [];
|
|
831
|
+
}
|
|
832
|
+
record = readerLedger(home);
|
|
833
|
+
forgetRemovedWorkflows(home, names, record.state.pruned);
|
|
834
|
+
// An intent can be committed before its directory is materialized. Until all unpruned intents are present,
|
|
835
|
+
// a second pass must list again even if no more ledger bytes arrive (including a create during this scan).
|
|
836
|
+
const present = new Set(names), incomplete = [...record.state.intents.keys()].some(wid => !record.state.pruned.has(wid) && !present.has(wid));
|
|
837
|
+
if (incomplete)
|
|
838
|
+
listings.delete(home);
|
|
839
|
+
else
|
|
840
|
+
listings.set(home, { mark: readerLedgerIdentity(record), checked: now, names });
|
|
841
|
+
return { record, names, checked: now };
|
|
842
|
+
}
|
|
843
|
+
const ownPasses = new Map();
|
|
568
844
|
/** The workflows `own` ("main:<pi session id>") shows as its own (`ownedBy`), snapshotted exactly as `allWorkflows`
|
|
569
845
|
* does: the same list as `allWorkflows(home).filter(w => ownedBy(w, own))`, but who owns a workflow is decided from
|
|
570
846
|
* the orchestrator ledger alone (the origin of its create-intent or `created`, the session its run named), so the
|
|
@@ -580,14 +856,42 @@ export function ownWorkflows(home, own, options = {}) {
|
|
|
580
856
|
// create-intent before it creates the directory, so every directory listed here already has its intent in a ledger
|
|
581
857
|
// read afterwards; a workflow another session creates in between is attributed without opening its journal. (Read
|
|
582
858
|
// the other way round, such a workflow would look unknown to the ledger and its journal would be read.)
|
|
583
|
-
const
|
|
584
|
-
|
|
859
|
+
const { record, names, checked: listed } = readerWorkflowListing(home), ix = record.state, mark = readerLedgerIdentity(record), now = Date.now();
|
|
860
|
+
let passes = ownPasses.get(home);
|
|
861
|
+
if (!passes)
|
|
862
|
+
ownPasses.set(home, passes = new Map());
|
|
863
|
+
const key = JSON.stringify([own, !!options.started]), prior = passes.get(key);
|
|
864
|
+
const current = prior && prior.names === names && !prior.retryUnknown && prior.mark === mark && prior.appends === journalAppends() && now >= prior.checked && now - prior.checked < SETTLED_RECHECK_MS;
|
|
865
|
+
const includes = (w) => options.started ? w.origin === own : ownedBy(w, own);
|
|
866
|
+
if (current && !prior.pending.length) {
|
|
867
|
+
// Another explicit reader may have loaded these journals since the preceding pass.
|
|
868
|
+
releaseLoadedSettledJournals();
|
|
869
|
+
return prior.result;
|
|
870
|
+
}
|
|
871
|
+
const candidates = current ? prior.candidates : names.filter(wid => !wid.startsWith(".") && !ix.pruned.has(wid)).filter(wid => {
|
|
585
872
|
const known = ix.intents.has(wid) || ix.created.has(wid), session = ix.sessions.get(wid);
|
|
586
873
|
const origin = known ? ix.intents.get(wid) ?? ix.created.get(wid)?.origin : firstOrigin(home, wid);
|
|
587
874
|
return origin === own || (!options.started && session !== undefined && `main:${session}` === own);
|
|
588
|
-
});
|
|
589
|
-
|
|
590
|
-
|
|
875
|
+
}).sort().reverse();
|
|
876
|
+
try {
|
|
877
|
+
const changed = new Map((current ? prior.pending : candidates).map(wid => [wid, snapshotWithLedger(home, wid, ix, mark)]));
|
|
878
|
+
const old = new Map(prior?.result.map(w => [w.wid, w]));
|
|
879
|
+
const result = candidates.map(wid => changed.get(wid) ?? old.get(wid)).filter(w => w && includes(w));
|
|
880
|
+
const same = prior && prior.result.length === result.length && result.every((w, i) => w === prior.result[i]);
|
|
881
|
+
// A rescan can reuse digests checked earlier: the outer pass inherits the oldest dependency check.
|
|
882
|
+
let checked = current ? prior.checked : Math.min(now, listed);
|
|
883
|
+
const pending = candidates.filter(wid => {
|
|
884
|
+
const memo = digests.get(pathsOf(home, wid).journal), digest = memo?.digest;
|
|
885
|
+
if (digest?.settled)
|
|
886
|
+
checked = Math.min(checked, memo.checked);
|
|
887
|
+
return !digest?.settled || (ix.revisions.get(wid) ?? 0) > digest.snapshot.rev;
|
|
888
|
+
});
|
|
889
|
+
passes.set(key, { mark, checked, appends: journalAppends(), names, retryUnknown: names.some(wid => !ix.intents.has(wid) && !ix.created.has(wid) && !ix.pruned.has(wid)), candidates, pending, result: same ? prior.result : result });
|
|
890
|
+
return same ? prior.result : result;
|
|
891
|
+
}
|
|
892
|
+
finally {
|
|
893
|
+
releaseSettledJournals();
|
|
894
|
+
}
|
|
591
895
|
}
|
|
592
896
|
/** P10/P11: Per-workflow script console log written by the orchestrator (bounded, human-readable). */
|
|
593
897
|
export function scriptLogPath(home, wid) { return join(workflowDir(home, wid), "script.log"); }
|
|
@@ -621,9 +925,9 @@ export function compactWorkflow(wf, leases) {
|
|
|
621
925
|
function origins(home) {
|
|
622
926
|
const ids = new Map();
|
|
623
927
|
const pruned = prunedIds(home);
|
|
624
|
-
for (const
|
|
625
|
-
if (
|
|
626
|
-
ids.set(
|
|
928
|
+
for (const [wid, origin] of readerLedger(home).state.origins)
|
|
929
|
+
if (!pruned.has(wid))
|
|
930
|
+
ids.set(wid, origin);
|
|
627
931
|
for (const wid of workflowIds(home))
|
|
628
932
|
if (!ids.has(wid))
|
|
629
933
|
ids.set(wid, undefined);
|
|
@@ -653,8 +957,7 @@ export function statusView(home, options = {}) {
|
|
|
653
957
|
}
|
|
654
958
|
/** The stats the running orchestrator published (none when no orchestrator runs). */
|
|
655
959
|
export function runningStats(home) {
|
|
656
|
-
const
|
|
657
|
-
ledgerStates.set(path, state);
|
|
960
|
+
const state = readerLedger(home).state.state;
|
|
658
961
|
const o = state.orchestrator, stats = o && !o.exited && processAlive(o.pid, o.start) ? readStats(home, o.pid) : undefined;
|
|
659
962
|
return stats ? { orchestratorStats: stats } : {};
|
|
660
963
|
}
|
|
@@ -668,7 +971,7 @@ const latestCalls = (wf) => [...new Map(wf.calls.map(c => [c.key, c])).values()]
|
|
|
668
971
|
/** Provider slots from the orchestrator ledger: holders per provider (hold/release{pool,slot,exec}) and the limits of
|
|
669
972
|
* the settings in effect (the latest config{hash,config}); config-rejected after it is reported too. */
|
|
670
973
|
// One fold per orchestrator ledger, extended as it grows (ledger.ts; the executor folds the same entries the same way).
|
|
671
|
-
|
|
974
|
+
// Pi readers share the compact incremental fold in reader-ledger.ts.
|
|
672
975
|
/** The orchestrator running now (its last `orchestrator` record, without an exit, whose process lives), and a note when
|
|
673
976
|
* its version is not the one this process loaded: running work stays on the version it started with. */
|
|
674
977
|
export function orchestratorView(state, loaded = packageVersion(), now = Date.now()) {
|
|
@@ -721,8 +1024,7 @@ export const NOTIFY_SINCE = "1.0.28";
|
|
|
721
1024
|
* older orchestrator would accept the request and its child would drop it); none when none runs (the next one starts
|
|
722
1025
|
* on the installed version) or it is current. */
|
|
723
1026
|
export function orchestratorTooOld(home, feature, since, loaded = packageVersion()) {
|
|
724
|
-
const
|
|
725
|
-
ledgerStates.set(path, state);
|
|
1027
|
+
const state = readerLedger(home).state.state;
|
|
726
1028
|
const o = state.orchestrator;
|
|
727
1029
|
if (!o || o.exited || !processAlive(o.pid, o.start) || !newer(since, o.version) || !newer(loaded, o.version))
|
|
728
1030
|
return undefined;
|
|
@@ -731,8 +1033,7 @@ export function orchestratorTooOld(home, feature, since, loaded = packageVersion
|
|
|
731
1033
|
}
|
|
732
1034
|
/** orchestratorView of the home's orchestrator ledger. */
|
|
733
1035
|
export function runningOrchestrator(home) {
|
|
734
|
-
const
|
|
735
|
-
ledgerStates.set(path, state);
|
|
1036
|
+
const state = readerLedger(home).state.state;
|
|
736
1037
|
return orchestratorView(state);
|
|
737
1038
|
}
|
|
738
1039
|
/** One `exhausted` line of the status views (the `provider-exhausted` wait uses it as its detail). */
|
|
@@ -751,13 +1052,12 @@ export function originLabel(origin) {
|
|
|
751
1052
|
return origin.startsWith("main:") ? `session ${origin.slice(5, 13)}` : clip(restartLine(origin), 40);
|
|
752
1053
|
}
|
|
753
1054
|
export function slotsView(home, now = Date.now()) {
|
|
754
|
-
const
|
|
755
|
-
ledgerStates.set(path, state);
|
|
1055
|
+
const ix = readerLedger(home).state, state = ix.state;
|
|
756
1056
|
const { held, config, rejected } = state, used = state.exhausted;
|
|
757
1057
|
const exhausted = [...used].sort(([a], [b]) => a.localeCompare(b)).map(([p, x]) => exhaustedLine(p, x, now));
|
|
758
1058
|
const limits = config?.settings.providers ?? {};
|
|
759
1059
|
const holders = new Map(), byOrigin = new Map();
|
|
760
|
-
const created =
|
|
1060
|
+
const created = ix.created;
|
|
761
1061
|
for (const e of held.values())
|
|
762
1062
|
if (e.pool !== "memory") {
|
|
763
1063
|
holders.set(e.pool, (holders.get(e.pool) ?? 0) + 1);
|
|
@@ -15,7 +15,7 @@ import { compileFanout } from "../compat/fanout.js";
|
|
|
15
15
|
import { contentHash, ulid } from "../kernel/ids.js";
|
|
16
16
|
import { openJournal, syncDirectory } from "../kernel/journal.js";
|
|
17
17
|
import { publishFile } from "../kernel/mailbox.js";
|
|
18
|
-
import { journalPath, pinnedDir, workflowDir } from "../paths.js";
|
|
18
|
+
import { digestDir, factsDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
|
|
19
19
|
import { JT } from "../types.js";
|
|
20
20
|
/** Every file publishPins writes for one revision, relative to its directory (inputs given relative too). */
|
|
21
21
|
function publishedFiles(inputs, origin) {
|
|
@@ -427,6 +427,14 @@ export class Store {
|
|
|
427
427
|
await rm(this.stagePath(rid), { recursive: true, force: true });
|
|
428
428
|
await syncDirectory(join(this.ledgers.home, 'staging')).catch(error => { if (error.code !== 'ENOENT')
|
|
429
429
|
throw error; });
|
|
430
|
+
// Readers' caches of it (derived, never authoritative: no sync needed).
|
|
431
|
+
await rm(join(digestDir(this.ledgers.home), `${wid}.json`), { force: true });
|
|
432
|
+
const cached = await readdir(digestDir(this.ledgers.home)).catch(error => { if (error.code !== 'ENOENT')
|
|
433
|
+
throw error; return []; });
|
|
434
|
+
for (const name of cached)
|
|
435
|
+
if (name.startsWith(`${wid}.json.`) && name.endsWith('.tmp'))
|
|
436
|
+
await rm(join(digestDir(this.ledgers.home), name), { force: true });
|
|
437
|
+
await rm(join(factsDir(this.ledgers.home), wid), { recursive: true, force: true });
|
|
430
438
|
}
|
|
431
439
|
/** A1, A5: Restore committed revisions; the engine reconciles pending retirement intents. A pruned wid is never
|
|
432
440
|
* materialized again; its interrupted removal is finished here (a failure is reported and retried next start). */
|
package/dist/paths.js
CHANGED
|
@@ -14,6 +14,12 @@ export const binDir = (home) => path.join(home, "bin");
|
|
|
14
14
|
export const orchInbox = (home) => path.join(home, "inbox");
|
|
15
15
|
/** Sender outboxes live under this root (kernel Outbox.open(root, ...)). */
|
|
16
16
|
export const outboxRoot = (home) => home;
|
|
17
|
+
/** Derived, rebuildable reader caches (never authoritative): deleting it only costs a slower next read. */
|
|
18
|
+
export const cacheDir = (home) => path.join(process.env.DSA_CACHE_HOME ?? home, "cache");
|
|
19
|
+
/** Digests of settled workflow journals (orchestrator/snapshot.ts). */
|
|
20
|
+
export const digestDir = (home) => path.join(cacheDir(home), "digests");
|
|
21
|
+
/** Facts of final calls shown by the UI (ui/data.ts), per workflow. */
|
|
22
|
+
export const factsDir = (home) => path.join(cacheDir(home), "facts");
|
|
17
23
|
export const workflowDir = (home, wid) => path.join(home, "w", wid);
|
|
18
24
|
export const journalPath = (home, wid) => path.join(workflowDir(home, wid), "journal.jsonl");
|
|
19
25
|
/** Per-call directory; `key` is the script key, `gen` the generation. */
|
package/dist/requests.js
CHANGED
|
@@ -7,7 +7,7 @@ import { readdir } from 'node:fs/promises';
|
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
9
9
|
import { contentHash } from "./kernel/ids.js";
|
|
10
|
-
import { readJournalSnapshot } from "./kernel/journal.js";
|
|
10
|
+
import { findJournalEntry, readJournalSnapshot } from "./kernel/journal.js";
|
|
11
11
|
import { publishRequest } from "./kernel/mailbox.js";
|
|
12
12
|
import { OsLock } from "./platform/lock.js";
|
|
13
13
|
import { orchInbox, orchLedger, outboxRoot } from "./paths.js";
|
|
@@ -68,7 +68,7 @@ export function specDigest(req) {
|
|
|
68
68
|
/** The envelope recorded for `rid`: the orchestrator's admitted copy (ledger `request`, kept after prune), else any
|
|
69
69
|
* sender's outbox `sent` entry (published or about to be). Read-only. */
|
|
70
70
|
export async function findRequest(home, rid) {
|
|
71
|
-
const admitted =
|
|
71
|
+
const admitted = findJournalEntry(orchLedger(home), e => e.type === 'request' && e.request.rid === rid);
|
|
72
72
|
if (admitted)
|
|
73
73
|
return { request: admitted.request, admitted: true };
|
|
74
74
|
const dir = join(outboxRoot(home), 'outbox');
|