@ngockhoale/ukit 3.4.75 → 3.4.77

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.
@@ -48,8 +48,10 @@ export function foldOperationEvidence(bank = {}, receipt, ledger) {
48
48
  }
49
49
  const prior = bank[key] || {};
50
50
  const seen = Array.isArray(bank.seenToolUseIds) ? bank.seenToolUseIds : [];
51
- if (receipt.toolUseId && (seen.includes(receipt.toolUseId) || Object.values(bank).some((entry) =>
52
- [entry?.mutation, entry?.state].some((proof) => proof?.toolUseId === receipt.toolUseId)))) return bank;
51
+ // Dedup per (toolUseId, domain): one chained command may prove several goals, never the same goal twice.
52
+ const seenKey = `${receipt.toolUseId}|${op.domain}`;
53
+ if (receipt.toolUseId && (seen.includes(seenKey) || seen.includes(receipt.toolUseId) || Object.values(bank).some((entry) =>
54
+ [entry?.mutation, entry?.state].some((proof) => proof?.toolUseId === receipt.toolUseId && proof.operation?.domain === op.domain)))) return bank;
53
55
  if (receipt.toolUseId && (!bounded(receipt.toolUseId) || seen.length >= 256)) return { ...bank, overflow: true };
54
56
  // Carry remote parity across successful state checks only until the next mutation; gate checks live HEAD.
55
57
  const lastMutation = Object.values(bank).reduce((max, entry) => {
@@ -84,7 +86,7 @@ export function foldOperationEvidence(bank = {}, receipt, ledger) {
84
86
  ...(remoteSync ? { remoteSync } : {}),
85
87
  ...(github ? { github } : {}),
86
88
  } };
87
- return { ...bank, seenToolUseIds: receipt.toolUseId ? [...seen, receipt.toolUseId] : seen,
89
+ return { ...bank, seenToolUseIds: receipt.toolUseId ? [...seen, seenKey] : seen,
88
90
  [key]: { ...prior, [op.role]: proof } };
89
91
  }
90
92
 
@@ -155,10 +157,36 @@ export function operationEvidenceStatus(goal, ledger = {}) {
155
157
  return { complete: true, operationProof: 'executed-and-verified' };
156
158
  }
157
159
 
160
+ // Every independent native obligation of the contract. `operationGoals` lists them all (a prompt that orders
161
+ // commit/push AND a script deploy owns both); `operationGoal` stays the primary for older readers. A stale list
162
+ // whose head is not exactly the primary goal (stale after a re-route that only replaced operationGoal) is
163
+ // ignored rather than trusted.
164
+ export function contractOperationGoals(contract) {
165
+ const primary = contract?.operationGoal;
166
+ if (!primary) return [];
167
+ const list = Array.isArray(contract.operationGoals) ? contract.operationGoals.filter((goal) => goal && typeof goal === 'object') : [];
168
+ return list.length > 1 && JSON.stringify(list[0]) === JSON.stringify(primary) ? list.slice(0, 4) : [primary];
169
+ }
170
+
171
+ // A task-owned native mutation attempt (successful or not) for this goal. Completion evidence only: it never
172
+ // gates whether an operation may run, it only separates "attempted, now prove it" from "not yet attempted".
173
+ export function operationAttempted(goal, ledger = {}) {
174
+ if (!goal || !ledger.taskInstanceId || !ledger.sessionKey || !goal.scope) return false;
175
+ return Object.entries(ledger.operationBank || {}).some(([key, entry]) => key !== 'overflow' && key !== 'seenToolUseIds'
176
+ && entry?.mutation?.taskInstanceId === ledger.taskInstanceId && entry.mutation.sessionKey === ledger.sessionKey
177
+ && entry.mutation.operation?.domain === goal.domain && entry.mutation.operation.scope === goal.scope);
178
+ }
179
+
158
180
  export function operationCompletionPolicy(contract, _adapterGoal, ledger) {
159
181
  if (contract?.publication && !contract.operationGoal) return null; // Publication uses the registry-bound release-publication proof.
160
182
  const kind = String(contract?.taskKind || '').toUpperCase();
161
183
  if (!['OPERATIONAL', 'MIXED', 'CONFIGURATION'].includes(kind)
162
184
  || (kind === 'CONFIGURATION' && contract.configurationScope !== 'external')) return null;
163
- return operationEvidenceStatus(contract.operationGoal, ledger) || { complete: false, operationProof: null };
185
+ const goals = contractOperationGoals(contract);
186
+ if (goals.length <= 1) return operationEvidenceStatus(contract.operationGoal, ledger) || { complete: false, operationProof: null };
187
+ // Multi-operation task: each independent goal needs its own proof; one never stands in for another.
188
+ const statuses = goals.map((goal) => ({ goal, status: operationEvidenceStatus(goal, ledger) || { complete: false, operationProof: null } }));
189
+ const unmet = statuses.filter((entry) => entry.status.complete !== true).map((entry) => entry.goal);
190
+ return { complete: unmet.length === 0, operationProof: unmet.length === 0 ? statuses.map((entry) => entry.status.operationProof).join('+') : null,
191
+ unmetGoals: unmet };
164
192
  }
@@ -209,6 +209,8 @@ export function normalizeEvaluatorStdout(stdout) {
209
209
  ...(parsed.outcome === 'blocked' && parsed.complete === false ? { outcome: 'blocked', complete: false } : {}),
210
210
  };
211
211
  }
212
+ // A message-less non-completion release (the finite handback was already delivered) is never a pass.
213
+ if (parsed && parsed.outcome === 'blocked' && parsed.complete === false) return { kind: 'none', outcome: 'blocked', complete: false };
212
214
  return { kind: 'complete' };
213
215
  }
214
216
 
