@ngockhoale/ukit 3.5.15 → 3.5.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/manifests/platform.full.yaml +48 -0
  3. package/package.json +2 -1
  4. package/scripts/release/heavy-first.mjs +12 -0
  5. package/scripts/release/release-steps.mjs +7 -4
  6. package/scripts/release/run-core-batch.mjs +50 -0
  7. package/src/cli/commands/mission.js +102 -0
  8. package/src/cli/commands/rescue.js +83 -0
  9. package/src/cli/index.js +14 -0
  10. package/src/core/compact/contextBudget.js +62 -41
  11. package/src/core/compact/threshold.js +14 -32
  12. package/src/core/observability/schema/registry.js +91 -0
  13. package/src/core/runtimeConfig.js +53 -2
  14. package/src/diagnostics/routeOutcomes.js +5 -1
  15. package/src/diagnostics/skillAccuracy.js +5 -2
  16. package/src/render/buildVariables.js +2 -5
  17. package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
  18. package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
  19. package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
  20. package/template_project/.claude/hooks/context-window-guard.sh +82 -27
  21. package/template_project/.claude/hooks/delegation-gate.mjs +1 -1
  22. package/template_project/.claude/hooks/handoff-resume.sh +11 -2
  23. package/template_project/.claude/hooks/mission-capture.mjs +37 -0
  24. package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
  25. package/template_project/.claude/hooks/shell-watch.mjs +34 -0
  26. package/template_project/.claude/hooks/skill-router.sh +13 -0
  27. package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
  28. package/template_project/.claude/settings.json +36 -4
  29. package/template_project/.claude/skills/backend-api/SKILL.md +1 -1
  30. package/template_project/.claude/skills/delivery/SKILL.md +1 -1
  31. package/template_project/.claude/skills/docs-manager/SKILL.md +1 -1
  32. package/template_project/.claude/skills/duraone/SKILL.md +2 -1
  33. package/template_project/.claude/skills/file-organizer/SKILL.md +1 -1
  34. package/template_project/.claude/skills/frontend/SKILL.md +1 -1
  35. package/template_project/.claude/skills/frontend-vue/SKILL.md +1 -1
  36. package/template_project/.claude/skills/pdf-processing/SKILL.md +1 -1
  37. package/template_project/.claude/skills/postgres/SKILL.md +1 -1
  38. package/template_project/.claude/skills/testing-quality/SKILL.md +2 -0
  39. package/template_project/.claude/skills/webapp-testing/SKILL.md +1 -1
  40. package/template_project/.claude/ukit/index/route-task.mjs +3 -1
  41. package/template_project/.claude/ukit/index/tier-lane.mjs +1 -1
  42. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
  43. package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
  44. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +107 -4
  45. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
  46. package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
  47. package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
  48. package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
  49. package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
  50. package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
  51. package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
  52. package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
  53. package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
  54. package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
  55. package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
  56. package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
  57. package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
  58. package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
  59. package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
  60. package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
  61. package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
  62. package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
  63. package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
  64. package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
  65. package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
  66. package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
  67. package/template_project/.claude/ukit/runtime/shell-watch.mjs +278 -0
  68. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
  69. package/template_project/.omp/RULES.md +1 -1
  70. package/template_project/.omp/config.yml +2 -2
  71. package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
  72. package/template_project/AGENTS.md +5 -1
  73. package/template_project/CLAUDE.md +5 -1
  74. package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
  75. package/template_project/instructions/core.md +5 -1
  76. package/template_project/instructions/overlays/omp-rules.md +1 -1
  77. package/template_project/ukit/storage/config.json +32 -10
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: pdf-processing
3
- description: Production-ready PDF processing toolkit with forms, tables, OCR, validation, and batch operations. Supports extracting text/tables, creating/modifying PDFs, and handling complex forms.
3
+ description: Production-ready PDF processing toolkit with forms, tables, OCR, validation, and batch operations. Use when extracting text/tables from a PDF, filling or reading PDF forms, OCR-ing scans, or creating/modifying PDFs.
4
4
  enabledByDefault: false
5
5
  ---
6
6
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: postgres
3
- description: PostgreSQL conventions and patterns for UKit SQL work.
3
+ description: PostgreSQL conventions and patterns for UKit SQL work. Use when writing or reviewing PostgreSQL queries, views, functions, procedures, migrations, or indexes.
4
4
  enabledByDefault: false
5
5
  ---
6
6
 
@@ -9,6 +9,8 @@ description: Quality-driven testing methodology combining Test-Driven Developmen
9
9
 
10
10
  High-quality code starts with high-quality tests. This skill enforces Test-Driven Development (TDD) and prevents common testing mistakes.
11
11
 
