@denizokcu/haze 1.1.0 → 1.2.0

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 (149) hide show
  1. package/CHANGELOG.md +49 -1
  2. package/README.md +17 -10
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/busyIndicator.d.ts +11 -0
  6. package/dist/cli/chat/busyIndicator.js +34 -0
  7. package/dist/cli/chat/chatMetrics.d.ts +0 -1
  8. package/dist/cli/chat/chatMetrics.js +1 -7
  9. package/dist/cli/chat/followUpQueue.d.ts +11 -0
  10. package/dist/cli/chat/followUpQueue.js +38 -0
  11. package/dist/cli/chat/messages.d.ts +0 -22
  12. package/dist/cli/chat/messages.js +40 -85
  13. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  14. package/dist/cli/chat/sessionLifecycle.js +8 -1
  15. package/dist/cli/chat/sessionRecorder.d.ts +9 -0
  16. package/dist/cli/chat/sessionRecorder.js +12 -0
  17. package/dist/cli/chat/startupSequence.d.ts +29 -0
  18. package/dist/cli/chat/startupSequence.js +59 -0
  19. package/dist/cli/chat/transcriptPartition.d.ts +23 -0
  20. package/dist/cli/chat/transcriptPartition.js +78 -0
  21. package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
  22. package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
  23. package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
  24. package/dist/cli/chat/wizard/lspHandlers.js +85 -0
  25. package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
  26. package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
  27. package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
  28. package/dist/cli/chat/wizard/providerHandlers.js +420 -0
  29. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
  30. package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
  31. package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
  32. package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
  33. package/dist/cli/chat/wizard/types.d.ts +63 -0
  34. package/dist/cli/chat/wizard/types.js +24 -0
  35. package/dist/cli/chat/wizard/uiState.d.ts +56 -0
  36. package/dist/cli/chat/wizard/uiState.js +15 -0
  37. package/dist/cli/chat/wizardDispatch.d.ts +11 -113
  38. package/dist/cli/chat/wizardDispatch.js +41 -815
  39. package/dist/cli/commands/chat.js +69 -110
  40. package/dist/cli/commands/formatters.d.ts +0 -3
  41. package/dist/cli/commands/formatters.js +0 -29
  42. package/dist/cli/commands/runCommand.d.ts +2 -0
  43. package/dist/cli/commands/runCommand.js +73 -4
  44. package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
  45. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  46. package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
  47. package/dist/cli/commands/streaming/assistantSegments.js +48 -0
  48. package/dist/cli/commands/streaming/attemptOutcome.d.ts +25 -5
  49. package/dist/cli/commands/streaming/attemptOutcome.js +69 -16
  50. package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
  51. package/dist/cli/commands/streaming/attemptSetup.js +30 -13
  52. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
  53. package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
  54. package/dist/cli/commands/streaming/goalSupervisor.d.ts +18 -3
  55. package/dist/cli/commands/streaming/goalSupervisor.js +71 -12
  56. package/dist/cli/commands/streaming/prepareStep.d.ts +40 -0
  57. package/dist/cli/commands/streaming/prepareStep.js +116 -0
  58. package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
  59. package/dist/cli/commands/streaming/recoverySlices.js +29 -0
  60. package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
  61. package/dist/cli/commands/streaming/stallRecovery.js +2 -6
  62. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  63. package/dist/cli/commands/streaming/streamLoop.js +283 -268
  64. package/dist/cli/commands/streaming/toolGroupRenderer.js +2 -1
  65. package/dist/cli/commands/streaming/toolPartHandlers.d.ts +19 -0
  66. package/dist/cli/commands/streaming/toolPartHandlers.js +108 -0
  67. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  68. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  69. package/dist/cli/commands/streaming.d.ts +12 -1
  70. package/dist/cli/commands/streaming.js +20 -25
  71. package/dist/cli/index.js +6 -3
  72. package/dist/config/modelCatalog.d.ts +32 -0
  73. package/dist/config/modelCatalog.js +84 -0
  74. package/dist/config/providerPresets.d.ts +7 -0
  75. package/dist/config/providerPresets.js +195 -391
  76. package/dist/config/settings.d.ts +10 -2
  77. package/dist/config/settings.js +3 -0
  78. package/dist/core/agent/budgets.d.ts +10 -0
  79. package/dist/core/agent/budgets.js +10 -0
  80. package/dist/core/agent/compaction.d.ts +42 -3
  81. package/dist/core/agent/compaction.js +53 -5
  82. package/dist/core/agent/completionController.d.ts +16 -7
  83. package/dist/core/agent/completionController.js +13 -6
  84. package/dist/core/agent/contextBudget.d.ts +56 -0
  85. package/dist/core/agent/contextBudget.js +53 -0
  86. package/dist/core/agent/errors.js +2 -2
  87. package/dist/core/agent/events.d.ts +36 -1
  88. package/dist/core/agent/goalPolicy.d.ts +4 -3
  89. package/dist/core/agent/goalPolicy.js +9 -4
  90. package/dist/core/agent/overflow.d.ts +45 -0
  91. package/dist/core/agent/overflow.js +91 -0
  92. package/dist/core/agent/requestAssembly.d.ts +7 -0
  93. package/dist/core/agent/requestAssembly.js +15 -7
  94. package/dist/core/agent/workState.d.ts +25 -15
  95. package/dist/core/agent/workState.js +84 -44
  96. package/dist/core/safety/shellClassifier.d.ts +16 -0
  97. package/dist/core/safety/shellClassifier.js +31 -0
  98. package/dist/core/session/sessionSlimming.js +8 -0
  99. package/dist/core/session/sessionStore.d.ts +71 -1
  100. package/dist/core/session/sessionStore.js +121 -6
  101. package/dist/core/validation/outputParser.d.ts +1 -1
  102. package/dist/core/validation/outputParser.js +6 -1
  103. package/dist/llm/client.d.ts +2 -2
  104. package/dist/llm/client.js +14 -6
  105. package/dist/llm/hazeTools.d.ts +64 -208
  106. package/dist/llm/tools/shellTool.js +27 -8
  107. package/dist/llm/tools/taskTool.d.ts +64 -208
  108. package/dist/llm/tools/taskTool.js +22 -10
  109. package/dist/ui/components/TextInput.d.ts +18 -1
  110. package/dist/ui/components/TextInput.js +50 -73
  111. package/dist/ui/components/useInputSuggestions.d.ts +27 -0
  112. package/dist/ui/components/useInputSuggestions.js +98 -0
  113. package/dist/ui/theme.d.ts +8 -8
  114. package/dist/ui/theme.js +11 -12
  115. package/dist/ui/themes/registry.d.ts +5 -0
  116. package/dist/ui/themes/registry.js +436 -0
  117. package/dist/utils/format.d.ts +10 -0
  118. package/dist/utils/format.js +45 -0
  119. package/package.json +16 -15
  120. package/dist/ui/themes/af-magic.d.ts +0 -7
  121. package/dist/ui/themes/af-magic.js +0 -25
  122. package/dist/ui/themes/agnoster.d.ts +0 -10
  123. package/dist/ui/themes/agnoster.js +0 -40
  124. package/dist/ui/themes/bira.d.ts +0 -10
  125. package/dist/ui/themes/bira.js +0 -28
  126. package/dist/ui/themes/bureau.d.ts +0 -10
  127. package/dist/ui/themes/bureau.js +0 -28
  128. package/dist/ui/themes/clean.d.ts +0 -9
  129. package/dist/ui/themes/clean.js +0 -27
  130. package/dist/ui/themes/cloud.d.ts +0 -6
  131. package/dist/ui/themes/cloud.js +0 -24
  132. package/dist/ui/themes/dst.d.ts +0 -10
  133. package/dist/ui/themes/dst.js +0 -28
  134. package/dist/ui/themes/fishy.d.ts +0 -7
  135. package/dist/ui/themes/fishy.js +0 -25
  136. package/dist/ui/themes/index.d.ts +0 -8
  137. package/dist/ui/themes/index.js +0 -36
  138. package/dist/ui/themes/light.d.ts +0 -3
  139. package/dist/ui/themes/light.js +0 -21
  140. package/dist/ui/themes/purple.d.ts +0 -7
  141. package/dist/ui/themes/purple.js +0 -26
  142. package/dist/ui/themes/robbyrussell.d.ts +0 -8
  143. package/dist/ui/themes/robbyrussell.js +0 -26
  144. package/dist/ui/themes/solarized-dark.d.ts +0 -16
  145. package/dist/ui/themes/solarized-dark.js +0 -44
  146. package/dist/ui/themes/solarized-light.d.ts +0 -12
  147. package/dist/ui/themes/solarized-light.js +0 -40
  148. package/dist/ui/themes/steeef.d.ts +0 -11
  149. package/dist/ui/themes/steeef.js +0 -29
