@ngockhoale/ukit 3.4.74 → 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.
@@ -20,6 +20,8 @@ export function compactOperation(operation) {
20
20
  || operation.presentTargets.length > 256 || !operation.presentTargets.every(bounded)))) return { invalid: true };
21
21
  return { domain: operation.domain, scope: operation.scope, role: operation.role, target: operation.target,
22
22
  ...(operation.state !== undefined ? { state: operation.state } : {}),
23
+ ...(bounded(operation.candidate) ? { candidate: operation.candidate } : {}),
24
+ ...(bounded(operation.integrity) ? { integrity: operation.integrity, ...(bounded(operation.integrityFor) ? { integrityFor: operation.integrityFor } : {}) } : {}),
23
25
  ...(operation.presentTargets !== undefined ? { presentTargets: operation.presentTargets === null ? null : [...operation.presentTargets] } : {}),
24
26
  complete: operation.complete === true, ...(validRemoteSync(operation.remoteSync) ? { remoteSync: { ...operation.remoteSync } } : {}),
25
27
  ...(validGithubView(operation.github) ? { github: { ...operation.github } } : {}) };
@@ -65,11 +67,18 @@ export function foldOperationEvidence(bank = {}, receipt, ledger) {
65
67
  : (op.role === 'state' && op.domain === 'git-integrity' && receipt.success === true && op.complete === true
66
68
  && validGithubView(priorGithub) && Number.isSafeInteger(priorGithub.observedSequence)
67
69
  && priorGithub.observedSequence > lastMutation) ? { ...priorGithub } : null;
70
+ const own = bounded(op.integrity) && (op.role === 'mutation' || bounded(op.integrityFor));
71
+ const kept = !own && op.role === 'state' && op.complete === true && prior.state?.sequence > lastMutation
72
+ && op.state === `published:${prior.state.operation.integrityFor}`;
73
+ const src = own ? op : kept ? prior.state.operation : {};
74
+ const { integrity, integrityFor } = src;
68
75
  const proof = { success: receipt.success === true, exitStatusUnproven: receipt.exitStatusUnproven === true, sequence: receipt.sequence,
69
76
  toolUseId: receipt.toolUseId, taskInstanceId: receipt.taskInstanceId,
70
77
  sessionKey: receipt.sessionKey, operation: {
71
78
  domain: op.domain, scope: op.scope, role: op.role, target: op.target,
72
79
  ...(op.state !== undefined ? { state: op.state } : {}),
80
+ ...(bounded(op.candidate) ? { candidate: op.candidate } : {}),
81
+ ...(integrity ? { integrity, ...(integrityFor ? { integrityFor } : {}) } : {}),
73
82
  ...(op.presentTargets !== undefined ? { presentTargets: [...op.presentTargets] } : {}),
74
83
  complete: op.complete === true,
75
84
  ...(remoteSync ? { remoteSync } : {}),
@@ -788,8 +788,18 @@ async function realDirectoryOrAbsent(target) {
788
788
  }
789
789
  }
790
790
 
791
+ function snapshotDeclaredSuccessors(fileCell) {
792
+ const m = String(fileCell ?? '').match(/(?:→|->)\s*(.*)$/s);
793
+ if (!m) return [];
794
+ const id = 'TASK-[A-Za-z0-9._-]*[A-Za-z0-9]';
795
+ const list = m[1].trim().replace(/[.;]+$/, '');
796
+ if (!new RegExp(`^${id}(?:\\s*,\\s*${id})*$`, 'i').test(list)) return [];
797
+ return [...new Set(list.split(',').map((x) => x.trim().toLowerCase()))];
798
+ }
799
+
791
800
  function parseArchiveSnapshotStatuses(text) {
792
801
  const map = new Map();
802
+ const successors = new Map();
793
803
  for (const line of String(text).split('\n')) {
794
804
  const row = line.trim();
795
805
  if (!/^\|\s*TASK-/i.test(row)) continue;
@@ -798,25 +808,37 @@ function parseArchiveSnapshotStatuses(text) {
798
808
  const key = cells[0].toLowerCase();
799
809
  if (map.has(key)) return null;
800
810
  map.set(key, cells[4].toLowerCase());
811
+ successors.set(key, snapshotDeclaredSuccessors(cells[7]));
801
812
  }
813
+ Object.defineProperty(map, 'successors', { value: successors, enumerable: false });
802
814
  return map;
803
815
  }
804
816
 
805
- // Terminal-success under the snapshot: done, or grounded cancellation resolved by a terminal successor.
806
817
  function snapshotTaskTerminal(key, statuses, seen = new Set()) {
807
818
  if (seen.has(key)) return false;
808
819
  seen.add(key);
809
- const st = statuses.get(key);
810
- if (st === 'done') return true;
811
- if (st !== 'cancelled_superseded') return false;
812
- const root = key.replace(/-r\d+$/, '');
813
- const currentRepair = BigInt(key.match(/-r(\d+)$/)?.[1] ?? '0');
814
- for (const [other, ost] of statuses) {
815
- if (!other.startsWith(`${root}-r`) || !/^\d+$/.test(other.slice(root.length + 2))) continue;
816
- if (BigInt(other.slice(root.length + 2)) <= currentRepair) continue;
817
- if (ost === 'done' || (ost === 'cancelled_superseded' && snapshotTaskTerminal(other, statuses, seen))) return true;
820
+ try {
821
+ const st = statuses.get(key);
822
+ if (st === 'done') return true;
823
+ if (st !== 'cancelled_superseded') return false;
824
+ const root = key.replace(/-r\d+$/, '');
825
+ const currentRepair = BigInt(key.match(/-r(\d+)$/)?.[1] ?? '0');
826
+ for (const [other, ost] of statuses) {
827
+ if (!other.startsWith(`${root}-r`) || !/^\d+$/.test(other.slice(root.length + 2))) continue;
828
+ if (BigInt(other.slice(root.length + 2)) <= currentRepair) continue;
829
+ if (ost === 'done' || (ost === 'cancelled_superseded' && snapshotTaskTerminal(other, statuses, seen))) return true;
830
+ }
831
+ const declared = statuses.successors?.get(key) || [];
832
+ return declared.length > 0
833
+ && declared.every((s) => s !== key && statuses.has(s) && snapshotTaskTerminal(s, statuses, seen));
834
+ } finally {
835
+ seen.delete(key);
818
836
  }
819
- return false;
837
+ }
838
+
839
+ export function archiveSnapshotTaskTerminal(snapshotText, taskId) {
840
+ const statuses = parseArchiveSnapshotStatuses(snapshotText);
841
+ return statuses !== null && snapshotTaskTerminal(goalKey(taskId), statuses);
820
842
  }
821
843
 
822
844
  async function claimCycleFinalized(projectRoot, cycle, taskId) {
@@ -974,9 +974,9 @@ async function evalIndexAllDone(projectRoot, { goalScope = '', scopeQueue = '',
974
974
  }
975
975
  const failing = [];
976
976
  const liveIds = new Set(scoped.map((r) => goalTaskId(r.id)));
977
- const liveCls = new Map(scoped.filter((r) => indexTaskRowIsWellFormed(r.raw)).map((r) => {
977
+ const liveCls = buildSupersessionGraph(scoped.filter((r) => indexTaskRowIsWellFormed(r.raw)).map((r) => {
978
978
  const c = indexTaskCells(r.raw);
979
- 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]) };
980
980
  }));
981
981
  for (const scopedRow of scoped) {
982
982
  const row = scopedRow.raw;
@@ -1004,13 +1004,23 @@ async function evalIndexAllDone(projectRoot, { goalScope = '', scopeQueue = '',
1004
1004
  // another column.
1005
1005
  function parseIndexStatuses(text) {
1006
1006
  const map = new Map();
1007
+ const entries = [];
1007
1008
  for (const line of String(text).split('\n')) {
1008
1009
  const row = line.trim();
1009
1010
  if (!/^\|\s*TASK-/i.test(row)) continue;
1010
1011
  if (!indexTaskRowIsWellFormed(row)) return null;
1011
1012
  const cells = indexTaskCells(row);
1012
- 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]) });
1013
1022
  }
1023
+ Object.defineProperty(map, 'entries', { value: entries, enumerable: false });
1014
1024
  return map;
1015
1025
  }
1016
1026
 
@@ -1109,7 +1119,7 @@ async function evalFinalizedCycles(projectRoot, goalScope, scopeQueue = '', cycl
1109
1119
  }
1110
1120
  const archIds = new Set(snapshot ? [...snapshot.keys()].map(goalTaskId) : []);
1111
1121
  const archCls = classifyTaskStatus(status, id, archIds);
1112
- 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 })));
1113
1123
  const archTerminal = archCls === 'delivered' || (archCls === 'cancelled-grounded' && groundedCancellationResolved(id, archClsByKey));
1114
1124
  if (!archTerminal) {
1115
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>`)'}`);
@@ -1336,22 +1346,54 @@ const REVIEW_OBLIGATION_STATUSES = new Set(['pending_review', 'approved', 'appro
1336
1346
  // (`TASK-xxx-R1`, `-R2`, …), so a successor of any `-R<n>` row is a sibling `<root>-R<m>`
1337
1347
  // row with m > n; suffixes compare numerically (BigInt, like the claim runtime), so R2 does
1338
1348
  // not resolve R10. The root is the id with its trailing `-R<n>` stripped.
1339
- function groundedCancellationResolved(id, clsByKey, seen = new Set()) {
1349
+ function groundedCancellationResolved(id, graph, seen = new Set()) {
1340
1350
  const key = goalTaskId(id);
1341
1351
  if (seen.has(key)) return false;
1352
+ const rows = graph.get(key);
1353
+ if (!rows || rows.length === 0) return false;
1342
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) {
1343
1364
  const root = key.replace(/-r\d+$/, '');
1344
1365
  const ownSuffix = key.match(/-r(\d+)$/);
1345
1366
  const ownNum = ownSuffix ? BigInt(ownSuffix[1]) : 0n;
1346
1367
  const prefix = `${root}-r`;
1347
- for (const [other, cls] of clsByKey) {
1368
+ for (const other of graph.keys()) {
1348
1369
  if (!other.startsWith(prefix) || !/^\d+$/.test(other.slice(prefix.length))) continue;
1349
- const num = BigInt(other.slice(prefix.length));
1350
- if (num <= ownNum) continue;
1351
- if (cls === 'delivered') return true;
1352
- 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 || [] });
1353
1395
  }
1354
- return false;
1396
+ return graph;
1355
1397
  }
1356
1398
 
1357
1399
  /** Classify one task. `allIds` = Set of lower-cased ids in the same task set (for successor grounding). */
@@ -1394,7 +1436,7 @@ function goalVerificationVerdict(ledger) {
1394
1436
  *
1395
1437
  * @param {object} [input]
1396
1438
  * @param {{ phase?: string, paused?: boolean } | null} [input.runCursor]
1397
- * @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]
1398
1440
  * @param {{ verdict?: string, verified?: boolean, verify?: string } | null} [input.ledger]
1399
1441
  * @param {boolean|number} [input.agentsRunning]
1400
1442
  * @param {boolean} [input.snapshotConsistent]
@@ -1415,17 +1457,19 @@ export function deriveGoalStatus({ runCursor = null, tasks = null, ledger = null
1415
1457
  key: goalTaskId(t.id),
1416
1458
  status: String(t.status ?? '').trim().toLowerCase(),
1417
1459
  dependsOn: Array.isArray(t.dependsOn) ? t.dependsOn.map(goalTaskId) : [],
1460
+ successors: Array.isArray(t.successors) ? t.successors.map(goalTaskId).filter(Boolean) : [],
1418
1461
  }))
1419
1462
  : [];
1420
1463
  const allKeys = new Set(list.map((t) => t.key));
1421
1464
  for (const t of list) t.cls = classifyTaskStatus(t.status, t.id, allKeys);
1422
1465
  // A dependency is satisfied by delivery, history, or a grounded cancellation whose successor
1423
1466
  // was delivered; approved/cancelled-without-grounds never satisfy it.
1424
- const deliveredKeys = new Set(list.filter((t) => t.cls === 'delivered').map((t) => t.key));
1425
- const doneIds = new Set(list.filter((t) => t.cls === 'delivered' || t.cls === 'history').map((t) => t.key));
1426
- const clsByKey = new Map(list.map((t) => [t.key, t.cls]));
1427
- for (const t of list) {
1428
- 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);
1429
1473
  }
1430
1474
  // Only a RESOLVED grounded cancellation leaves pending; an orphan one is an open obligation.
1431
1475
  const pending = list.filter((t) => !doneIds.has(t.key));
@@ -1521,7 +1565,7 @@ function indexTasks(indexText) {
1521
1565
  if (!indexTaskRowIsWellFormed(row)) return { id: '', status: 'malformed' };
1522
1566
  const cells = indexTaskCells(row);
1523
1567
  const deps = (cells[3] || '').split(',').map((d) => d.trim()).filter((d) => d && d.toLowerCase() !== 'none');
1524
- return { id: cells[0] || '', status: (cells[4] || '').toLowerCase(), deps };
1568
+ return { id: cells[0] || '', status: (cells[4] || '').toLowerCase(), deps, successors: declaredSuccessors(cells[7]) };
1525
1569
  });
