@ngockhoale/ukit 3.4.73 → 3.4.75

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.
Files changed (28) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/manifests/documentation.yaml +10 -0
  3. package/manifests/platform.full.yaml +15 -0
  4. package/package.json +4 -1
  5. package/template_project/.claude/commands/ukit/handoff-fullstack.md +34 -12
  6. package/template_project/.claude/hooks/completion-gate.sh +10 -1
  7. package/template_project/.claude/hooks/handoff-resume.sh +38 -53
  8. package/template_project/.claude/hooks/owner-stop-gate.mjs +41 -0
  9. package/template_project/.claude/hooks/skill-router.sh +473 -36
  10. package/template_project/.claude/hooks/verification-guard.sh +8 -1
  11. package/template_project/.claude/settings.json +33 -1
  12. package/template_project/.claude/ukit/index/publication-intent.mjs +128 -13
  13. package/template_project/.claude/ukit/index/route-task.mjs +124 -26
  14. package/template_project/.claude/ukit/runtime/block-breaker.mjs +1 -0
  15. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +8 -1
  16. package/template_project/.claude/ukit/runtime/cron-operation-adapter.mjs +14 -5
  17. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +399 -35
  18. package/template_project/.claude/ukit/runtime/handoff-intent.mjs +5 -0
  19. package/template_project/.claude/ukit/runtime/handoff-provenance.mjs +277 -0
  20. package/template_project/.claude/ukit/runtime/loop-state.mjs +23 -4
  21. package/template_project/.claude/ukit/runtime/operation-evidence.mjs +9 -0
  22. package/template_project/.claude/ukit/runtime/reinject-context.mjs +10 -0
  23. package/template_project/.claude/ukit/runtime/resumable-run.mjs +33 -11
  24. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +284 -58
  25. package/template_project/.omp/hooks/pre/ukit-bridge.js +171 -3
  26. package/scripts/dev/worktree-preflight.mjs +0 -166
  27. package/scripts/measure-decision-gateway.mjs +0 -306
  28. package/scripts/probe/codex-capability-probe.mjs +0 -169
@@ -562,6 +562,40 @@ function serializeVerificationRecipe(recipe, artifactClass) {
562
562
  };
563
563
  }
564
564
 
