@ngockhoale/ukit 3.4.73 → 3.4.74

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.
@@ -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:
@@ -1664,19 +1702,26 @@ async function bumpHandoffStallCount({ projectRoot, signature, lockBudgetMs, sna
1664
1702
  *
1665
1703
  * Advisory lane: EVERY failure path returns { kind: 'none' }, never throws.
1666
1704
  */
1667
- export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot, now = Date.now(), lockBudgetMs = LOCK_BUDGET_MS, transcriptPath = null, stopHookActive = false, completionKind = null } = {}) {
1705
+ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot, now = Date.now(), lockBudgetMs = LOCK_BUDGET_MS, transcriptPath = null, stopHookActive = false, completionKind = null, ownership = null } = {}) {
1668
1706
  // `runRoot` is the checkout whose RUN.md cursor this session may be held to: the
1669
1707
  // git-verified linked worktree when the session runs in one, else `projectRoot`.
1670
1708
  // Policy (gate config) stays with `projectRoot`; the cursor, its exit predicate
1671
1709
  // and its stall state are per-checkout.
1672
1710
  const gate = await loadHandoffGateConfig(projectRoot);
1673
1711
  if (!gate.enabled) return { kind: 'none' };
1674
-
1675
1712
  let text;
1676
1713
  try {
1677
1714
  text = await fs.readFile(path.join(runRoot, 'docs', 'AI_HANDOFF', 'RUN.md'), 'utf8');
1678
- } catch {
1679
- return { kind: 'none' };
1715
+ } catch (error) {
1716
+ if (error.code === 'ENOENT') return { kind: 'none' };
1717
+ return { kind: 'advisory', blockedOutcome: true, systemMessage: '[ukit-stop-coordinator] handoff cursor unreadable; ownership UNKNOWN. Report BLOCKED.' };
1718
+ }
1719
+ // This evaluator can mutate stall state and pause the cursor. Historical
1720
+ // transcript commands do not authorize those mutations.
1721
+ if (ownership?.status !== 'OWNED') {
1722
+ return ownership?.status === 'NOT_OWNED'
1723
+ ? { kind: 'none' }
1724
+ : { kind: 'advisory', blockedOutcome: true, systemMessage: '[ukit-stop-coordinator] handoff ownership UNKNOWN; cursor was not changed. Report BLOCKED and reconcile provenance.' };
1680
1725
  }
1681
1726
  const { command, goal, phase, cursor, next, exitPredicate, goalScope, scopeQueue, cycle: cycleField } = parseRunCursor(text);
1682
1727
  // Shared terminal predicate — tests/handoff/cycle21 greps this exact shape across
@@ -1693,7 +1738,8 @@ export async function evaluateHandoffCursor({ projectRoot, runRoot = projectRoot
1693
1738
  // Session scope: a run owned by another session must not hijack an unrelated session. Decided
1694
1739
  // before pause and before every `done` branch, so a non-owner session never receives the pause
1695
1740
  // advisory. Only a positive "not fullstack" releases; unknown (null) keeps the block.
1696
- const transcriptOwner = gate.scope === 'session' ? await transcriptShowsHandoffRun(transcriptPath) : true;
1741
+ const transcriptOwner = ownership?.status === 'OWNED' ? true
1742
+ : gate.scope === 'session' ? await transcriptShowsHandoffRun(transcriptPath) : true;
1697
1743
  if (gate.scope === 'session' && transcriptOwner === false) {
1698
1744
  return { kind: 'none' };
1699
1745
  }
@@ -2402,6 +2448,16 @@ export async function stopCoordinationInput({ projectRoot, payload = {}, authori
2402
2448
  'docs/AI_HANDOFF/tasks',
2403
2449
  ].map((input) => path.join(projectRoot, input));
2404
2450
  if (payload.transcript_path) inputs.push(payload.transcript_path);
2451
+ // Binding changes are authority changes even if the cursor and route did not
2452
+ // change. Hash the binding named by the cursor; never replay across it.
2453
+ try {
2454
+ const cursor = await fs.readFile(path.join(await resolveRunRoot(projectRoot, payload?.cwd), 'docs/AI_HANDOFF/RUN.md'), 'utf8');
2455
+ const runId = /^RunId:\s*(\S+)\s*$/im.exec(cursor)?.[1];
2456
+ if (runId) {
2457
+ const { provenancePath } = await import('./handoff-provenance.mjs');
2458
+ inputs.push(provenancePath(projectRoot, runId));
2459
+ }
2460
+ } catch { /* no readable cursor: the ordinary input currency remains conservative */ }
2405
2461
  async function stopInputKey() {
2406
2462
  const hash = crypto.createHash('sha256');
2407
2463
  const currency = crypto.createHash('sha256');
@@ -2549,7 +2605,15 @@ export async function runStopCoordinator({
2549
2605
  extraText: payload?.error != null ? JSON.stringify(payload.error) : '',
2550
2606
  });
2551
2607
  if (quotaSignal) {
2552
- const pause = await markRunCursorPaused(await resolveRunRoot(projectRoot, payload?.cwd));
2608
+ const runRoot = await resolveRunRoot(projectRoot, payload?.cwd);
2609
+ let ownership;
2610
+ try {
2611
+ const { resolveCursorApplicability } = await import('./handoff-provenance.mjs');
2612
+ ownership = await resolveCursorApplicability({ projectRoot, runRoot, sessionId: explicitSession });
2613
+ } catch {
2614
+ ownership = { status: 'UNKNOWN', reason: 'handoff provenance runtime unavailable' };
2615
+ }
2616
+ const pause = ownership.status === 'OWNED' ? await markRunCursorPaused(runRoot) : null;
2553
2617
  return {
2554
2618
  skip: null,
2555
2619
  merged: {
@@ -2562,9 +2626,11 @@ export async function runStopCoordinator({
2562
2626
  terminalOutcome: 'WAIT_FOR_APPROVAL',
2563
2627
  systemMessage:
2564
2628
  `[ukit-stop-coordinator] stop released: a provider quota/rate-limit signal ("${quotaSignal}") ` +
2565
- `was detected. ` + (pause.ok
2629
+ `was detected. ` + (pause?.ok
2566
2630
  ? 'The run cursor is marked PAUSED; nothing was resumed or completed. '
2567
- : 'No RUN.md cursor found to pause; nothing was resumed or completed. ')
2631
+ : ownership.status !== 'OWNED'
2632
+ ? `The run cursor was not changed (ownership ${ownership.status}: ${ownership.reason}); nothing was resumed or completed. `
2633
+ : 'The run cursor could not be paused; nothing was resumed or completed. ')
2568
2634
  + 'Continue in a NEW message (or /ukit:handoff-fullstack) once the quota resets.',
2569
2635
  policyOwner: 'quota-pause',
2570
2636
  policies: ['quota-pause'],
@@ -2582,7 +2648,18 @@ export async function runStopCoordinator({
2582
2648
  try {
2583
2649
  const state = JSON.parse(await fs.readFile(path.join(projectRoot, '.ukit/storage/cache/stop-coordinator/state.json'), 'utf8'));
2584
2650
  const decision = state.stopClaims?.[dedupeKey]?.decision;
2585
- if (decision?.decision === 'block') return { skip: null, merged: decision };
2651
+ if (decision?.decision === 'block') {
2652
+ if (decision.terminalCompletionBlocked !== true || decision.policyOwner !== 'task-watchdog') return { skip: null, merged: decision };
2653
+ // A watchdog block over terminal completion is still a Stop attempt. Count it in the same
2654
+ // no-progress breaker as freshly evaluated decisions; otherwise a fast
2655
+ // reentrant chain can replay one block forever without advancing it.
2656
+ try {
2657
+ const loop = await import('./loop-state.mjs');
2658
+ const merged = await loop.applyLoopBreak({ merged: decision, projectRoot, runRoot: await resolveRunRoot(projectRoot, payload?.cwd), payload, sessionKey, now, lockBudgetMs });
2659
+ if (merged.loopBreak === true) merged.terminalOutcome = 'BLOCKED_AND_STOP';
2660
+ return { skip: null, merged };
2661
+ } catch { return { skip: null, merged: decision }; }
2662
+ }
2586
2663
  } catch { /* an in-flight/failed first call cannot authorize completion */ }
2587
2664
  return { skip: null, merged: { decision: 'block',
2588
2665
  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 +2676,33 @@ export async function runStopCoordinator({
2599
2676
  process.stderr.write(`[ukit-stop-coordinator] completion evaluator failed: ${failures.completion}\n`);
2600
2677
  }
2601
2678
 
2679
+ const runRoot = await resolveRunRoot(projectRoot, payload?.cwd);
2680
+ let ownership;
2681
+ try {
2682
+ const { resolveCursorApplicability } = await import('./handoff-provenance.mjs');
2683
+ ownership = await resolveCursorApplicability({ projectRoot, runRoot, sessionId: explicitSession });
2684
+ } catch {
2685
+ ownership = { status: 'UNKNOWN', reason: 'handoff provenance runtime unavailable' };
2686
+ }
2687
+ if (ownership.reason === 'run cursor absent') {
2688
+ try {
2689
+ const watchdogRuntime = await import('./task-watchdog.mjs');
2690
+ const tasks = await watchdogRuntime.listInProgressTasks(projectRoot);
2691
+ if (tasks.length) ownership = { status: 'UNKNOWN', reason: 'watchdog tasks exist without a run cursor' };
2692
+ } catch {
2693
+ ownership = { status: 'UNKNOWN', reason: 'watchdog task inventory unavailable' };
2694
+ }
2695
+ }
2602
2696
  let watchdog = null;
2603
2697
  try {
2604
2698
  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
- });
2699
+ // Evaluating the watchdog writes anchors and hard-trip counters; do not
2700
+ // enter it until the cursor's binding proves this task owns that run.
2701
+ watchdog = ownership.status === 'OWNED'
2702
+ ? await watchdogRuntime.evaluateStopWatchdog({
2703
+ projectRoot, now, lockBudgetMs, cycle: await readRunCycle(runRoot),
2704
+ })
2705
+ : { kind: 'none' };
2611
2706
  } catch (error) {
2612
2707
  failures.watchdog = error?.message || String(error);
2613
2708
  process.stderr.write(`[ukit-stop-coordinator] task-watchdog evaluator failed: ${failures.watchdog}\n`);
@@ -2615,15 +2710,18 @@ export async function runStopCoordinator({
2615
2710
 
2616
2711
  let handoff = null;
2617
2712
  try {
2618
- handoff = await evaluateHandoffCursor({
2713
+ handoff = ownership.status === 'OWNED' ? await evaluateHandoffCursor({
2619
2714
  projectRoot,
2620
- runRoot: await resolveRunRoot(projectRoot, payload?.cwd),
2715
+ runRoot,
2621
2716
  now,
2622
2717
  lockBudgetMs,
2623
2718
  transcriptPath: typeof payload?.transcript_path === 'string' ? payload.transcript_path : null,
2624
2719
  stopHookActive: payload?.stop_hook_active === true,
2625
2720
  completionKind: completion?.kind ?? null,
2626
- });
2721
+ ownership,
2722
+ }) : ownership.status === 'UNKNOWN' && ownership.reason !== 'run cursor absent'
2723
+ ? { 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.` }
2724
+ : { kind: 'none' };
2627
2725
  } catch (error) {
2628
2726
  failures.handoff = error?.message || String(error);
2629
2727
  process.stderr.write(`[ukit-stop-coordinator] handoff-cursor evaluator failed: ${failures.handoff}\n`);
@@ -2640,6 +2738,8 @@ export async function runStopCoordinator({
2640
2738
  } catch { /* advisory lane: an unreadable breaker never changes the stop verdict */ }
2641
2739
 
2642
2740
  let merged = coordinateStopDecisions({ completion, watchdog, handoff, failures });
2741
+ if (completion?.outcome === 'blocked' && completion?.complete === false) merged.terminalCompletionBlocked = true;
2742
+ if (ownership.status === 'UNKNOWN' && ownership.reason !== 'run cursor absent' && merged.decision !== 'block') merged.blockedOutcome = true;
2643
2743
 
2644
2744
  // Reconcile BEFORE the loop-breaker so a conflicting block is already released when
2645
2745
  // the loop detector looks at the decision (the loop-state lane independently ignores
@@ -2811,7 +2911,7 @@ async function main() {
2811
2911
  }
2812
2912
  if (merged.systemMessage) {
2813
2913
  writeDecisionLine({ systemMessage: merged.systemMessage, policyOwner: merged.policyOwner,
2814
- ...(merged.blockedOutcome ? { outcome: 'blocked', complete: false, continue: false } : {}),
2914
+ ...(merged.blockedOutcome ? { outcome: 'blocked', complete: false } : {}),
2815
2915
  });
2816
2916
  }
2817
2917
  // Neither → silent release: both policies decided "complete".
@@ -1468,17 +1468,50 @@ export async function runSessionStop(
1468
1468
  // cursor's Next: line is the continuation instruction. Advisory on failure,
1469
1469
  // bounded by the stopGateMaxStalledBlocks breaker (always advances post-S3).
1470
1470
  let handoff = null;
1471
+ let cursorActive = false;
1472
+ try {
1473
+ const cursor = await fs.promises.readFile(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8');
1474
+ const phase = /^Phase:\s*(\S+)/im.exec(cursor)?.[1];
1475
+ cursorActive = !phase || !/^(done|blocked)\b/i.test(phase);
1476
+ } catch (error) {
1477
+ cursorActive = error.code !== 'ENOENT';
1478
+ }
1471
1479
  if (coordinator) {
1472
1480
  try {
1481
+ const { resolveCursorApplicability } = await import('../../../.claude/ukit/runtime/handoff-provenance.mjs');
1482
+ let ownership = await resolveCursorApplicability({ projectRoot, sessionId: payload.session_id });
1483
+ // A session that never published a route AND whose whole transcript (and its
1484
+ // delegation parents) shows no handoff intent cannot be the claimant: omp has
1485
+ // no turn id linking before_agent_start to session_stop, so absence of a route
1486
+ // alone cannot tell an ordinary session from an interrupted claimant. The
1487
+ // transcript is an INTENT signal only — it can release a non-claimant, never
1488
+ // grant ownership. Any intent, unknown scan or unreadable parent stays UNKNOWN.
1489
+ if (cursorActive && ownership.status === 'UNKNOWN' && ownership.reason === 'route identity unavailable'
1490
+ && typeof payload.transcript_path === 'string' && payload.transcript_path) {
1491
+ try {
1492
+ const intentMod = await import('../../../.claude/ukit/runtime/handoff-intent.mjs');
1493
+ const scan = await intentMod.transcriptHandoffIntentInherited(payload.transcript_path);
1494
+ if (scan.known && !scan.intent && !scan.unresolvedParent) {
1495
+ ownership = { status: 'NOT_OWNED', reason: 'no route and no handoff intent in session transcript' };
1496
+ }
1497
+ } catch { /* unreadable intent evidence keeps ownership UNKNOWN */ }
1498
+ }
1499
+ if (cursorActive && ownership.status === 'UNKNOWN') {
1500
+ return finish({ decision: 'block', reason: `UKit handoff ownership UNKNOWN (${ownership.reason}); completion is unproven. Reconcile provenance before stopping.` });
1501
+ }
1473
1502
  handoff = await coordinator.evaluateHandoffCursor({
1474
1503
  projectRoot,
1504
+ ownership,
1475
1505
  now,
1476
1506
  lockBudgetMs,
1477
1507
  transcriptPath: typeof payload.transcript_path === 'string' ? payload.transcript_path : null,
1478
1508
  });
1479
1509
  } catch (error) {
1480
- pi.logger?.warn?.(`[UKit] handoff-cursor evaluator failed (advisory lane): ${error?.message || error}`);
1510
+ 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.' });
1481
1512
  }
1513
+ } else if (cursorActive) {
1514
+ return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: stop coordinator unavailable; completion is unproven.' });
1482
1515
  }
1483
1516
  const handoffBlock = handoff?.kind === 'block' ? handoff.reason : null;
1484
1517
  // A breaker-release advisory (or any handoff systemMessage) is the omp