@ngockhoale/ukit 3.4.73 → 3.4.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/manifests/documentation.yaml +10 -0
- package/manifests/platform.full.yaml +15 -0
- package/package.json +4 -1
- package/template_project/.claude/commands/ukit/handoff-fullstack.md +34 -12
- package/template_project/.claude/hooks/completion-gate.sh +10 -1
- package/template_project/.claude/hooks/handoff-resume.sh +38 -53
- package/template_project/.claude/hooks/owner-stop-gate.mjs +41 -0
- package/template_project/.claude/hooks/skill-router.sh +473 -36
- package/template_project/.claude/hooks/verification-guard.sh +8 -1
- package/template_project/.claude/settings.json +33 -1
- package/template_project/.claude/ukit/index/publication-intent.mjs +128 -13
- package/template_project/.claude/ukit/index/route-task.mjs +124 -26
- package/template_project/.claude/ukit/runtime/block-breaker.mjs +1 -0
- package/template_project/.claude/ukit/runtime/compact-threshold.mjs +8 -1
- package/template_project/.claude/ukit/runtime/cron-operation-adapter.mjs +14 -5
- package/template_project/.claude/ukit/runtime/execution-ledger.mjs +399 -35
- package/template_project/.claude/ukit/runtime/handoff-intent.mjs +5 -0
- package/template_project/.claude/ukit/runtime/handoff-provenance.mjs +277 -0
- package/template_project/.claude/ukit/runtime/loop-state.mjs +23 -4
- package/template_project/.claude/ukit/runtime/operation-evidence.mjs +9 -0
- package/template_project/.claude/ukit/runtime/reinject-context.mjs +10 -0
- package/template_project/.claude/ukit/runtime/resumable-run.mjs +33 -11
- package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +284 -58
- package/template_project/.omp/hooks/pre/ukit-bridge.js +171 -3
- package/scripts/dev/worktree-preflight.mjs +0 -166
- package/scripts/measure-decision-gateway.mjs +0 -306
- package/scripts/probe/codex-capability-probe.mjs +0 -169
|
@@ -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({
|
|
@@ -1468,17 +1583,66 @@ export async function runSessionStop(
|
|
|
1468
1583
|
// cursor's Next: line is the continuation instruction. Advisory on failure,
|
|
1469
1584
|
// bounded by the stopGateMaxStalledBlocks breaker (always advances post-S3).
|
|
1470
1585
|
let handoff = null;
|
|
1586
|
+
let cursorActive = false;
|
|
1587
|
+
try {
|
|
1588
|
+
const cursor = await fs.promises.readFile(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8');
|
|
1589
|
+
const phase = /^Phase:\s*(\S+)/im.exec(cursor)?.[1];
|
|
1590
|
+
cursorActive = !phase || !/^(done|blocked)\b/i.test(phase);
|
|
1591
|
+
} catch (error) {
|
|
1592
|
+
cursorActive = error.code !== 'ENOENT';
|
|
1593
|
+
}
|
|
1471
1594
|
if (coordinator) {
|
|
1472
1595
|
try {
|
|
1596
|
+
const { resolveCursorApplicability } = await import('../../../.claude/ukit/runtime/handoff-provenance.mjs');
|
|
1597
|
+
let ownership = await resolveCursorApplicability({ projectRoot, sessionId: payload.session_id });
|
|
1598
|
+
// A session that never published a route AND whose whole transcript (and its
|
|
1599
|
+
// delegation parents) shows no handoff intent cannot be the claimant: omp has
|
|
1600
|
+
// no turn id linking before_agent_start to session_stop, so absence of a route
|
|
1601
|
+
// alone cannot tell an ordinary session from an interrupted claimant. The
|
|
1602
|
+
// transcript is an INTENT signal only — it can release a non-claimant, never
|
|
1603
|
+
// grant ownership. Any intent, unknown scan or unreadable parent stays UNKNOWN.
|
|
1604
|
+
if (cursorActive && ownership.status === 'UNKNOWN' && ownership.reason === 'route identity unavailable'
|
|
1605
|
+
&& typeof payload.transcript_path === 'string' && payload.transcript_path) {
|
|
1606
|
+
try {
|
|
1607
|
+
const intentMod = await import('../../../.claude/ukit/runtime/handoff-intent.mjs');
|
|
1608
|
+
const scan = await intentMod.transcriptHandoffIntentInherited(payload.transcript_path);
|
|
1609
|
+
if (scan.known && !scan.intent && !scan.unresolvedParent) {
|
|
1610
|
+
ownership = { status: 'NOT_OWNED', reason: 'no route and no handoff intent in session transcript' };
|
|
1611
|
+
}
|
|
1612
|
+
} catch { /* unreadable intent evidence keeps ownership UNKNOWN */ }
|
|
1613
|
+
}
|
|
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
|
+
}
|
|
1624
|
+
return finish({ decision: 'block', reason: `UKit handoff ownership UNKNOWN (${ownership.reason}); completion is unproven. Reconcile provenance before stopping.` });
|
|
1625
|
+
}
|
|
1473
1626
|
handoff = await coordinator.evaluateHandoffCursor({
|
|
1474
1627
|
projectRoot,
|
|
1628
|
+
ownership,
|
|
1475
1629
|
now,
|
|
1476
1630
|
lockBudgetMs,
|
|
1477
1631
|
transcriptPath: typeof payload.transcript_path === 'string' ? payload.transcript_path : null,
|
|
1478
1632
|
});
|
|
1479
1633
|
} catch (error) {
|
|
1480
|
-
pi.logger?.warn?.(`[UKit] handoff-cursor evaluator failed
|
|
1634
|
+
pi.logger?.warn?.(`[UKit] handoff-cursor evaluator failed: ${error?.message || error}`);
|
|
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
|
+
}
|
|
1481
1643
|
}
|
|
1644
|
+
} else if (cursorActive) {
|
|
1645
|
+
return finish({ decision: 'block', reason: 'UKit handoff ownership UNKNOWN: stop coordinator unavailable; completion is unproven.' });
|
|
1482
1646
|
}
|
|
1483
1647
|
const handoffBlock = handoff?.kind === 'block' ? handoff.reason : null;
|
|
1484
1648
|
// A breaker-release advisory (or any handoff systemMessage) is the omp
|
|
@@ -1587,11 +1751,15 @@ export default function hook(pi) {
|
|
|
1587
1751
|
});
|
|
1588
1752
|
});
|
|
1589
1753
|
pi.on('tool_result', (event, context) => runToolResult(pi, event, { projectRoot, context }));
|
|
1754
|
+
pi.on('input', (event, context) => { observeOwnerInput(event, context); });
|
|
1590
1755
|
pi.on('before_agent_start', (event, context) => runBeforeAgentStart(pi, event, { projectRoot, context }));
|
|
1591
1756
|
pi.on('session.compacting', (event, context) => runSessionCompacting(pi, event, { projectRoot, context }));
|
|
1592
1757
|
pi.on('session_start', (event, context) => runSessionStart(pi, event, { projectRoot, context }));
|
|
1593
1758
|
pi.on('session_switch', (event, context) => runSessionSwitch(pi, event, { projectRoot, context }));
|
|
1594
1759
|
pi.on('session_compact', (event, context) => runSessionCompact(pi, event, { projectRoot, context }));
|
|
1595
1760
|
pi.on('session_stop', (event, context) => runSessionStop(pi, event, { projectRoot, context }));
|
|
1596
|
-
pi.on('before_subagent_spawn', (event, 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
|
+
});
|
|
1597
1765
|
}
|
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Bootstrap the gitignored UKit runtime in a fresh `git worktree` so targeted tests can run.
|
|
3
|
-
//
|
|
4
|
-
// A new worktree only has tracked files. `.claude/`, `.ukit/`, `CLAUDE.md`, … are generated by
|
|
5
|
-
// `ukit install` and gitignored, so mirror/runtime tests fail there for environment reasons.
|
|
6
|
-
// This reuses `bin/ukit install` (no new generator), idempotently:
|
|
7
|
-
// - already bootstrapped → no-op
|
|
8
|
-
// - missing prerequisites → run `ukit install` once, re-check
|
|
9
|
-
// - not a linked worktree → refuse (the primary checkout's .claude/ is the maintainer runtime)
|
|
10
|
-
// Install can also create template-owned scaffolds missing from the checkout (docs/AI_HANDOFF/PLAN.md, SPEC.md);
|
|
11
|
-
// those are not gitignored, so they are reported as `visibleWrites` + a warning, never hidden or deleted.
|
|
12
|
-
// `ukit install` writes the install flavour of root CLAUDE.md/AGENTS.md, but those files are
|
|
13
|
-
// gitignored *render outputs* of template_project/instructions (docs:render). The preflight
|
|
14
|
-
// re-renders them when they drift — never a tracked render target, which is only reported.
|
|
15
|
-
// It copies nothing from another checkout (no sessions, secrets, handoff state) and does not
|
|
16
|
-
// link node_modules — run `yarn install` in the worktree (a symlinked node_modules is warned:
|
|
17
|
-
// realpath-sensitive hooks resolve it outside the project and misjudge delete targets).
|
|
18
|
-
//
|
|
19
|
-
// Usage: node scripts/dev/worktree-preflight.mjs [--root <dir>] [--check] [--json]
|
|
20
|
-
// Exit: 0 ready · 1 prerequisites missing (--check, or bootstrap failed) · 2 refused
|
|
21
|
-
|
|
22
|
-
import { spawnSync } from 'node:child_process';
|
|
23
|
-
import fs from 'node:fs';
|
|
24
|
-
import path from 'node:path';
|
|
25
|
-
import { fileURLToPath } from 'node:url';
|
|
26
|
-
|
|
27
|
-
// Generated by `ukit install`; each is required by a mirror/runtime test family.
|
|
28
|
-
export const PREREQUISITES = [
|
|
29
|
-
'node_modules',
|
|
30
|
-
'.claude/settings.json',
|
|
31
|
-
'.claude/hooks',
|
|
32
|
-
'.claude/ukit/runtime/execution-ledger.mjs',
|
|
33
|
-
'.ukit/storage/config.json',
|
|
34
|
-
'CLAUDE.md',
|
|
35
|
-
'AGENTS.md',
|
|
36
|
-
];
|
|
37
|
-
|
|
38
|
-
// Explicit bounds so a wedged git/render child can never hang the preflight. Normal runs take
|
|
39
|
-
// milliseconds; these sit far above that yet below `ukit install`'s own 120s budget.
|
|
40
|
-
const GIT_TIMEOUT_MS = 30_000;
|
|
41
|
-
const RENDER_TIMEOUT_MS = 60_000;
|
|
42
|
-
|
|
43
|
-
function git(root, args) {
|
|
44
|
-
const res = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: GIT_TIMEOUT_MS });
|
|
45
|
-
return res.status === 0 ? res.stdout.trim() : null;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export function isLinkedWorktree(root) {
|
|
49
|
-
const gitDir = git(root, ['rev-parse', '--path-format=absolute', '--git-dir']);
|
|
50
|
-
const common = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
|
|
51
|
-
return Boolean(gitDir && common && path.resolve(gitDir) !== path.resolve(common));
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function isTracked(root, rel) {
|
|
55
|
-
const res = spawnSync('git', ['ls-files', '--error-unmatch', '--', rel], { cwd: root, stdio: 'ignore', timeout: GIT_TIMEOUT_MS });
|
|
56
|
-
// A timed-out probe proves nothing: treat as tracked so the file is reported, never overwritten.
|
|
57
|
-
return res.status === 0 || Boolean(res.error);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const RENDER_CLI = 'scripts/docs/render-instructions.mjs';
|
|
61
|
-
|
|
62
|
-
// Visible (non-ignored) paths in `git status`. `ukit install` creates template-owned scaffolds that
|
|
63
|
-
// are missing from the checkout (docs/AI_HANDOFF/PLAN.md, SPEC.md — mergeStrategy skip, handoff-clear
|
|
64
|
-
// restores them to template, never deletes them). They are not gitignored, so a HEAD that lost them
|
|
65
|
-
// turns the bootstrap into a visible write. Report it truthfully instead of hiding or deleting it.
|
|
66
|
-
function visibleStatus(root) {
|
|
67
|
-
const res = spawnSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: root, encoding: 'utf8', timeout: GIT_TIMEOUT_MS });
|
|
68
|
-
return res.status === 0 ? new Set(res.stdout.split('\n').filter(Boolean)) : null;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// → rel paths whose rendered bytes differ from disk (`DRIFT <target>` lines of --check).
|
|
72
|
-
export function renderDrift(root) {
|
|
73
|
-
const res = spawnSync(process.execPath, [path.join(root, RENDER_CLI), '--check'], { cwd: root, encoding: 'utf8', timeout: RENDER_TIMEOUT_MS });
|
|
74
|
-
// A killed check prints nothing, which would read as "no drift" — fail loudly instead.
|
|
75
|
-
if (res.error) throw new Error(`render check did not complete (${res.error.code || res.error.message})`);
|
|
76
|
-
return `${res.stdout || ''}`.split('\n').map((l) => l.match(/^DRIFT (.+)$/)?.[1]).filter(Boolean);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export function missingPrerequisites(root) {
|
|
80
|
-
return PREREQUISITES.filter((rel) => !fs.existsSync(path.join(root, rel)));
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function preflight({ root, check = false } = {}) {
|
|
84
|
-
const projectRoot = fs.realpathSync(root);
|
|
85
|
-
const result = { root: projectRoot, ok: false, bootstrapped: false, missing: [], rendered: [], visibleWrites: [], warnings: [], home: null, error: null };
|
|
86
|
-
|
|
87
|
-
if (!fs.existsSync(path.join(projectRoot, 'bin/ukit'))) {
|
|
88
|
-
return { ...result, exitCode: 2, error: `not a UKit checkout (no bin/ukit): ${projectRoot}` };
|
|
89
|
-
}
|
|
90
|
-
if (!isLinkedWorktree(projectRoot)) {
|
|
91
|
-
return { ...result, exitCode: 2, error: 'refusing: not a linked worktree (git worktree add …); the primary checkout keeps its own runtime' };
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
result.missing = missingPrerequisites(projectRoot);
|
|
95
|
-
if (result.missing.length > 0) {
|
|
96
|
-
if (check) return { ...result, exitCode: 1 };
|
|
97
|
-
if (result.missing.includes('node_modules')) {
|
|
98
|
-
return { ...result, exitCode: 1, error: 'node_modules missing — run `yarn install` in the worktree first (not linked from another checkout)' };
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// `ukit install` also writes user-level state (~/.ukit playbooks). Point HOME inside the
|
|
102
|
-
// worktree's ignored .cache/ so a preflight never mutates the real home or leaks from it.
|
|
103
|
-
result.home = path.join(projectRoot, '.cache/worktree-preflight-home');
|
|
104
|
-
fs.mkdirSync(result.home, { recursive: true });
|
|
105
|
-
const visibleBefore = visibleStatus(projectRoot);
|
|
106
|
-
const install = spawnSync(process.execPath, [path.join(projectRoot, 'bin/ukit'), 'install'], {
|
|
107
|
-
cwd: projectRoot,
|
|
108
|
-
encoding: 'utf8',
|
|
109
|
-
env: { ...process.env, HOME: result.home, USERPROFILE: result.home },
|
|
110
|
-
timeout: 120_000,
|
|
111
|
-
});
|
|
112
|
-
result.bootstrapped = true;
|
|
113
|
-
const visibleAfter = visibleStatus(projectRoot);
|
|
114
|
-
if (visibleBefore && visibleAfter) {
|
|
115
|
-
result.visibleWrites = [...visibleAfter].filter((l) => !visibleBefore.has(l)).map((l) => l.slice(3));
|
|
116
|
-
if (result.visibleWrites.length > 0) {
|
|
117
|
-
result.warnings.push(`ukit install created non-ignored file(s) missing from this checkout: ${result.visibleWrites.join(', ')} — template-owned scaffolds; restore/commit them (not deleted)`);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
result.missing = missingPrerequisites(projectRoot);
|
|
121
|
-
if (install.status !== 0 || result.missing.length > 0) {
|
|
122
|
-
const tail = `${install.stdout || ''}${install.stderr || ''}`.trim().split('\n').slice(-5).join('\n');
|
|
123
|
-
return { ...result, exitCode: 1, error: `ukit install did not produce all prerequisites (exit ${install.status})\n${tail}` };
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
if (fs.lstatSync(path.join(projectRoot, 'node_modules')).isSymbolicLink()) {
|
|
128
|
-
result.warnings.push('node_modules is a symlink — realpath-sensitive tests (block-dangerous) fail; run `yarn install` in this worktree for a real copy');
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
const drift = renderDrift(projectRoot);
|
|
132
|
-
if (drift.length > 0) {
|
|
133
|
-
if (check) return { ...result, missing: drift.map((t) => `render:${t}`), exitCode: 1 };
|
|
134
|
-
const tracked = drift.filter((t) => isTracked(projectRoot, t));
|
|
135
|
-
if (tracked.length > 0) {
|
|
136
|
-
return { ...result, exitCode: 1, error: `tracked render target(s) drifted, not overwriting: ${tracked.join(', ')} — commit or revert the source edit` };
|
|
137
|
-
}
|
|
138
|
-
const write = spawnSync(process.execPath, [path.join(projectRoot, RENDER_CLI), '--write'], { cwd: projectRoot, encoding: 'utf8', timeout: RENDER_TIMEOUT_MS });
|
|
139
|
-
const still = renderDrift(projectRoot);
|
|
140
|
-
if (write.status !== 0 || still.length > 0) {
|
|
141
|
-
return { ...result, exitCode: 1, error: `docs:render did not clear drift: ${still.join(', ') || (write.stderr || '').trim()}` };
|
|
142
|
-
}
|
|
143
|
-
result.rendered = drift;
|
|
144
|
-
}
|
|
145
|
-
return { ...result, ok: true, exitCode: 0 };
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function main(argv) {
|
|
149
|
-
const args = { root: process.cwd(), check: false, json: false };
|
|
150
|
-
for (let i = 0; i < argv.length; i += 1) {
|
|
151
|
-
if (argv[i] === '--root') args.root = path.resolve(argv[++i] || '');
|
|
152
|
-
else if (argv[i] === '--check') args.check = true;
|
|
153
|
-
else if (argv[i] === '--json') args.json = true;
|
|
154
|
-
}
|
|
155
|
-
const { exitCode, ...result } = preflight(args);
|
|
156
|
-
if (args.json) {
|
|
157
|
-
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
158
|
-
} else if (result.ok) {
|
|
159
|
-
console.log(`[worktree-preflight] ready${result.bootstrapped ? ' (bootstrapped via ukit install)' : ' (already bootstrapped)'}: ${result.root}`);
|
|
160
|
-
} else {
|
|
161
|
-
console.error(`[worktree-preflight] ${result.error || `missing: ${result.missing.join(', ')}`}`);
|
|
162
|
-
}
|
|
163
|
-
process.exit(exitCode);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(process.argv.slice(2));
|