1526
1570
  }
1527
1571
 
@@ -1556,9 +1600,9 @@ function indexTaskSnapshotHash(indexText) {
1556
1600
 
1557
1601
  function firstOpenIndexTaskId(indexText) {
1558
1602
  const allIds = new Set(indexTaskRows(indexText).map((r) => goalTaskId(indexTaskCells(r)[0])));
1559
- const clsByKey = new Map(indexTaskRows(indexText).filter((r) => indexTaskRowIsWellFormed(r)).map((r) => {
1603
+ const clsByKey = buildSupersessionGraph(indexTaskRows(indexText).filter((r) => indexTaskRowIsWellFormed(r)).map((r) => {
1560
1604
  const c = indexTaskCells(r);
1561
- 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]) };
1562
1606
  }));
1563
1607
  for (const row of indexTaskRows(indexText)) {
1564
1608
  const cells = indexTaskCells(row);
@@ -1777,35 +1821,58 @@ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot
1777
1821
  // to run them deadlocks the stop (FS-04).
1778
1822
  const allKeys = new Set(rows.map((t) => goalTaskId(t.id)));
1779
1823
  for (const t of rows) t.cls = t.status === 'malformed' ? 'malformed' : classifyTaskStatus(t.status, t.id, allKeys);
1780
- 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 })));
1781
1825
  const depSatisfied = (d) => {
1782
- const c = clsOf.get(d);
1783
- if (c === 'delivered' || c === 'history') return true;
1784
- if (c === 'cancelled-grounded') {
1785
- // Satisfied once the recovery successor (if any) is delivered; with no successor row the
1786
- // grounded cancellation itself is terminal.
1787
- return groundedCancellationResolved(d, clsOf);
1788
- }
1789
- 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)));
1790
1830
  };