@@ -0,0 +1,48 @@
1
+ import { agentEvent } from '../../../core/agent/events.js';
2
+ import { assistantDisplayText, normalizeAssistantText, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './assistantText.js';
3
+ import { responseCompletionMetrics } from './turnRuntime.js';
4
+ /**
5
+ * Assistant segment lifecycle (extracted from streamLoop.ts): one segment is
6
+ * the text between tool calls (or the final answer). Segments start lazily
7
+ * (gated by `shouldStartAssistantStream`), finalize with duplicate/lead-in
8
+ * suppression, and reset for the next segment.
9
+ */
10
+ export function resetAssistantSegment(loopState) {
11
+ loopState.currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
12
+ loopState.assistantStarted = false;
13
+ loopState.assistantStartedAt = Date.now();
14
+ loopState.currentAssistantText = '';
15
+ }
16
+ export function finalizeAssistantSegment(loopState, callbacks, options = {}) {
17
+ const finalText = assistantDisplayText(loopState.currentAssistantText);
18
+ const normalized = normalizeAssistantText(finalText);
19
+ const hidden = (loopState.assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
20
+ || (options.beforeTool === true && isShortLeadInBeforeTool(finalText))
21
+ || (options.beforeTool !== true && isShortUnfinishedLeadIn(finalText))
22
+ || (normalized.length > 0 && loopState.visibleAssistantTexts.has(normalized));
23
+ if (loopState.assistantStarted) {
24
+ if (!hidden)
25
+ loopState.rememberVisibleAssistantText(finalText);
26
+ callbacks.onEvent?.(agentEvent({ type: 'message_end', id: loopState.currentAssistantId, text: finalText, hidden }));
27
+ callbacks.updateMessage(loopState.currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, loopState.assistantStartedAt) });
28
+ }
29
+ else if (!hidden) {
30
+ if (!hidden)
31
+ loopState.rememberVisibleAssistantText(finalText);
32
+ callbacks.onEvent?.(agentEvent({ type: 'message_start', id: loopState.currentAssistantId, role: 'assistant' }));
33
+ callbacks.onEvent?.(agentEvent({ type: 'message_end', id: loopState.currentAssistantId, text: finalText, hidden: false }));
34
+ callbacks.addMessage({ id: loopState.currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: loopState.assistantStartedAt, ...responseCompletionMetrics(finalText, loopState.assistantStartedAt) });
35
+ }
36
+ resetAssistantSegment(loopState);
37
+ return !hidden;
38
+ }
39
+ /** Finalize any pending assistant text right before a tool call starts, demoting hidden lead-ins to the tool group caption. */
40
+ export function finalizePendingAssistantBeforeTool(deps) {
41
+ const { loopState, callbacks, toolDisplay } = deps;
42
+ if (loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted) {
43
+ const pending = assistantDisplayText(loopState.currentAssistantText);
44
+ const shown = finalizeAssistantSegment(loopState, callbacks, { beforeTool: true });
45
+ if (!shown && pending)
46
+ toolDisplay.setGroupCaption(pending);
47
+ }
48
+ }
@@ -30,9 +30,10 @@ export declare function terminalTurnStatus(input: {
30
30
  mutationCount?: number;
31
31
  validationOutcome?: ValidationOutcome;
32
32
  taskProgress?: WorkTaskProgress;
33
+ redPair?: 'not-required' | 'missing' | 'satisfied';
33
34
  }): TurnStatus;