565
+
566
+ // Advisory writers (verification recipe stamp, review-policy counters) used to rewrite the
567
+ // whole shared route state from a snapshot read earlier — restoring a stale task over a newer
568
+ // publication, or erasing the pending/revision markers. They now re-read under the session
569
+ // sidecar lock (the lock every route writer takes) and apply the mutation only when the
570
+ // shared slot is still the committed publication the snapshot was derived from. Anything
571
+ // else (pending/mismatched/foreign/replaced) skips: advisory data is never worth state.
572
+ async function updateCommittedRouteState(projectRoot, snapshot, mutate) {
573
+ const statePath = path.join(projectRoot, '.claude', 'ukit', 'skill-router-state.json');
574
+ const sessionId = typeof snapshot?.sessionId === 'string' ? snapshot.sessionId.trim() : '';
575
+ const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96);
576
+ const sidecar = sessionId ? path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${safe || 'default'}.json`) : null;
577
+ const apply = async () => {
578
+ let current;
579
+ try { current = JSON.parse(await fs.readFile(statePath, 'utf8')); } catch { return false; }
580
+ if (!current || typeof current !== 'object' || current.routePublicationIncomplete) return false;
581
+ if ((current.sessionId ?? null) !== (snapshot.sessionId ?? null)
582
+ || (current.taskInstanceId ?? null) !== (snapshot.taskInstanceId ?? null)
583
+ || (current.routePersistenceRevision ?? null) !== (snapshot.routePersistenceRevision ?? null)) return false;
584
+ if (current.routePersistenceRevision) {
585
+ let committed;
586
+ try { committed = JSON.parse(await fs.readFile(sidecar, 'utf8')); } catch { return false; }
587
+ if (committed?.routePublicationIncomplete || committed?.routePersistenceRevision !== current.routePersistenceRevision) return false;
588
+ }
589
+ if (!current.routeSummary || typeof current.routeSummary !== 'object') return false;
590
+ if (mutate(current.routeSummary) === false) return false;
591
+ await writeJsonAtomicLocal(statePath, current);
592
+ return true;
593
+ };
594
+ if (!sidecar) return apply();
595
+ const locked = await withAsyncLock(sidecar, { deadlineMs: 2000 }, apply);
596
+ return locked.ok ? locked.value : false;
597
+ }
598
+
565
599
  async function stampVerificationRecipe({ projectRoot }) {
566
600
  const mapModule = await loadVerificationMapModule();
567
601
  if (!mapModule) return; // reader absent (partial install): pre-map behavior
@@ -591,10 +625,11 @@ async function stampVerificationRecipe({ projectRoot }) {
591
625
  const before = JSON.stringify(routeSummary.verificationRecipe ?? null);
592
626
  const after = JSON.stringify(serialized);
593
627
  if (before === after) return; // no stamp change → no rewrite
594
- routeSummary.verificationRecipe = serialized;
595
- if (artifactClass) routeSummary.artifactClass = artifactClass;
596
- else delete routeSummary.artifactClass;
597
- await writeJsonAtomicLocal(statePath, state);
628
+ await updateCommittedRouteState(projectRoot, state, (summary) => {
629
+ summary.verificationRecipe = serialized;
630
+ if (artifactClass) summary.artifactClass = artifactClass;
631
+ else delete summary.artifactClass;
632
+ });
598
633
  }
599
634
 
600
635
  // ─── Review-policy advisory lane (C85 TASK-015, BL-015) ────────────────────
@@ -743,14 +778,17 @@ export async function evaluateStopReviewPolicy({ projectRoot, completionKind = n
743
778
  // Persist the round counter + last verdict for the next stop (same atomic
744
779
  // write as the recipe stamp). A stale verdict is honest — it is the last
745
780
  // recorded policy decision, keyed by its action.
746
- routeSummary.reviewRounds = Number.isFinite(decision.reviewRounds) ? decision.reviewRounds : round;
747
- routeSummary.lastReviewPolicy = {
781
+ const reviewRounds = Number.isFinite(decision.reviewRounds) ? decision.reviewRounds : round;
782
+ const lastReviewPolicy = {
748
783
  action: decision.action,
749
784
  namedCheck: decision.namedCheck ?? null,
750
785
  signalsHit: Array.isArray(decision.signalsHit) ? decision.signalsHit : [],
751
786
  at: new Date().toISOString(),
752
787
  };
753
- await writeJsonAtomicLocal(statePath, state);
788
+ await updateCommittedRouteState(projectRoot, state, (summary) => {
789
+ summary.reviewRounds = reviewRounds;
790
+ summary.lastReviewPolicy = lastReviewPolicy;
791
+ });
754
792
 
755
793
  // Round 5: persist the decision on the ledger (delegated runs only) and fold the final
756
794
  // acceptance + dispatch hint + telemetry summary onto the returned decision. Advisory:
@@ -936,9 +974,9 @@ async function evalIndexAllDone(projectRoot, { goalScope = '', scopeQueue = '',
936
974
  }
937
975
  const failing = [];
938
976
  const liveIds = new Set(scoped.map((r) => goalTaskId(r.id)));
939
- const liveCls = new Map(scoped.filter((r) => indexTaskRowIsWellFormed(r.raw)).map((r) => {
977
+ const liveCls = buildSupersessionGraph(scoped.filter((r) => indexTaskRowIsWellFormed(r.raw)).map((r) => {
940
978
  const c = indexTaskCells(r.raw);
941
- return [goalTaskId(c[0]), classifyTaskStatus((c[4] || '').toLowerCase(), c[0], liveIds)];
979
+ return { id: c[0], cls: classifyTaskStatus((c[4] || '').toLowerCase(), c[0], liveIds), successors: declaredSuccessors(c[7]) };
942
980
  }));
943
981
  for (const scopedRow of scoped) {
944
982
  const row = scopedRow.raw;
@@ -966,13 +1004,23 @@ async function evalIndexAllDone(projectRoot, { goalScope = '', scopeQueue = '',
966
1004
  // another column.
967
1005
  function parseIndexStatuses(text) {
968
1006
  const map = new Map();
1007
+ const entries = [];
969
1008
  for (const line of String(text).split('\n')) {
970
1009
  const row = line.trim();
971
1010
  if (!/^\|\s*TASK-/i.test(row)) continue;
972
1011
  if (!indexTaskRowIsWellFormed(row)) return null;
973
1012
  const cells = indexTaskCells(row);
974
- map.set(String(cells[0]).toUpperCase(), String(cells[4] || '').toLowerCase());
1013
+ const key = String(cells[0]).toUpperCase();
1014
+ const status = String(cells[4] || '').toLowerCase();
1015
+ if (map.has(key) && map.get(key) !== status) {
1016
+ const prev = classifyTaskStatus(map.get(key), key) === 'delivered';
1017
+ map.set(key, prev ? status : map.get(key));
1018
+ } else {
1019
+ map.set(key, status);
1020
+ }
1021
+ entries.push({ id: cells[0], status, successors: declaredSuccessors(cells[7]) });
975
1022
  }
1023
+ Object.defineProperty(map, 'entries', { value: entries, enumerable: false });
976
1024
  return map;
977
1025
  }
978
1026
 
@@ -1071,7 +1119,7 @@ async function evalFinalizedCycles(projectRoot, goalScope, scopeQueue = '', cycl
1071
1119
  }
1072
1120
  const archIds = new Set(snapshot ? [...snapshot.keys()].map(goalTaskId) : []);
1073
1121
  const archCls = classifyTaskStatus(status, id, archIds);
1074
- const archClsByKey = new Map([...(snapshot || new Map()).entries()].map(([k, st]) => [goalTaskId(k), classifyTaskStatus(st, k, archIds)]));
1122
+ const archClsByKey = buildSupersessionGraph((snapshot?.entries || []).map((e) => ({ id: e.id, cls: classifyTaskStatus(e.status, e.id, archIds), successors: e.successors })));
1075
1123
  const archTerminal = archCls === 'delivered' || (archCls === 'cancelled-grounded' && groundedCancellationResolved(id, archClsByKey));
1076
1124
  if (!archTerminal) {
1077
1125
  failing.push(`${file.replace(/\.md$/i, '')}=${status || '?'}${snapshot ? ' (not in the archive INDEX snapshot)' : ' (no INDEX snapshot — run `node .claude/ukit/runtime/resumable-run.mjs archive-cycle <root> <NN>`)'}`);
@@ -1298,22 +1346,54 @@ const REVIEW_OBLIGATION_STATUSES = new Set(['pending_review', 'approved', 'appro
1298
1346
  // (`TASK-xxx-R1`, `-R2`, …), so a successor of any `-R<n>` row is a sibling `<root>-R<m>`
1299
1347
  // row with m > n; suffixes compare numerically (BigInt, like the claim runtime), so R2 does
1300
1348
  // not resolve R10. The root is the id with its trailing `-R<n>` stripped.
1301
- function groundedCancellationResolved(id, clsByKey, seen = new Set()) {
1349
+ function groundedCancellationResolved(id, graph, seen = new Set()) {
1302
1350
  const key = goalTaskId(id);
1303
1351
  if (seen.has(key)) return false;
1352
+ const rows = graph.get(key);
1353
+ if (!rows || rows.length === 0) return false;
1304
1354
  seen.add(key);
1355
+ try {
1356
+ return rows.every((r) => r.cls === 'delivered'
1357
+ || (r.cls === 'cancelled-grounded' && supersessionRowResolved(key, r, graph, seen)));
1358
+ } finally {
1359
+ seen.delete(key);
1360
+ }
1361
+ }
1362
+
1363
+ function supersessionRowResolved(key, row, graph, seen) {
1305
1364
  const root = key.replace(/-r\d+$/, '');
1306
1365
  const ownSuffix = key.match(/-r(\d+)$/);
1307
1366
  const ownNum = ownSuffix ? BigInt(ownSuffix[1]) : 0n;
1308
1367
  const prefix = `${root}-r`;
1309
- for (const [other, cls] of clsByKey) {
1368
+ for (const other of graph.keys()) {
1310
1369
  if (!other.startsWith(prefix) || !/^\d+$/.test(other.slice(prefix.length))) continue;
1311
- const num = BigInt(other.slice(prefix.length));
1312
- if (num <= ownNum) continue;
1313
- if (cls === 'delivered') return true;
1314
- if (cls === 'cancelled-grounded' && groundedCancellationResolved(other, clsByKey, seen)) return true;
1370
+ if (BigInt(other.slice(prefix.length)) <= ownNum) continue;
1371
+ if (groundedCancellationResolved(other, graph, seen)) return true;
1372
+ }
1373
+ const declared = Array.isArray(row.successors) ? row.successors : [];
1374
+ if (declared.length === 0) return false;
1375
+ return declared.every((s) => s !== key && graph.has(s) && groundedCancellationResolved(s, graph, seen));
1376
+ }
1377
+
1378
+ function declaredSuccessors(fileCell) {
1379
+ const cell = String(fileCell ?? '');
1380
+ const m = cell.match(/(?:→|->)\s*(.*)$/s);
1381
+ if (!m) return [];
1382
+ const id = 'TASK-[A-Za-z0-9._-]*[A-Za-z0-9]';
1383
+ const list = m[1].trim().replace(/[.;]+$/, '');
1384
+ if (!new RegExp(`^${id}(?:\\s*,\\s*${id})*$`, 'i').test(list)) return [];
1385
+ return [...new Set(list.split(',').map(goalTaskId))];
1386
+ }
1387
+
1388
+ function buildSupersessionGraph(entries) {
1389
+ const graph = new Map();
1390
+ for (const e of entries) {
1391
+ const key = goalTaskId(e.id);
1392
+ if (!key) continue;
1393
+ if (!graph.has(key)) graph.set(key, []);
1394
+ graph.get(key).push({ cls: e.cls, successors: e.successors || [] });
1315
1395
  }
1316
- return false;
1396
+ return graph;
1317
1397
  }
1318
1398
 
1319
1399
  /** Classify one task. `allIds` = Set of lower-cased ids in the same task set (for successor grounding). */
@@ -1356,7 +1436,7 @@ function goalVerificationVerdict(ledger) {
1356
1436
  *
1357
1437
  * @param {object} [input]
1358
1438
  * @param {{ phase?: string, paused?: boolean } | null} [input.runCursor]
1359
- * @param {Array<{id: string, status: string, dependsOn?: string[]}> | null} [input.tasks]
1439
+ * @param {Array<{id: string, status: string, dependsOn?: string[], successors?: string[]}> | null} [input.tasks]
1360
1440
  * @param {{ verdict?: string, verified?: boolean, verify?: string } | null} [input.ledger]
1361
1441
  * @param {boolean|number} [input.agentsRunning]
1362
1442
  * @param {boolean} [input.snapshotConsistent]
@@ -1377,17 +1457,19 @@ export function deriveGoalStatus({ runCursor = null, tasks = null, ledger = null
1377
1457
  key: goalTaskId(t.id),
1378
1458
  status: String(t.status ?? '').trim().toLowerCase(),
1379
1459
  dependsOn: Array.isArray(t.dependsOn) ? t.dependsOn.map(goalTaskId) : [],
1460
+ successors: Array.isArray(t.successors) ? t.successors.map(goalTaskId).filter(Boolean) : [],
1380
1461
  }))
1381
1462
  : [];
1382
1463
  const allKeys = new Set(list.map((t) => t.key));
1383
1464
  for (const t of list) t.cls = classifyTaskStatus(t.status, t.id, allKeys);
1384
1465
  // A dependency is satisfied by delivery, history, or a grounded cancellation whose successor
1385
1466
  // was delivered; approved/cancelled-without-grounds never satisfy it.
1386
- const deliveredKeys = new Set(list.filter((t) => t.cls === 'delivered').map((t) => t.key));
1387
- const doneIds = new Set(list.filter((t) => t.cls === 'delivered' || t.cls === 'history').map((t) => t.key));
1388
- const clsByKey = new Map(list.map((t) => [t.key, t.cls]));
1389
- for (const t of list) {
1390
- if (t.cls === 'cancelled-grounded' && groundedCancellationResolved(t.key, clsByKey)) doneIds.add(t.key);
1467
+ const clsByKey = buildSupersessionGraph(list.map((t) => ({ id: t.key, cls: t.cls, successors: t.successors })));
1468
+ const doneIds = new Set();
1469
+ for (const key of clsByKey.keys()) {
1470
+ const rowsOfKey = list.filter((t) => t.key === key);
1471
+ if (rowsOfKey.every((t) => t.cls === 'delivered' || t.cls === 'history'
1472
+ || (t.cls === 'cancelled-grounded' && groundedCancellationResolved(key, clsByKey)))) doneIds.add(key);
1391
1473
  }
1392
1474
  // Only a RESOLVED grounded cancellation leaves pending; an orphan one is an open obligation.
1393
1475
  const pending = list.filter((t) => !doneIds.has(t.key));
@@ -1483,7 +1565,7 @@ function indexTasks(indexText) {
1483
1565
  if (!indexTaskRowIsWellFormed(row)) return { id: '', status: 'malformed' };
1484
1566
  const cells = indexTaskCells(row);
1485
1567
  const deps = (cells[3] || '').split(',').map((d) => d.trim()).filter((d) => d && d.toLowerCase() !== 'none');
1486
- return { id: cells[0] || '', status: (cells[4] || '').toLowerCase(), deps };
1568
+ return { id: cells[0] || '', status: (cells[4] || '').toLowerCase(), deps, successors: declaredSuccessors(cells[7]) };
1487
1569
  });
1488
1570
  }
1489
1571
 
@@ -1518,9 +1600,9 @@ function indexTaskSnapshotHash(indexText) {
1518
1600
 
1519
1601
  function firstOpenIndexTaskId(indexText) {
1520
1602
  const allIds = new Set(indexTaskRows(indexText).map((r) => goalTaskId(indexTaskCells(r)[0])));
1521
- const clsByKey = new Map(indexTaskRows(indexText).filter((r) => indexTaskRowIsWellFormed(r)).map((r) => {
1603
+ const clsByKey = buildSupersessionGraph(indexTaskRows(indexText).filter((r) => indexTaskRowIsWellFormed(r)).map((r) => {
1522
1604
  const c = indexTaskCells(r);
1523
- return [goalTaskId(c[0]), classifyTaskStatus((c[4] || '').toLowerCase(), c[0], allIds)];
1605
+ return { id: c[0], cls: classifyTaskStatus((c[4] || '').toLowerCase(), c[0], allIds), successors: declaredSuccessors(c[7]) };
1524
1606
  }));
1525
1607
  for (const row of indexTaskRows(indexText)) {
1526
1608
  const cells = indexTaskCells(row);
@@ -1664,19 +1746,26 @@ async function bumpHandoffStallCount({ projectRoot, signature, lockBudgetMs, sna
1664
1746
  *
1665
1747
  * Advisory lane: EVERY failure path returns { kind: 'none' }, never throws.
1666
1748
  */
1667
- export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot, now = Date.now(), lockBudgetMs = LOCK_BUDGET_MS, transcriptPath = null, stopHookActive = false, completionKind = null } = {}) {
1749
+ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot, now = Date.now(), lockBudgetMs = LOCK_BUDGET_MS, transcriptPath = null, stopHookActive = false, completionKind = null, ownership = null } = {}) {
1668
1750
  // `runRoot` is the checkout whose RUN.md cursor this session may be held to: the
1669
1751
  // git-verified linked worktree when the session runs in one, else `projectRoot`.
1670
1752
  // Policy (gate config) stays with `projectRoot`; the cursor, its exit predicate
1671
1753
  // and its stall state are per-checkout.
1672
1754
  const gate = await loadHandoffGateConfig(projectRoot);
1673
1755
  if (!gate.enabled) return { kind: 'none' };
1674
-
1675
1756
  let text;
1676
1757
  try {
1677
1758
  text = await fs.readFile(path.join(runRoot, 'docs', 'AI_HANDOFF', 'RUN.md'), 'utf8');
1678
- } catch {
1679
- return { kind: 'none' };
1759
+ } catch (error) {
1760
+ if (error.code === 'ENOENT') return { kind: 'none' };
1761
+ return { kind: 'advisory', blockedOutcome: true, systemMessage: '[ukit-stop-coordinator] handoff cursor unreadable; ownership UNKNOWN. Report BLOCKED.' };
1762
+ }
1763
+ // This evaluator can mutate stall state and pause the cursor. Historical
1764
+ // transcript commands do not authorize those mutations.
1765
+ if (ownership?.status !== 'OWNED') {
1766
+ return ownership?.status === 'NOT_OWNED'
1767
+ ? { kind: 'none' }
1768
+ : { kind: 'advisory', blockedOutcome: true, systemMessage: '[ukit-stop-coordinator] handoff ownership UNKNOWN; cursor was not changed. Report BLOCKED and reconcile provenance.' };
1680
1769
  }
1681
1770
  const { command, goal, phase, cursor, next, exitPredicate, goalScope, scopeQueue, cycle: cycleField } = parseRunCursor(text);
1682
1771
  // Shared terminal predicate — tests/handoff/cycle21 greps this exact shape across
@@ -1693,7 +1782,8 @@ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot
1693
1782
  // Session scope: a run owned by another session must not hijack an unrelated session. Decided
1694
1783
  // before pause and before every `done` branch, so a non-owner session never receives the pause
1695
1784
  // advisory. Only a positive "not fullstack" releases; unknown (null) keeps the block.
1696
- const transcriptOwner = gate.scope === 'session' ? await transcriptShowsHandoffRun(transcriptPath) : true;
1785
+ const transcriptOwner = ownership?.status === 'OWNED' ? true
1786
+ : gate.scope === 'session' ? await transcriptShowsHandoffRun(transcriptPath) : true;
1697
1787
  if (gate.scope === 'session' && transcriptOwner === false) {
1698
1788
  return { kind: 'none' };
1699
1789
  }
@@ -1731,35 +1821,58 @@ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot
1731
1821
  // to run them deadlocks the stop (FS-04).
1732
1822
  const allKeys = new Set(rows.map((t) => goalTaskId(t.id)));
1733
1823
  for (const t of rows) t.cls = t.status === 'malformed' ? 'malformed' : classifyTaskStatus(t.status, t.id, allKeys);
1734
- const clsOf = new Map(rows.map((t) => [goalTaskId(t.id), t.cls]));
1824
+ const clsOf = buildSupersessionGraph(rows.filter((t) => t.id).map((t) => ({ id: t.id, cls: t.cls, successors: t.successors })));
1735
1825
  const depSatisfied = (d) => {
1736
- const c = clsOf.get(d);
1737
- if (c === 'delivered' || c === 'history') return true;
1738
- if (c === 'cancelled-grounded') {
1739
- // Satisfied once the recovery successor (if any) is delivered; with no successor row the
1740
- // grounded cancellation itself is terminal.
1741
- return groundedCancellationResolved(d, clsOf);
1742
- }
1743
- return false;
1826
+ const dRows = clsOf.get(d);
1827
+ if (!dRows) return false;
1828
+ return dRows.every((r) => r.cls === 'delivered' || r.cls === 'history'
1829
+ || (r.cls === 'cancelled-grounded' && groundedCancellationResolved(d, clsOf)));
1744
1830
  };
1745
1831
  const pending = rows.filter((t) => t.cls !== 'delivered' && t.cls !== 'history'
1746
1832
  && !(t.cls === 'cancelled-grounded' && groundedCancellationResolved(t.id, clsOf)));
1747
1833
  const planning = pending.filter((t) => t.cls === 'needs-planning');
1834
+ const ownerObligations = pending.filter((t) => t.cls === 'cancelled-grounded');
1835
+ const describeObligation = (t) => {
1836
+ const succ = (t.successors || []).map((sId) => {
1837
+ const sRows = clsOf.get(goalTaskId(sId));
1838
+ return `${String(sId).toUpperCase()}=${sRows ? sRows.map((r) => r.cls).join('/') : 'missing'}`;
1839
+ });
1840
+ return `${t.id}=${t.status}${succ.length > 0 ? ` (awaiting successor(s): ${succ.join(', ')})` : ' (no resolved successor)'}`;
1841
+ };
1748
1842
  // INDEX has no dependency column: the authority is the task file's `## Dependencies`