1791
1831
  const pending = rows.filter((t) => t.cls !== 'delivered' && t.cls !== 'history'
1792
1832
  && !(t.cls === 'cancelled-grounded' && groundedCancellationResolved(t.id, clsOf)));
1793
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
+ };
1794
1842
  // INDEX has no dependency column: the authority is the task file's `## Dependencies`
1795
1843
  // section. Unreadable file, unknown dependency id => fail closed (row counts as executable).
1796
1844
  const executable = [];
1797
1845
  for (const t of pending) {
1798
1846
  if (t.cls === 'malformed') { executable.push(t); continue; }
1799
- if (t.cls === 'blocked' || t.cls === 'needs-planning') continue;
1847
+ if (t.cls === 'blocked' || t.cls === 'needs-planning' || t.cls === 'cancelled-grounded') continue;
1800
1848
  const deps = await readTaskFileDependencies(runRoot, t.id);
1801
1849
  if (deps === null) { executable.push(t); continue; }
1802
1850
  if (deps.every(depSatisfied)) executable.push(t);
1803
1851
  else if (deps.some((d) => !allKeys.has(d))) executable.push(t);
1804
- 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);
1805
1853
  }
1806
1854
  if (rows.length === 0) return { kind: 'none' };
1807
1855
  if (executable.length === 0) {
1808
- 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
+ }
1809
1876
  // FS-04(d)/FS-05: the ONLY remaining rows are planner-gated. Defined terminal
