pi-braid 0.43.27 → 0.43.29

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.
@@ -8,6 +8,12 @@
8
8
  * session growth, branch commits, result schema) — never from the worker's
9
9
  * own claim alone.
10
10
  *
11
+ * Each row also carries its queue rank and the worker ids it waits for, so the
12
+ * order workers may run in is read from the registry: `orderWorkerRows`
13
+ * prints it, and a verdict says `blocked` while a dependency has not been
14
+ * delivered. Both facts are the registry's own; no caller has to remember
15
+ * which piece of work lands first.
16
+ *
11
17
  * Registry file location: ~/.pi/agent/braid/projects/<sanitized-cwd>/workers.json
12
18
  * (per-CWD, beside locks.json, shared across all agents on the same project).
13
19
  *
@@ -68,6 +74,17 @@ export interface WorkerEntry {
68
74
  outputFile: string | null;
69
75
  branch: string | null;
70
76
  files: string[];
77
+ /**
78
+ * Queue rank: lower runs sooner. Null is unranked, which sorts after every
79
+ * ranked row. Filled with null on a row admitted before the field existed.
80
+ */
81
+ priority: number | null;
82
+ /**
83
+ * Worker ids this row waits for, in declared order. Empty means it waits for
84
+ * nothing. Fixed at admission: a dependency gained after the work started is
85
+ * a second unit of work wearing the first one's id.
86
+ */
87
+ dependsOn: string[];
71
88
  spawnedAt: string;
72
89
  lastSeenAt: string | null;
73
90
  resultAt: string | null;
@@ -107,6 +124,13 @@ export interface RegisterWorkerInput {
107
124
  files?: string[];
108
125
  branch?: string;
109
126
  outputFile?: string;
127
+ /** Queue rank: lower runs sooner; null or absent is unranked. */
128
+ priority?: number | null;
129
+ /**
130
+ * Worker ids this row waits for. Refused when an id is unknown, is this
131
+ * row's own id, or would close a dependency loop.
132
+ */
133
+ dependsOn?: string[];
110
134
  /**
111
135
  * Worker handle, when the caller already has it at admission time. Absent
112
136
  * stays null: a handle is never invented, and a pane is a place to look, not
@@ -129,6 +153,10 @@ export interface RegisterWorkerResult {
129
153
  reason?: string;
130
154
  /** True when a live entry already admitted this request and was reused. */
131
155
  reused?: boolean;
156
+ /** Machine-readable reason when the admission itself was refused. */
157
+ refusedBy?: DependencyRefusalReason;
158
+ /** The dependency id the refusal names. */
159
+ offendingId?: string;
132
160
  }
133
161
  export interface UpdateWorkerPatch {
134
162
  pane?: string;
@@ -138,6 +166,8 @@ export interface UpdateWorkerPatch {
138
166
  branch?: string;
139
167
  files?: string[];
140
168
  status?: WorkerStatus;
169
+ /** Queue rank to set; null clears it back to unranked. */
170
+ priority?: number | null;
141
171
  /** Resume point to record; stamped with the write time. */
142
172
  checkpoint?: WorkerCheckpointInput;
143
173
  }
@@ -156,10 +186,20 @@ export interface WorkerCheckOptions {
156
186
  now?: number;
157
187
  /** Frozen-session threshold in seconds; defaults to 600. */
158
188
  stalledAfterSec?: number;
189
+ /**
190
+ * The registry the entry belongs to, which is what its dependencies are
191
+ * resolved against. checkWorker always supplies it; a caller that omits it
192
+ * leaves dependency satisfaction unread, so no row is reported blocked.
193
+ */
194
+ registry?: WorkerRegistry;
159
195
  }
160
196
  export interface WorkerCheckResult {
161
197
  workerId: string;
162
198
  status: WorkerVerdictStatus;
199
+ /** The row's own stored status, beside the verdict — never replaced by it. */
200
+ storedStatus: WorkerStatus;
201
+ /** Dependency ids nothing has satisfied yet; empty when the row may run. */
202
+ blockedBy: string[];
163
203
  reason: string;
164
204
  outputFile: string | null;
165
205
  outputExists: boolean;
@@ -188,12 +228,36 @@ export interface WorkerCheckResult {
188
228
  effectEvidence: WorkerEffectEvidence | null;
189
229
  }
190
230
  /**
191
- * A status the registry reports. `resumable` is derived, never stored: it says
192
- * the entry is mid-flight with a checkpoint to resume from, which is a
193
- * statement about evidence rather than a lifecycle state a caller sets. No
194
- * stored row carries it, so the on-disk status set is unchanged.
231
+ * Why a dependency edge was refused at admission: the id is not in the registry,
232
+ * the row names itself, or the edge would close a loop.
195
233
  */
196
- export type WorkerVerdictStatus = WorkerStatus | "resumable";
234
+ export type DependencyRefusalReason = "unknown-dependency" | "self-dependency" | "dependency-cycle";
235
+ /** One refused dependency edge, as the admission reports it. */
236
+ export interface DependencyRefusal {
237
+ reason: DependencyRefusalReason;
238
+ /** The offending id: the unknown one, the row's own, or where a loop starts. */
239
+ id: string;
240
+ /**
241
+ * The loop from the admitted row back to itself, e.g. `[a, b, a]`; empty
242
+ * when the refusal names no loop.
243
+ */
244
+ path: string[];
245
+ /** The refusal in one sentence, prefixed with its reason token. */
246
+ message: string;
247
+ }
248
+ /** One listing row: the entry, and the dependency ids still blocking it. */
249
+ export interface WorkerOrderRow {
250
+ entry: WorkerEntry;
251
+ blockedBy: string[];
252
+ }
253
+ /**
254
+ * A status the registry reports. `resumable` and `blocked` are derived, never
255
+ * stored: `resumable` says the entry is mid-flight with a checkpoint to resume
256
+ * from, `blocked` that a dependency has not been delivered. Both are statements
257
+ * about evidence rather than lifecycle states a caller sets, so no stored row
258
+ * carries either and the on-disk status set is unchanged.
259
+ */
260
+ export type WorkerVerdictStatus = WorkerStatus | "resumable" | "blocked";
197
261
  export declare const WORKER_REGISTRY_VERSION = 1;
198
262
  /**
199
263
  * Spec names a worker result may declare: the accepted set, and the one source
@@ -203,7 +267,10 @@ export declare const WORKER_REGISTRY_VERSION = 1;
203
267
  export declare const WORKER_SPECS: readonly string[];
204
268
  export declare const WORKER_STATUSES: readonly WorkerStatus[];
205
269
  export declare const WORKER_OUTCOMES: readonly WorkerOutcome[];
206
- /** Statuses check-worker may report: the stored statuses plus `resumable`. */
270
+ /**
271
+ * Statuses check-worker may report: the stored statuses plus the derived ones,
272
+ * `resumable` and `blocked`, which no row ever carries on disk.
273
+ */
207
274
  export declare const WORKER_VERDICT_STATUSES: readonly WorkerVerdictStatus[];
208
275
  /** Statuses a worker's result schema may self-report. */
209
276
  export declare const RESULT_SCHEMA_STATUSES: readonly string[];
@@ -268,6 +335,7 @@ export interface WorkerAdmissionDecision {
268
335
  export declare function decideAdmission(existing: WorkerEntry | undefined, requestId: string, request: {
269
336
  spec?: string;
270
337
  files?: string[];
338
+ dependsOn?: readonly string[];
271
339
  }): WorkerAdmissionDecision;
272
340
  /**
273
341
  * Persist a refused admission against the live worker that refused it. A
@@ -278,6 +346,48 @@ export declare function decideAdmission(existing: WorkerEntry | undefined, reque
278
346
  * refuses nothing.
279
347
  */
280
348
  export declare function recordAdmissionRefusal(workerId: string, requestId: string, cwd?: string): boolean;
349
+ /** Priority values the registry accepts: finite numbers, or null for unranked. */
350
+ export declare function normalizePriority(raw: unknown): number | null;
351
+ /**
352
+ * Dependency ids as the registry stores them: strings, trimmed, non-empty,
353
+ * first occurrence kept. A malformed or absent value waits for nothing.
354
+ */
355
+ export declare function normalizeDependsOn(raw: unknown): string[];
356
+ /** Statuses that satisfy a dependency edge; a failed worker delivered nothing. */
357
+ export declare const WORKER_SATISFYING_STATUSES: readonly WorkerStatus[];
358
+ /** True when the row that id names delivered the work a dependent waits for. */
359
+ export declare function isDependencySatisfied(entry: WorkerEntry | undefined): boolean;
360
+ /**
361
+ * The dependency ids of one row that nothing has satisfied yet, in declared
362
+ * order. An id with no row at all is unsatisfied: admission refuses unknown ids,
363
+ * so a missing one means the row was hand-edited or removed, and neither is a
364
+ * delivery.
365
+ */
366
+ export declare function unsatisfiedDependencies(entry: WorkerEntry, registry: WorkerRegistry): string[];
367
+ /**
368
+ * Decide whether `dependsOn` may be recorded for `workerId`, against the graph
369
+ * the registry holds now. Null means the edges stand. A refused edge writes
370
+ * nothing: the caller reports the reason and the id, and the row is untouched.
371
+ *
372
+ * A row naming itself is refused as a self-dependency before the unknown check,
373
+ * which would otherwise answer `unknown-dependency` for an id that is by
374
+ * construction not admitted yet and hide the actual defect.
375
+ */
376
+ export declare function validateDependencies(workerId: string, dependsOn: readonly string[], registry: WorkerRegistry): DependencyRefusal | null;
377
+ /**
378
+ * Split listing rows into the order they may be acted on: rows whose
379
+ * dependencies are all satisfied first, then blocked rows, each group ranked by
380
+ * priority ascending with unranked rows after every ranked one, ties by
381
+ * admission time and then id so the order is total.
382
+ *
383
+ * Satisfaction is read against the whole registry rather than the rows being
384
+ * printed: a closed row still satisfies its dependents, so it must be read
385
+ * before a listing that hides closed rows is filtered.
386
+ */
387
+ export declare function orderWorkerRows(entries: readonly WorkerEntry[], registry: WorkerRegistry): {
388
+ ready: WorkerOrderRow[];
389
+ blocked: WorkerOrderRow[];
390
+ };
281
391
  /**
282
392
  * Admit a worker. Refuses when a live (not closed) entry exists for the
283
393
  * same workerId; a closed entry is rolled over (retries are countable).
@@ -591,6 +701,12 @@ export declare function workerEffectEvidenceForEntry(entry: WorkerEntry, opts?:
591
701
  * recorded gate exited 0. None of the three is the no-effect-evidence flag;
592
702
  * the flag is a field on the verdict, never a different status, and a row
593
703
  * that is not a terminal completion carries null.
704
+ *
705
+ * A row whose `dependsOn` holds an id that is not `merged` or `completed`
706
+ * reads as `blocked`, naming each blocking id with the status it carries; the
707
+ * row's own stored status travels beside the verdict, so a blocked row and a
708
+ * ready one are never the same answer. The dependencies are read against the
709
+ * registry the row belongs to, which checkWorker supplies.
594
710
  */
595
711
  export declare function evaluateWorker(entry: WorkerEntry, opts?: WorkerCheckOptions): WorkerCheckResult;
596
712
  /**
@@ -8,6 +8,12 @@
8
8
  * session growth, branch commits, result schema) — never from the worker's
9
9
  * own claim alone.
10
10
  *
11
+ * Each row also carries its queue rank and the worker ids it waits for, so the
12
+ * order workers may run in is read from the registry: `orderWorkerRows`
13
+ * prints it, and a verdict says `blocked` while a dependency has not been
14
+ * delivered. Both facts are the registry's own; no caller has to remember
15
+ * which piece of work lands first.
16
+ *
11
17
  * Registry file location: ~/.pi/agent/braid/projects/<sanitized-cwd>/workers.json
12
18
  * (per-CWD, beside locks.json, shared across all agents on the same project).
13
19
  *
@@ -52,10 +58,14 @@ export const WORKER_OUTCOMES = [
52
58
  "false-done",
53
59
  "closed",
54
60
  ];
55
- /** Statuses check-worker may report: the stored statuses plus `resumable`. */
61
+ /**
62
+ * Statuses check-worker may report: the stored statuses plus the derived ones,
63
+ * `resumable` and `blocked`, which no row ever carries on disk.
64
+ */
56
65
  export const WORKER_VERDICT_STATUSES = [
57
66
  ...WORKER_STATUSES,
58
67
  "resumable",
68
+ "blocked",
59
69
  ];
60
70
  /** Statuses a worker's result schema may self-report. */
61
71
  export const RESULT_SCHEMA_STATUSES = [
@@ -87,7 +97,7 @@ export const WORKER_STATUS_LAYERS = [
87
97
  role: "computed verdict",
88
98
  owner: "check-worker",
89
99
  values: WORKER_VERDICT_STATUSES,
90
- states: "what check-worker derives from evidence, resumable never stored",
100
+ states: "what check-worker derives from evidence, resumable and blocked never stored",
91
101
  },
92
102
  {
93
103
  role: "result attestation",
@@ -136,6 +146,10 @@ function normalizeEntry(raw) {
136
146
  requestId,
137
147
  checkpoint: isCheckpoint(raw.checkpoint) ? raw.checkpoint : null,
138
148
  admissionRefusals: Array.isArray(raw.admissionRefusals) ? raw.admissionRefusals : [],
149
+ // A row admitted before the queue facts existed is unranked and waits for
150
+ // nothing, which is exactly what the absent fields mean.
151
+ priority: typeof raw.priority === "number" && Number.isFinite(raw.priority) ? raw.priority : null,
152
+ dependsOn: normalizeDependsOn(raw.dependsOn),
139
153
  };
140
154
  }
141
155
  function isCheckpoint(raw) {
@@ -272,6 +286,16 @@ function requestDifferences(entry, request) {
272
286
  differences.push(`files [${recorded.join(", ")}] vs [${requested.join(", ")}]`);
273
287
  }
274
288
  }
289
+ // Dependencies are part of what the work is, so a retry that changes them is
290
+ // a different request, not the same one resubmitted.
291
+ if (request.dependsOn !== undefined) {
292
+ const recorded = [...normalizeDependsOn(entry.dependsOn)].sort();
293
+ const requested = [...normalizeDependsOn(request.dependsOn)].sort();
294
+ const same = recorded.length === requested.length && recorded.every((id, i) => id === requested[i]);
295
+ if (!same) {
296
+ differences.push(`dependsOn [${recorded.join(", ")}] vs [${requested.join(", ")}]`);
297
+ }
298
+ }
275
299
  return differences;
276
300
  }
277
301
  /**
@@ -330,6 +354,162 @@ export function recordAdmissionRefusal(workerId, requestId, cwd) {
330
354
  writeWorkers(located.registry, located.key);
331
355
  return true;
332
356
  }
357
+ // ── Queue facts: priority and dependencies ─────────────────────────────────
358
+ // The registry owns the ids, so it owns what a wait means. A dependency is
359
+ // satisfied by `merged` or `completed` and by nothing else: a worker that
360
+ // failed, stalled or was closed without delivering did not produce the thing
361
+ // the next one waits for. Edges are decided at admission, where an unknown id,
362
+ // a self-edge or a loop is refused before anything is written; satisfaction is
363
+ // read at every check, because the answer changes as the rows it names move.
364
+ /** Priority values the registry accepts: finite numbers, or null for unranked. */
365
+ export function normalizePriority(raw) {
366
+ if (raw === undefined || raw === null)
367
+ return null;
368
+ if (typeof raw !== "number" || !Number.isFinite(raw)) {
369
+ throw new Error(`priority must be a finite number or null, got ${JSON.stringify(raw)}`);
370
+ }
371
+ return raw;
372
+ }
373
+ /**
374
+ * Dependency ids as the registry stores them: strings, trimmed, non-empty,
375
+ * first occurrence kept. A malformed or absent value waits for nothing.
376
+ */
377
+ export function normalizeDependsOn(raw) {
378
+ if (!Array.isArray(raw))
379
+ return [];
380
+ const ids = [];
381
+ for (const value of raw) {
382
+ if (typeof value !== "string")
383
+ continue;
384
+ const id = value.trim();
385
+ if (id.length === 0 || ids.includes(id))
386
+ continue;
387
+ ids.push(id);
388
+ }
389
+ return ids;
390
+ }
391
+ /** Statuses that satisfy a dependency edge; a failed worker delivered nothing. */
392
+ export const WORKER_SATISFYING_STATUSES = ["merged", "completed"];
393
+ /** Look a row up by id, without reading the prototype chain as a registry row. */
394
+ function knownWorker(registry, workerId) {
395
+ return Object.prototype.hasOwnProperty.call(registry.workers, workerId)
396
+ ? registry.workers[workerId]
397
+ : undefined;
398
+ }
399
+ /** True when the row that id names delivered the work a dependent waits for. */
400
+ export function isDependencySatisfied(entry) {
401
+ return entry !== undefined && WORKER_SATISFYING_STATUSES.includes(entry.status);
402
+ }
403
+ /**
404
+ * The dependency ids of one row that nothing has satisfied yet, in declared
405
+ * order. An id with no row at all is unsatisfied: admission refuses unknown ids,
406
+ * so a missing one means the row was hand-edited or removed, and neither is a
407
+ * delivery.
408
+ */
409
+ export function unsatisfiedDependencies(entry, registry) {
410
+ return normalizeDependsOn(entry.dependsOn).filter((id) => !isDependencySatisfied(knownWorker(registry, id)));
411
+ }
412
+ /**
413
+ * The loop an admission would close, as ids from the new row back to itself,
414
+ * or null when it closes none. Walks the graph as it would stand after the
415
+ * write: the admitted row contributes only its declared edges (a rolled-over
416
+ * row's old ones die with it), every other row its recorded ones.
417
+ */
418
+ function dependencyCyclePath(workerId, dependsOn, registry) {
419
+ const edgesOf = (id) => id === workerId
420
+ ? [...dependsOn]
421
+ : normalizeDependsOn(knownWorker(registry, id)?.dependsOn ?? []);
422
+ const seen = new Set([workerId]);
423
+ const walk = (from, path) => {
424
+ for (const next of edgesOf(from)) {
425
+ if (next === workerId)
426
+ return [...path, workerId];
427
+ if (seen.has(next))
428
+ continue;
429
+ seen.add(next);
430
+ const found = walk(next, [...path, next]);
431
+ if (found)
432
+ return found;
433
+ }
434
+ return null;
435
+ };
436
+ return walk(workerId, [workerId]);
437
+ }
438
+ /**
439
+ * Decide whether `dependsOn` may be recorded for `workerId`, against the graph
440
+ * the registry holds now. Null means the edges stand. A refused edge writes
441
+ * nothing: the caller reports the reason and the id, and the row is untouched.
442
+ *
443
+ * A row naming itself is refused as a self-dependency before the unknown check,
444
+ * which would otherwise answer `unknown-dependency` for an id that is by
445
+ * construction not admitted yet and hide the actual defect.
446
+ */
447
+ export function validateDependencies(workerId, dependsOn, registry) {
448
+ const ids = normalizeDependsOn(dependsOn);
449
+ if (ids.includes(workerId)) {
450
+ return {
451
+ reason: "self-dependency",
452
+ id: workerId,
453
+ path: [workerId, workerId],
454
+ message: `self-dependency: worker ${workerId} names itself in dependsOn; a worker ` +
455
+ `cannot wait for its own result`,
456
+ };
457
+ }
458
+ for (const id of ids) {
459
+ if (!knownWorker(registry, id)) {
460
+ return {
461
+ reason: "unknown-dependency",
462
+ id,
463
+ path: [],
464
+ message: `unknown-dependency: worker ${workerId} depends on ${id}, which is not in the ` +
465
+ `registry and never was`,
466
+ };
467
+ }
468
+ }
469
+ const path = dependencyCyclePath(workerId, ids, registry);
470
+ if (path) {
471
+ return {
472
+ reason: "dependency-cycle",
473
+ id: path[1] ?? workerId,
474
+ path,
475
+ message: `dependency-cycle: worker ${workerId}'s dependsOn would close a loop: ` +
476
+ `${path.join(" -> ")}`,
477
+ };
478
+ }
479
+ return null;
480
+ }
481
+ /**
482
+ * Split listing rows into the order they may be acted on: rows whose
483
+ * dependencies are all satisfied first, then blocked rows, each group ranked by
484
+ * priority ascending with unranked rows after every ranked one, ties by
485
+ * admission time and then id so the order is total.
486
+ *
487
+ * Satisfaction is read against the whole registry rather than the rows being
488
+ * printed: a closed row still satisfies its dependents, so it must be read
489
+ * before a listing that hides closed rows is filtered.
490
+ */
491
+ export function orderWorkerRows(entries, registry) {
492
+ const rows = entries.map((entry) => ({
493
+ entry,
494
+ blockedBy: unsatisfiedDependencies(entry, registry),
495
+ }));
496
+ rows.sort(compareOrderRows);
497
+ return {
498
+ ready: rows.filter((row) => row.blockedBy.length === 0),
499
+ blocked: rows.filter((row) => row.blockedBy.length > 0),
500
+ };
501
+ }
502
+ /** Actionable order inside one group; both priorities null falls through to time. */
503
+ function compareOrderRows(a, b) {
504
+ const pa = a.entry.priority ?? Number.POSITIVE_INFINITY;
505
+ const pb = b.entry.priority ?? Number.POSITIVE_INFINITY;
506
+ if (pa !== pb)
507
+ return pa - pb;
508
+ const bySpawn = a.entry.spawnedAt.localeCompare(b.entry.spawnedAt);
509
+ if (bySpawn !== 0)
510
+ return bySpawn;
511
+ return a.entry.workerId.localeCompare(b.entry.workerId);
512
+ }
333
513
  // ── CRUD ───────────────────────────────────────────────────────────────────
334
514
  /**
335
515
  * Admit a worker. Refuses when a live (not closed) entry exists for the
@@ -346,7 +526,13 @@ export function registerWorker(input, cwd) {
346
526
  const registry = readWorkers(key);
347
527
  const existing = registry.workers[input.workerId];
348
528
  const requestId = resolveRequestId(input.workerId, input.requestId);
349
- const decision = decideAdmission(existing, requestId, { spec: input.spec, files: input.files });
529
+ const priority = normalizePriority(input.priority);
530
+ const dependsOn = normalizeDependsOn(input.dependsOn);
531
+ const decision = decideAdmission(existing, requestId, {
532
+ spec: input.spec,
533
+ files: input.files,
534
+ dependsOn,
535
+ });
350
536
  if (decision.action === "reuse") {
351
537
  return { ok: true, entry: decision.entry, reused: true };
352
538
  }
@@ -359,6 +545,18 @@ export function registerWorker(input, cwd) {
359
545
  }
360
546
  return { ok: false, reason: decision.reason, entry: decision.entry };
361
547
  }
548
+ // A dependency that cannot be satisfied refuses the admission before any
549
+ // write: the row, the branch and the locks the caller made for it stand as
550
+ // they were, and the reason names what is wrong with the edge.
551
+ const dependencyRefusal = validateDependencies(input.workerId, dependsOn, registry);
552
+ if (dependencyRefusal) {
553
+ return {
554
+ ok: false,
555
+ reason: dependencyRefusal.message,
556
+ refusedBy: dependencyRefusal.reason,
557
+ offendingId: dependencyRefusal.id,
558
+ };
559
+ }
362
560
  const nowIso = new Date().toISOString();
363
561
  const entry = {
364
562
  workerId: input.workerId,
@@ -371,6 +569,8 @@ export function registerWorker(input, cwd) {
371
569
  outputFile: input.outputFile ?? null,
372
570
  branch: input.branch ?? null,
373
571
  files: input.files ?? [],
572
+ priority,
573
+ dependsOn,
374
574
  spawnedAt: nowIso,
375
575
  lastSeenAt: nowIso,
376
576
  resultAt: null,
@@ -416,6 +616,8 @@ export function updateWorker(workerId, patch, cwd) {
416
616
  entry.files = patch.files;
417
617
  if (patch.status !== undefined)
418
618
  entry.status = parseWorkerStatus(patch.status);
619
+ if (patch.priority !== undefined)
620
+ entry.priority = normalizePriority(patch.priority);
419
621
  if (patch.checkpoint !== undefined)
420
622
  entry.checkpoint = stampCheckpoint(patch.checkpoint);
421
623
  entry.lastSeenAt = new Date().toISOString();
@@ -1253,6 +1455,18 @@ function normalizeLiveStatus(raw) {
1253
1455
  }
1254
1456
  return null;
1255
1457
  }
1458
+ /**
1459
+ * Say what is holding a row, per blocking id: the status of the row it waits
1460
+ * for, or that no row carries the id at all.
1461
+ */
1462
+ function describeBlockers(ids, registry) {
1463
+ return ids
1464
+ .map((id) => {
1465
+ const dependency = registry ? knownWorker(registry, id) : undefined;
1466
+ return dependency ? `${id} (status ${dependency.status})` : `${id} (no row)`;
1467
+ })
1468
+ .join(", ");
1469
+ }
1256
1470
  /**
1257
1471
  * Compute the verdict for a worker entry. `completed` requires the output
1258
1472
  * file to exist and the result schema to parse (impl spec also requires at
@@ -1284,6 +1498,12 @@ function normalizeLiveStatus(raw) {
1284
1498
  * recorded gate exited 0. None of the three is the no-effect-evidence flag;
1285
1499
  * the flag is a field on the verdict, never a different status, and a row
1286
1500
  * that is not a terminal completion carries null.
1501
+ *
1502
+ * A row whose `dependsOn` holds an id that is not `merged` or `completed`
1503
+ * reads as `blocked`, naming each blocking id with the status it carries; the
1504
+ * row's own stored status travels beside the verdict, so a blocked row and a
1505
+ * ready one are never the same answer. The dependencies are read against the
1506
+ * registry the row belongs to, which checkWorker supplies.
1287
1507
  */
1288
1508
  export function evaluateWorker(entry, opts = {}) {
1289
1509
  const now = opts.now ?? Date.now();
@@ -1305,6 +1525,9 @@ export function evaluateWorker(entry, opts = {}) {
1305
1525
  branchAhead,
1306
1526
  })
1307
1527
  : null;
1528
+ // Dependencies are read off the registry the row belongs to; without it the
1529
+ // answer is not knowable here, so no row is called blocked on a guess.
1530
+ const blockedBy = opts.registry ? unsatisfiedDependencies(entry, opts.registry) : [];
1308
1531
  // The stall window is read once: a session written inside it is liveness a
1309
1532
  // checkpoint must not outrank, and it is the only case where a checkpoint
1310
1533
  // changes the verdict.
@@ -1313,6 +1536,8 @@ export function evaluateWorker(entry, opts = {}) {
1313
1536
  const checkpoint = entry.checkpoint ?? null;
1314
1537
  const base = {
1315
1538
  workerId: entry.workerId,
1539
+ storedStatus: entry.status,
1540
+ blockedBy,
1316
1541
  outputFile: entry.outputFile,
1317
1542
  outputExists,
1318
1543
  outputAgeSec,
@@ -1341,6 +1566,18 @@ export function evaluateWorker(entry, opts = {}) {
1341
1566
  reason: `closed ${entry.closedAt} with outcome ${entry.status}`,
1342
1567
  };
1343
1568
  }
1569
+ // A row waiting on a dependency nothing delivered is not actionable, whatever
1570
+ // it has recorded itself: the verdict says so and names the ids, and the row's
1571
+ // own status is reported beside it rather than overwritten. A closed row is
1572
+ // exempt above — its outcome is already decided, and its dependents read that.
1573
+ if (blockedBy.length > 0) {
1574
+ return {
1575
+ ...base,
1576
+ status: "blocked",
1577
+ reason: `waits on ${describeBlockers(blockedBy, opts.registry)}; ` +
1578
+ `stored status ${entry.status}`,
1579
+ };
1580
+ }
1344
1581
  if (entry.status === "error") {
1345
1582
  return { ...base, status: "error", reason: "registry marked error" };
1346
1583
  }
@@ -1470,7 +1707,12 @@ export function checkWorker(workerId, opts = {}) {
1470
1707
  if (!located)
1471
1708
  return null;
1472
1709
  const fallbackBranch = opts.fallbackBranch ?? lockBranchFor(workerId, located.key);
1473
- return evaluateWorker(located.registry.workers[workerId], { ...opts, fallbackBranch });
1710
+ // The located registry is the one this entry's dependencies are read against.
1711
+ return evaluateWorker(located.registry.workers[workerId], {
1712
+ ...opts,
1713
+ fallbackBranch,
1714
+ registry: located.registry,
1715
+ });
1474
1716
  }
1475
1717
  /** Median of a non-empty list; the mean of the middle pair on an even count. */
1476
1718
  function median(values) {
package/docs/LOCAL_DEV.md CHANGED
@@ -138,7 +138,7 @@ before and after a full run. A non-zero delta is the leak this rule prevents.
138
138
  ### New fixtures: use `node:test`
139
139
 
140
140
  A new fixture is written on `node:test`. The runner does not care which style a
141
- file uses - 107 of the core suite's 342 fixtures already use `node:test` - so the
141
+ file uses - 109 of the core suite's 343 fixtures already use `node:test` - so the
142
142
  reason is the failure the other style produces. A hand-rolled helper that calls
143
143
  `fn()` without awaiting it discards the case's promise, so an `async` case runs
144
144
  detached and the file can print its green tally before that case settles, with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.43.27",
3
+ "version": "0.43.29",
4
4
  "description": "🥨 Braid - Metacognitive extension suite for pi coding agent: Adds memory, plan tracking, structured cognitive signals and completion checks on top of pi core loop, so long sessions keep their context and stop claiming unfinished work.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -22,20 +22,20 @@ in a pipeline." It's the broadest use of the term in the codebase.
22
22
  These are the entry points for enforcement. They register with pi core
23
23
  and delegate to the actual enforcement logic.
24
24
 
25
- | File | Event |
26
- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
27
- | `register-session-start.ts` | `session_start` |
28
- | `register-session-start-discoverability.ts` | `session_start` (Background phase, via `registerSessionStartHandler`) - surfaces disk-backed prior state (scratchpad, memory, sessions, resume file, tags) before the first turn. Per-signal dedup with per-project disk persistence. |
29
- | `register-session-compact.ts` | `session_compact` |
30
- | `register-session-shutdown.ts` | `session_shutdown` |
31
- | `register-session-shutdown-resumption.ts` | (read by discoverability handler) - resume file creation on shutdown. |
32
- | `register-input-handler.ts` | `input` |
33
- | `register-message-end.ts` | `message_end` |
34
- | `register-tool-call.ts` | `tool_call` |
35
- | `register-tool-result.ts` | `tool_execution_end` |
36
- | `register-agent-end-api-error.ts` | `agent_end` (classifies a terminal assistant API error into guidance) |
37
- | `register-post-cycle-hygiene.ts` | `turn_end` (priority 1 - auto-tag + inspect + advise on text-only yield after work) |
38
- | `register-adherence-meter.ts` | `session_start` (Background - counts `enforcement_violation` events per session), `turn_end` (priority 40 - escalates a rule repeating past K to the owner, bounded), `session_shutdown` (writes the owner report). Owner-facing only: never sends a tracked message and never registers a tool. |
25
+ | File | Event |
26
+ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
27
+ | `register-session-start.ts` | `session_start` |
28
+ | `register-session-start-discoverability.ts` | `session_start` (Background phase, via `registerSessionStartHandler`) - surfaces disk-backed prior state (scratchpad, memory, sessions, resume file, tags, journal) before the first turn. Per-signal dedup with per-project disk persistence; the journal pointer is exempt and carries what is open. |
29
+ | `register-session-compact.ts` | `session_compact` |
30
+ | `register-session-shutdown.ts` | `session_shutdown` |
31
+ | `register-session-shutdown-resumption.ts` | (read by discoverability handler) - resume file creation on shutdown. |
32
+ | `register-input-handler.ts` | `input` |
33
+ | `register-message-end.ts` | `message_end` |
34
+ | `register-tool-call.ts` | `tool_call` |
35
+ | `register-tool-result.ts` | `tool_execution_end` |
36
+ | `register-agent-end-api-error.ts` | `agent_end` (classifies a terminal assistant API error into guidance) |
37
+ | `register-post-cycle-hygiene.ts` | `turn_end` (priority 1 - auto-tag + inspect + advise on text-only yield after work) |
38
+ | `register-adherence-meter.ts` | `session_start` (Background - counts `enforcement_violation` events per session), `turn_end` (priority 40 - escalates a rule repeating past K to the owner, bounded), `session_shutdown` (writes the owner report). Owner-facing only: never sends a tracked message and never registers a tool. |
39
39
 
40
40
  ### Orchestrators (not `register-*`, but invoked at turn end)
41
41
 
@@ -48,12 +48,13 @@ and delegate to the actual enforcement logic.
48
48
 
49
49
  ### Other utilities
50
50
 
51
- | File | Purpose |
52
- | ------------------ | -------------------------------------- |
53
- | `tool-tracker.ts` | Per-tool-call tracking. 137L. |
54
- | `orphan-chains.ts` | Detects orphan tool call chains. 59L. |
55
- | `blocking.ts` | Tool call blocking logic. 79L. |
56
- | `probe-handler.ts` | Lightweight probe for LLM calls. 158L. |
51
+ | File | Purpose |
52
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------- |
53
+ | `tool-tracker.ts` | Per-tool-call tracking. 137L. |
54
+ | `orphan-chains.ts` | Detects orphan tool call chains. 59L. |
55
+ | `blocking.ts` | Tool call blocking logic. 79L. |
56
+ | `probe-handler.ts` | Lightweight probe for LLM calls. 158L. |
57
+ | `open-intents.ts` | Composes the session-start journal pointer and names the intents whose status is open, under a fixed ceiling. 215L. |
57
58
 
58
59
  ### Analysis pipeline
59
60