1749
1843
  // section. Unreadable file, unknown dependency id => fail closed (row counts as executable).
1750
1844
  const executable = [];
1751
1845
  for (const t of pending) {
1752
1846
  if (t.cls === 'malformed') { executable.push(t); continue; }
1753
- if (t.cls === 'blocked' || t.cls === 'needs-planning') continue;
1847
+ if (t.cls === 'blocked' || t.cls === 'needs-planning' || t.cls === 'cancelled-grounded') continue;
1754
1848
  const deps = await readTaskFileDependencies(runRoot, t.id);
1755
1849
  if (deps === null) { executable.push(t); continue; }
1756
1850
  if (deps.every(depSatisfied)) executable.push(t);
1757
1851
  else if (deps.some((d) => !allKeys.has(d))) executable.push(t);
1758
- else if (deps.some((d) => clsOf.get(d) === 'unresolved')) executable.push(t);
1852
+ else if (deps.some((d) => (clsOf.get(d) || []).some((r) => r.cls === 'unresolved'))) executable.push(t);
1759
1853
  }
1760
1854
  if (rows.length === 0) return { kind: 'none' };
1761
1855
  if (executable.length === 0) {
1762
- if (planning.length === 0) return { kind: 'none' }; // legacy terminal: genuinely stuck / externally blocked
1856
+ if (planning.length === 0 && ownerObligations.length === 0) return { kind: 'none' };
1857
+ if (ownerObligations.length > 0) {
1858
+ const pauseSup = await markRunCursorPaused(runRoot);
1859
+ const planningTail = planning.length > 0
1860
+ ? [`Planner-gated row(s) also remain: ${planning.slice(0, 5).map((t) => (t.id ? `${t.id}=${t.status}` : '(malformed INDEX row)')).join(', ')} (run /ukit:handoff-create resume-gates).`]
1861
+ : [];
1862
+ return {
1863
+ kind: 'advisory',
1864
+ waitForApproval: true,
1865
+ systemMessage: [
1866
+ `[ukit-stop-coordinator] handoff run released UNFINISHED: Phase: blocked and no executable row remains, but ${ownerObligations.length} superseded row(s) are unresolved: ${ownerObligations.slice(0, 5).map(describeObligation).join('; ')}.`,
1867
+ 'Cancelled work cannot be executed: these are OWNER/PLANNER obligations. The run ends this stop UNFINISHED, never as completed.',
1868
+ ...planningTail,
1869
+ pauseSup?.ok
1870
+ ? 'RUN.md is marked `Paused: yes` (Phase untouched): the open obligation is persisted and no resume is auto-injected.'
1871
+ : 'WARNING: RUN.md could not be marked `Paused: yes` (write failed) — the unfinished obligation is NOT durably marked.',
1872
+ 'RESOLVE: the owner/planner must complete or re-plan each declared successor (or add the `<ID>-R<n>` recovery row / correct the INDEX File cell `→ TASK-x`), then resume explicitly with /ukit:handoff-fullstack (or clear with /ukit:handoff-clear). Nothing resumes automatically.',
1873
+ ].join('\n'),
1874
+ };
1875
+ }
1763
1876
  // FS-04(d)/FS-05: the ONLY remaining rows are planner-gated. Defined terminal
1764
1877
  // outcome — release WITHOUT a completion claim and persist the durable
1765
1878
  // unfinished marker through the existing `Paused: yes` writer (Phase untouched,
@@ -1799,12 +1912,19 @@ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot
1799
1912
  'Run /ukit:handoff-create resume-gates (validator + plan review) for these tasks.',
1800
1913
  ]