12
+ **Full suite rule:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run`; only a `PASS` verdict counts. Targeted 1-3 file runs use the bare runner.
13
+
12
14
  **Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.
13
15
 
14
16
  **The Iron Law:**
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: webapp-testing
3
- description: Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
3
+ description: Toolkit for interacting with and testing local web applications using Playwright. Use when verifying frontend behaviour in a real browser, debugging UI, capturing screenshots, or reading browser console logs.
4
4
  license: Complete terms in LICENSE.txt
5
5
  ---
6
6
 
@@ -23,7 +23,7 @@ import { buildTierLane, classifyModelTier, resolveMainTier } from './tier-lane.m
23
23
  export { buildTierLane, classifyModelTier, resolveMainTier };
24
24
  import { detectUnicGateway } from './unic-gateway.mjs';
25
25
  import { withAsyncLock } from '../runtime/async-lock.mjs';
26
- import { appendDecisionReceipt, recordLedgerEvent } from '../runtime/execution-ledger.mjs';
26
+ import { appendDecisionReceipt, recordLedgerEvent, rotateAppendLogSync } from '../runtime/execution-ledger.mjs';
27
27
  import {
28
28
  RESUMABLE_RUN_SCHEMA_VERSION,
29
29
  readResumableRun,
@@ -6731,6 +6731,7 @@ function routeAuditSegmentsPath(filePath) {
6731
6731
  async function spillRouteAuditEntries(filePath, evicted) {
6732
6732
  if (!evicted?.length) return;
6733
6733
  try {
6734
+ rotateAppendLogSync(routeAuditSegmentsPath(filePath));
6734
6735
  await fs.appendFile(
6735
6736
  routeAuditSegmentsPath(filePath),
6736
6737
  evicted.map((item) => JSON.stringify(item)).join('\n') + '\n',
@@ -6744,6 +6745,7 @@ async function spillRouteAuditEntries(filePath, evicted) {
6744
6745
  function spillRouteAuditEntriesSync(filePath, evicted) {
6745
6746
  if (!evicted?.length) return;
6746
6747
  try {
6748
+ rotateAppendLogSync(routeAuditSegmentsPath(filePath));
6747
6749
  fsSync.appendFileSync(
6748
6750
  routeAuditSegmentsPath(filePath),
6749
6751
  evicted.map((item) => JSON.stringify(item)).join('\n') + '\n',
@@ -52,7 +52,7 @@ export function buildTierLane({ modelTier = null, escalatedTier = null, mainTier
52
52
  };
53
53
  }
54
54
  const policy = delegationPolicy ?? 'allow-qualified-sidecar';
55
- const brief = 'Give the worker scope, dependencies, acceptance criteria and the verification to run; verify its diff yourself after it returns, then run the project\'s bare test runner yourself (e.g. `npm test`, no pipe/tail/grep/compound command) and read its exit status — that status is the verification evidence.';
55
+ const brief = 'Give the worker scope, dependencies, acceptance criteria and the verification to run; verify its diff yourself after it returns, then run the project\'s bare test runner yourself (e.g. `npm test`, no pipe/tail/grep/compound command) and read its exit status — that status is the verification evidence. A full-suite run uses `node .claude/ukit/index/test-batches.mjs run` (its exit status is the evidence).';
56
56
  // A high-risk target on a Tier 2 coding lane is still Tier 2 work: the inline-by-policy exemption
57
57
  // (hand-off costs more than the work) does not apply, otherwise the Tier 3 orchestrator would be the
58
58
  // one editing the dangerous file. Risk raises verification rigor, not the executor.
@@ -14,7 +14,7 @@ import {
14
14
  } from './token-utils.mjs';
15
15
  // Sibling runtime module: installs copy the whole runtime dir, so the negotiated-capacity
16
16
  // resolver is always present next to this file.
17
- import { resolveContextCapTokens } from './context-capacity.mjs';
17
+ import { resolveContextCapTokens, resolveContextTiers } from './context-capacity.mjs';
18
18
 
19
19
  const DEFAULT_MAX_PROMPT_ENTRIES = 12;
20
20
  const DEFAULT_MAX_OUTPUT_ENTRIES = 12;
@@ -488,38 +488,28 @@ export async function resolveCompactCapacity(config = {}, { record } = {}) {
488
488
  }
489
489
 
490
490
  export async function buildCompactThresholds(config = {}) {
491
- const explicitSoftThreshold = finiteNumber(config?.compact?.tokenThreshold, 0);
492
- const shippedHardCap = positiveInteger(config?.compact?.hardCapTokens, 235_000);
493
- // Upgrade safety: an install that predates compact.contextWindowTokens still carries the
494
- // old 500k hard cap; the cap must never sit above the declared window it guards.
495
- const declaredWindow = positiveInteger(config?.compact?.contextWindowTokens, 0);
496
- const effectiveShippedHardCap = declaredWindow > 0 ? Math.min(shippedHardCap, declaredWindow) : shippedHardCap;
497
- // Only tighten once a record exists: an install with no evidence yet (and every caller
498
- // that passes no project root) keeps the shipped tuning unchanged.
499
- const record = await readContextCapacityRecord(config?.projectRoot);
500
- const negotiated = record ? await resolveCompactCapacity(config, { record }) : null;
501
- const hardCapTokens = negotiated
502
- ? Math.max(1, Math.min(effectiveShippedHardCap, negotiated.capTokens))
503
- : effectiveShippedHardCap;
504
- // An explicit operator tokenThreshold is honoured but still clamped under the
505
- // negotiated cap: an advisory soft/hard pair sitting at or above hardCapTokens can
506
- // never fire, because context-hardcap-gate.sh already refuses tools at the cap
507
- // (C92-H-01 — on a default install tokenThreshold is the shipped 150k default, not a
508
- // real operator choice, so this is correcting a number, not overriding intent).
509
- const softThreshold = explicitSoftThreshold > 0
510
- ? Math.max(1, Math.min(explicitSoftThreshold, hardCapTokens - 1))
511
- : Math.max(1, Math.round(hardCapTokens * SOFT_TO_CAP_RATIO));
491
+ // UKit-owned tiers (compact.bestTokens/okTokens/mandatoryTokens/stopTokens, legacy
492
+ // hardCapTokens -> stopTokens, tokenThreshold -> bestTokens). They are deliberately NOT
493
+ // clamped to contextWindowTokens or the negotiated model window: the tiers are UKit
494
+ // policy, and the host auto-compaction window (rendered separately) keeps sessions below
495
+ // stopTokens. The capacity record is still read for diagnostics only.
496
+ const tiers = resolveContextTiers(config);
497
+ const hardCapTokens = tiers.stopTokens;
498
+ const softThreshold = Math.max(1, Math.min(tiers.bestTokens, hardCapTokens - 1));
512
499
  const hardThreshold = Math.min(
513
500
  hardCapTokens,
514
501
  Math.max(softThreshold + 1, Math.round(softThreshold * 1.6)),
515
502
  );
516
503
  const baselineTokens = Math.max(120, Math.min(18_000, Math.round(softThreshold * 0.18)));
504
+ const record = await readContextCapacityRecord(config?.projectRoot);
505
+ const negotiated = record ? await resolveCompactCapacity(config, { record }) : null;
517
506
 
518
507
  return {
519
508
  softThreshold,
520
509
  hardThreshold,
521
510
  baselineTokens,
522
511
  hardCapTokens,
512
+ tiers,
523
513
  capacitySource: negotiated?.capacity?.source ?? 'shipped',
524
514
  capacityTokens: negotiated?.capacity?.tokens ?? null,
525
515
  };
@@ -958,13 +948,9 @@ export async function buildCompactPressureState(rawState = null, config = {}) {
958
948
  const thresholds = await buildCompactThresholds(config);
959
949
  const rawSoftThreshold = finiteNumber(rawState?.softThreshold, 0);
960
950
  const rawHardThreshold = finiteNumber(rawState?.hardThreshold, 0);
961
- if (!finiteNumber(config?.compact?.tokenThreshold, 0) && rawSoftThreshold > 0) {
962
- // A persisted pair is only honoured while it still sits inside the negotiated cap.
963
- // The record outlives capacity negotiation: an install that ran before the record
964
- // existed, or before the model was verified, carries thresholds tuned for the
965
- // shipped 500k ceiling — restoring them re-pins the advisory ABOVE the live
966
- // hardCapTokens forever (C92-H-02). Falling through keeps the freshly derived
967
- // pair, which is also what the rewritten record persists, so the file self-heals.
951
+ if (!finiteNumber(config?.compact?.tokenThreshold, 0) && !finiteNumber(config?.compact?.bestTokens, 0) && rawSoftThreshold > 0) {
952
+ // A persisted pair is honoured only while it sits strictly inside stopTokens, so a stale
953
+ // record can never pin the advisory at/above the stop line (C92-H-02).
968
954
  if (rawSoftThreshold < thresholds.hardCapTokens) {
969
955
  thresholds.softThreshold = rawSoftThreshold;
970
956
  thresholds.hardThreshold = Math.min(
@@ -30,7 +30,7 @@ export const CAPACITY_ENV_VAR = 'UKIT_CONTEXT_WINDOW_TOKENS';
30
30
  export const DEFAULT_CAPACITY_TOKENS = 100_000;
31
31
  // The shipped operator ceiling (compact.hardCapTokens) — only ever an UPPER bound; negotiated
32
32
  // capacity can tighten it but never raise it.
33
- export const SHIPPED_HARD_CAP_TOKENS = 235_000;
33
+ export const SHIPPED_HARD_CAP_TOKENS = 185_000;
34
34
  // A verified window is only ever usable as an estimate: the response itself plus the
35
35
  // char/token estimator's own undercount must fit too, so only half the window becomes
36
36
  // the advisory cap (500k cap from a 1M window — the original tuning, made explicit).
@@ -149,3 +149,66 @@ export function resolveContextCapTokens({ env, config, modelMetadata } = {}) {
149
149
  capTokens: Math.max(1, Math.min(ceiling, derived)),
150
150
  };
151
151
  }
152
+
153
+ // ── UKit-owned context tiers ──
154
+ // UKit owns these four numbers (compact.bestTokens / okTokens / mandatoryTokens / stopTokens)
155
+ // and they do NOT depend on any model's context window:
156
+ // < best green silent
157
+ // best..ok yellow one-line advisory (delegate broad reads, short replies)
158
+ // ok..mandatory orange staying under mandatoryTokens is required: land, persist, delegate
159
+ // mandatory..stop red over the mandatory line: persist now; new work is blocked at stop
160
+ // >= stop stop the hard gate blocks new work except persist-to-disk writes; host
161
+ // auto-compaction (always automatic) fires and UKit restores the work.
162
+ // Legacy keys keep working: compact.hardCapTokens maps to stopTokens and
163
+ // compact.tokenThreshold maps to bestTokens WHEN SET (they win over the new keys, so an
164
+ // install that pinned them behaves as before; delete them to adopt the shipped tiers).
165
+ export const DEFAULT_CONTEXT_TIERS = Object.freeze({
166
+ bestTokens: 100_000,
167
+ okTokens: 150_000,
168
+ mandatoryTokens: 200_000,
169
+ stopTokens: 250_000,
170
+ });
171
+
172
+ function positiveInt(value) {
173
+ return typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value > 0
174
+ ? value
175
+ : null;
176
+ }
177
+
178
+ export function resolveContextTiers(config = {}) {
179
+ const compact = config?.compact ?? {};
180
+ const stop = positiveInt(compact.hardCapTokens) ?? positiveInt(compact.stopTokens) ?? DEFAULT_CONTEXT_TIERS.stopTokens;
181
+ const mandatory = Math.min(positiveInt(compact.mandatoryTokens) ?? DEFAULT_CONTEXT_TIERS.mandatoryTokens, stop);
182
+ const ok = Math.min(positiveInt(compact.okTokens) ?? DEFAULT_CONTEXT_TIERS.okTokens, mandatory);
183
+ const best = Math.min(positiveInt(compact.tokenThreshold) ?? positiveInt(compact.bestTokens) ?? DEFAULT_CONTEXT_TIERS.bestTokens, ok);
184
+ return { bestTokens: best, okTokens: ok, mandatoryTokens: mandatory, stopTokens: stop };
185
+ }
186
+
187
+ // -> 'green' | 'yellow' | 'orange' | 'red' | 'stop'
188
+ export function classifyContextTier(tokens, tiers = DEFAULT_CONTEXT_TIERS) {
189
+ const value = Number(tokens);
190
+ if (!Number.isFinite(value)) return 'green';
191
+ if (value >= tiers.stopTokens) return 'stop';
192
+ if (value >= tiers.mandatoryTokens) return 'red';
193
+ if (value >= tiers.okTokens) return 'orange';
194
+ if (value >= tiers.bestTokens) return 'yellow';
195
+ return 'green';
196
+ }
197
+
198
+ // One-line tier text, shared by the prompt guard and the tool gate. Compaction is always
199
+ // automatic: no tier ever asks the user to run /compact.
200
+ export function contextTierMessage(tier, tokens, tiers = DEFAULT_CONTEXT_TIERS) {
201
+ const n = Math.round(Number(tokens) || 0).toLocaleString('en-US');
202
+ switch (tier) {
203
+ case 'yellow':
204
+ return `UKit context ~${n} tokens (OK): prefer delegating broad reads to subagents and keep replies short.`;
205
+ case 'orange':
206
+ return `UKit context ~${n} tokens (MANDATORY zone ${tiers.okTokens.toLocaleString('en-US')}-${tiers.mandatoryTokens.toLocaleString('en-US')}): staying under ${tiers.mandatoryTokens.toLocaleString('en-US')} is required. Land the current item, defer the rest to docs/STATUS.md or handoff tasks, delegate broad work, start nothing new inline.`;
207
+ case 'red':
208
+ return `UKit context ~${n} tokens: over the mandatory ${tiers.mandatoryTokens.toLocaleString('en-US')} line - land and persist state to disk now; new work is blocked at ${tiers.stopTokens.toLocaleString('en-US')}. Host auto-compaction is automatic; do not ask the user to /compact.`;
209
+ case 'stop':
210
+ return `STOP new work: context >=${tiers.stopTokens.toLocaleString('en-US')} (~${n}) - persist state to disk now (STATUS/handoff); the host auto-compaction will fire and UKit restores the work after it - do not ask the user to /compact.`;
211
+ default:
212
+ return '';
213
+ }
214
+ }
@@ -19,7 +19,9 @@ import { operationCompletionPolicy, foldOperationEvidence, compactOperation, con
19
19
 
20
20
  const LEDGER_VERSION = 1;
21
21
  const RESUME_INTENT_VERSION = 1;
22
- const RESUME_INTENT_TTL_MS = 30 * 60 * 1000;
22
+ // Cross-session reuse bound only. A same-session compaction restore (`compact: true` read)
23
+ // ignores age: multi-hour runs compact long after the intent's PreCompact write.
24
+ const RESUME_INTENT_TTL_MS = 24 * 60 * 60 * 1000;
23
25
  const MAX_RECEIPTS = 24;
24
26
  // TASK-005 (FR-005): bounded OutcomeRecord dedupe slot — a resumable-run
25
27
  // pointer (interrupted run) emits `outcome.observed` once per task; replays
@@ -482,13 +484,17 @@ export async function readResumableExecution(projectRoot, payload = {}) {
482
484
  return { state, ledger, sessionId };
483
485
  }
484
486
 
485
- export async function readResumeIntent(projectRoot, payload = {}, { consume = false, now = Date.now() } = {}) {
487
+ export async function readResumeIntent(projectRoot, payload = {}, { consume = false, now = Date.now(), compact = false } = {}) {
486
488
  const sessionId = explicitSessionId(payload);
487
489
  if (!sessionId) return null;
488
490
  const intent = await readJson(resumeIntentPath(projectRoot, sessionId), null);
489
491
  if (!intent || intent.version !== RESUME_INTENT_VERSION) return null;
490
492
  if (intent.sessionKey !== safeSegment(sessionId) || intent.sessionHash !== resumeSessionHash(sessionId)) return null;
491
- if (!intent.promptKey || !intent.requestKey || !Number.isFinite(intent.expiresAt) || intent.expiresAt <= now) return null;
493
+ if (!intent.promptKey || !intent.requestKey) return null;
494
+ // The file is keyed by session id and re-checked against sessionHash above, so a compact
495
+ // read is same-session by construction: age is irrelevant there.
496
+ if (!compact && (!Number.isFinite(intent.expiresAt) || intent.expiresAt <= now)) return null;
497
+ if (intent.cwd && intent.cwd !== projectRoot) return null;
492
498
 
493
499
  const state = await readRouteState(projectRoot, payload);
494
500
  const ledger = await readExecutionLedger(projectRoot, payload);
@@ -515,6 +521,39 @@ export async function readResumeIntent(projectRoot, payload = {}, { consume = fa
515
521
  return intent;
516
522
  }
517
523
 
524
+ // Durable mission snapshot persisted at PreCompact so the post-compaction session can
525
+ // re-orient without the host summary: goal, contract, evidence, next step, git state.
526
+ function resumeIntentSnapshot(state, ledger, cwd) {
527
+ const routing = state?.routingContext || {};
528
+ const goal = String(routing.lastExplicitUserPromptText ?? routing.promptText ?? '').slice(0, 4000);
529
+ const contract = state?.routeSummary?.executionContract?.taskKind
530
+ || state?.routeSummary?.taskKind || state?.routeSummary?.executionMode || null;
531
+ let unmet = [];
532
+ let reason = '';
533
+ try {
534
+ if (state?.routeSummary?.executionContract?.taskKind) {
535
+ const verdict = evaluateCompletion({ state, ledger, cwd });
536
+ unmet = verdict.missingEvidence || [];
537
+ reason = String(verdict.reason || '').slice(0, 400);
538
+ } else {
539
+ unmet = requiredEvidence(state).filter((item) => !evidenceSatisfied(item, ledger, state));
540
+ }
541
+ } catch { /* snapshot is best-effort; the identity fields above stay authoritative */ }
542
+ const observed = [ledger?.sourceSucceeded && 'source-read', ledger?.writeSucceeded && 'write-receipt',
543
+ ledger?.verificationSucceeded && 'verification-receipt'].filter(Boolean);
544
+ const dirty = gitOutputRaw(['status', '--porcelain'], cwd);
545
+ return {
546
+ goal,
547
+ contract,
548
+ observedEvidence: observed,
549
+ unmetEvidence: unmet.slice(0, 12),
550
+ nextStep: unmet.length
551
+ ? `Produce the missing evidence (${unmet.slice(0, 6).join(', ')}) for the goal above${reason ? ` — ${reason}` : ''}`
552
+ : 'Re-check completion evidence against the goal, then finish or continue the next missing milestone',
553
+ git: { head: gitOutputRaw(['rev-parse', 'HEAD'], cwd), dirtyFiles: dirty ? dirty.split('\n').length : 0 },
554
+ };
555
+ }
556
+
518
557
  export async function writeResumeIntent(projectRoot, payload = {}, { now = Date.now() } = {}) {
519
558
  const sessionId = explicitSessionId(payload);
520
559
  if (!sessionId) return null;
@@ -533,6 +572,8 @@ export async function writeResumeIntent(projectRoot, payload = {}, { now = Date.
533
572
  taskInstanceId: state.taskInstanceId || null,
534
573
  requestKey: ledger.requestKey,
535
574
  routeFingerprint: state.fingerprint || null,
575
+ cwd: projectRoot,
576
+ ...resumeIntentSnapshot(state, ledger, projectRoot),
536
577
  createdAt: now,
537
578
  expiresAt: now + RESUME_INTENT_TTL_MS,
538
579
  };
@@ -925,6 +966,10 @@ function simpleCommandVerifierKind(tokens) {
925
966
  if (/^(?:-e|-p|--eval|--print)$/.test(arg)) return null; // inline code: later words are its argv
926
967
  if (/^(?:-r|--require|--import|--loader|--experimental-loader|-C|--conditions)$/.test(arg)) { i += 1; continue; }
927
968
  if (/^-/.test(arg)) continue;
969
+ if (/(?:^|\/)test-batches\.mjs$/.test(arg)) {
970
+ const mode = rest.slice(i + 1).find((a) => !/^-/.test(a));
971
+ return !mode || mode === 'run' ? 'test' : null;
972
+ }
928
973
  return runnerWordKind(arg);
929
974
  }
930
975
  }
@@ -1509,6 +1554,38 @@ function promptNamesBookkeepingFile(state, file) {
1509
1554
  return promptNamesBookkeeping(state);
1510
1555
  }
1511
1556
 
1557
+ // Field #7/#13 (greenfield/brownfield onboarding): a project that declares NO test command
1558
+ // cannot ever produce a test-verified verdict, so demanding one blocks Stop forever (9Router:
1559
+ // no package.json, verified with `node --check`). Detection is cheap and conservative —
1560
+ // any recognizable test surface keeps the strict test-verified requirement.
1561
+ const NPM_DEFAULT_TEST = /no test specified/i;
1562
+ const testSurfaceMemo = new Map();
1563
+ export function projectDeclaresTestCommand(cwd) {
1564
+ const root = path.resolve(cwd || process.cwd());
1565
+ if (testSurfaceMemo.has(root)) return testSurfaceMemo.get(root);
1566
+ const exists = (rel) => { try { return fsSync.existsSync(path.join(root, rel)); } catch { return false; } };
1567
+ const read = (rel) => { try { return fsSync.readFileSync(path.join(root, rel), 'utf8'); } catch { return ''; } };
1568
+ let found = false;
1569
+ const pkgRaw = read('package.json');
1570
+ if (pkgRaw) {
1571
+ try {
1572
+ const scripts = JSON.parse(pkgRaw)?.scripts || {};
1573
+ found = Object.entries(scripts).some(([name, body]) => /^test(?::|$)/.test(name) && !NPM_DEFAULT_TEST.test(String(body)));
1574
+ } catch { found = true; } // unreadable manifest: stay strict
1575
+ }
1576
+ if (!found) {
1577
+ found = ['pytest.ini', 'tox.ini', 'conftest.py', 'go.mod', 'Cargo.toml', 'phpunit.xml', 'phpunit.xml.dist', 'build.gradle', 'build.gradle.kts', 'pom.xml', 'mix.exs', 'Gemfile']
1578
+ .some(exists)
1579
+ || /\[tool\.pytest|\[tool:pytest/.test(read('pyproject.toml') + read('setup.cfg'))
1580
+ || /^test\s*:/m.test(read('Makefile'))
1581
+ || ['tests', 'test', '__tests__', 'spec'].some((dir) => {
1582
+ try { return fsSync.statSync(path.join(root, dir)).isDirectory(); } catch { return false; }
1583
+ });
1584
+ }
1585
+ testSurfaceMemo.set(root, found);
1586
+ return found;
1587
+ }
1588
+
1512
1589
  function contentFingerprint(cwd) { return memoGit(`content\0${cwd}`, () => contentFingerprintRaw(cwd)); }
1513
1590
  function contentFingerprintRaw(cwd) {
1514
1591
  if (!cwd) return null;
@@ -3774,6 +3851,12 @@ export async function recordLedgerEvent(event, {
3774
3851
  // contended acquisition never pays sweep latency. Advisory — never throws.
3775
3852
  // BUG-C23-10: a persistent failure is still surfaced as a bounded degrade.
3776
3853
  try { await maybeSweepExecLedgerDir(path.dirname(target)); } catch (error) { noteSweepFailure(error); }
3854
+ // Field #8: per-session route-state sidecars (cache/route-state/<session>.json) were never
3855
+ // pruned (1,513 files in one consumer). Same bounded sampled sweep: 30-day age cap, count
3856
+ // cap only for files idle > 24 h, so a live session's route state is never evicted.
3857
+ try {
3858
+ await maybeSweepExecLedgerDir(path.join(path.dirname(path.dirname(target)), 'route-state'), { maxFiles: 400 });
3859
+ } catch (error) { noteSweepFailure(error); }
3777
3860
  return outcome.value;
3778
3861
  }
3779
3862
 
@@ -4376,8 +4459,11 @@ function evidenceSatisfied(evidence, ledger = {}, state = {}, { cwd } = {}) {
4376
4459
  // verdict record the boolean path below is unchanged (backward compatible).
4377
4460
  const verdicts = [ledger.verdict, ...(ledger.verdictHistory || [])].filter(Boolean);
4378
4461
  if (verdicts.length > 0) {
4462
+ // #7/#13: with no declared test command a current check-only verdict is the strongest
4463
+ // evidence the project can produce; a project with a test surface stays strict.
4464
+ const noTestSurface = () => !projectDeclaresTestCommand(verdicts.find((v) => v.workspaceRoot)?.workspaceRoot || cwd);
4379
4465
  return verdicts.some(
4380
- (verdict) => VERDICT_SATISFYING_KINDS.has(verdict.kind)
4466
+ (verdict) => (VERDICT_SATISFYING_KINDS.has(verdict.kind) || (verdict.kind === 'check-only' && noTestSurface()))
4381
4467
  && verdictCurrent(verdict, { cwd }).current === true,
4382
4468
  );
4383
4469
  }
@@ -6060,6 +6146,22 @@ async function main() {
6060
6146
 
6061
6147
  const DECISION_LOG_HEADER = 'ts\tphase\tdecision\twhy\tevidence\tresult';
6062
6148
 
6149
+ // Field #8: append-only telemetry logs grew without bound (decisions.tsv 13 MB / 76k rows,
6150
+ // route-audit.segments.jsonl 12.5 MB in one consumer) on slow external volumes. Before an
6151
+ // append, a log past `maxBytes` is renamed to `<file>.1` (one generation, replacing the older
6152
+ // one), so disk use stays ≤ ~2× the cap. Rename is atomic; a lost race at worst drops one old
6153
+ // generation of diagnostics, never the row being written. Readers merge `.1` + current.
6154
+ export const APPEND_LOG_MAX_BYTES = 4 * 1024 * 1024;
6155
+ export function rotateAppendLogSync(target, maxBytes = APPEND_LOG_MAX_BYTES) {
6156
+ try {
6157
+ if (fsSync.statSync(target).size < maxBytes) return false;
6158
+ fsSync.renameSync(target, `${target}.1`);
6159
+ return true;
6160
+ } catch {
6161
+ return false;
6162
+ }
6163
+ }
6164
+
6063
6165
  function decisionLogPath(projectRoot) {
6064
6166
  return path.join(projectRoot, '.ukit', 'storage', 'decisions.tsv');
6065
6167
  }
@@ -6093,6 +6195,7 @@ export async function appendDecision(projectRoot, {
6093
6195
  ].map(sanitizeDecisionCell).join('\t');
6094
6196
  try {
6095
6197
  await fs.mkdir(path.dirname(target), { recursive: true });
6198
+ rotateAppendLogSync(target);
6096
6199
  let needsHeader = true;
6097
6200
  try {
6098
6201
  needsHeader = (await fs.stat(target)).size === 0;
@@ -16,6 +16,7 @@ let recordAllowedSuccess = () => 0;
16
16
  try { ({ adviseOnBlock, recordAllowedSuccess } = await import('./block-breaker.mjs')); } catch { /* advisory only */ }
17
17
  // TASK-019: chain rows and direct-hook rows share one versioned schema and one
18
18
  // append API (hook-telemetry.mjs) — including safeName for session files.
19
+ import { capPromptInjection, DEFAULT_MAX_PROMPT_INJECTION_CHARS } from './prompt-injection-cap.mjs';
19
20
  import { appendTelemetryRow, recordHookTiming, TELEMETRY_VERSION } from './hook-telemetry.mjs';
20
21
  // TASK-018 review fix round 1: the chain budget is resolved by ONE shared module
21
22
  // so the runner's inner deadline and the bridge's outer pi.exec timeout can never
@@ -224,6 +225,24 @@ function coalesceJsonStdout(text) {
224
225
  return `${JSON.stringify(merged)}\n`;
225
226
  }
226
227
 
228
+ function readPromptInjectionCap(projectRoot) {
229
+ try {
230
+ const cfg = JSON.parse(fs.readFileSync(path.join(projectRoot, '.ukit', 'storage', 'config.json'), 'utf8'));
231
+ const n = Number(cfg?.compact?.maxPromptInjectionChars);
232
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_MAX_PROMPT_INJECTION_CHARS;
233
+ } catch { return DEFAULT_MAX_PROMPT_INJECTION_CHARS; }
234
+ }
235
+
236
+ function capPromptOutput(out, payloadText, firstScriptArg) {
237
+ try {
238
+ const payload = JSON.parse(payloadText || '{}');
239
+ if (payload?.hook_event_name !== 'UserPromptSubmit') return out;
240
+ const first = firstScriptArg ? parseScriptArg(firstScriptArg).scriptPath : '';
241
+ const projectRoot = first ? path.resolve(path.dirname(first), '../..') : (payload.cwd || process.cwd());
242
+ return capPromptInjection(out, readPromptInjectionCap(projectRoot));
243
+ } catch { return out; }
244
+ }
245
+
227
246
  // B1 (TASK-001, SPEC §FR-001): a child that emits a `hookSpecificOutput`
228
247
  // permission decision owns the verdict. `hookSpecificOutput` alone is NOT
229
248
  // enough — a child killed mid-write can carry the marker in a truncated
@@ -980,7 +999,7 @@ try {
980
999
  else process.stderr.write(breakerAdvice(`${last.scriptName} blocked (exit 2) with no reason`));
981
1000
  process.exitCode = 2;
982
1001
  } else {
983
- process.stdout.write(coalesceJsonStdout(`${contextStdout}${last.stdout || ''}`));
1002
+ process.stdout.write(capPromptOutput(coalesceJsonStdout(`${contextStdout}${last.stdout || ''}`), payloadText, scriptPaths[0]));
984
1003
  // A spawn-unavailable `last` carries only the warning already written above.
985
1004
  if (last.stderr && last.failureKind !== 'spawn-unavailable') process.stderr.write(last.stderr);
986
1005
  process.exitCode = last.code === 0 ? 0 : (lastIsFailClosed ? 2 : 0);
@@ -0,0 +1,85 @@
1
+ // Mission semantic checkpoint (WP3). Contract:
2
+ // writeCheckpoint({projectRoot, missionId, trigger, git, graph?, now?}) -> Promise<checkpoint|null>
3
+ // writes <mid>/checkpoints/<seq>.json atomically (tmp+rename), keeps the last 5, never throws.
4
+ // latestCheckpoint(projectRoot, missionId) -> checkpoint|null
5
+ // Checkpoint {v,seq,ts,graphRev,trigger,objective:{promptId,text},facts[{text,src}],activeReqIds,decisions[{id,text,status}],
6
+ // hypotheses[],assumptions[],pending[],failures[],restrictions[],activeTaskId,nextAction,git:{head,branch,dirty},
7
+ // stop:{ownerStop,blockers[]}}
8
+ // Typed buckets never merge. facts come ONLY from verified ACs that hold ac.evidence; a hypothesis linked to an AC
9
+ // (acId) moves to facts only when that AC has evidence. Planned/unverified work is listed under pending, never as done.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { loadGraph } from './graph.mjs';
13
+ import { listPrompts } from './journal.mjs';
14
+ import { missionDir, readJsonFile, writeJsonAtomicFile } from './store.mjs';
15
+ import { activeTaskOf, buildWorkingMemory, readMemoryItems } from './working.mjs';
16
+
17
+ export const KEEP_CHECKPOINTS = 5;
18
+ const num = (id) => Number(String(id).replace(/\D/g, '')) || 0;
19
+ const dirOf = (projectRoot, mid) => path.join(missionDir(projectRoot, mid), 'checkpoints');
20
+
21
+ function seqs(projectRoot, mid) {
22
+ try { return fs.readdirSync(dirOf(projectRoot, mid)).filter((f) => /^\d+\.json$/.test(f)).map((f) => num(f)).sort((a, b) => a - b); } catch { return []; }
23
+ }
24
+
25
+ export function latestCheckpoint(projectRoot, missionId) {
26
+ const all = seqs(projectRoot, missionId);
27
+ for (let i = all.length - 1; i >= 0; i -= 1) {
28
+ const c = readJsonFile(path.join(dirOf(projectRoot, missionId), `${all[i]}.json`), null);
29
+ if (c) return c;
30
+ }
31
+ return null;
32
+ }
33
+
34
+ export function buildBuckets(g, items, prompts) {
35
+ const first = prompts.find((p) => p.origin === 'user');
36
+ const facts = [];
37
+ for (const ac of Object.values(g.state.acs)) {
38
+ const ev = ac.status === 'verified' ? (ac.evidence || [])[ac.evidence.length - 1] : null;
39
+ if (ev) facts.push({ text: `${ac.id} verified: ${g.acText(ac)}`.slice(0, 200), src: `${ev.kind}:${ev.ref}` });
40
+ }
41
+ const verifiedAc = (id) => id && g.state.acs[id]?.status === 'verified' && (g.state.acs[id].evidence || []).length > 0;
42
+ const hypotheses = [];
43
+ for (const h of items.hypotheses) {
44
+ if (verifiedAc(h.acId)) { const ev = g.state.acs[h.acId].evidence.slice(-1)[0]; facts.push({ text: h.text, src: `${ev.kind}:${ev.ref}` }); } else hypotheses.push({ id: h.id, text: h.text });
45
+ }
46
+ const live = Object.values(g.state.reqs).filter((r) => (r.status === 'active' || r.status === 'conflict') && r.kind !== 'question');
47
+ const pending = Object.values(g.state.tasks).filter((t) => !['verified', 'cancelled'].includes(t.status))
48
+ .sort((a, b) => num(a.id) - num(b.id)).slice(0, 40).map((t) => ({ id: t.id, status: t.status, title: t.title.slice(0, 100) }));
49
+ const lastUser = [...prompts].reverse().find((p) => p.origin === 'user');
50
+ const restrictions = Object.values(g.state.reqs).filter((r) => (r.kind === 'prohibition' || r.kind === 'constraint') && r.status !== 'superseded')
51
+ .slice(0, 20).map((r) => ({ id: r.id, text: r.text.slice(0, 160), promptId: r.promptId }));
52
+ return {
53
+ objective: first ? { promptId: first.promptId, text: first.text.slice(0, 300) } : { promptId: null, text: '' },
54
+ facts: facts.slice(-40), hypotheses: hypotheses.slice(-20), pending, restrictions,
55
+ activeReqIds: live.map((r) => r.id).slice(0, 60),
56
+ decisions: items.decisions.slice(-30).map((d) => ({ id: d.id, text: d.text, status: d.status || 'accepted' })),
57
+ assumptions: items.assumptions.slice(-20).map((a) => ({ id: a.id, text: a.text })),
58
+ failures: items.failures.slice(-20).map((f) => ({ id: f.id, text: f.text })),
59
+ stop: {
60
+ ownerStop: Boolean(lastUser?.ownerStop),
61
+ blockers: Object.entries(g.state.blockers).map(([taskId, b]) => ({ taskId, code: b.code, reason: String(b.reason || '').slice(0, 120) })).slice(0, 20),
62
+ },
63
+ };
64
+ }
65
+
66
+ export async function writeCheckpoint({ projectRoot, missionId, trigger = 'manual', git = {}, graph, now = Date.now() } = {}) {
67
+ try {
68
+ const g = graph || await loadGraph({ projectRoot, missionId });
69
+ const items = readMemoryItems(projectRoot, missionId);
70
+ const b = buildBuckets(g, items, listPrompts(projectRoot, missionId));
71
+ const working = await buildWorkingMemory({ projectRoot, missionId, graph: g, now });
72
+ const all = seqs(projectRoot, missionId);
73
+ const seq = (all[all.length - 1] || 0) + 1;
74
+ const cp = {
75
+ v: 1, seq, ts: now, graphRev: g.state.rev, trigger, ...b,
76
+ activeTaskId: activeTaskOf(g)?.id || null, nextAction: working?.nextAction || '',
77
+ git: { head: git.head || null, branch: git.branch || null, dirty: Boolean(git.dirty) },
78
+ };
79
+ writeJsonAtomicFile(path.join(dirOf(projectRoot, missionId), `${seq}.json`), cp);
80
+ for (const old of seqs(projectRoot, missionId).slice(0, -KEEP_CHECKPOINTS)) {
81
+ try { fs.unlinkSync(path.join(dirOf(projectRoot, missionId), `${old}.json`)); } catch { /* */ }
82
+ }
83
+ return cp;
84
+ } catch { return null; }
85
+ }