34
35
  /** Bounded recovery slice an attempt proposes for the next agent call. */
35
- type AttemptRecovery = {
36
+ export type AttemptRecovery = {
36
37
  kind: 'length' | 'rescue' | 'goal';
37
38
  control: string;
38
39
  slice: {
@@ -44,9 +45,9 @@ type AttemptRecovery = {
44
45
  export type AgentAttemptResult = TurnResult & {
45
46
  retry?: {
46
47
  attempt: number;
47
- contextOverflowRecovered: boolean;
48
48
  delayMs: number; /** The retry aborts the previous controller (idle stall); hand the loop a fresh one. */
49
- freshController?: boolean;
49
+ freshController?: boolean; /** Message-budget multiplier for the next attempt after an overflow retry (Pillar 1.4). */
50
+ overflowShrinkFactor?: number;
50
51
  };
51
52
  /** When set, run one bounded recovery slice next (length-continuation, rescue, or goal continuation). */
52
53
  recovery?: AttemptRecovery;
@@ -63,6 +64,10 @@ export interface AttemptOutcomeDeps {
63
64
  goal: SessionGoal;
64
65
  remainingTurnDeadlineMs: () => number;
65
66
  stream: AttemptStreamOutcome;
67
+ /** Current attempt number (for overflow retry bookkeeping). */
68
+ retryAttempt: number;
69
+ /** Context-overflow retries already consumed by this turn (Pillar 1.4). */
70
+ overflowRetries: number;
66
71
  }
67
72
  /**
68
73
  * Classify the finished attempt: project work evidence onto the turn state,
@@ -78,19 +83,34 @@ export interface AttemptFailureDeps {
78
83
  abortController: AbortController;
79
84
  turnState: TurnExecutionState;
80
85
  retryAttempt: number;
81
- contextOverflowRecovered: boolean;
86
+ /** Whether the failed attempt completed at least one step since the previous retry (Pillar 1.3: progress refills the shared pool). */
87
+ progressSinceLastRetry?: boolean;
88
+ /** Context-overflow retries already consumed by this turn (Pillar 1.4). */
89
+ overflowRetries?: number;
82
90
  abortCause: TurnAbortCause;
83
91
  stallGuard: StreamStallGuard | undefined;
84
92
  salvage: AttemptSalvage;
85
93
  error: unknown;
86
94
  /** Retry-pool size for this turn (`modelRetries` setting); defaults to DEFAULT_MODEL_RETRIES. */
87
95
  maxRetries?: number;
96
+ /** Backoff base for the shared model-retry pool (`retryBaseDelayMs` setting); defaults to DEFAULT_RETRY_BASE_DELAY_MS. */
97
+ retryBaseDelayMs?: number;
98
+ goal: SessionGoal;
99
+ turnOptions: TurnExecutionOptions;
88
100
  }
89
101
  /**
90
102
  * Classify a failed attempt from the recorded abort cause and the error:
91
103
  * idle-stall retry/pause (shared bounded retry pool), absolute turn deadline,
92
104
  * user abort, context-overflow compaction retry, transient model retry, or a
93
105
  * hard model-call failure. Completed-step progress is always preserved.
106
+ *
107
+ * Pillar 1.3: the shared retry pool resets whenever the failed attempt made
108
+ * progress (completed at least one step) since the previous retry — a long
109
+ * turn with intermittent blips never exhausts the pool. Pillar 1.4: each
110
+ * context-overflow retry shrinks the message budget (0.6 → 0.36); once the
111
+ * bounded overflow retries are exhausted the goal checkpoints
112
+ * (`context_exhausted`) instead of hard-failing, so the supervisor or the
113
+ * R-resume can continue after the user compacts, clears context, or switches
114
+ * models — never a false hard block.
94
115
  */
95
116
  export declare function handleAttemptFailure(deps: AttemptFailureDeps): AgentAttemptResult;
96
- export {};
@@ -3,13 +3,14 @@ import { agentEvent } from '../../../core/agent/events.js';
3
3
  import { isContextOverflowError, isRetryableModelError } from '../../../core/agent/errors.js';
4
4
  import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
5
5
  import { assessCompletionReadiness, classifyTerminalOutcome, decideGoalContinuation, decideLengthRecovery, decideRescue, describeCompletionReadiness, goalContinuationRecoverable, isBudgetExhausted, rescueEligibleRequest } from '../../../core/agent/completionController.js';
6
- import { clampSlice, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
7
- import { deriveValidationOutcome } from '../../../core/agent/workState.js';
6
+ import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
7
+ import { deriveValidationOutcome, redPairStatus } from '../../../core/agent/workState.js';
8
8
  import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
9
- import { buildIncompleteGoalResume } from './goalCheckpoint.js';
10
- import { formatSeconds } from '../formatters.js';
9
+ import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
10
+ import { formatSeconds } from '../../../utils/format.js';
11
11
  import { retryDelayMs } from './turnRuntime.js';
12
- import { formatIdleMinutes, salvageConversationToLastStep } from './stallRecovery.js';
12
+ import { salvageConversationToLastStep } from './stallRecovery.js';
13
+ import { formatIdleMinutes } from '../../../utils/format.js';
13
14
  /**
14
15
  * CLI adapter for the authoritative turn-status decision. The pure policy
15
16
  * lives in `core/agent/completionController.ts`; this keeps the single call site
@@ -30,6 +31,7 @@ export function terminalTurnStatus(input) {
30
31
  mutationCount: input.mutationCount ?? 0,
31
32
  ...(input.validationOutcome ? { validationOutcome: input.validationOutcome } : {}),
32
33
  ...(input.taskProgress ? { taskProgress: input.taskProgress } : {}),
34
+ ...(input.redPair ? { redPair: input.redPair } : {}),
33
35
  };
34
36
  return decideTerminalStatus(state, {
35
37
  sawToolCall: input.sawToolCall,
@@ -46,6 +48,8 @@ export function projectGoalEvidence(turnState, goal) {
46
48
  turnState.validationKind = goal.validations.at(-1)?.kind ?? goal.carriedValidation?.kind;
47
49
  turnState.validationAfterMutation = goal.validationSeq > 0 && goal.validationSeq >= goal.mutationSeq;
48
50
  turnState.taskProgress = goal.taskProgress;
51
+ // Opportunistic red→green: only an actually observed red can gate.
52
+ turnState.redPair = redPairStatus(goal);
49
53
  }
50
54
  /**
51
55
  * Classify the finished attempt: project work evidence onto the turn state,
@@ -64,10 +68,28 @@ export function finalizeAttemptOutcome(deps) {
64
68
  const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, unresolvedToolInputError: stream.unresolvedToolInputError };
65
69
  const readiness = assessCompletionReadiness(turnState, completionEvidence);
66
70
  const classification = classifyTerminalOutcome(turnState, completionEvidence);
67
- const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress });
71
+ const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress, ...(turnState.redPair ? { redPair: turnState.redPair } : {}) });
68
72
  if (stream.unresolvedMalformedToolName)
69
73
  callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
70
74
  goal.phase = 'done';
75
+ // Non-error overflow recovery (Pillar 1.2/1.4): a silent overflow completed
76
+ // its response, so compact only — the next physical turn (or the supervisor)
77
+ // continues from the smaller history; a length-stop overflow dropped the
78
+ // truncated final and retries the same request once per shrink step.
79
+ if (stream.usageOverflow && !abortController.signal.aborted) {
80
+ const compacted = callbacks.compactConversation?.('Automatic recovery after a context-window overflow detected from provider usage. Preserve the active user request and concrete next steps.') ?? false;
81
+ const willRetry = compacted && stream.usageOverflow === 'length-stop' && deps.overflowRetries < MAX_OVERFLOW_RETRIES;
82
+ callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: `silent usage overflow (window exceeded on a successful finish)` }));
83
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'overflow', method: 'heuristic' }));
84
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'overflow', method: compacted ? 'heuristic' : 'none', compacted, willRetry }));
85
+ if (willRetry) {
86
+ callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
87
+ callbacks.addMessage({ role: 'system', text: 'Context window filled by truncated input; compacted older context and retrying the same request at a smaller budget.' });
88
+ return { status: 'failed', retry: { attempt: deps.retryAttempt, delayMs: 0, overflowShrinkFactor: OVERFLOW_SHRINK_FACTOR ** (deps.overflowRetries + 1) } };
89
+ }
90
+ if (compacted)
91
+ callbacks.addMessage({ role: 'system', text: 'Context overflow detected from provider usage; compacted older context. Completed work is preserved.' });
92
+ }
71
93
  // Goal status reflects completion readiness, not the shallow text status:
72
94
  // unfinished-but-recoverable work is waiting on continuation (supervisor or
73
95
  // the user), while tool/input failures are concrete blockers. Prose alone
@@ -89,10 +111,16 @@ export function finalizeAttemptOutcome(deps) {
89
111
  // physical turns; a bare runAgentTurn caller surfaces them as resume info.
90
112
  const goalId = turnOptions.goalContext?.goalId ?? goal.id;
91
113
  const goalCycle = turnOptions.goalContext?.cycle ?? 1;
114
+ const carriedEvidence = {
115
+ ...(turnOptions.goalContext?.requestHash ? { requestHash: turnOptions.goalContext.requestHash } : {}),
116
+ // Carry red evidence until the same check passes after the mutation. This
117
+ // includes boundaries reached after red capture but before the first edit.
118
+ ...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
119
+ };
92
120
  const discardRejectedFinal = () => callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
93
121
  const checkpointResult = () => {
94
122
  discardRejectedFinal();
95
- return { status: 'failed', resume: buildIncompleteGoalResume(value, goalId, goalCycle, turnState, readiness) };
123
+ return { status: 'failed', resume: buildIncompleteGoalResume(value, goalId, goalCycle, turnState, readiness, carriedEvidence) };
96
124
  };
97
125
  if (!abortController.signal.aborted) {
98
126
  const lengthDecision = decideLengthRecovery(turnState, turnBudget);
@@ -116,7 +144,7 @@ export function finalizeAttemptOutcome(deps) {
116
144
  discardRejectedFinal();
117
145
  if (readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation')
118
146
  turnState.validationContinuationUsed = true;
119
- return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
147
+ return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress), taskCountsOf(turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
120
148
  }
121
149
  else if (rescueSlice && rescueSlice.steps > 0) {
122
150
  return { status: turnStatus, recovery: { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } } };
@@ -136,10 +164,24 @@ export function finalizeAttemptOutcome(deps) {
136
164
  * idle-stall retry/pause (shared bounded retry pool), absolute turn deadline,
137
165
  * user abort, context-overflow compaction retry, transient model retry, or a
138
166
  * hard model-call failure. Completed-step progress is always preserved.
167
+ *
168
+ * Pillar 1.3: the shared retry pool resets whenever the failed attempt made
169
+ * progress (completed at least one step) since the previous retry — a long
170
+ * turn with intermittent blips never exhausts the pool. Pillar 1.4: each
171
+ * context-overflow retry shrinks the message budget (0.6 → 0.36); once the
172
+ * bounded overflow retries are exhausted the goal checkpoints
173
+ * (`context_exhausted`) instead of hard-failing, so the supervisor or the
174
+ * R-resume can continue after the user compacts, clears context, or switches
175
+ * models — never a false hard block.
139
176
  */
140
177
  export function handleAttemptFailure(deps) {
141
- const { value, callbacks, abortController, turnState, retryAttempt, contextOverflowRecovered, abortCause, stallGuard, salvage, error } = deps;
178
+ const { value, callbacks, abortController, turnState, abortCause, stallGuard, salvage, error, goal, turnOptions } = deps;
142
179
  const maxRetries = deps.maxRetries ?? DEFAULT_MODEL_RETRIES;
180
+ const retryBaseDelayMs = deps.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;
181
+ const overflowRetries = deps.overflowRetries ?? 0;
182
+ // Progress refills the shared pool: consecutive failures chain backoff, but
183
+ // a failed attempt that completed steps since the last retry starts fresh.
184
+ const retryAttempt = deps.progressSinceLastRetry && deps.retryAttempt > 0 ? 0 : deps.retryAttempt;
143
185
  if (abortController.signal.aborted) {
144
186
  if (abortCause.kind === 'model-stream-idle') {
145
187
  // Transport stall, not a user cancel. Preserve completed work first: the
@@ -148,12 +190,12 @@ export function handleAttemptFailure(deps) {
148
190
  // instead of re-running — possibly mutating — tool work.
149
191
  salvageConversationToLastStep(callbacks, salvage);
150
192
  if (stallGuard?.retryEligible) {
151
- const delay = retryDelayMs(retryAttempt);
193
+ const delay = retryDelayMs(retryAttempt, retryBaseDelayMs);
152
194
  callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: `model stream idle for ${formatSeconds(IDLE_TIMEOUT_MS)}` }));
153
195
  callbacks.addMessage({ role: 'system', text: `Model stream stalled for ${formatIdleMinutes(IDLE_TIMEOUT_MS)}; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}. Completed steps are preserved.` });
154
196
  // freshController: this stall aborted the controller to kill the hung
155
197
  // stream; the retry needs a live signal.
156
- return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay, freshController: true } };
198
+ return { status: 'failed', retry: { attempt: retryAttempt + 1, delayMs: delay, freshController: true } };
157
199
  }
158
200
  // Bounded retries exhausted, or the stalled step emitted partial output.
159
201
  // Pause with the active goal preserved (work state is untouched by this
@@ -179,15 +221,26 @@ export function handleAttemptFailure(deps) {
179
221
  }
180
222
  const text = error instanceof Error ? error.message : String(error);
181
223
  callbacks.debugLog(`error: ${text}`);
182
- if (!contextOverflowRecovered && isContextOverflowError(error)) {
224
+ // Bounded overflow retries with progressive shrink (Pillar 1.4): each retry
225
+ // compacts and multiplies the message budget by 0.6; once MAX_OVERFLOW_RETRIES
226
+ // are consumed the goal checkpoints instead of hard-failing.
227
+ if (overflowRetries >= MAX_OVERFLOW_RETRIES && isContextOverflowError(error)) {
228
+ callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: false, error: text }));
229
+ callbacks.addMessage({ role: 'system', text: 'Context overflow persisted after bounded compaction retries; pausing the goal with a checkpoint. Completed work is preserved in the conversation. Press R to resume after compacting or clearing context, or switch to a larger-context model.' });
230
+ return { status: 'failed', resume: buildIncompleteGoalResume(value, turnOptions.goalContext?.goalId ?? goal.id, turnOptions.goalContext?.cycle ?? 1, turnState, 'context_exhausted', {}) };
231
+ }
232
+ if (isContextOverflowError(error)) {
183
233
  const canCompact = typeof callbacks.compactConversation === 'function';
184
234
  const compacted = canCompact
185
235
  ? callbacks.compactConversation?.('Automatic recovery after provider context overflow. Preserve the active user request and concrete next steps.') ?? false
186
236
  : false;
187
237
  callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
238
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'overflow', method: 'heuristic' }));
239
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'overflow', method: compacted ? 'heuristic' : 'none', compacted, willRetry: compacted }));
188
240
  if (compacted) {
189
- callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
190
- return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
241
+ const shrink = OVERFLOW_SHRINK_FACTOR ** (overflowRetries + 1);
242
+ callbacks.addMessage({ role: 'system', text: `Context overflow detected; compacted older context and retrying the same request at ${Math.round(shrink * 100)}% of the message budget.` });
243
+ return { status: 'failed', retry: { attempt: retryAttempt, delayMs: 0, overflowShrinkFactor: shrink } };
191
244
  }