1810
1877
  // outcome — release WITHOUT a completion claim and persist the durable
1811
1878
  // unfinished marker through the existing `Paused: yes` writer (Phase untouched,
@@ -1845,12 +1912,19 @@ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot
1845
1912
  'Run /ukit:handoff-create resume-gates (validator + plan review) for these tasks.',
1846
1913
  ]
1847
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
+ : [];
1848
1921
  return {
1849
1922
  kind: 'block',
1850
1923
  reason: [
1851
1924
  `UKit handoff run: Phase: blocked, but independent in-scope work is still executable (${named}).`,
1852
1925
  'A blocker on one task does not end the run.',
1853
1926
  ...planningNote,
1927
+ ...obligationNote,
1854
1928
  ...reconcileNote,
1855
1929
  '',
1856
1930
  'CONTINUE IMMEDIATELY: execute the executable row(s) above, then rewrite the run cursor.',
@@ -2177,6 +2251,44 @@ export async function detectUserInterruption(transcriptPath, {
2177
2251
  }
2178
2252
  }
2179
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
+
2180
2292
  // ─── Provider quota / rate-limit pause (goal-loop liveness) ────────────────
2181
2293
  // A provider quota exhaustion is a genuine external pause: forcing continuation
2182
2294
  // would bounce the model against a wall, and reporting completion would be a
@@ -2639,6 +2751,20 @@ export async function runStopCoordinator({
2639
2751
  }
2640
2752
  } catch { /* advisory lane: detection failure never changes the stop */ }
2641
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
+
2642
2768
  const initialInput = await stopCoordinationInput({ projectRoot, payload });
2643
2769
  const dedupeKey = initialInput.key;
2644
2770
  const claimToken = crypto.randomUUID();
@@ -18,7 +18,10 @@ import {
18
18
  markNotified,
19
19
  readExecutionLedger,
20
20
  readRouteState,
21
+ ownerStopActive,
22
+ ownerStopGovernsStart,
21
23
  } from '../../../.claude/ukit/runtime/execution-ledger.mjs';
24
+ import { classifyOwnerControl } from '../../../.claude/ukit/index/publication-intent.mjs';
22
25
  import {
23
26
  PAYLOAD_INLINE_MAX_BYTES,
24
27
  createPayloadReferenceAsync,
@@ -261,6 +264,28 @@ export function isSubagentSession(context = {}) {
261
264
  }
262
265
  }
263
266
 
267
+ export function parentSessionIdOf(context = {}) {
268
+ try {
269
+ const parent = context?.sessionManager?.getHeader?.()?.parentSession;
270
+ if (typeof parent !== 'string' || !parent) return undefined;
271
+ const match = /^[^_]*_(.+)\.jsonl$/.exec(parent.split(/[/\\]/).pop());
272
+ return match ? match[1] : undefined;
273
+ } catch {
274
+ return undefined;
275
+ }
276
+ }
277
+
278
+ const OWNER_STOP_START_REASON = 'Owner STOP is in effect for this session: no new tool, shell command, edit or subagent may start until the owner sends a new request. Do not retry; report the stop and wait.';
279
+ export async function ownerStopBlocksStart(projectRoot, event = {}, context = {}) {
280
+ try {
281
+ const meta = runtimeMetadata(event, context);
282
+ const own = context?.sessionManager?.getSessionId?.();
283
+ return await ownerStopGovernsStart(projectRoot, [meta.sessionId, own, meta.parentSessionId]);
284
+ } catch {
285
+ return false;
286
+ }
287
+ }
288
+
264
289
  function runtimeMetadata(event = {}, context = {}) {
265
290
  const sessionManager = context?.sessionManager;
266
291
  const transcriptPath = event.transcriptPath ?? event.transcript_path ?? sessionManager?.getSessionFile?.();
@@ -276,9 +301,71 @@ function runtimeMetadata(event = {}, context = {}) {
276
301
  cwd: context?.cwd ?? event.cwd,
277
302
  transcriptPath,
278
303
  subagentSession: isSubagentSession(context) ? true : undefined,
304
+ parentSessionId: parentSessionIdOf(context),
279
305
  };
280
306
  }
281
307
 
308
+ const OWN_CONTINUATION_TTL_MS = 10 * 60 * 1000;
309
+ const ownContinuations = new Map();
310
+ function rememberOwnContinuation(sessionId, text, now = Date.now()) {
311
+ const key = String(sessionId ?? '').trim();
312
+ const value = String(text ?? '').trim();
313
+ if (!key || !value) return;
314
+ const list = (ownContinuations.get(key) || []).filter((entry) => now - entry.ts <= OWN_CONTINUATION_TTL_MS);
315
+ list.push({ text: value, ts: now });
316
+ ownContinuations.set(key, list.slice(-4));
317
+ }
318
+ function takeOwnContinuation(sessionId, prompt, now = Date.now()) {
319
+ const key = String(sessionId ?? '').trim();
320
+ const value = String(prompt ?? '').trim();
321
+ if (!key || !value) return false;
322
+ const list = (ownContinuations.get(key) || []).filter((entry) => now - entry.ts <= OWN_CONTINUATION_TTL_MS);
323
+ const index = list.findIndex((entry) => entry.text === value);
324
+ if (index < 0) { ownContinuations.set(key, list); return false; }
325
+ list.splice(index, 1);
326
+ ownContinuations.set(key, list);
327
+ return true;
328
+ }
329
+
330
+ const ownerInputs = new Map();
331
+ const OWNER_INPUT_KEEP = 32;
332
+ let ownerInputHostSeen = false;
333
+ function ownerInputKey(event, context) {
334
+ return String(event?.sessionId ?? event?.session_id ?? context?.sessionManager?.getSessionId?.()
335
+ ?? context?.sessionManager?.getSessionFile?.() ?? '').trim();
336
+ }
337
+ export function observeOwnerInput(event, context = {}) {
338
+ const key = ownerInputKey(event, context);
339
+ const text = String(event?.text ?? '').trim();
340
+ if (!key || !text) return;
341
+ ownerInputHostSeen = true;
342
+ const book = ownerInputs.get(key) || { seq: 0, stopSeq: 0, pending: [] };
343
+ book.seq += 1;
344
+ const stop = classifyOwnerControl(text).kind === 'stop';
345
+ if (stop) book.stopSeq = book.seq;
346
+ book.pending.push({ seq: book.seq, text, stop });
347
+ if (book.pending.length > OWNER_INPUT_KEEP) book.pending.splice(0, book.pending.length - OWNER_INPUT_KEEP);
348
+ ownerInputs.set(key, book);
349
+ }
350
+ export function takeOwnerInputOrder(sessionId, prompt) {
351
+ if (!ownerInputHostSeen) return undefined;
352
+ const book = ownerInputs.get(String(sessionId ?? '').trim());
353
+ const value = String(prompt ?? '').trim();
354
+ if (!book || !value) return 'unproven';
355
+ for (let start = 0; start < book.pending.length; start += 1) {
356
+ let joined = '';
357
+ for (let end = start; end < book.pending.length; end += 1) {
358
+ joined = end === start ? book.pending[end].text : `${joined}\n\n${book.pending[end].text}`;
359
+ if (joined !== value) continue;
360
+ const parts = book.pending.slice(start, end + 1);
361
+ book.pending.splice(0, end + 1);
362
+ if (parts.some((part) => part.stop)) return 'contains-stop';
363
+ return parts.some((part) => part.seq < book.stopSeq) ? 'before-stop' : 'after-stop';
364
+ }
365
+ }
366
+ return 'unproven';
367
+ }
368
+
282
369
  // OMP 18.12.5 before_agent_start has no origin field. Recover only the nearest
283
370
  // native prompt-bearing branch entry, never a prefix claimed by prompt text.
284
371
  export function promptOriginFromBranch(prompt, context = {}) {
@@ -315,7 +402,9 @@ function buildHookPayload(hookEventName, fields = {}) {
315
402
  ['transcriptPath', 'transcript_path'],
316
403
  ['source', 'source'],
317
404
  ['promptOrigin', 'ukit_prompt_origin'],
405
+ ['ownerInput', 'ukit_owner_input'],
318
406
  ['subagentSession', 'ukit_subagent_session'],
407
+ ['parentSessionId', 'ukit_parent_session_id'],
319
408
  ];
320
409
  for (const [field, payloadField] of mappings) {
321
410
  if (fields[field] !== undefined && fields[field] !== null) {
@@ -888,6 +977,9 @@ async function readAllowUnsafeEval(projectRoot) {
888
977
  }
889
978
 
890
979
  export async function runToolCall(pi, event, { projectRoot, context: extensionContext = {}, allowUnsafeEval } = {}) {
980
+ if (await ownerStopBlocksStart(projectRoot, event, extensionContext)) {
981
+ return { block: true, toolName: null, invoked: [], context: [], reason: OWNER_STOP_START_REASON };
982
+ }
891
983
  const rawToolName = event.toolName ?? event.tool;
892
984
  if (String(rawToolName ?? '').trim().toLowerCase() === 'eval') {
893
985
  const allowed = allowUnsafeEval ?? await readAllowUnsafeEval(projectRoot);
@@ -1029,7 +1121,8 @@ export async function runBeforeAgentStart(pi, event, { projectRoot, context: ext
1029
1121
  const metadata = runtimeMetadata(event, extensionContext);
1030
1122
  const payload = buildHookPayload('UserPromptSubmit', {
1031
1123
  prompt: event.prompt,
1032
- promptOrigin: promptOriginFromBranch(event.prompt, extensionContext),
1124
+ promptOrigin: takeOwnContinuation(metadata.sessionId, event.prompt) ? 'system' : promptOriginFromBranch(event.prompt, extensionContext),
1125
+ ownerInput: takeOwnerInputOrder(metadata.sessionId, event.prompt),
1033
1126
  ...metadata,
1034
1127
  });
1035
1128
  const result = await runScriptChain(pi, HOOK_EVENT_MAP.before_agent_start, payload, { projectRoot });
@@ -1351,6 +1444,20 @@ async function readStopGateMaxCrashStreaks(projectRoot) {
1351
1444
  // the shared state file (.ukit/storage/cache/stop-coordinator/state.json) stay
1352
1445
  // byte-identical across both engines.
1353
1446
  const STOP_GATE_LOCK_BUDGET_MS = 600;
1447
+ const unknownOwnershipReported = new Map();
1448
+ async function unknownOwnershipRepeat(projectRoot, sessionId, reason) {
1449
+ let fingerprint = 'no-cursor';
1450
+ try {
1451
+ const stat = await fs.promises.stat(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'));
1452
+ fingerprint = `${stat.size}:${Math.floor(stat.mtimeMs)}`;
1453
+ } catch { /* fingerprint stays constant */ }
1454
+ const key = `${projectRoot}\u0000${sessionId ?? 'no-session'}`;
1455
+ const signature = `${reason}\u0000${fingerprint}`;
1456
+ const repeat = unknownOwnershipReported.get(key) === signature;
1457
+ unknownOwnershipReported.set(key, signature);
1458
+ return repeat;
1459
+ }
1460
+
1354
1461
  const HANDOFF_PROVENANCE_PREFIX = '[ukit-stop-coordinator] handoff-cursor also requested a block: ';
1355
1462
 
1356
1463
  let stopCoordinatorModulePromise = null;
@@ -1424,6 +1531,11 @@ export async function runSessionStop(
1424
1531
  pi.logger?.warn?.(`[UKit] stop-coordinator module unavailable (dedupe + handoff lanes skipped): ${error?.message || error}`);
1425
1532
  }
1426
1533
  const state = suppliedState ?? await readRouteState(projectRoot, payload);
1534
+ if (coordinator && ownerStopActive(state, payload)) {
1535
+ const released = await coordinator.releaseForOwnerStop({ projectRoot, payload });
1536
+ pi.logger?.warn?.(`[UKit] ${released?.systemMessage ?? 'stop allowed: the owner requested STOP; nothing completed or resumed.'}`);
1537
+ return undefined;
1538
+ }
1427
1539
  const ledger = suppliedLedger ?? await readExecutionLedger(projectRoot, payload) ?? {};
1428
1540
  const authority = () => ({ state, ledger: suppliedLedger ?? null });
1429
1541
  const claimToken = crypto.randomUUID();
@@ -1443,6 +1555,9 @@ export async function runSessionStop(
1443
1555
  return { continue: true, additionalContext: '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.' };
1444
1556
  }
1445
1557
  const finish = async (output) => {
1558
+ if (output && (output.continue === true || output.decision === 'block')) {
1559
+ rememberOwnContinuation(payload.session_id, output.additionalContext ?? output.reason);
1560
+ }
1446
1561
  if (coordinator) {
1447
1562
  const evaluatedInput = await coordinator.stopCoordinationInput({ projectRoot, payload, authority: authority() });
1448
1563
  await coordinator.publishStopDecision({
@@ -1497,6 +1612,15 @@ export async function runSessionStop(
1497
1612
  } catch { /* unreadable intent evidence keeps ownership UNKNOWN */ }
1498
1613
  }
1499
1614
  if (cursorActive && ownership.status === 'UNKNOWN') {
1615
+ if (await unknownOwnershipRepeat(projectRoot, payload.session_id, ownership.reason)) {
1616
+ sendContext(pi, [
1617
+ `[UKit] Handoff ownership is still UNKNOWN (${ownership.reason}) and no new evidence or authority exists. `
1618
+ + 'Stop released without completion: the handoff cursor, its tasks and ownership were NOT changed, '
1619
+ + 'and unfinished work stays unfinished until an owner request or a proven owning session resumes it.',
1620
+ ], 'nextTurn', { display: true });
1621
+ await recordEpisode();
1622
+ return finish(undefined);
1623
+ }
1500
1624
  return finish({ decision: 'block', reason: `UKit handoff ownership UNKNOWN (${ownership.reason}); completion is unproven. Reconcile provenance before stopping.` });
1501
1625
  }
1502
1626
  handoff = await coordinator.evaluateHandoffCursor({
@@ -1508,7 +1632,14 @@ export async function runSessionStop(
1508
1632
  });
1509
1633
  } catch (error) {
1510
1634
  pi.logger?.warn?.(`[UKit] handoff-cursor evaluator failed: ${error?.message || error}`);
1511
- if (cursorActive) return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: provenance or cursor evaluation failed; completion is unproven.' });
1635
+ if (cursorActive) {
1636
+ if (await unknownOwnershipRepeat(projectRoot, payload.session_id, `evaluation failed: ${error?.message || error}`)) {
1637
+ sendContext(pi, ['[UKit] Handoff provenance evaluation still fails; stop released without completion and without touching the handoff cursor (unproven, unfinished work preserved).'], 'nextTurn', { display: true });
1638
+ await recordEpisode();
1639
+ return finish(undefined);
1640
+ }
1641
+ return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: provenance or cursor evaluation failed; completion is unproven.' });
1642
+ }
1512
1643
  }
1513
1644
  } else if (cursorActive) {
1514
1645
  return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: stop coordinator unavailable; completion is unproven.' });
@@ -1620,11 +1751,15 @@ export default function hook(pi) {
1620
1751
  });
1621
1752
  });
1622
1753
  pi.on('tool_result', (event, context) => runToolResult(pi, event, { projectRoot, context }));
1754
+ pi.on('input', (event, context) => { observeOwnerInput(event, context); });
1623
1755
  pi.on('before_agent_start', (event, context) => runBeforeAgentStart(pi, event, { projectRoot, context }));
1624
1756
  pi.on('session.compacting', (event, context) => runSessionCompacting(pi, event, { projectRoot, context }));
1625
1757
  pi.on('session_start', (event, context) => runSessionStart(pi, event, { projectRoot, context }));
1626
1758
  pi.on('session_switch', (event, context) => runSessionSwitch(pi, event, { projectRoot, context }));
1627
1759
  pi.on('session_compact', (event, context) => runSessionCompact(pi, event, { projectRoot, context }));
1628
1760
  pi.on('session_stop', (event, context) => runSessionStop(pi, event, { projectRoot, context }));
1629
- pi.on('before_subagent_spawn', (event, context) => selectWorkerModel(event, { projectRoot, context }));
1761
+ pi.on('before_subagent_spawn', async (event, context) => {
1762
+ if (await ownerStopBlocksStart(projectRoot, event, context)) return { block: true, reason: OWNER_STOP_START_REASON };
1763
+ return selectWorkerModel(event, { projectRoot, context });
1764
+ });
1630
1765
  }