@peer-agent/runtime-core 0.0.1-beta.43 → 0.0.1-beta.45

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.
@@ -0,0 +1,545 @@
1
+ /**
2
+ * Goal execution checkpoint pure helpers.
3
+ *
4
+ * Checkpoint is the authoritative "what happens next" cursor across compaction.
5
+ * Chat summary may explain; it must not replace these structured fields.
6
+ *
7
+ * See peer-knowledge/knowledge/architecture/24-goal-runner-context-checkpoint-and-seamless-resume.md
8
+ */
9
+ import { randomId, sha256Hex } from "./iso-crypto.js";
10
+ export const GOAL_CHECKPOINT_SCHEMA_VERSION = 1;
11
+ export const GOAL_CHECKPOINT_STATUSES = Object.freeze([
12
+ 'preparing',
13
+ 'committed',
14
+ 'consumed',
15
+ 'superseded',
16
+ 'invalid',
17
+ ]);
18
+ export const GOAL_CHECKPOINT_REASONS = Object.freeze([
19
+ 'soft_threshold',
20
+ 'hard_threshold',
21
+ 'provider_overflow',
22
+ 'task_boundary',
23
+ 'manual_compact',
24
+ 'process_recovery',
25
+ ]);
26
+ export const GOAL_RESUME_POLICIES = Object.freeze([
27
+ 'continue_same_turn',
28
+ 'start_recovery_turn',
29
+ 'verify_then_continue',
30
+ 'wait_for_user',
31
+ ]);
32
+ export const GOAL_CHECKPOINT_LIMITS = Object.freeze({
33
+ maxRecentActions: 12,
34
+ maxDecisions: 12,
35
+ maxBlockers: 10,
36
+ maxRisks: 10,
37
+ maxOpenQuestions: 10,
38
+ maxPendingVerifications: 10,
39
+ maxDoNotRepeat: 10,
40
+ maxEvidenceRefs: 100,
41
+ maxOpenToolCalls: 20,
42
+ maxTextChars: 2_000,
43
+ maxHandoffChars: 4_000,
44
+ maxInstructionChars: 2_000,
45
+ });
46
+ function asString(value, fallback = '') {
47
+ if (typeof value !== 'string')
48
+ return fallback;
49
+ return value.trim();
50
+ }
51
+ function clampText(value, maxChars, fallback = '') {
52
+ const text = asString(value, fallback);
53
+ if (!text)
54
+ return fallback;
55
+ if (text.length <= maxChars)
56
+ return text;
57
+ return `${text.slice(0, Math.max(0, maxChars - 1))}…`;
58
+ }
59
+ function uniqueStrings(values, max) {
60
+ const out = [];
61
+ const seen = new Set();
62
+ for (const value of values) {
63
+ const text = asString(value);
64
+ if (!text || seen.has(text))
65
+ continue;
66
+ seen.add(text);
67
+ out.push(text);
68
+ if (out.length >= max)
69
+ break;
70
+ }
71
+ return out;
72
+ }
73
+ function normalizeStringList(value, max, itemMax = GOAL_CHECKPOINT_LIMITS.maxTextChars) {
74
+ if (!Array.isArray(value))
75
+ return [];
76
+ return uniqueStrings(value.map((item) => clampText(item, itemMax)), max);
77
+ }
78
+ function normalizeProgress(value) {
79
+ const source = value && typeof value === 'object' ? value : {};
80
+ const total = Number.isFinite(source.total) ? Math.max(0, Math.trunc(Number(source.total))) : 0;
81
+ const completed = Number.isFinite(source.completed) ? Math.max(0, Math.trunc(Number(source.completed))) : 0;
82
+ const failed = Number.isFinite(source.failed) ? Math.max(0, Math.trunc(Number(source.failed))) : 0;
83
+ const blocked = Number.isFinite(source.blocked) ? Math.max(0, Math.trunc(Number(source.blocked))) : 0;
84
+ const percent = Number.isFinite(source.percent)
85
+ ? Math.max(0, Math.min(100, Math.trunc(Number(source.percent))))
86
+ : (total > 0 ? Math.round((completed / total) * 100) : 0);
87
+ const nextRunnableTaskIds = normalizeStringList(source.nextRunnableTaskIds, 32, 200);
88
+ return { total, completed, failed, blocked, percent, nextRunnableTaskIds };
89
+ }
90
+ function normalizeAction(value, index) {
91
+ if (!value || typeof value !== 'object')
92
+ return null;
93
+ const source = value;
94
+ const summary = clampText(source.summary, GOAL_CHECKPOINT_LIMITS.maxTextChars);
95
+ if (!summary)
96
+ return null;
97
+ const kind = asString(source.kind, 'tool');
98
+ const status = asString(source.status, 'unknown');
99
+ return {
100
+ actionId: asString(source.actionId, `action-${index + 1}`),
101
+ kind: (kind === 'inspect'
102
+ || kind === 'edit'
103
+ || kind === 'write'
104
+ || kind === 'tool'
105
+ || kind === 'test'
106
+ || kind === 'verify'
107
+ || kind === 'decision') ? kind : 'tool',
108
+ summary,
109
+ status: (status === 'completed'
110
+ || status === 'failed'
111
+ || status === 'running'
112
+ || status === 'unknown') ? status : 'unknown',
113
+ ...(asString(source.target) ? { target: clampText(source.target, 500) } : {}),
114
+ evidenceRefs: normalizeStringList(source.evidenceRefs, 20, 300),
115
+ ...(asString(source.result) ? { result: clampText(source.result, GOAL_CHECKPOINT_LIMITS.maxTextChars) } : {}),
116
+ ...(asString(source.occurredAt) ? { occurredAt: asString(source.occurredAt) } : {}),
117
+ };
118
+ }
119
+ function normalizeToolCall(value, index) {
120
+ if (!value || typeof value !== 'object')
121
+ return null;
122
+ const source = value;
123
+ const toolCallId = asString(source.toolCallId, `tool-call-${index + 1}`);
124
+ if (!toolCallId)
125
+ return null;
126
+ const status = asString(source.status, 'unknown');
127
+ const replayPolicy = asString(source.replayPolicy, 'query_status');
128
+ return {
129
+ toolCallId,
130
+ ...(asString(source.toolName) ? { toolName: clampText(source.toolName, 200) } : {}),
131
+ status: (status === 'requested'
132
+ || status === 'running'
133
+ || status === 'completed'
134
+ || status === 'failed'
135
+ || status === 'unknown') ? status : 'unknown',
136
+ resultEvidenceRefs: normalizeStringList(source.resultEvidenceRefs, 20, 300),
137
+ replayPolicy: (replayPolicy === 'never'
138
+ || replayPolicy === 'query_status'
139
+ || replayPolicy === 'safe_retry'
140
+ || replayPolicy === 'ask_user') ? replayPolicy : 'query_status',
141
+ ...(asString(source.idempotencyKey) ? { idempotencyKey: clampText(source.idempotencyKey, 200) } : {}),
142
+ };
143
+ }
144
+ function normalizeFirstAction(value, fallbackTaskId = '') {
145
+ const source = value && typeof value === 'object' ? value : {};
146
+ const kind = asString(source.kind, 'inspect');
147
+ const instruction = clampText(source.instruction, GOAL_CHECKPOINT_LIMITS.maxInstructionChars, fallbackTaskId
148
+ ? `Continue the current task (${fallbackTaskId}) from the checkpoint.`
149
+ : 'Continue the current goal from the checkpoint.');
150
+ const successCheck = clampText(source.successCheck, GOAL_CHECKPOINT_LIMITS.maxTextChars, 'Observable progress is written back through goal_update_task with evidenceRefs.');
151
+ return {
152
+ kind: (kind === 'tool'
153
+ || kind === 'inspect'
154
+ || kind === 'edit'
155
+ || kind === 'verify'
156
+ || kind === 'synthesize'
157
+ || kind === 'wait_user') ? kind : 'inspect',
158
+ instruction,
159
+ ...(asString(source.target) ? { target: clampText(source.target, 500) } : {}),
160
+ successCheck,
161
+ requiredEvidenceRefs: normalizeStringList(source.requiredEvidenceRefs, 20, 300),
162
+ ...(Array.isArray(source.forbiddenUntilComplete)
163
+ ? { forbiddenUntilComplete: normalizeStringList(source.forbiddenUntilComplete, 20, 300) }
164
+ : {}),
165
+ };
166
+ }
167
+ function normalizeBudget(value) {
168
+ const source = value && typeof value === 'object' ? value : {};
169
+ const num = (key, fallback = 0) => (Number.isFinite(source[key]) ? Math.max(0, Math.trunc(Number(source[key]))) : fallback);
170
+ const contextWindow = Number.isFinite(source.contextWindow)
171
+ ? Math.max(0, Math.trunc(Number(source.contextWindow)))
172
+ : null;
173
+ return {
174
+ contextWindow,
175
+ beforeTokens: num('beforeTokens'),
176
+ targetTokens: num('targetTokens'),
177
+ systemTokens: num('systemTokens'),
178
+ toolsTokens: num('toolsTokens'),
179
+ checkpointTokens: num('checkpointTokens'),
180
+ continuityTokens: num('continuityTokens'),
181
+ recentTailTokens: num('recentTailTokens'),
182
+ keepBudgetTokens: num('keepBudgetTokens'),
183
+ compactionCount: num('compactionCount'),
184
+ };
185
+ }
186
+ function stableStringify(value) {
187
+ if (value === null || typeof value !== 'object') {
188
+ return JSON.stringify(value);
189
+ }
190
+ if (Array.isArray(value)) {
191
+ return `[${value.map((item) => stableStringify(item)).join(',')}]`;
192
+ }
193
+ const record = value;
194
+ const keys = Object.keys(record).sort();
195
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
196
+ }
197
+ /**
198
+ * Digest excludes lifecycle fields so content identity stays stable across
199
+ * preparing → committed → consumed transitions.
200
+ */
201
+ export function computeGoalCheckpointDigest(checkpoint) {
202
+ const { status: _status, committedAt: _committedAt, consumedAt: _consumedAt, digest: _digest, ...content } = checkpoint;
203
+ return sha256Hex(stableStringify(content));
204
+ }
205
+ export function isGoalCheckpointStatus(value) {
206
+ return typeof value === 'string' && GOAL_CHECKPOINT_STATUSES.includes(value);
207
+ }
208
+ export function isGoalCheckpointReason(value) {
209
+ return typeof value === 'string' && GOAL_CHECKPOINT_REASONS.includes(value);
210
+ }
211
+ export function isGoalResumePolicy(value) {
212
+ return typeof value === 'string' && GOAL_RESUME_POLICIES.includes(value);
213
+ }
214
+ export function createGoalCheckpointIds(now = new Date()) {
215
+ const stamp = now.toISOString().replace(/[:.]/g, '-');
216
+ return {
217
+ checkpointId: `cp-${stamp}-${randomId().slice(0, 8)}`,
218
+ compactionId: `compact-${stamp}-${randomId().slice(0, 8)}`,
219
+ };
220
+ }
221
+ export function normalizeGoalCheckpoint(input, options = {}) {
222
+ const source = input && typeof input === 'object' ? input : {};
223
+ const now = asString(options.now, new Date().toISOString());
224
+ const ids = createGoalCheckpointIds(new Date(now));
225
+ const planId = asString(source.planId, asString(options.fallbackPlanId));
226
+ const runId = asString(source.runId, asString(options.fallbackRunId));
227
+ if (!planId || !runId) {
228
+ throw new Error('[goal-checkpoint] planId and runId are required');
229
+ }
230
+ const currentTaskId = asString(source.currentTaskId) || undefined;
231
+ const status = isGoalCheckpointStatus(source.status) ? source.status : 'preparing';
232
+ const reason = isGoalCheckpointReason(source.reason) ? source.reason : 'soft_threshold';
233
+ const resumePolicy = isGoalResumePolicy(source.resumePolicy)
234
+ ? source.resumePolicy
235
+ : 'start_recovery_turn';
236
+ const recentActions = (Array.isArray(source.recentActions) ? source.recentActions : [])
237
+ .map((item, index) => normalizeAction(item, index))
238
+ .filter((item) => Boolean(item))
239
+ .slice(0, GOAL_CHECKPOINT_LIMITS.maxRecentActions);
240
+ const openToolCalls = (Array.isArray(source.openToolCalls) ? source.openToolCalls : [])
241
+ .map((item, index) => normalizeToolCall(item, index))
242
+ .filter((item) => Boolean(item))
243
+ .slice(0, GOAL_CHECKPOINT_LIMITS.maxOpenToolCalls);
244
+ const normalized = {
245
+ schemaVersion: GOAL_CHECKPOINT_SCHEMA_VERSION,
246
+ checkpointId: asString(source.checkpointId, ids.checkpointId),
247
+ compactionId: asString(source.compactionId, ids.compactionId),
248
+ sequence: Number.isFinite(source.sequence) ? Math.max(1, Math.trunc(Number(source.sequence))) : 1,
249
+ status,
250
+ reason,
251
+ planId,
252
+ planVersion: Number.isFinite(source.planVersion)
253
+ ? Math.max(0, Math.trunc(Number(source.planVersion)))
254
+ : Math.max(0, Math.trunc(Number(options.fallbackPlanVersion ?? 0))),
255
+ runId,
256
+ ...(asString(source.conversationId) ? { conversationId: asString(source.conversationId) } : {}),
257
+ ...(asString(source.streamId) ? { streamId: asString(source.streamId) } : {}),
258
+ ...(asString(source.contextEpochId) ? { contextEpochId: asString(source.contextEpochId) } : {}),
259
+ ...(asString(source.conversationRevision) ? { conversationRevision: asString(source.conversationRevision) } : {}),
260
+ ...(currentTaskId ? { currentTaskId } : {}),
261
+ ...(asString(source.runnerPhase) ? { runnerPhase: asString(source.runnerPhase) } : {}),
262
+ ...(asString(source.runnerIntent) ? { runnerIntent: asString(source.runnerIntent) } : {}),
263
+ progress: normalizeProgress(source.progress),
264
+ objectiveNow: clampText(source.objectiveNow, GOAL_CHECKPOINT_LIMITS.maxTextChars, 'Continue the active goal.'),
265
+ currentWork: clampText(source.currentWork, GOAL_CHECKPOINT_LIMITS.maxTextChars, 'Resume from the latest executable scene.'),
266
+ recentActions,
267
+ completedSincePrevious: normalizeStringList(source.completedSincePrevious, 20),
268
+ mostImportantFact: clampText(source.mostImportantFact, GOAL_CHECKPOINT_LIMITS.maxTextChars, currentTaskId
269
+ ? `Current task is ${currentTaskId}.`
270
+ : 'Continue the active goal from the latest checkpoint.'),
271
+ decisions: normalizeStringList(source.decisions, GOAL_CHECKPOINT_LIMITS.maxDecisions),
272
+ blockers: normalizeStringList(source.blockers, GOAL_CHECKPOINT_LIMITS.maxBlockers),
273
+ risks: normalizeStringList(source.risks, GOAL_CHECKPOINT_LIMITS.maxRisks),
274
+ openQuestions: normalizeStringList(source.openQuestions, GOAL_CHECKPOINT_LIMITS.maxOpenQuestions),
275
+ pendingVerifications: normalizeStringList(source.pendingVerifications, GOAL_CHECKPOINT_LIMITS.maxPendingVerifications),
276
+ doNotRepeat: normalizeStringList(source.doNotRepeat, GOAL_CHECKPOINT_LIMITS.maxDoNotRepeat),
277
+ handoffNote: clampText(source.handoffNote, GOAL_CHECKPOINT_LIMITS.maxHandoffChars, 'Resume the current task. Do not restart completed work.'),
278
+ firstAction: normalizeFirstAction(source.firstAction, currentTaskId || ''),
279
+ evidenceRefs: normalizeStringList(source.evidenceRefs, GOAL_CHECKPOINT_LIMITS.maxEvidenceRefs, 300),
280
+ mustReadEvidenceRefs: normalizeStringList(source.mustReadEvidenceRefs, Math.min(20, GOAL_CHECKPOINT_LIMITS.maxEvidenceRefs), 300),
281
+ openToolCalls,
282
+ budget: normalizeBudget(source.budget),
283
+ resumePolicy,
284
+ createdAt: asString(source.createdAt, now),
285
+ ...(asString(source.committedAt) ? { committedAt: asString(source.committedAt) } : {}),
286
+ ...(asString(source.consumedAt) ? { consumedAt: asString(source.consumedAt) } : {}),
287
+ };
288
+ return {
289
+ ...normalized,
290
+ digest: computeGoalCheckpointDigest(normalized),
291
+ };
292
+ }
293
+ export function validateGoalCheckpoint(checkpoint) {
294
+ try {
295
+ const normalized = normalizeGoalCheckpoint(checkpoint);
296
+ const errors = [];
297
+ if (!normalized.checkpointId)
298
+ errors.push('checkpointId is required');
299
+ if (!normalized.planId)
300
+ errors.push('planId is required');
301
+ if (!normalized.runId)
302
+ errors.push('runId is required');
303
+ if (!normalized.firstAction?.instruction)
304
+ errors.push('firstAction.instruction is required');
305
+ if (!normalized.firstAction?.successCheck)
306
+ errors.push('firstAction.successCheck is required');
307
+ if (!normalized.mostImportantFact)
308
+ errors.push('mostImportantFact is required');
309
+ if (normalized.digest !== computeGoalCheckpointDigest(normalized)) {
310
+ errors.push('digest mismatch');
311
+ }
312
+ return {
313
+ ok: errors.length === 0,
314
+ errors,
315
+ checkpoint: errors.length === 0 ? normalized : null,
316
+ };
317
+ }
318
+ catch (error) {
319
+ return {
320
+ ok: false,
321
+ errors: [error instanceof Error ? error.message : String(error)],
322
+ checkpoint: null,
323
+ };
324
+ }
325
+ }
326
+ function collectLeafTasks(tasks, out = []) {
327
+ if (!Array.isArray(tasks))
328
+ return out;
329
+ for (const task of tasks) {
330
+ if (!task || typeof task !== 'object')
331
+ continue;
332
+ const record = task;
333
+ const subtasks = Array.isArray(record.subtasks) ? record.subtasks : [];
334
+ if (subtasks.length === 0)
335
+ out.push(record);
336
+ else
337
+ collectLeafTasks(subtasks, out);
338
+ }
339
+ return out;
340
+ }
341
+ function deriveProgressFromPlan(plan) {
342
+ const leaves = collectLeafTasks(plan.tasks);
343
+ const total = leaves.length;
344
+ let completed = 0;
345
+ let failed = 0;
346
+ let blocked = 0;
347
+ const nextRunnableTaskIds = [];
348
+ for (const leaf of leaves) {
349
+ const status = asString(leaf.status, 'pending');
350
+ if (status === 'completed')
351
+ completed += 1;
352
+ else if (status === 'failed')
353
+ failed += 1;
354
+ else if (status === 'waiting_user' || status === 'blocked')
355
+ blocked += 1;
356
+ else if (status === 'pending' || status === 'running') {
357
+ const taskId = asString(leaf.taskId);
358
+ if (taskId)
359
+ nextRunnableTaskIds.push(taskId);
360
+ }
361
+ }
362
+ return {
363
+ total,
364
+ completed,
365
+ failed,
366
+ blocked,
367
+ percent: total > 0 ? Math.round((completed / total) * 100) : 0,
368
+ nextRunnableTaskIds: nextRunnableTaskIds.slice(0, 32),
369
+ };
370
+ }
371
+ function findTaskTitle(plan, taskId) {
372
+ if (!taskId)
373
+ return '';
374
+ const leaves = collectLeafTasks(plan.tasks);
375
+ const hit = leaves.find((task) => asString(task.taskId) === taskId);
376
+ return hit ? asString(hit.title) : '';
377
+ }
378
+ /**
379
+ * Deterministic checkpoint builder used when no LLM handoff is available.
380
+ * Callers may overlay narrative fields before normalizeGoalCheckpoint().
381
+ */
382
+ export function buildDeterministicGoalCheckpoint(input) {
383
+ const plan = input.plan && typeof input.plan === 'object' ? input.plan : {};
384
+ const runner = plan.runner && typeof plan.runner === 'object'
385
+ ? plan.runner
386
+ : {};
387
+ const progress = deriveProgressFromPlan(plan);
388
+ const currentTaskId = asString(runner.currentTaskId)
389
+ || progress.nextRunnableTaskIds[0]
390
+ || undefined;
391
+ const taskTitle = findTaskTitle(plan, currentTaskId);
392
+ const previous = runner.contextCheckpoint && typeof runner.contextCheckpoint === 'object'
393
+ ? runner.contextCheckpoint
394
+ : null;
395
+ const previousSequence = Number.isFinite(previous?.sequence)
396
+ ? Math.max(0, Math.trunc(Number(previous?.sequence)))
397
+ : Number.isFinite(runner.lastConsumedCheckpointSequence)
398
+ ? Math.max(0, Math.trunc(Number(runner.lastConsumedCheckpointSequence)))
399
+ : 0;
400
+ const runId = asString(input.runId)
401
+ || asString(runner.runId)
402
+ || asString(plan.planId);
403
+ const now = asString(input.now, new Date().toISOString());
404
+ const ids = createGoalCheckpointIds(new Date(now));
405
+ return normalizeGoalCheckpoint({
406
+ schemaVersion: GOAL_CHECKPOINT_SCHEMA_VERSION,
407
+ checkpointId: asString(input.checkpointId, ids.checkpointId),
408
+ compactionId: asString(input.compactionId, ids.compactionId),
409
+ sequence: Number.isFinite(input.sequence)
410
+ ? Math.max(1, Math.trunc(Number(input.sequence)))
411
+ : previousSequence + 1,
412
+ status: 'preparing',
413
+ reason: input.reason,
414
+ planId: asString(plan.planId),
415
+ planVersion: Number.isFinite(plan.version) ? Math.trunc(Number(plan.version)) : 0,
416
+ runId,
417
+ conversationId: asString(input.conversationId, asString(plan.conversationId)) || undefined,
418
+ streamId: asString(input.streamId) || undefined,
419
+ currentTaskId,
420
+ runnerPhase: asString(runner.phase) || undefined,
421
+ runnerIntent: asString(runner.intent) || undefined,
422
+ progress,
423
+ objectiveNow: clampText(plan.goal, GOAL_CHECKPOINT_LIMITS.maxTextChars, asString(plan.title, 'Continue the active goal.')),
424
+ currentWork: taskTitle
425
+ ? `Resume task ${currentTaskId}: ${taskTitle}`
426
+ : 'Resume the current executable scene.',
427
+ recentActions: Array.isArray(input.recentActions) ? input.recentActions : [],
428
+ completedSincePrevious: [],
429
+ mostImportantFact: taskTitle
430
+ ? `Current task is ${currentTaskId} (${taskTitle}).`
431
+ : 'Continue the active goal from the latest checkpoint.',
432
+ decisions: [],
433
+ blockers: asString(runner.blockedReason) ? [asString(runner.blockedReason)] : [],
434
+ risks: [],
435
+ openQuestions: [],
436
+ pendingVerifications: [],
437
+ doNotRepeat: [],
438
+ handoffNote: [
439
+ `Goal: ${asString(plan.goal, asString(plan.title, plan.planId))}`,
440
+ currentTaskId ? `Current task: ${currentTaskId}${taskTitle ? ` / ${taskTitle}` : ''}` : 'Current task: (none)',
441
+ 'First action: continue the current task without repeating completed work.',
442
+ 'Write evidence back through goal_update_task before marking completion.',
443
+ ].join('\n'),
444
+ firstAction: {
445
+ kind: 'inspect',
446
+ instruction: currentTaskId
447
+ ? `Continue task ${currentTaskId}${taskTitle ? ` (${taskTitle})` : ''} from the current scene.`
448
+ : 'Inspect the active goal plan and continue the next runnable task.',
449
+ target: currentTaskId,
450
+ successCheck: 'Task progress or verification evidence is written back with evidenceRefs.',
451
+ requiredEvidenceRefs: [],
452
+ },
453
+ evidenceRefs: [],
454
+ mustReadEvidenceRefs: [],
455
+ openToolCalls: Array.isArray(input.openToolCalls) ? input.openToolCalls : [],
456
+ budget: input.budget ?? {
457
+ contextWindow: null,
458
+ beforeTokens: 0,
459
+ targetTokens: 0,
460
+ systemTokens: 0,
461
+ toolsTokens: 0,
462
+ checkpointTokens: 0,
463
+ continuityTokens: 0,
464
+ recentTailTokens: 0,
465
+ keepBudgetTokens: 0,
466
+ compactionCount: Number.isFinite(runner.compactionCount)
467
+ ? Math.max(0, Math.trunc(Number(runner.compactionCount)))
468
+ : 0,
469
+ },
470
+ resumePolicy: 'start_recovery_turn',
471
+ createdAt: now,
472
+ }, {
473
+ fallbackPlanId: asString(plan.planId),
474
+ fallbackRunId: runId,
475
+ fallbackPlanVersion: Number.isFinite(plan.version) ? Math.trunc(Number(plan.version)) : 0,
476
+ now,
477
+ });
478
+ }
479
+ export function formatGoalCheckpointForPrompt(checkpoint) {
480
+ const validation = validateGoalCheckpoint(checkpoint);
481
+ if (!validation.ok || !validation.checkpoint) {
482
+ return '';
483
+ }
484
+ const cp = validation.checkpoint;
485
+ const lines = [
486
+ 'Active Goal execution checkpoint (authoritative runtime state, scope=run).',
487
+ 'This is factual runtime state for seamless resume after context compaction.',
488
+ 'It is not a user message and must not be overridden by lower-priority summaries.',
489
+ '',
490
+ `checkpointId=${cp.checkpointId}`,
491
+ `sequence=${cp.sequence}`,
492
+ `planId=${cp.planId}`,
493
+ `runId=${cp.runId}`,
494
+ `status=${cp.status}`,
495
+ `reason=${cp.reason}`,
496
+ `digest=${cp.digest}`,
497
+ `resumePolicy=${cp.resumePolicy}`,
498
+ cp.currentTaskId ? `currentTaskId=${cp.currentTaskId}` : 'currentTaskId=(none)',
499
+ '',
500
+ `Current objective: ${cp.objectiveNow}`,
501
+ `Current work: ${cp.currentWork}`,
502
+ `Most important fact: ${cp.mostImportantFact}`,
503
+ `Progress: ${cp.progress.completed}/${cp.progress.total} completed (${cp.progress.percent}%)`,
504
+ ];
505
+ if (cp.recentActions.length) {
506
+ lines.push('Recent actions:');
507
+ for (const action of cp.recentActions) {
508
+ const refs = action.evidenceRefs.length ? ` [evidenceRefs=${action.evidenceRefs.join(',')}]` : '';
509
+ lines.push(`- [${action.status}] ${action.summary}${refs}`);
510
+ }
511
+ }
512
+ if (cp.pendingVerifications.length) {
513
+ lines.push('Pending verification:');
514
+ for (const item of cp.pendingVerifications)
515
+ lines.push(`- ${item}`);
516
+ }
517
+ if (cp.doNotRepeat.length) {
518
+ lines.push('Do not repeat:');
519
+ for (const item of cp.doNotRepeat)
520
+ lines.push(`- ${item}`);
521
+ }
522
+ if (cp.openToolCalls.length) {
523
+ lines.push('Open tool calls:');
524
+ for (const call of cp.openToolCalls) {
525
+ lines.push(`- ${call.toolCallId} status=${call.status} replayPolicy=${call.replayPolicy}`);
526
+ }
527
+ }
528
+ if (cp.mustReadEvidenceRefs.length) {
529
+ lines.push('Must read evidence:');
530
+ for (const ref of cp.mustReadEvidenceRefs)
531
+ lines.push(`- ${ref}`);
532
+ }
533
+ lines.push(`First action (${cp.firstAction.kind}): ${cp.firstAction.instruction}`);
534
+ if (cp.firstAction.target)
535
+ lines.push(`First action target: ${cp.firstAction.target}`);
536
+ lines.push(`First action success check: ${cp.firstAction.successCheck}`);
537
+ lines.push('Handoff:');
538
+ lines.push(cp.handoffNote);
539
+ lines.push('');
540
+ lines.push('Resume rules:');
541
+ lines.push('- Prefer executing firstAction before starting unrelated work.');
542
+ lines.push('- Do not mark work complete without evidenceRefs.');
543
+ lines.push('- Do not repeat doNotRepeat items unless conditions changed with new evidence.');
544
+ return lines.join('\n');
545
+ }
@@ -0,0 +1,34 @@
1
+ import { type GoalIdempotencyLedgerEntry } from './goal-idempotency.ts';
2
+ /**
3
+ * Resolve durable ledger file path:
4
+ * {storeDir}/idempotency/{planId}/{runId}.json
5
+ */
6
+ export declare function resolveGoalIdempotencyLedgerPath(input: {
7
+ readonly storeDir: string;
8
+ readonly planId: string;
9
+ readonly runId: string;
10
+ }): string;
11
+ /**
12
+ * Durable Goal idempotency ledger, scoped by planId + runId.
13
+ * Survives process restart so compact/resume cannot re-fire completed side effects.
14
+ */
15
+ export declare function createDurableGoalIdempotencyLedger(input: {
16
+ readonly storeDir: string;
17
+ readonly planId: string;
18
+ readonly runId: string;
19
+ readonly ledgerPath?: string;
20
+ }): {
21
+ get(key: string): GoalIdempotencyLedgerEntry | null;
22
+ remember(input: {
23
+ readonly idempotencyKey: string;
24
+ readonly status: string;
25
+ readonly evidenceRefs?: readonly string[];
26
+ readonly toolCallId?: string;
27
+ readonly toolName?: string;
28
+ readonly planId?: string;
29
+ readonly runId?: string;
30
+ }): GoalIdempotencyLedgerEntry | null;
31
+ snapshot(): Map<string, GoalIdempotencyLedgerEntry>;
32
+ clear(): void;
33
+ readonly filePath: string | null;
34
+ };