192
245
  callbacks.addMessage({ role: 'system', text: canCompact
193
246
  ? 'Context overflow detected, but there was not enough conversation history to compact automatically.'
@@ -196,10 +249,10 @@ export function handleAttemptFailure(deps) {
196
249
  // Transient model errors share the bounded retry pool with idle-stream
197
250
  // stalls, so a turn can never retry more than its configured total.
198
251
  if (retryAttempt < maxRetries && isRetryableModelError(error)) {
199
- const delay = retryDelayMs(retryAttempt);
252
+ const delay = retryDelayMs(retryAttempt, retryBaseDelayMs);
200
253
  callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
201
254
  callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
202
- return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
255
+ return { status: 'failed', retry: { attempt: retryAttempt + 1, delayMs: delay } };
203
256
  }
204
257
  callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
205
258
  return { status: 'failed' };
@@ -1,8 +1,8 @@
1
1
  import type { ModelMessage, ToolSet } from 'ai';
2
2
  import type { ContextFile } from '../../../config/contextFiles.js';
3
- import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
4
- import { calculateRequestTokenBudget } from '../../../core/agent/contextBudget.js';
5
3
  import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
4
+ import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
5
+ import { calculateRequestTokenBudget, type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
6
6
  import { providerRequestSettings, type ModelRuntimeSelection } from '../../../llm/client.js';
7
7
  import { type ToolCategory, type TurnExecutionScope } from '../../../llm/requestContext.js';
8
8
  import type { LoadedMcpTools } from '../../../llm/mcp.js';
@@ -47,13 +47,16 @@ export interface AttemptSetup {
47
47
  toolCategories: Map<string, ToolCategory>;
48
48
  /** Retry-pool size for this attempt's turn, from the `modelRetries` setting (default 2). */
49
49
  modelRetries: number;
50
+ /** Backoff base for the shared model-retry pool, from the `retryBaseDelayMs` setting (default 1000ms). */
51
+ retryBaseDelayMs: number;
50
52
  }
51
53
  export interface AttemptSetupDeps {
52
54
  value: string;
53
55
  contextFiles: ContextFile[];
54
56
  callbacks: StreamCallbacks;
55
57
  retryingExistingRequest: boolean;
56
- contextOverflowRecovered: boolean;
58
+ /** Multiplier for the message-token budget after context-overflow retries (1 = none, 0.6/0.36 after each; Pillar 1.4). */
59
+ overflowShrinkFactor: number;
57
60
  session: PromptSession | undefined;
58
61
  modelOverride: string | undefined;
59
62
  abortController: AbortController;
@@ -67,6 +70,10 @@ export interface AttemptSetupDeps {
67
70
  sliceBudget: ToolExecutionBudgetState;
68
71
  goal: SessionGoal;
69
72
  onContextFileRead: (path: string) => void;
73
+ /** Turn-scoped usage anchor for provider-usage-backed context estimation (Pillar 1.1). */
74
+ usageAnchor: {
75
+ current: ContextUsageAnchor | undefined;
76
+ };
70
77
  }
71
78
  /**
72
79
  * Assemble one attempt: resolve the model (single fresh settings read, CR-024),
@@ -1,12 +1,11 @@
1
1
  import { readSettings } from '../../../config/settings.js';
2
- import { DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
2
+ import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_RETRY_BASE_DELAY_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_MODEL_RETRIES, withToolExecutionBudget } from '../../../core/agent/budgets.js';
3
3
  import { agentEvent } from '../../../core/agent/events.js';
4
4
  import { isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
5
5
  import { formatGoalStatus } from '../../../core/agent/goalPolicy.js';
6
- import { calculateRequestTokenBudget, estimateMessagesTokens } from '../../../core/agent/contextBudget.js';
7
- import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
6
+ import { calculateRequestTokenBudget, estimateConversationTokens } from '../../../core/agent/contextBudget.js';
7
+ import { stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
8
8
  import { compactModelMessages } from '../../../core/agent/compaction.js';
9
- import { DEFAULT_MAX_OUTPUT_TOKENS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, withToolExecutionBudget } from '../../../core/agent/budgets.js';
10
9
  import { withToolDeadline } from '../../../core/deadline.js';
11
10
  import { isMutatingCapability, isValidationCapable } from '../../../core/agent/toolCapabilities.js';
12
11
  import { userTurnMessage } from '../../../core/attachments/imageAttachments.js';
@@ -40,9 +39,11 @@ export function restrictToRescueTools(tools) {
40
39
  * configured (the caller-reported failure path).
41
40
  */
42
41
  export async function prepareAttempt(deps) {
43
- const { value, contextFiles, callbacks, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead } = deps;
44
- // Single choke point: one fresh settings read per turn, shared by model
45
- // resolution and request assembly (CR-024).
42
+ const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
43
+ // Single choke point: one fresh settings read per attempt, shared by model
44
+ // resolution and request assembly (CR-024, relaxed in Pillar 1.9 so a
45
+ // provider/model switch mid-goal applies from the next attempt — the first
46
+ // attempt of each physical turn keeps the original read).
46
47
  const turnSettings = await readSettings();
47
48
  const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
48
49
  if (!runtime?.model) {
@@ -88,9 +89,14 @@ export async function prepareAttempt(deps) {
88
89
  callbacks.setWorkState?.(goal);
89
90
  callbacks.setGoalStatus?.(formatGoalStatus(goal));
90
91
  const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
91
- const durableRequestMessages = compactToolHistory(retryingExistingRequest
92
+ // Keep the active provider history exact. Routine tool-history slimming used
93
+ // to rewrite older successful calls/results here, invalidating provider
94
+ // prompt-cache prefixes before the context budget required compaction.
95
+ // Durable session snapshots are slimmed independently at the persistence
96
+ // boundary; only the model-aware compaction below may rewrite active history.
97
+ const durableRequestMessages = retryingExistingRequest
92
98
  ? stripSyntheticControls(callbacks.getConversation())
93
- : [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]).messages;
99
+ : [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])];
94
100
  // Model-aware request budget (RH-005): message allowance is the context
95
101
  // window minus system prompt, tool schemas, output reserve, and a safety
96
102
  // margin — not a fixed 40K constant. Small contexts get a safe budget; the
@@ -98,11 +104,21 @@ export async function prepareAttempt(deps) {
98
104
  const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
99
105
  const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: assembled.systemPrompt, tools: availableTools });
100
106
  // A context-overflow retry progressively shrinks the target so it cannot loop
101
- // at an unchanged budget; further overflows get even smaller (RH-005).
102
- const overflowTargetTokens = contextOverflowRecovered ? Math.floor(requestBudget.messageTokens * 0.6) : requestBudget.messageTokens;
107
+ // at an unchanged budget; further overflows get even smaller (RH-005, Pillar
108
+ // 1.4: 0.6 after the first, 0.36 after the second).
109
+ const overflowShrinkFactor = deps.overflowShrinkFactor;
110
+ const overflowTargetTokens = overflowShrinkFactor < 1 ? Math.floor(requestBudget.messageTokens * overflowShrinkFactor) : requestBudget.messageTokens;
111
+ const overheadTokens = requestBudget.systemTokens + requestBudget.toolSchemaTokens;
103
112
  let requestMessages = durableRequestMessages;
104
- if (estimateMessagesTokens(requestMessages) > overflowTargetTokens) {
105
- requestMessages = compactModelMessages(requestMessages, { tokenBudget: overflowTargetTokens, workState: goal }).messages;
113
+ if (estimateConversationTokens(requestMessages, usageAnchor.current, overheadTokens).tokens > overflowTargetTokens) {
114
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'threshold', method: 'heuristic' }));
115
+ const compacted = compactModelMessages(requestMessages, { tokenBudget: overflowTargetTokens, workState: goal });
116
+ requestMessages = compacted.messages;
117
+ if (compacted.compacted) {
118
+ usageAnchor.current = undefined;
119
+ callbacks.recordCompaction?.({ method: 'heuristic', olderCount: compacted.olderCount, keptCount: compacted.keptCount, summary: compacted.summary ?? '' });
120
+ }
121
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: compacted.compacted ? 'heuristic' : 'none', compacted: compacted.compacted, olderCount: compacted.olderCount, keptCount: compacted.keptCount }));
106
122
  }
