pi-braid 0.43.27 → 0.43.28

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
  *
@@ -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 - 108 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.28",
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",
@@ -63,6 +63,14 @@ import {
63
63
  type WorkerStats,
64
64
  type PopulationRead,
65
65
  } from "../../lib/orchestrator/index.js";
66
+ // The queue-fact readers come from their module directly: the barrel above is
67
+ // one way into the library, not the only one, and it does not re-export these.
68
+ import {
69
+ normalizeDependsOn,
70
+ orderWorkerRows,
71
+ validateDependencies,
72
+ type WorkerOrderRow,
73
+ } from "../../lib/orchestrator/workers.js";
66
74
 
67
75
  const log = createLogger("orchestrator");
68
76
 
@@ -454,11 +462,28 @@ function textResult(text: string, details: Record<string, unknown> = {}) {
454
462
  /** One-line registry listing for a worker entry. */
455
463
  function workerLine(entry: WorkerEntry): string {
456
464
  const closed = entry.closedAt ? ` closed=${entry.closedAt}` : "";
465
+ // Printed only when the row carries one: an unranked, wait-free row keeps the
466
+ // line it had before the queue facts existed.
467
+ const priority = typeof entry.priority === "number" ? ` priority=${entry.priority}` : "";
468
+ const dependsOn =
469
+ Array.isArray(entry.dependsOn) && entry.dependsOn.length > 0
470
+ ? ` depends-on=${entry.dependsOn.join(", ")}`
471
+ : "";
457
472
  return ` ${entry.workerId} spec=${entry.spec} status=${entry.status} pane=${
458
473
  entry.pane ?? "-"
459
474
  } session=${entry.workerSession ?? "-"} output=${
460
475
  entry.outputFile ?? "-"
461
- } branch=${entry.branch ?? "-"}${closed}`;
476
+ } branch=${entry.branch ?? "-"}${closed}${priority}${dependsOn}`;
477
+ }
478
+
479
+ /**
480
+ * One listing entry: the row line, plus the ids holding it after it, indented
481
+ * under the row so the marker can never be read as a row of its own.
482
+ */
483
+ function workerListLine(row: WorkerOrderRow): string {
484
+ const line = workerLine(row.entry);
485
+ if (row.blockedBy.length === 0) return line;
486
+ return `${line}\n blocked-by: ${row.blockedBy.join(", ")}`;
462
487
  }
463
488
 
464
489
  /**
@@ -488,6 +513,8 @@ function formatCheckVerdict(verdict: WorkerCheckResult): string {
488
513
  return [
489
514
  `Worker ${verdict.workerId}`,
490
515
  `status: ${verdict.status}`,
516
+ `storedStatus: ${verdict.storedStatus}`,
517
+ `blockedBy: ${verdict.blockedBy.length > 0 ? verdict.blockedBy.join(", ") : "-"}`,
491
518
  `reason: ${verdict.reason}`,
492
519
  `outputFile: ${verdict.outputFile ?? "-"} (${age})`,
493
520
  `sessionGrowthAgeSec: ${verdict.sessionGrowthAgeSec ?? "-"}`,
@@ -648,6 +675,25 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
648
675
  description: "Lifecycle status for update-worker (see the tool description).",
649
676
  }),
650
677
  ),
678
+ priority: Type.Optional(
679
+ // `{ anyOf: [{ type: "number" }, { type: "null" }] }` written as its own
680
+ // keywords: the builder's named constructors have no null literal, and the
681
+ // schema this hand-built object emits is plain JSON Schema.
682
+ Type.Unsafe<number | null>({
683
+ anyOf: [{ type: "number" }, { type: "null" }],
684
+ description:
685
+ "Queue rank: lower runs sooner; null is unranked, which sorts after every ranked row. " +
686
+ "spawn-worker/register-worker record it at admission; update-worker changes or clears it.",
687
+ }),
688
+ ),
689
+ dependsOn: Type.Optional(
690
+ Type.Array(Type.String(), {
691
+ description:
692
+ "Worker ids this row waits for (spawn-worker/register-worker only: dependencies are fixed at admission). " +
693
+ "Refused when an id is unknown, is this worker's own id, or would close a loop; a refused admission writes nothing. " +
694
+ "check-worker reports `blocked`, naming these ids, while any of them is not merged or completed.",
695
+ }),
696
+ ),
651
697
  phase: Type.Optional(
652
698
  Type.String({
653
699
  description:
@@ -729,6 +775,8 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
729
775
  workspace?: string;
730
776
  workerSession?: string;
731
777
  status?: string;
778
+ priority?: number | null;
779
+ dependsOn?: string[];
732
780
  phase?: string;
733
781
  lastStep?: string;
734
782
  requestId?: string;
@@ -756,6 +804,8 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
756
804
  workspace,
757
805
  workerSession,
758
806
  status,
807
+ priority,
808
+ dependsOn,
759
809
  phase,
760
810
  lastStep,
761
811
  requestId,
@@ -790,8 +840,16 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
790
840
  // live row for one worker. A different request, or the same id
791
841
  // describing different work, is refused with both ids named.
792
842
  const effectiveRequestId = resolveRequestId(workerId, requestId);
793
- const existing = readWorkers(projectCwd).workers[workerId];
794
- const decision = decideAdmission(existing, effectiveRequestId, { spec, files });
843
+ const registryAtSpawn = readWorkers(projectCwd);
844
+ const existing = registryAtSpawn.workers[workerId];
845
+ // Dependencies are part of what the work is, so a retry carries the same
846
+ // set; changing them under the same request id is different work.
847
+ const dependsOnIds = normalizeDependsOn(dependsOn);
848
+ const decision = decideAdmission(existing, effectiveRequestId, {
849
+ spec,
850
+ files,
851
+ dependsOn: dependsOnIds,
852
+ });
795
853
  if (decision.action === "reuse" && decision.entry) {
796
854
  return textResult(reuseReport(decision.entry, effectiveRequestId), {
797
855
  entry: decision.entry,
@@ -806,6 +864,13 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
806
864
  throw new Error(`spawn-worker: ${decision.reason}.`);
807
865
  }
808
866
 
867
+ // A dependency that cannot be satisfied refuses the spawn before a
868
+ // branch or a lock exists, so a refused spawn leaves nothing to undo.
869
+ const dependencyRefusal = validateDependencies(workerId, dependsOnIds, registryAtSpawn);
870
+ if (dependencyRefusal) {
871
+ throw new Error(`spawn-worker: ${dependencyRefusal.message}.`);
872
+ }
873
+
809
874
  const conflicts = filesHeldByOthers(files, workerId, repoRoot);
810
875
  if (conflicts.length > 0) {
811
876
  return textResult(
@@ -834,6 +899,8 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
834
899
  files,
835
900
  branch: branchName,
836
901
  outputFile,
902
+ priority,
903
+ dependsOn: dependsOnIds,
837
904
  requestId: effectiveRequestId,
838
905
  },
839
906
  projectCwd,
@@ -913,6 +980,8 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
913
980
  files,
914
981
  branch,
915
982
  outputFile,
983
+ priority,
984
+ dependsOn,
916
985
  pane,
917
986
  workerSession,
918
987
  requestId,
@@ -945,6 +1014,8 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
945
1014
  files,
946
1015
  branch,
947
1016
  outputFile,
1017
+ priority,
1018
+ dependsOn,
948
1019
  pane,
949
1020
  workerSession,
950
1021
  requestId,
@@ -959,6 +1030,14 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
959
1030
  if (!workerId) {
960
1031
  throw new Error("update-worker requires workerId");
961
1032
  }
1033
+ if (dependsOn !== undefined) {
1034
+ throw new Error(
1035
+ "update-worker: dependencies are fixed at admission — dependsOn is admitted by " +
1036
+ "spawn-worker/register-worker only. A worker that gains a dependency after it " +
1037
+ "started is a second unit of work wearing the first one's id; close the entry and " +
1038
+ "admit it again.",
1039
+ );
1040
+ }
962
1041
 
963
1042
  const patch: UpdateWorkerPatch = {};
964
1043
  if (pane !== undefined) patch.pane = pane;
@@ -968,6 +1047,7 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
968
1047
  if (branch !== undefined) patch.branch = branch;
969
1048
  if (files !== undefined) patch.files = files;
970
1049
  if (status !== undefined) patch.status = parseWorkerStatus(status);
1050
+ if (priority !== undefined) patch.priority = priority;
971
1051
  if (phase !== undefined || lastStep !== undefined) {
972
1052
  if (!phase || !lastStep) {
973
1053
  throw new Error(
@@ -1031,7 +1111,10 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
1031
1111
  const closedCount = all.filter((entry) => entry.closedAt).length;
1032
1112
  const byStatus = WORKER_STATUSES.map((s) => `${s}=${counts.get(s) ?? 0}`).join(" ");
1033
1113
 
1034
- const lines = shown.map(workerLine).join("\n");
1114
+ // Actionable order over the rows being shown, with satisfaction read
1115
+ // against every row: a closed dependency still counts as delivered.
1116
+ const ordered = orderWorkerRows(shown, registry);
1117
+ const lines = [...ordered.ready, ...ordered.blocked].map(workerListLine).join("\n");
1035
1118
  return textResult(
1036
1119
  `Workers (${repoRoot ?? process.cwd()}):\n${lines}\ncounts: total=${all.length} live=${
1037
1120
  all.length - closedCount