@@ -2258,7 +2260,10 @@ export async function ownerStopState({ projectRoot, payload = {} } = {}) {
2258
2260
  try {
2259
2261
  const route = JSON.parse(await fs.readFile(path.join(projectRoot, '.ukit/storage/cache/route-state', `${safe}.json`), 'utf8'));
2260
2262
  if (String(route?.sessionId || '').trim() !== String(sessionId).trim()) return { active: false };
2261
- if (route.routePublicationIncomplete === true) return { active: false };
2263
+ // An incomplete publication fails closed for COMPLETION (no task identity is trusted), but the owner STOP it
2264
+ // carries is honoured: the pending marker is written with the standing STOP so an interrupted publication
2265
+ // cannot lift it. Only a marker that itself carries the STOP keeps it active.
2266
+ if (route.routePublicationIncomplete === true && route?.ownerControl?.kind !== 'stop') return { active: false };
2262
2267
  return route?.ownerControl?.kind === 'stop' ? { active: true, control: route.ownerControl } : { active: false };
2263
2268
  } catch {
2264
2269
  return { active: false };
@@ -16,6 +16,7 @@ import {
16
16
  evidencePromptKey,
17
17
  incrementContinuation,
18
18
  markNotified,
19
+ markHandback,
19
20
  readExecutionLedger,
20
21
  readRouteState,
21
22
  ownerStopActive,
@@ -1119,6 +1120,17 @@ export async function runBeforeAgentStart(pi, event, { projectRoot, context: ext
1119
1120
  // advisory refresh — routing continues on the previously recorded model
1120
1121
  }
1121
1122
  const metadata = runtimeMetadata(event, extensionContext);
1123
+ // Turn evidence for the UNKNOWN-ownership stop lanes: this is the bridge's only
1124
+ // signal that a NEW logical turn started. A session_stop arriving later can be
1125
+ // called "the same stop" only if NO before_agent_start fired since its block.
1126
+ try {
1127
+ const turnKey = unknownOwnershipTurnKey(projectRoot, metadata.sessionId);
1128
+ // Process-wide monotonic sequence: an evicted-then-reinserted key always receives a
1129
+ // value above any count recorded before eviction, so eviction can never masquerade
1130
+ // as "no new turn" (see unknownOwnershipRepeat).
1131
+ unknownOwnershipTurnSeq += 1;
1132
+ boundedSet(unknownOwnershipTurnCounts, turnKey, unknownOwnershipTurnSeq);
1133
+ } catch { /* evidence unavailable → anti-wedge semantics apply */ }
1122
1134
  const payload = buildHookPayload('UserPromptSubmit', {
1123
1135
  prompt: event.prompt,
1124
1136
  promptOrigin: takeOwnContinuation(metadata.sessionId, event.prompt) ? 'system' : promptOriginFromBranch(event.prompt, extensionContext),
@@ -1444,18 +1456,370 @@ async function readStopGateMaxCrashStreaks(projectRoot) {
1444
1456
  // the shared state file (.ukit/storage/cache/stop-coordinator/state.json) stay
1445
1457
  // byte-identical across both engines.
1446
1458
  const STOP_GATE_LOCK_BUDGET_MS = 600;
1459
+ // Finite-exit memory for the UNKNOWN-ownership stop lanes: block ONCE per exact
1460
+ // (session, task identity, cursor bytes, reason), then release an identical repeat
1461
+ // without completion. Properties (user acceptance):
1462
+ // DURABLE — the recorded verdict persists per key, so a host restart (a REAL new
1463
+ // process) still honors it: an identical repeat releases; a restart must not
1464
+ // resurrect the block.
1465
+ // LOGICAL-STOP BY TURN EVIDENCE, not wall-clock — omp has no stop-event id (no
1466
+ // turn linkage between before_agent_start and session_stop), but the bridge
1467
+ // OBSERVES before_agent_start: a stop that arrives after a new turn started is
1468
+ // a genuinely later stop (the continuation turn ran and stopped again with
1469
+ // unchanged evidence → finite exit); a stop with NO intervening turn is the
1470
+ // same logical stop (duplicate callback → RETAIN the block, never consume the
1471
+ // exit). Turn evidence is process-local: a different process has none and
1472
+ // fails anti-wedge (release once, sticky). A release is sticky per signature.
1473
+ // TASK-SCOPED — the key binds the route state's taskInstanceId, falling back to
1474
+ // the cursor's own RunId, then 'no-run'; the signature hashes the FULL cursor
1475
+ // bytes (streamed sha256), so even two legacy cursors without any identity
1476
+ // never share a bound — different bytes are different tasks.
1477
+ // CONSERVATIVE FINGERPRINT — the cursor is streamed in full; a cursor too large
1478
+ // to fingerprint (pathological) is NEVER released in these lanes (block).
1479
+ // OPAQUE — shard file names are sha256(session+task); shard contents are
1480
+ // sha256(reason, cursor hash) plus timestamps: no session/task id, no reason
1481
+ // text and no cursor bytes ever reach disk.
1482
+ // NO CROSS-SESSION LOSS — one shard file per hashed key: a read-modify-write —
1483
+ // even one that proceeds after its lock budget lapses — touches ONLY its own
1484
+ // key's shard, so another session's record can never be lost. The per-key lock
1485
+ // (exclusive create, stale takeover, bounded wait) serializes same-key
1486
+ // writers; atomic rename keeps every write torn-file-free.
1487
+ // BOUNDED — shards are capped (new keys beyond the cap stay in-proc only) and
1488
+ // the in-proc Map is capped as well: the fallback floor is bounded per
1489
+ // process — never a wedge, never unbounded.
1490
+ const UNKNOWN_OWNERSHIP_REPORTED_MAX = 256;
1491
+ const UNKNOWN_OWNERSHIP_CURSOR_HASH_MAX = 8 * 1024 * 1024;
1492
+ const UNKNOWN_OWNERSHIP_CURSOR_CHUNK = 64 * 1024;
1447
1493
  const unknownOwnershipReported = new Map();
1448
- async function unknownOwnershipRepeat(projectRoot, sessionId, reason) {
1449
- let fingerprint = 'no-cursor';
1494
+ const unknownOwnershipStoreQueue = new Map();
1495
+ const unknownOwnershipTurnCounts = new Map();
1496
+ // Turn count observed when the coordinator-up path last emitted a block for a session;
1497
+ // a turn after it means the cached dedupe replay must not swallow the next stop.
1498
+ const coordinatedBlockTurnMark = new Map();
1499
+ // Both in-process turn maps are bounded; eviction is never a wedge (see unknownOwnershipRepeat).
1500
+ const UNKNOWN_OWNERSHIP_STATE_MAX = 256;
1501
+ let unknownOwnershipTurnSeq = 0;
1502
+ function boundedSet(map, key, value) {
1503
+ map.delete(key);
1504
+ map.set(key, value);
1505
+ while (map.size > UNKNOWN_OWNERSHIP_STATE_MAX) map.delete(map.keys().next().value);
1506
+ }
1507
+ let unknownOwnershipTempCounter = 0;
1508
+ // Turn evidence is scoped to the project root AND session: a turn in one repo never
1509
+ // advances another repo's finite exit.
1510
+ function unknownOwnershipTurnKey(projectRoot, sessionId) {
1511
+ return `${projectRoot}\u0000${String(sessionId ?? 'no-session')}`;
1512
+ }
1513
+ // Process-local identity for the turn-evidence comparison: turn counts only mean
1514
+ // something inside the process that observed them.
1515
+ const unknownOwnershipProcessId = crypto.randomBytes(16).toString('hex');
1516
+ function unknownOwnershipStoreKey(sessionId, taskIdentity) {
1517
+ return `${sessionId ?? 'no-session'}\u0000${taskIdentity || 'no-run'}`;
1518
+ }
1519
+ function withUnknownOwnershipStore(projectRoot, mutate) {
1520
+ // Serialize same-host read-modify-write cycles per project root; a failed
1521
+ // previous write must not poison the queue.
1522
+ const prev = unknownOwnershipStoreQueue.get(projectRoot) || Promise.resolve();
1523
+ const next = prev.catch(() => {}).then(mutate);
1524
+ unknownOwnershipStoreQueue.set(projectRoot, next);
1525
+ const purge = () => {
1526
+ if (unknownOwnershipStoreQueue.get(projectRoot) === next) unknownOwnershipStoreQueue.delete(projectRoot);
1527
+ };
1528
+ next.then(purge, purge);
1529
+ return next;
1530
+ }
1531
+ // CREATE-ONLY MARKER PRIMITIVES (no lock, no reclaim). Each marker is published with
1532
+ // link(2) from a fully written temp file: link fails with EEXIST when the name exists, so a
1533
+ // reader sees either no marker or a complete one, and no two creators can both win one name.
1534
+ // Nothing is overwritten and no lock is taken over, so an orphaned lock file cannot wedge a stop.
1535
+ const UNKNOWN_OWNERSHIP_MARKER_DIR = path.join('.ukit', 'storage', 'cache', 'omp-bridge-unknown-markers');
1536
+ const UNKNOWN_OWNERSHIP_MARKER_MAX = 512;
1537
+ const UNKNOWN_OWNERSHIP_TMP_STALE_MS = 60 * 1000;
1538
+ const UNKNOWN_OWNERSHIP_MARKER_RE = /^([0-9a-f]{64})\.([0-9a-f]{64})\.(block|release)$/;
1539
+ const unknownOwnershipMarkerDir = (projectRoot) => path.join(projectRoot, UNKNOWN_OWNERSHIP_MARKER_DIR);
1540
+ const unknownOwnershipMarkerFile = (projectRoot, keyHash, sigHash, kind) => path.join(unknownOwnershipMarkerDir(projectRoot), `${keyHash}.${sigHash}.${kind}`);
1541
+ // Returns true when this call created the marker, false when the name already existed.
1542
+ // Any other error propagates (storage failure) and is never reported as EEXIST.
1543
+ async function createUnknownOwnershipMarker(file, body) {
1544
+ unknownOwnershipTempCounter += 1;
1545
+ const tmp = `${file}.tmp-${process.pid}-${unknownOwnershipTempCounter}-${crypto.randomBytes(6).toString('hex')}`;
1546
+ await fs.promises.writeFile(tmp, body, { flag: 'wx' });
1547
+ try {
1548
+ await fs.promises.link(tmp, file);
1549
+ return true;
1550
+ } catch (error) {
1551
+ if (error?.code === 'EEXIST') return false;
1552
+ throw error;
1553
+ } finally {
1554
+ await fs.promises.rm(tmp, { force: true }).catch(() => {});
1555
+ }
1556
+ }
1557
+ // ENOENT → null (absent). A published marker is whole, so an unparseable body is external
1558
+ // damage: it is reported as FOREIGN ({p:null}) and releases once, never as turn evidence.
1559
+ async function readUnknownOwnershipMarker(file) {
1560
+ let raw;
1561
+ try {
1562
+ raw = await fs.promises.readFile(file, 'utf8');
1563
+ } catch (error) {
1564
+ if (error?.code === 'ENOENT') return null;
1565
+ throw error;
1566
+ }
1567
+ try {
1568
+ const body = JSON.parse(raw);
1569
+ if (body && body.v === 2 && typeof body.p === 'string' && Number.isFinite(body.k)) return body;
1570
+ } catch { /* fall through: foreign */ }
1571
+ return { v: 2, p: null, k: null };
1572
+ }
1573
+ // A published release is sticky. Storage errors are distinct from a missing marker:
1574
+ // inaccessible storage must not trap a cached block indefinitely.
1575
+ async function releaseMarkerExists(projectRoot, keyHash, sigHash) {
1576
+ try {
1577
+ await fs.promises.stat(unknownOwnershipMarkerFile(projectRoot, keyHash, sigHash, 'release'));
1578
+ return true;
1579
+ } catch (error) {
1580
+ if (error?.code === 'ENOENT') return false;
1581
+ throw error;
1582
+ }
1583
+ }
1584
+ // No final marker is ever removed: only temp files from crashed writers are swept once stale.
1585
+ // Capacity is therefore NOT recovered by pruning; at the cap the store stays saturated. A stat-then-unlink prune can delete a marker that
1586
+ // another process recreated under the same hashed name in between (a delayed unlink hits the
1587
+ // successor). The admission threshold is soft: concurrent blocks may exceed it, and releases
1588
+ // bypass it. At capacity a new block is refused and that stop is FAIL-OPEN released. Only temp files are swept, and
1589
+ // their names embed a per-writer random suffix, so no later writer can recreate them.
1590
+ async function reserveUnknownOwnershipSlot(dir) {
1591
+ let names;
1592
+ // A readdir failure propagates (storage error); it is never reported as saturation.
1593
+ names = await fs.promises.readdir(dir);
1594
+ const now = Date.now();
1595
+ let finals = 0;
1596
+ for (const name of names) {
1597
+ if (name.includes('.tmp-')) {
1598
+ const full = path.join(dir, name);
1599
+ try {
1600
+ if (now - (await fs.promises.stat(full)).mtimeMs > UNKNOWN_OWNERSHIP_TMP_STALE_MS) await fs.promises.rm(full, { force: true });
1601
+ } catch { /* raced */ }
1602
+ continue;
1603
+ }
1604
+ if (UNKNOWN_OWNERSHIP_MARKER_RE.test(name)) finals += 1;
1605
+ }
1606
+ // Check-then-create: creators racing at the boundary can each pass this check, so the store may
1607
+ // exceed UNKNOWN_OWNERSHIP_MARKER_MAX by up to the number of concurrent creators. No marker is deleted.
1608
+ return finals < UNKNOWN_OWNERSHIP_MARKER_MAX;
1609
+ }
1610
+ const unknownOwnershipPendingRelease = new Map();
1611
+ const UNKNOWN_OWNERSHIP_PENDING_MAX = 256;
1612
+ async function persistUnknownOwnershipRelease(projectRoot, keyHash, sigHash, k) {
1613
+ const pendingKey = `${projectRoot}\u0000${keyHash}\u0000${sigHash}`;
1614
+ let persisted = false;
1615
+ try {
1616
+ await fs.promises.mkdir(unknownOwnershipMarkerDir(projectRoot), { recursive: true });
1617
+ await createUnknownOwnershipMarker(unknownOwnershipMarkerFile(projectRoot, keyHash, sigHash, 'release'), JSON.stringify({ v: 2, p: unknownOwnershipProcessId, k: k ?? 0 }));
1618
+ persisted = true;
1619
+ } catch { persisted = false; }
1620
+ unknownOwnershipPendingRelease.delete(pendingKey);
1621
+ if (!persisted) {
1622
+ unknownOwnershipPendingRelease.set(pendingKey, k ?? 0);
1623
+ while (unknownOwnershipPendingRelease.size > UNKNOWN_OWNERSHIP_PENDING_MAX) {
1624
+ unknownOwnershipPendingRelease.delete(unknownOwnershipPendingRelease.keys().next().value);
1625
+ }
1626
+ }
1627
+ return persisted;
1628
+ }
1629
+ // Marker-phase decision (create-only, no lock). A .release marker is sticky. A .block marker
1630
+ // written by THIS process decides by turn evidence (moved counter → release; missing or
1631
+ // unchanged → duplicate, block retained). A foreign or unreadable .block releases once.
1632
+ // No .block → create it exclusively; losing the create race re-reads the winner (bounded).
1633
+ async function decideUnknownOwnershipMarkers(projectRoot, keyHash, sigHash, turnKey) {
1634
+ await fs.promises.mkdir(unknownOwnershipMarkerDir(projectRoot), { recursive: true });
1635
+ const blockFile = unknownOwnershipMarkerFile(projectRoot, keyHash, sigHash, 'block');
1636
+ if (await releaseMarkerExists(projectRoot, keyHash, sigHash)) {
1637
+ return { decided: 'repeat', k: unknownOwnershipTurnCounts.get(turnKey) ?? 0, release: false };
1638
+ }
1639
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1640
+ const marker = await readUnknownOwnershipMarker(blockFile);
1641
+ if (marker === null) {
1642
+ const current = unknownOwnershipTurnCounts.get(turnKey) ?? 0;
1643
+ // At the soft admission limit (concurrent creators may overshoot it) no durable record is created and the stop is FAIL-OPEN released: a
1644
+ // saturated store must never wedge a stop behind an endless block, and releasing claims no
1645
+ // completion (cursor untouched). Nothing is pruned, so no existing marker is removed.
1646
+ if (!(await reserveUnknownOwnershipSlot(unknownOwnershipMarkerDir(projectRoot)))) {
1647
+ return { decided: 'degraded', reason: 'saturated', release: false, durable: false };
1648
+ }
1649
+ const created = await createUnknownOwnershipMarker(blockFile, JSON.stringify({ v: 2, p: unknownOwnershipProcessId, k: current }));
1650
+ if (created) return { decided: 'first', k: current, release: false };
1651
+ continue;
1652
+ }
1653
+ if (marker.p === unknownOwnershipProcessId) {
1654
+ const current = unknownOwnershipTurnCounts.get(turnKey);
1655
+ if (current !== undefined && current !== marker.k) return { decided: 'repeat', k: marker.k, release: true };
1656
+ return { decided: 'duplicate', k: marker.k, release: false };
1657
+ }
1658
+ return { decided: 'repeat', k: marker.k ?? 0, release: true };
1659
+ }
1660
+ throw new Error('unknown-ownership marker race did not settle');
1661
+ }
1662
+ // Test-only: drive the verdict directly and bump turn evidence without the router.
1663
+ export function unknownOwnershipTestHooks() {
1664
+ return {
1665
+ repeat: unknownOwnershipRepeat,
1666
+ bumpTurn(projectRoot, sessionId) {
1667
+ unknownOwnershipTurnSeq += 1;
1668
+ boundedSet(unknownOwnershipTurnCounts, unknownOwnershipTurnKey(projectRoot, sessionId), unknownOwnershipTurnSeq);
1669
+ },
1670
+ };
1671
+ }
1672
+ function rememberUnknownOwnership(memKey, entry) {
1673
+ unknownOwnershipReported.set(memKey, entry);
1674
+ if (unknownOwnershipReported.size > UNKNOWN_OWNERSHIP_REPORTED_MAX) {
1675
+ const oldest = unknownOwnershipReported.keys().next().value;
1676
+ if (oldest !== undefined && oldest !== memKey) unknownOwnershipReported.delete(oldest);
1677
+ }
1678
+ }
1679
+ // Full streaming fingerprint: the WHOLE cursor is hashed, so evidence changes are
1680
+ // never invisible because of a prefix cut. A pathologically large cursor is
1681
+ // unfingerprintable → the caller fails conservative (block; never release).
1682
+ async function unknownOwnershipCursorFingerprint(projectRoot) {
1683
+ const cursorPath = path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md');
1684
+ const handle = await fs.promises.open(cursorPath, 'r');
1450
1685
  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;
1686
+ const hash = crypto.createHash('sha256');
1687
+ const chunk = Buffer.alloc(UNKNOWN_OWNERSHIP_CURSOR_CHUNK);
1688
+ let total = 0;
1689
+ let headText = '';
1690
+ for (;;) {
1691
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
1692
+ if (bytesRead === 0) break;
1693
+ const bytes = chunk.subarray(0, bytesRead);
1694
+ hash.update(bytes);
1695
+ if (headText === '') headText = bytes.toString('utf8');
1696
+ total += bytesRead;
1697
+ if (total > UNKNOWN_OWNERSHIP_CURSOR_HASH_MAX) {
1698
+ return { unfingerprintable: true, runId: /^RunId:\s*(\S+)/im.exec(headText)?.[1] || null };
1699
+ }
1700
+ }
1701
+ return { unfingerprintable: false, hash: hash.digest('hex'), runId: /^RunId:\s*(\S+)/im.exec(headText)?.[1] || null };
1702
+ } finally {
1703
+ try { await handle.close(); } catch { /* best effort */ }
1704
+ }
1705
+ }
1706
+ // Degraded releases (cursor too large to fingerprint; store saturated; store unavailable) are
1707
+ // explicit verdicts 'degraded:<reason>' that release with a named notice. They never claim
1708
+ // completion, never touch the cursor, and are never memorized, so they cannot pin a block.
1709
+ const UNKNOWN_DEGRADED_NOTICE = {
1710
+ fingerprint: 'the handoff cursor exceeds the fingerprint bound (8 MiB), so its evidence cannot be proven unchanged',
1711
+ saturated: 'the UNKNOWN repeat store is saturated (512 durable records); capacity does not recover automatically, so this stop is released without a durable record',
1712
+ storage: 'the UNKNOWN repeat store is unavailable (storage error); this stop is released without a durable record',
1713
+ unreadable: 'the handoff cursor exists but cannot be read, so its evidence cannot be checked; this stop is released without a completion claim',
1714
+ };
1715
+ const isUnknownRelease = (verdict) => verdict === 'repeat' || (typeof verdict === 'string' && verdict.startsWith('degraded:'));
1716
+ // A plain repeat proves the evidence is unchanged. A degraded release cannot prove that, so the
1717
+ // notice states the uncertainty instead of asserting that no new evidence exists.
1718
+ function unknownReleaseClause(verdict) {
1719
+ return typeof verdict === 'string' && verdict.startsWith('degraded:')
1720
+ ? 'new evidence could not be verified (degraded release)'
1721
+ : 'no new evidence or authority exists';
1722
+ }
1723
+ function unknownDegradedNotice(verdict) {
1724
+ if (typeof verdict !== 'string' || !verdict.startsWith('degraded:')) return '';
1725
+ const notice = UNKNOWN_DEGRADED_NOTICE[verdict.slice('degraded:'.length)] ?? 'the UNKNOWN repeat store could not decide';
1726
+ return `[UKit] Degraded release (no completion claim): ${notice}.`;
1727
+ }
1728
+ // Returns 'first' (record a block), 'duplicate' (same logical stop — no new turn
1729
+ // since the block: retain the block, do NOT consume the finite exit) or 'repeat'
1730
+ // (a genuinely later stop with unchanged evidence — or already-released evidence,
1731
+ // or a record from another process: release again).
1732
+ async function unknownOwnershipRepeat(projectRoot, sessionId, reason, taskInstanceId = null, { now = Date.now() } = {}) {
1733
+ let fingerprint;
1734
+ try {
1735
+ fingerprint = await unknownOwnershipCursorFingerprint(projectRoot);
1736
+ } catch (error) {
1737
+ // A genuinely absent cursor keeps the shared 'no-cursor' bound. Any other read error (EISDIR,
1738
+ // EACCES, EIO, ...) means the evidence cannot be read: that is a DEGRADED release, never a
1739
+ // label that could be mistaken for an unchanged-evidence repeat.
1740
+ if (error?.code !== 'ENOENT') return 'degraded:unreadable';
1741
+ fingerprint = { unfingerprintable: false, hash: 'no-cursor', runId: null };
1742
+ }
1743
+ // A cursor too large to fingerprint cannot be proven unchanged. It is a DEGRADED release (no
1744
+ // completion claim, cursor untouched) — never an endless block that no repeat can clear.
1745
+ if (fingerprint.unfingerprintable) return 'degraded:fingerprint';
1746
+ // Task identity precedence: route-state taskInstanceId (what the ledger and the
1747
+ // gates bind) → the cursor's own RunId → 'no-run' (the byte hash still isolates).
1748
+ const taskIdentity = taskInstanceId || fingerprint.runId || 'no-run';
1749
+ const storeKey = unknownOwnershipStoreKey(sessionId, taskIdentity);
1750
+ // Opaque on disk: hashed shard name (no raw session/task id) and hashed
1751
+ // signature (no reason text, no cursor bytes).
1752
+ const keyHash = crypto.createHash('sha256').update(storeKey).digest('hex');
1753
+ const sigHash = crypto.createHash('sha256').update(`${reason}\u0000${fingerprint.hash}`).digest('hex');
1754
+ const signature = sigHash;
1755
+ const memKey = `${projectRoot}\u0000${storeKey}`;
1756
+ const turnKey = unknownOwnershipTurnKey(projectRoot, sessionId);
1757
+ // Every decision (memory AND marker) runs inside the per-root queue, so a concurrent
1758
+ // same-process duplicate waits for the first call's memory record.
1759
+ return withUnknownOwnershipStore(projectRoot, async () => {
1760
+ // A release this process already proved but could not persist: retry it first. Whether or
1761
+ // not it lands, the proven release is authoritative for this evidence.
1762
+ const pendingKey = `${projectRoot}\u0000${keyHash}\u0000${sigHash}`;
1763
+ if (unknownOwnershipPendingRelease.has(pendingKey)) {
1764
+ await persistUnknownOwnershipRelease(projectRoot, keyHash, sigHash, unknownOwnershipPendingRelease.get(pendingKey));
1765
+ return 'repeat';
1766
+ }
1767
+ const mem = unknownOwnershipReported.get(memKey);
1768
+ if (mem && mem.s === sigHash) {
1769
+ // Same process → the turn counter is authoritative evidence. A duplicate callback
1770
+ // never mutates the record: the initial block is retained, the exit NOT consumed.
1771
+ if (mem.r === 1) return 'repeat'; // sticky: this evidence was already released
1772
+ const turns = unknownOwnershipTurnCounts.get(turnKey);
1773
+ // A MISSING counter is unknown evidence (bounded state evicted it), never proof of a
1774
+ // new turn: retain the block and do not consume the exit. A real turn re-inserts the
1775
+ // counter with a process-wide sequence value that differs from mem.k, so it releases.
1776
+ if (turns !== undefined && turns !== mem.k) {
1777
+ rememberUnknownOwnership(memKey, { s: signature, t: mem.t, r: 1, k: turns }); // sticky release
1778
+ await persistUnknownOwnershipRelease(projectRoot, keyHash, sigHash, turns); // survive memory eviction
1779
+ return 'repeat'; // a turn ran since the block: genuinely later stop
1780
+ }
1781
+ // P0 stale-cached-block fix: while this r:0 record was cached, ANOTHER bridge
1782
+ // instance may have durably released this exact evidence (a .release marker is
1783
+ // create-once-sticky, so its presence proves a prior release decision). The
1784
+ // durable release outranks this process's cached block — without this check the
1785
+ // cached block would override it forever, because no turn can advance this
1786
+ // process's counter while the host idles. Adopt the durable release as sticky.
1787
+ try {
1788
+ if (await releaseMarkerExists(projectRoot, keyHash, sigHash)) {
1789
+ rememberUnknownOwnership(memKey, { s: signature, t: mem.t, r: 1, k: mem.k });
1790
+ return 'repeat';
1791
+ }
1792
+ } catch {
1793
+ return 'degraded:storage';
1794
+ }
1795
+ return 'duplicate'; // no new turn: same logical stop → retain the block
1796
+ }
1797
+ // No process-local record: consult the durable markers (possibly written by another
1798
+ // process). Turn evidence does not survive processes, so a foreign record releases once.
1799
+ // Storage failure or capacity saturation is FAIL-OPEN: release without durable state, so
1800
+ // a broken or full store can never hold a stop open. Release claims no completion.
1801
+ let k = unknownOwnershipTurnCounts.get(turnKey) ?? 0;
1802
+ try {
1803
+ const outcome = await decideUnknownOwnershipMarkers(projectRoot, keyHash, sigHash, turnKey);
1804
+ // Degraded verdicts are never memorized: they release explicitly and pin nothing.
1805
+ if (outcome.decided === 'degraded') return `degraded:${outcome.reason}`;
1806
+ if (outcome.k !== undefined) k = outcome.k;
1807
+ if (outcome.release) await persistUnknownOwnershipRelease(projectRoot, keyHash, sigHash, k);
1808
+ const verdict = outcome.decided;
1809
+ rememberUnknownOwnership(memKey, { s: signature, t: now, r: verdict === 'repeat' ? 1 : 0, k });
1810
+ return verdict;
1811
+ } catch {
1812
+ return 'degraded:storage';
1813
+ }
1814
+ });
1815
+ }
1816
+
1817
+ // Test-only observability for the bounded in-process state (sizes, never contents).
1818
+ export function unknownOwnershipStateSizesForTest() {
1819
+ return { turns: unknownOwnershipTurnCounts.size, marks: coordinatedBlockTurnMark.size, reported: unknownOwnershipReported.size };
1820
+ }
1821
+ export function unknownOwnershipMarkForTest(projectRoot, sessionId) {
1822
+ return coordinatedBlockTurnMark.get(unknownOwnershipTurnKey(projectRoot, sessionId)) ?? null;
1459
1823
  }
1460
1824
 
1461
1825
  const HANDOFF_PROVENANCE_PREFIX = '[ukit-stop-coordinator] handoff-cursor also requested a block: ';
@@ -1531,9 +1895,20 @@ export async function runSessionStop(
1531
1895
  pi.logger?.warn?.(`[UKit] stop-coordinator module unavailable (dedupe + handoff lanes skipped): ${error?.message || error}`);
1532
1896
  }
1533
1897
  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.'}`);
1898
+ if (ownerStopActive(state, payload)) {
1899
+ // The STOP marker is read from the route state (execution-ledger), not from the
1900
+ // coordinator — an unloadable coordinator module must not turn an explicit owner
1901
+ // STOP into an endless gate. `releaseForOwnerStop` (cursor → PAUSED) is a
1902
+ // best-effort side effect: without the coordinator the stop is still released,
1903
+ // the cursor stays untouched and nothing completed or resumed.
1904
+ if (coordinator) {
1905
+ const released = await coordinator.releaseForOwnerStop({ projectRoot, payload });
1906
+ pi.logger?.warn?.(`[UKit] ${released?.systemMessage ?? 'stop allowed: the owner requested STOP; nothing completed or resumed.'}`);
1907
+ } else {
1908
+ pi.logger?.warn?.('[UKit] stop allowed: the owner requested STOP (stop-coordinator module unavailable; the run cursor could not be marked PAUSED). Nothing completed or resumed; no continuation or further automatic turn is scheduled.');
1909
+ }
1910
+ // A released owner STOP is not replayable authority: clear the turn mark (same rule as finish).
1911
+ coordinatedBlockTurnMark.delete(unknownOwnershipTurnKey(projectRoot, payload.session_id));
1537
1912
  return undefined;
1538
1913
  }
1539
1914
  const ledger = suppliedLedger ?? await readExecutionLedger(projectRoot, payload) ?? {};
@@ -1542,9 +1917,16 @@ export async function runSessionStop(
1542
1917
  const initialInput = coordinator
1543
1918
  ? await coordinator.stopCoordinationInput({ projectRoot, payload, authority: authority() }) : null;
1544
1919
  const key = initialInput ? `omp:${initialInput.key}` : null;
1920
+ // Turn evidence overrides the coordinator's wall-clock dedupe: once a turn has run
1921
+ // since this session's last coordinated block, the cached block is a stale replay of
1922
+ // an EARLIER logical stop and must not swallow the new one (window forced to zero).
1923
+ const turnKeyForDedupe = unknownOwnershipTurnKey(projectRoot, payload.session_id);
1924
+ const turnsSinceBlock = (unknownOwnershipTurnCounts.get(turnKeyForDedupe) || 0) - (coordinatedBlockTurnMark.get(turnKeyForDedupe) ?? 0);
1925
+ const effectiveDedupeMs = coordinatedBlockTurnMark.has(turnKeyForDedupe) && turnsSinceBlock > 0
1926
+ ? 0 : (dedupeWindowMs ?? coordinator?.DEDUPE_WINDOW_MS);
1545
1927
  if (coordinator && await coordinator.alreadyCoordinatedThisStop({
1546
1928
  projectRoot, sessionKey: key, now,
1547
- dedupeWindowMs: dedupeWindowMs ?? coordinator.DEDUPE_WINDOW_MS,
1929
+ dedupeWindowMs: effectiveDedupeMs,
1548
1930
  lockBudgetMs, replayOnlyBlocked: true, claimToken,
1549
1931
  })) {
1550
1932
  try {
@@ -1558,6 +1940,16 @@ export async function runSessionStop(
1558
1940
  if (output && (output.continue === true || output.decision === 'block')) {
1559
1941
  rememberOwnContinuation(payload.session_id, output.additionalContext ?? output.reason);
1560
1942
  }
1943
+ // Mark the turn count at every coordinated continuation (block AND continue:true —
1944
+ // the coordinator stores both as a replayable 'block' decision) so a later turn can be
1945
+ // told apart from a duplicate callback of this same stop (see effectiveDedupeMs above).
1946
+ // A release clears the mark: a released stop is not a replayable authority.
1947
+ const markKey = unknownOwnershipTurnKey(projectRoot, payload.session_id);
1948
+ if (output && (output.continue === true || output.decision === 'block')) {
1949
+ boundedSet(coordinatedBlockTurnMark, markKey, unknownOwnershipTurnCounts.get(markKey) || 0);
1950
+ } else {
1951
+ coordinatedBlockTurnMark.delete(markKey);
1952
+ }
1561
1953
  if (coordinator) {
1562
1954
  const evaluatedInput = await coordinator.stopCoordinationInput({ projectRoot, payload, authority: authority() });
1563
1955
  await coordinator.publishStopDecision({
@@ -1612,15 +2004,19 @@ export async function runSessionStop(
1612
2004
  } catch { /* unreadable intent evidence keeps ownership UNKNOWN */ }
1613
2005
  }
1614
2006
  if (cursorActive && ownership.status === 'UNKNOWN') {
1615
- if (await unknownOwnershipRepeat(projectRoot, payload.session_id, ownership.reason)) {
2007
+ const unknownVerdict = await unknownOwnershipRepeat(projectRoot, payload.session_id, ownership.reason, state?.taskInstanceId, { now });
2008
+ if (isUnknownRelease(unknownVerdict)) {
1616
2009
  sendContext(pi, [
1617
- `[UKit] Handoff ownership is still UNKNOWN (${ownership.reason}) and no new evidence or authority exists. `
2010
+ unknownDegradedNotice(unknownVerdict),
2011
+ `[UKit] Handoff ownership is still UNKNOWN (${ownership.reason}) and ${unknownReleaseClause(unknownVerdict)}. `
1618
2012
  + 'Stop released without completion: the handoff cursor, its tasks and ownership were NOT changed, '
1619
2013
  + 'and unfinished work stays unfinished until an owner request or a proven owning session resumes it.',
1620
2014
  ], 'nextTurn', { display: true });
1621
2015
  await recordEpisode();
1622
2016
  return finish(undefined);
1623
2017
  }
2018
+ // 'first' records the block; 'duplicate' is the same logical stop again —
2019
+ // it retains the initial block instead of consuming the finite exit.
1624
2020
  return finish({ decision: 'block', reason: `UKit handoff ownership UNKNOWN (${ownership.reason}); completion is unproven. Reconcile provenance before stopping.` });
1625
2021
  }
1626
2022
  handoff = await coordinator.evaluateHandoffCursor({
@@ -1633,8 +2029,9 @@ export async function runSessionStop(
1633
2029
  } catch (error) {
1634
2030
  pi.logger?.warn?.(`[UKit] handoff-cursor evaluator failed: ${error?.message || error}`);
1635
2031
  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 });
2032
+ const failureVerdict = await unknownOwnershipRepeat(projectRoot, payload.session_id, `evaluation failed: ${error?.message || error}`, state?.taskInstanceId, { now });
2033
+ if (isUnknownRelease(failureVerdict)) {
2034
+ sendContext(pi, ['[UKit] Handoff provenance evaluation still fails; stop released without completion and without touching the handoff cursor (unproven, unfinished work preserved).', unknownDegradedNotice(failureVerdict)], 'nextTurn', { display: true });
1638
2035
  await recordEpisode();
1639
2036
  return finish(undefined);
1640
2037
  }
@@ -1642,6 +2039,23 @@ export async function runSessionStop(
1642
2039
  }
1643
2040
  }
1644
2041
  } else if (cursorActive) {
2042
+ // Same finite lifecycle as the two UNKNOWN lanes above: an unloadable
2043
+ // coordinator is an infrastructure failure, not proof of an owner — block once,
2044
+ // then release an identical repeat WITHOUT completion and without touching the
2045
+ // cursor, so a broken module can never wedge a session behind an endless gate.
2046
+ const downVerdict = await unknownOwnershipRepeat(projectRoot, payload.session_id, 'stop coordinator unavailable', state?.taskInstanceId, { now });
2047
+ if (isUnknownRelease(downVerdict)) {
2048
+ sendContext(pi, [
2049
+ unknownDegradedNotice(downVerdict),
2050
+ `[UKit] Handoff ownership is still UNKNOWN (stop coordinator unavailable) and ${unknownReleaseClause(downVerdict)}. `
2051
+ + 'Stop released without completion: the handoff cursor, its tasks and ownership were NOT changed, '
2052
+ + 'and unfinished work stays unfinished until an owner request or a proven owning session resumes it. '
2053
+ + 'Run `ukit install` to repair the runtime.',
2054
+ ], 'nextTurn', { display: true });
2055
+ await recordEpisode();
2056
+ return finish(undefined);
2057
+ }
2058
+ // 'first' records the block; 'duplicate' retains it (same logical stop).
1645
2059
  return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: stop coordinator unavailable; completion is unproven.' });
1646
2060
  }
1647
2061
  const handoffBlock = handoff?.kind === 'block' ? handoff.reason : null;
@@ -1687,6 +2101,11 @@ export async function runSessionStop(
1687
2101
  await resetCompletionCrashStreak(projectRoot);
1688
2102
  if (!evaluation.continue) {
1689
2103
  if (evaluation.capped) pi.logger?.warn?.(`[UKit] ${evaluation.reason}`);
2104
+ // Finite handback: record the one handback per task state; a later Stop at the same state is silent.
2105
+ if (suppliedLedger === undefined && (evaluation.outcome === 'handback' || evaluation.capped === true)
2106
+ && evaluation.gateRelease !== 'handback-delivered') {
2107
+ try { await markHandback(projectRoot, payload, evaluation, { deadlineMs: lockBudgetMs }); } catch { /* repeats one handback at most */ }
2108
+ }
1690
2109
  const missingEvidence = Array.isArray(evaluation.missingEvidence) ? evaluation.missingEvidence : [];
1691
2110
  // The visible-blocker exit (verification loop) carries no missingEvidence but must still
1692
2111
  // reach the user — a silent release is indistinguishable from a stall.
@@ -1718,8 +2137,10 @@ export async function runSessionStop(
1718
2137
  try {
1719
2138
  // TASK-007 (OMP-2a): the 600ms lock budget — a contended ledger lock must
1720
2139
  // never hold the omp host near its hook deadline.
1721
- if (evaluation.finalNotice) await markNotified(projectRoot, payload, ledger, { deadlineMs: lockBudgetMs });
1722
- else await incrementContinuation(projectRoot, payload, ledger, state?.requestKey || null, evidencePromptKey(state), { deadlineMs: lockBudgetMs });
2140
+ const marker = { stateFp: evaluation.stateFingerprint, taskKey: evaluation.handbackKey,
2141
+ opOnly: evaluation.missingEvidence?.length > 0 && evaluation.missingEvidence.every((item) => item === 'operation-verification') };
2142
+ if (evaluation.finalNotice) await markNotified(projectRoot, payload, ledger, { deadlineMs: lockBudgetMs, ...marker });
2143
+ else await incrementContinuation(projectRoot, payload, ledger, state?.requestKey || null, evidencePromptKey(state), { deadlineMs: lockBudgetMs, ...marker });
1723
2144
  } catch (error) {
1724
2145
  pi.logger?.warn?.(`[UKit] continuation bookkeeping failed open: ${error?.message || error}`);
1725
2146
  }