107
123
  requestMessages = withoutSystemMessages(requestMessages);
108
124
  callbacks.setConversation(stripSyntheticControls(requestMessages));
@@ -163,5 +179,6 @@ export async function prepareAttempt(deps) {
163
179
  contextFiles: activeContextFiles,
164
180
  toolCategories,
165
181
  modelRetries: typeof turnSettings.modelRetries === 'number' ? turnSettings.modelRetries : DEFAULT_MODEL_RETRIES,
182
+ retryBaseDelayMs: typeof turnSettings.retryBaseDelayMs === 'number' ? turnSettings.retryBaseDelayMs : DEFAULT_RETRY_BASE_DELAY_MS,
166
183
  };
167
184
  }
@@ -1,11 +1,14 @@
1
1
  import type { CompletionReadiness, TurnExecutionState } from '../../../core/agent/completionController.js';
2
- import type { ValidationOutcome } from '../../../core/agent/workState.js';
2
+ import type { RequestIntent } from '../../../core/agent/goalPolicy.js';
3
+ import type { RedEvidence, ValidationOutcome, WorkTaskProgress } from '../../../core/agent/workState.js';
4
+ import type { GoalLedgerFrontier } from '../../../core/session/sessionStore.js';
3
5
  /**
4
6
  * Bounded continuation checkpoint for a logical goal whose work is recoverably
5
- * unfinished. Safe metadata only — reasons, counts, enums — never commands,
6
- * content, or credentials. Carried on `TurnResult.resume` so a goal supervisor
7
- * (or the interactive resume affordance) can continue the same logical goal in
8
- * a fresh physical turn without replaying completed work.
7
+ * unfinished. Safe metadata only — reasons, counts, enums, and red-evidence
8
+ * command strings without output bodies —
9
+ * never raw content or credentials. Carried on `TurnResult.resume` so a goal
10
+ * supervisor (or the interactive resume affordance) can continue the same
11
+ * logical goal in a fresh physical turn without replaying completed work.
9
12
  */