1801
1914
  : [];
1915
+ const obligationNote = ownerObligations.length > 0
1916
+ ? [
1917
+ '',
1918
+ `Unresolved superseded row(s) are owner/planner obligations, NOT executable: ${ownerObligations.slice(0, 5).map(describeObligation).join('; ')}.`,
1919
+ ]
1920
+ : [];
1802
1921
  return {
1803
1922
  kind: 'block',
1804
1923
  reason: [
1805
1924
  `UKit handoff run: Phase: blocked, but independent in-scope work is still executable (${named}).`,
1806
1925
  'A blocker on one task does not end the run.',
1807
1926
  ...planningNote,
1927
+ ...obligationNote,
1808
1928
  ...reconcileNote,
1809
1929
  '',
1810
1930
  'CONTINUE IMMEDIATELY: execute the executable row(s) above, then rewrite the run cursor.',
@@ -2131,6 +2251,44 @@ export async function detectUserInterruption(transcriptPath, {
2131
2251
  }
2132
2252
  }
2133
2253
 
2254
+ export async function ownerStopState({ projectRoot, payload = {} } = {}) {
2255
+ const sessionId = [payload.session_id, payload.sessionId].find((value) => typeof value === 'string' && value.trim());
2256
+ if (!sessionId) return { active: false };
2257
+ const safe = String(sessionId).trim().replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
2258
+ try {
2259
+ const route = JSON.parse(await fs.readFile(path.join(projectRoot, '.ukit/storage/cache/route-state', `${safe}.json`), 'utf8'));
2260
+ if (String(route?.sessionId || '').trim() !== String(sessionId).trim()) return { active: false };
2261
+ if (route.routePublicationIncomplete === true) return { active: false };
2262
+ return route?.ownerControl?.kind === 'stop' ? { active: true, control: route.ownerControl } : { active: false };
2263
+ } catch {
2264
+ return { active: false };
2265
+ }
2266
+ }
2267
+
2268
+ export async function releaseForOwnerStop({ projectRoot, payload = {}, ownership = null } = {}) {
2269
+ const state = await ownerStopState({ projectRoot, payload });
2270
+ if (!state.active) return null;
2271
+ let paused = null;
2272
+ try {
2273
+ const runRoot = await resolveRunRoot(projectRoot, payload?.cwd);
2274
+ let resolved = ownership;
2275
+ if (!resolved) {
2276
+ try {
2277
+ const { resolveCursorApplicability } = await import('./handoff-provenance.mjs');
2278
+ resolved = await resolveCursorApplicability({ projectRoot, runRoot, sessionId: payload.session_id ?? payload.sessionId });
2279
+ } catch { resolved = { status: 'UNKNOWN', reason: 'handoff provenance runtime unavailable' }; }
2280
+ }
2281
+ if (resolved?.status === 'OWNED') paused = await markRunCursorPaused(runRoot);
2282
+ } catch { /* the cursor stays untouched; the stop is still released */ }
2283
+ return {
2284
+ released: true,
2285
+ paused: Boolean(paused?.ok),
2286
+ systemMessage: '[ukit-stop-coordinator] stop allowed: the owner requested STOP. No write or verification evidence is demanded and no continuation or further automatic turn is scheduled; '
2287
+ + (paused?.ok ? 'the run cursor is marked PAUSED. ' : 'the run cursor was not changed. ')
2288
+ + 'Unfinished work stays unfinished (nothing completed or resumed) until a new owner request.',
2289
+ };
2290
+ }
2291
+
2134
2292
  // ─── Provider quota / rate-limit pause (goal-loop liveness) ────────────────
2135
2293
  // A provider quota exhaustion is a genuine external pause: forcing continuation
2136
2294
  // would bounce the model against a wall, and reporting completion would be a
@@ -2402,6 +2560,16 @@ export async function stopCoordinationInput({ projectRoot, payload = {}, authori
2402
2560
  'docs/AI_HANDOFF/tasks',
2403
2561
  ].map((input) => path.join(projectRoot, input));
2404
2562
  if (payload.transcript_path) inputs.push(payload.transcript_path);
2563
+ // Binding changes are authority changes even if the cursor and route did not
2564
+ // change. Hash the binding named by the cursor; never replay across it.
2565
+ try {
2566
+ const cursor = await fs.readFile(path.join(await resolveRunRoot(projectRoot, payload?.cwd), 'docs/AI_HANDOFF/RUN.md'), 'utf8');
2567
+ const runId = /^RunId:\s*(\S+)\s*$/im.exec(cursor)?.[1];
2568
+ if (runId) {
2569
+ const { provenancePath } = await import('./handoff-provenance.mjs');
2570
+ inputs.push(provenancePath(projectRoot, runId));
2571
+ }
2572
+ } catch { /* no readable cursor: the ordinary input currency remains conservative */ }
2405
2573
  async function stopInputKey() {
2406
2574
  const hash = crypto.createHash('sha256');
2407
2575
  const currency = crypto.createHash('sha256');
@@ -2549,7 +2717,15 @@ export async function runStopCoordinator({
2549
2717
  extraText: payload?.error != null ? JSON.stringify(payload.error) : '',
2550
2718
  });
2551
2719
  if (quotaSignal) {
2552
- const pause = await markRunCursorPaused(await resolveRunRoot(projectRoot, payload?.cwd));
2720
+ const runRoot = await resolveRunRoot(projectRoot, payload?.cwd);
2721
+ let ownership;
2722
+ try {
2723
+ const { resolveCursorApplicability } = await import('./handoff-provenance.mjs');
2724
+ ownership = await resolveCursorApplicability({ projectRoot, runRoot, sessionId: explicitSession });
2725
+ } catch {
2726
+ ownership = { status: 'UNKNOWN', reason: 'handoff provenance runtime unavailable' };
2727
+ }
2728
+ const pause = ownership.status === 'OWNED' ? await markRunCursorPaused(runRoot) : null;
2553
2729
  return {
2554
2730
  skip: null,
2555
2731
  merged: {
@@ -2562,9 +2738,11 @@ export async function runStopCoordinator({
2562
2738
  terminalOutcome: 'WAIT_FOR_APPROVAL',
2563
2739
  systemMessage:
2564
2740
  `[ukit-stop-coordinator] stop released: a provider quota/rate-limit signal ("${quotaSignal}") ` +
2565
- `was detected. ` + (pause.ok
2741
+ `was detected. ` + (pause?.ok
2566
2742
  ? 'The run cursor is marked PAUSED; nothing was resumed or completed. '
2567
- : 'No RUN.md cursor found to pause; nothing was resumed or completed. ')
2743
+ : ownership.status !== 'OWNED'
2744
+ ? `The run cursor was not changed (ownership ${ownership.status}: ${ownership.reason}); nothing was resumed or completed. `
2745
+ : 'The run cursor could not be paused; nothing was resumed or completed. ')
2568
2746
  + 'Continue in a NEW message (or /ukit:handoff-fullstack) once the quota resets.',
2569
2747
  policyOwner: 'quota-pause',
2570
2748
  policies: ['quota-pause'],
@@ -2573,6 +2751,20 @@ export async function runStopCoordinator({
2573
2751
  }
2574
2752
  } catch { /* advisory lane: detection failure never changes the stop */ }
2575
2753
 
2754
+ const ownerStop = await releaseForOwnerStop({ projectRoot, payload });
2755
+ if (ownerStop) {
2756
+ return {
2757
+ skip: null,
2758
+ merged: {
2759
+ decision: null,
2760
+ terminalOutcome: 'WAIT_FOR_APPROVAL',
2761
+ systemMessage: ownerStop.systemMessage,
2762
+ policyOwner: 'owner-stop',
2763
+ policies: ['owner-stop'],
2764
+ },
2765
+ };
2766
+ }
2767
+
2576
2768
  const initialInput = await stopCoordinationInput({ projectRoot, payload });
2577
2769
  const dedupeKey = initialInput.key;
2578
2770
  const claimToken = crypto.randomUUID();
@@ -2582,7 +2774,18 @@ export async function runStopCoordinator({
2582
2774
  try {
2583
2775
  const state = JSON.parse(await fs.readFile(path.join(projectRoot, '.ukit/storage/cache/stop-coordinator/state.json'), 'utf8'));
2584
2776
  const decision = state.stopClaims?.[dedupeKey]?.decision;
2585
- if (decision?.decision === 'block') return { skip: null, merged: decision };
2777
+ if (decision?.decision === 'block') {
2778
+ if (decision.terminalCompletionBlocked !== true || decision.policyOwner !== 'task-watchdog') return { skip: null, merged: decision };
2779
+ // A watchdog block over terminal completion is still a Stop attempt. Count it in the same
2780
+ // no-progress breaker as freshly evaluated decisions; otherwise a fast
2781
+ // reentrant chain can replay one block forever without advancing it.
2782
+ try {
2783
+ const loop = await import('./loop-state.mjs');
2784
+ const merged = await loop.applyLoopBreak({ merged: decision, projectRoot, runRoot: await resolveRunRoot(projectRoot, payload?.cwd), payload, sessionKey, now, lockBudgetMs });
2785
+ if (merged.loopBreak === true) merged.terminalOutcome = 'BLOCKED_AND_STOP';
2786
+ return { skip: null, merged };
2787
+ } catch { return { skip: null, merged: decision }; }
2788
+ }
2586
2789
  } catch { /* an in-flight/failed first call cannot authorize completion */ }
2587
2790
  return { skip: null, merged: { decision: 'block',
2588
2791
  reason: 'UKit completion gate: Stop evaluation ownership is pending or unavailable (duplicate, claim capacity, or lock contention). No evaluator was admitted and no completion has been verified; a subsequent Stop can recheck ownership.',
@@ -2599,15 +2802,33 @@ export async function runStopCoordinator({
2599
2802
  process.stderr.write(`[ukit-stop-coordinator] completion evaluator failed: ${failures.completion}\n`);
2600
2803
  }
2601
2804
 
2805
+ const runRoot = await resolveRunRoot(projectRoot, payload?.cwd);
2806
+ let ownership;
2807
+ try {
2808
+ const { resolveCursorApplicability } = await import('./handoff-provenance.mjs');
2809
+ ownership = await resolveCursorApplicability({ projectRoot, runRoot, sessionId: explicitSession });
2810
+ } catch {
2811
+ ownership = { status: 'UNKNOWN', reason: 'handoff provenance runtime unavailable' };
2812
+ }
2813
+ if (ownership.reason === 'run cursor absent') {
2814
+ try {
2815
+ const watchdogRuntime = await import('./task-watchdog.mjs');
2816
+ const tasks = await watchdogRuntime.listInProgressTasks(projectRoot);
2817
+ if (tasks.length) ownership = { status: 'UNKNOWN', reason: 'watchdog tasks exist without a run cursor' };
2818
+ } catch {
2819
+ ownership = { status: 'UNKNOWN', reason: 'watchdog task inventory unavailable' };
2820
+ }
2821
+ }
2602
2822
  let watchdog = null;
2603
2823
  try {
2604
2824
  const watchdogRuntime = await import(new URL('./task-watchdog.mjs', import.meta.url).href);
2605
- watchdog = await watchdogRuntime.evaluateStopWatchdog({
2606
- projectRoot,
2607
- now,
2608
- lockBudgetMs,
2609
- cycle: await readRunCycle(await resolveRunRoot(projectRoot, payload?.cwd)),
2610
- });
2825
+ // Evaluating the watchdog writes anchors and hard-trip counters; do not
2826
+ // enter it until the cursor's binding proves this task owns that run.
2827
+ watchdog = ownership.status === 'OWNED'
2828
+ ? await watchdogRuntime.evaluateStopWatchdog({
2829
+ projectRoot, now, lockBudgetMs, cycle: await readRunCycle(runRoot),
2830
+ })
2831
+ : { kind: 'none' };
2611
2832
  } catch (error) {
2612
2833
  failures.watchdog = error?.message || String(error);
2613
2834
  process.stderr.write(`[ukit-stop-coordinator] task-watchdog evaluator failed: ${failures.watchdog}\n`);
@@ -2615,15 +2836,18 @@ export async function runStopCoordinator({
2615
2836
 
2616
2837
  let handoff = null;
2617
2838
  try {
2618
- handoff = await evaluateHandoffCursor({
2839
+ handoff = ownership.status === 'OWNED' ? await evaluateHandoffCursor({
2619
2840
  projectRoot,
2620
- runRoot: await resolveRunRoot(projectRoot, payload?.cwd),
2841
+ runRoot,
2621
2842
  now,
2622
2843
  lockBudgetMs,
2623
2844
  transcriptPath: typeof payload?.transcript_path === 'string' ? payload.transcript_path : null,
2624
2845
  stopHookActive: payload?.stop_hook_active === true,
2625
2846
  completionKind: completion?.kind ?? null,
2626
- });
2847
+ ownership,
2848
+ }) : ownership.status === 'UNKNOWN' && ownership.reason !== 'run cursor absent'
2849
+ ? { kind: 'advisory', systemMessage: `[ukit-stop-coordinator] handoff ownership UNKNOWN (${ownership.reason}); cursor and watchdog were not changed. Run completion is unproven; report BLOCKED and reconcile provenance before resuming.` }
2850
+ : { kind: 'none' };
2627
2851
  } catch (error) {
2628
2852
  failures.handoff = error?.message || String(error);
2629
2853
  process.stderr.write(`[ukit-stop-coordinator] handoff-cursor evaluator failed: ${failures.handoff}\n`);
@@ -2640,6 +2864,8 @@ export async function runStopCoordinator({
2640
2864
  } catch { /* advisory lane: an unreadable breaker never changes the stop verdict */ }
2641
2865
 
2642
2866
  let merged = coordinateStopDecisions({ completion, watchdog, handoff, failures });
2867
+ if (completion?.outcome === 'blocked' && completion?.complete === false) merged.terminalCompletionBlocked = true;
2868
+ if (ownership.status === 'UNKNOWN' && ownership.reason !== 'run cursor absent' && merged.decision !== 'block') merged.blockedOutcome = true;
2643
2869
 
2644
2870
  // Reconcile BEFORE the loop-breaker so a conflicting block is already released when
2645
2871
  // the loop detector looks at the decision (the loop-state lane independently ignores
@@ -2811,7 +3037,7 @@ async function main() {
2811
3037
  }
2812
3038
  if (merged.systemMessage) {
2813
3039
  writeDecisionLine({ systemMessage: merged.systemMessage, policyOwner: merged.policyOwner,
2814
- ...(merged.blockedOutcome ? { outcome: 'blocked', complete: false, continue: false } : {}),
3040
+ ...(merged.blockedOutcome ? { outcome: 'blocked', complete: false } : {}),
2815
3041
  });
2816
3042
  }
2817
3043
  // Neither → silent release: both policies decided "complete".