10
13
  export interface IncompleteGoalResume {
11
14
  kind: 'incomplete-goal';
@@ -25,13 +28,23 @@ export interface IncompleteGoalResume {
25
28
  completed: number;
26
29
  };
27
30
  validationOutcome?: ValidationOutcome;
31
+ /** sha256 prefix of the exact request bytes; binds downstream evidence to the mission (P1). */
32
+ requestHash?: string;
33
+ /** Unresolved pre-mutation failing repro for fix goals. */
34
+ redEvidence?: RedEvidence;
28
35
  }
29
- /** Supervisor-level checkpoint persisted between physical turns (in memory). */
36
+ /** Supervisor-level checkpoint persisted between physical turns (in memory and, via the goal ledger, in the session JSONL). */
30
37
  export interface GoalCheckpoint {
31
38
  goalId: string;
32
39
  request: string;
33
40
  cycle: number;
34
- readiness: CompletionReadiness;
41
+ /**
42
+ * Structured readiness that still blocks completion. Optional for a
43
+ * stored-goal resume whose ledger frontier predates a specific readiness
44
+ * (e.g. a crashed run): the continuation then uses the generic unfinished
45
+ * reason instead of guessing one.
46
+ */
47
+ readiness?: CompletionReadiness;
35
48
  taskCounts?: {
36
49
  total: number;
37
50
  pending: number;
@@ -44,7 +57,33 @@ export interface GoalCheckpoint {
44
57
  progressSignature: string;
45
58
  /** Consecutive physical turns without measurable progress. */
46
59
  noProgressCount: number;
60
+ requestHash?: string;
61
+ intent?: RequestIntent;
62
+ redEvidence?: RedEvidence;
47
63
  }
64
+ /** Durable goal-ledger append (P1): one entry per supervisor boundary; the writer stamps `type`/`at`. Shared by the supervisor and the session recorder. */
65
+ export interface GoalLedgerAppend {
66
+ goalId: string;
67
+ phase: 'goal_start' | 'goal_continue' | 'goal_end';
68
+ request: string;
69
+ requestHash: string;
70
+ intent: RequestIntent;
71
+ cycle: number;
72
+ mutationCount: number;
73
+ validationOutcome: ValidationOutcome;
74
+ progressSignature: string;
75
+ taskCounts?: {
76
+ total: number;
77
+ pending: number;
78
+ inProgress: number;
79
+ completed: number;
80
+ };
81
+ redEvidence?: RedEvidence;
82
+ stopReason?: string;
83
+ status?: 'complete' | 'failed' | 'aborted';
84
+ }
85
+ /** Hash binding for the exact mission bytes (P1): everything downstream that references "the mission" carries this. */
86
+ export declare function hashRequest(request: string): string;
48
87
  /** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
49
88
  export declare function goalCheckpointSignature(input: {
50
89
  mutationCount: number;
@@ -56,10 +95,32 @@ export declare function goalCheckpointSignature(input: {
56
95
  total: number;
57
96
  };
58
97
  }): string;
98
+ /** Goal-scoped evidence carried across a physical-turn boundary (checkpoint subset). */
99
+ export interface CarriedGoalEvidence {
100
+ requestHash?: string;
101
+ intent?: RequestIntent;
102
+ redEvidence?: RedEvidence;
103
+ }
59
104
  /**
60
105
  * Build the checkpoint payload for a `recoverable-incomplete` attempt that no
61
106
  * same-turn recovery can continue. Single construction site so every path
62
107
  * (voluntary final, budget boundary, tool-calls finish, exhausted recovery
63
108
  * slice) yields the same bounded shape.
64
109
  */
65
- export declare function buildIncompleteGoalResume(request: string, goalId: string, cycle: number, state: Pick<TurnExecutionState, 'stepsUsed' | 'mutationCount' | 'validationOutcome' | 'taskProgress'>, reason: CompletionReadiness): IncompleteGoalResume;
110
+ export declare function buildIncompleteGoalResume(request: string, goalId: string, cycle: number, state: Pick<TurnExecutionState, 'stepsUsed' | 'mutationCount' | 'validationOutcome' | 'taskProgress'>, reason: CompletionReadiness, carried?: CarriedGoalEvidence): IncompleteGoalResume;
111
+ /** Project task progress into the plain counts shape used by checkpoints and prompts. */
112
+ export declare function taskCountsOf(taskProgress: WorkTaskProgress | undefined): {
113
+ total: number;
114
+ pending: number;
115
+ inProgress: number;
116
+ completed: number;
117
+ } | undefined;
118
+ /**
119
+ * Rebuild a supervisor checkpoint from a durable ledger frontier (P1 resume
120
+ * path): safe metadata only, tolerant of ledger fields written by older
121
+ * versions. Carries red→green evidence so a crash resume matches in-process
122
+ * continuation (a captured red repro stays captured).
123
+ * `readiness` stays unset — the frontier predates a specific readiness, so
124
+ * continuation uses the generic unfinished reason.
125
+ */
126
+ export declare function checkpointFromGoalFrontier(frontier: GoalLedgerFrontier): GoalCheckpoint;
@@ -1,3 +1,8 @@
1
+ import crypto from 'node:crypto';
2
+ /** Hash binding for the exact mission bytes (P1): everything downstream that references "the mission" carries this. */
3
+ export function hashRequest(request) {
4
+ return crypto.createHash('sha256').update(request, 'utf8').digest('hex').slice(0, 16);
5
+ }
1
6
  /** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
2
7
  export function goalCheckpointSignature(input) {
3
8
  return JSON.stringify([input.mutationCount > 0, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null]);
@@ -8,7 +13,7 @@ export function goalCheckpointSignature(input) {
8
13
  * (voluntary final, budget boundary, tool-calls finish, exhausted recovery
9
14
  * slice) yields the same bounded shape.
10
15
  */
11
- export function buildIncompleteGoalResume(request, goalId, cycle, state, reason) {
16
+ export function buildIncompleteGoalResume(request, goalId, cycle, state, reason, carried = {}) {
12
17
  return {
13
18
  kind: 'incomplete-goal',
14
19
  request,
@@ -19,5 +24,35 @@ export function buildIncompleteGoalResume(request, goalId, cycle, state, reason)
19
24
  mutationCount: state.mutationCount,
20
25
  ...(state.taskProgress ? { taskCounts: { total: state.taskProgress.total, pending: state.taskProgress.pending, inProgress: state.taskProgress.inProgress, completed: state.taskProgress.completed } } : {}),
21
26
  ...(state.validationOutcome !== 'not_applicable' ? { validationOutcome: state.validationOutcome } : {}),
27
+ ...carried,
28
+ };
29
+ }
30
+ /** Project task progress into the plain counts shape used by checkpoints and prompts. */
31
+ export function taskCountsOf(taskProgress) {
32
+ return taskProgress ? { total: taskProgress.total, pending: taskProgress.pending, inProgress: taskProgress.inProgress, completed: taskProgress.completed } : undefined;
33
+ }
34
+ const VALIDATION_OUTCOMES = new Set(['passed', 'failed', 'stale', 'absent', 'not_applicable']);
35
+ /**
36
+ * Rebuild a supervisor checkpoint from a durable ledger frontier (P1 resume
37
+ * path): safe metadata only, tolerant of ledger fields written by older
38
+ * versions. Carries red→green evidence so a crash resume matches in-process
39
+ * continuation (a captured red repro stays captured).
40
+ * `readiness` stays unset — the frontier predates a specific readiness, so
41
+ * continuation uses the generic unfinished reason.
42
+ */
43
+ export function checkpointFromGoalFrontier(frontier) {
44
+ const validationOutcome = (VALIDATION_OUTCOMES.has(frontier.validationOutcome) ? frontier.validationOutcome : 'not_applicable');
45
+ return {
46
+ goalId: frontier.goalId,
47
+ request: frontier.request,
48
+ cycle: frontier.cycle,
49
+ mutationCount: frontier.mutationCount,
50
+ validationOutcome,
51
+ progressSignature: frontier.progressSignature,
52
+ noProgressCount: 0,
53
+ requestHash: frontier.requestHash,
54
+ ...(frontier.intent ? { intent: frontier.intent } : {}),
55
+ ...(frontier.taskCounts ? { taskCounts: frontier.taskCounts } : {}),
56
+ ...(frontier.redEvidence ? { redEvidence: { ...frontier.redEvidence } } : {}),
22
57
  };
23
58
  }