@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.
- package/dist/context-compaction.d.ts +14 -3
- package/dist/context-compaction.js +101 -21
- package/dist/goal-checkpoint.d.ts +226 -0
- package/dist/goal-checkpoint.js +545 -0
- package/dist/goal-idempotency-durable.d.ts +34 -0
- package/dist/goal-idempotency-durable.js +147 -0
- package/dist/goal-idempotency.d.ts +77 -0
- package/dist/goal-idempotency.js +254 -0
- package/dist/goal-keep-policy.d.ts +78 -0
- package/dist/goal-keep-policy.js +381 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/iso-crypto.d.ts +12 -0
- package/dist/iso-crypto.js +119 -0
- package/package.json +9 -5
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node-only durable Goal idempotency ledger (fs-backed).
|
|
3
|
+
* Keep this out of the browser/renderer import graph.
|
|
4
|
+
*/
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { createGoalIdempotencyLedger, } from "./goal-idempotency.js";
|
|
8
|
+
function asString(value, fallback = '') {
|
|
9
|
+
if (typeof value !== 'string')
|
|
10
|
+
return fallback;
|
|
11
|
+
return value.trim();
|
|
12
|
+
}
|
|
13
|
+
function createLedgerEntry(input) {
|
|
14
|
+
return {
|
|
15
|
+
status: asString(input.status, 'completed'),
|
|
16
|
+
evidenceRefs: Array.isArray(input.evidenceRefs)
|
|
17
|
+
? input.evidenceRefs.map((ref) => asString(ref)).filter(Boolean)
|
|
18
|
+
: [],
|
|
19
|
+
toolCallId: asString(input.toolCallId) || undefined,
|
|
20
|
+
toolName: asString(input.toolName) || undefined,
|
|
21
|
+
updatedAt: new Date().toISOString(),
|
|
22
|
+
planId: asString(input.planId) || undefined,
|
|
23
|
+
runId: asString(input.runId) || undefined,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function sanitizePathSegment(value) {
|
|
27
|
+
const raw = asString(value) || 'unknown';
|
|
28
|
+
return raw.replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 120);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Resolve durable ledger file path:
|
|
32
|
+
* {storeDir}/idempotency/{planId}/{runId}.json
|
|
33
|
+
*/
|
|
34
|
+
export function resolveGoalIdempotencyLedgerPath(input) {
|
|
35
|
+
const storeDir = asString(input.storeDir);
|
|
36
|
+
const planId = sanitizePathSegment(input.planId);
|
|
37
|
+
const runId = sanitizePathSegment(input.runId);
|
|
38
|
+
return path.join(storeDir, 'idempotency', planId, `${runId}.json`);
|
|
39
|
+
}
|
|
40
|
+
function loadDurableEntries(filePath) {
|
|
41
|
+
const entries = new Map();
|
|
42
|
+
try {
|
|
43
|
+
if (!existsSync(filePath))
|
|
44
|
+
return entries;
|
|
45
|
+
const raw = readFileSync(filePath, 'utf8');
|
|
46
|
+
if (!raw.trim())
|
|
47
|
+
return entries;
|
|
48
|
+
const parsed = JSON.parse(raw);
|
|
49
|
+
if (!parsed?.entries || typeof parsed.entries !== 'object')
|
|
50
|
+
return entries;
|
|
51
|
+
for (const [key, value] of Object.entries(parsed.entries)) {
|
|
52
|
+
if (!key || !value || typeof value !== 'object')
|
|
53
|
+
continue;
|
|
54
|
+
entries.set(key, {
|
|
55
|
+
status: asString(value.status, 'completed'),
|
|
56
|
+
evidenceRefs: Array.isArray(value.evidenceRefs)
|
|
57
|
+
? value.evidenceRefs.map((ref) => asString(ref)).filter(Boolean)
|
|
58
|
+
: [],
|
|
59
|
+
toolCallId: asString(value.toolCallId) || undefined,
|
|
60
|
+
toolName: asString(value.toolName) || undefined,
|
|
61
|
+
updatedAt: asString(value.updatedAt) || new Date().toISOString(),
|
|
62
|
+
planId: asString(value.planId) || undefined,
|
|
63
|
+
runId: asString(value.runId) || undefined,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// Corrupt / partial file: start empty rather than crash tool path.
|
|
69
|
+
}
|
|
70
|
+
return entries;
|
|
71
|
+
}
|
|
72
|
+
function persistDurableEntries(filePath, meta, entries) {
|
|
73
|
+
const dir = path.dirname(filePath);
|
|
74
|
+
mkdirSync(dir, { recursive: true });
|
|
75
|
+
const payload = {
|
|
76
|
+
version: 1,
|
|
77
|
+
planId: meta.planId,
|
|
78
|
+
runId: meta.runId,
|
|
79
|
+
updatedAt: new Date().toISOString(),
|
|
80
|
+
entries: Object.fromEntries(entries.entries()),
|
|
81
|
+
};
|
|
82
|
+
const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
83
|
+
writeFileSync(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
|
|
84
|
+
renameSync(tmp, filePath);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Durable Goal idempotency ledger, scoped by planId + runId.
|
|
88
|
+
* Survives process restart so compact/resume cannot re-fire completed side effects.
|
|
89
|
+
*/
|
|
90
|
+
export function createDurableGoalIdempotencyLedger(input) {
|
|
91
|
+
const planId = asString(input.planId);
|
|
92
|
+
const runId = asString(input.runId);
|
|
93
|
+
const storeDir = asString(input.storeDir);
|
|
94
|
+
if (!storeDir || !planId || !runId) {
|
|
95
|
+
// Fallback to process-local when identity is incomplete.
|
|
96
|
+
return createGoalIdempotencyLedger();
|
|
97
|
+
}
|
|
98
|
+
const filePath = asString(input.ledgerPath)
|
|
99
|
+
|| resolveGoalIdempotencyLedgerPath({ storeDir, planId, runId });
|
|
100
|
+
const entries = loadDurableEntries(filePath);
|
|
101
|
+
return {
|
|
102
|
+
get(key) {
|
|
103
|
+
return entries.get(key) ?? null;
|
|
104
|
+
},
|
|
105
|
+
remember(rememberInput) {
|
|
106
|
+
const key = asString(rememberInput.idempotencyKey);
|
|
107
|
+
if (!key)
|
|
108
|
+
return null;
|
|
109
|
+
const next = createLedgerEntry({
|
|
110
|
+
...rememberInput,
|
|
111
|
+
planId: rememberInput.planId || planId,
|
|
112
|
+
runId: rememberInput.runId || runId,
|
|
113
|
+
});
|
|
114
|
+
entries.set(key, next);
|
|
115
|
+
try {
|
|
116
|
+
persistDurableEntries(filePath, { planId, runId }, entries);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// Disk write must never fail the tool return path; in-memory still holds.
|
|
120
|
+
}
|
|
121
|
+
return next;
|
|
122
|
+
},
|
|
123
|
+
snapshot() {
|
|
124
|
+
return new Map(entries);
|
|
125
|
+
},
|
|
126
|
+
clear() {
|
|
127
|
+
entries.clear();
|
|
128
|
+
try {
|
|
129
|
+
if (existsSync(filePath)) {
|
|
130
|
+
writeFileSync(filePath, `${JSON.stringify({
|
|
131
|
+
version: 1,
|
|
132
|
+
planId,
|
|
133
|
+
runId,
|
|
134
|
+
updatedAt: new Date().toISOString(),
|
|
135
|
+
entries: {},
|
|
136
|
+
}, null, 2)}\n`, 'utf8');
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// ignore
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
get filePath() {
|
|
144
|
+
return filePath;
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export declare const GOAL_TOOL_REPLAY_POLICIES: readonly ["never", "query_status", "safe_retry", "ask_user", "reuse_completed"];
|
|
2
|
+
export type GoalToolReplayPolicy = (typeof GOAL_TOOL_REPLAY_POLICIES)[number];
|
|
3
|
+
export type GoalToolMutationClass = 'read_only' | 'idempotent_write' | 'non_idempotent_write' | 'unknown';
|
|
4
|
+
export interface GoalIdempotencyKeyInput {
|
|
5
|
+
readonly planId: string;
|
|
6
|
+
readonly runId: string;
|
|
7
|
+
readonly taskId?: string | null;
|
|
8
|
+
readonly toolName: string;
|
|
9
|
+
readonly args?: unknown;
|
|
10
|
+
readonly intent?: string | null;
|
|
11
|
+
}
|
|
12
|
+
export interface GoalOpenToolCallLike {
|
|
13
|
+
readonly toolCallId?: string;
|
|
14
|
+
readonly toolName?: string;
|
|
15
|
+
readonly status?: string;
|
|
16
|
+
readonly resultEvidenceRefs?: readonly string[];
|
|
17
|
+
readonly replayPolicy?: string;
|
|
18
|
+
readonly idempotencyKey?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface GoalToolReplayDecision {
|
|
21
|
+
readonly action: 'execute' | 'reuse' | 'query_status' | 'block' | 'ask_user';
|
|
22
|
+
readonly reason: string;
|
|
23
|
+
readonly policy: GoalToolReplayPolicy;
|
|
24
|
+
readonly mutationClass: GoalToolMutationClass;
|
|
25
|
+
readonly idempotencyKey: string;
|
|
26
|
+
readonly matchedCall?: GoalOpenToolCallLike | null;
|
|
27
|
+
readonly evidenceRefs?: readonly string[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Deterministic idempotency key for a Goal tool attempt.
|
|
31
|
+
* planId + runId + taskId + toolName + normalizedArgs + intent
|
|
32
|
+
*/
|
|
33
|
+
export declare function buildGoalIdempotencyKey(input: GoalIdempotencyKeyInput): string;
|
|
34
|
+
export declare function classifyGoalToolMutation(toolName: string, args?: unknown): GoalToolMutationClass;
|
|
35
|
+
export declare function defaultReplayPolicyForMutation(mutationClass: GoalToolMutationClass): GoalToolReplayPolicy;
|
|
36
|
+
export declare function decideGoalToolReplay(input: {
|
|
37
|
+
readonly planId: string;
|
|
38
|
+
readonly runId: string;
|
|
39
|
+
readonly taskId?: string | null;
|
|
40
|
+
readonly toolName: string;
|
|
41
|
+
readonly args?: unknown;
|
|
42
|
+
readonly intent?: string | null;
|
|
43
|
+
readonly openToolCalls?: readonly GoalOpenToolCallLike[] | null;
|
|
44
|
+
readonly completedLedger?: ReadonlyMap<string, {
|
|
45
|
+
readonly status: string;
|
|
46
|
+
readonly evidenceRefs?: readonly string[];
|
|
47
|
+
readonly toolCallId?: string;
|
|
48
|
+
}> | null;
|
|
49
|
+
}): GoalToolReplayDecision;
|
|
50
|
+
export interface GoalIdempotencyLedgerEntry {
|
|
51
|
+
status: string;
|
|
52
|
+
evidenceRefs: string[];
|
|
53
|
+
toolCallId?: string;
|
|
54
|
+
toolName?: string;
|
|
55
|
+
updatedAt: string;
|
|
56
|
+
planId?: string;
|
|
57
|
+
runId?: string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Process-local ledger (tests / fallback when no durable storeDir is available).
|
|
61
|
+
*/
|
|
62
|
+
export declare function createGoalIdempotencyLedger(): {
|
|
63
|
+
get(key: string): GoalIdempotencyLedgerEntry | null;
|
|
64
|
+
remember(input: {
|
|
65
|
+
readonly idempotencyKey: string;
|
|
66
|
+
readonly status: string;
|
|
67
|
+
readonly evidenceRefs?: readonly string[];
|
|
68
|
+
readonly toolCallId?: string;
|
|
69
|
+
readonly toolName?: string;
|
|
70
|
+
readonly planId?: string;
|
|
71
|
+
readonly runId?: string;
|
|
72
|
+
}): GoalIdempotencyLedgerEntry | null;
|
|
73
|
+
snapshot(): Map<string, GoalIdempotencyLedgerEntry>;
|
|
74
|
+
clear(): void;
|
|
75
|
+
readonly filePath: string | null;
|
|
76
|
+
};
|
|
77
|
+
export type GoalIdempotencyLedger = ReturnType<typeof createGoalIdempotencyLedger>;
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal tool idempotency helpers.
|
|
3
|
+
*
|
|
4
|
+
* After compact/resume, the model may re-issue the same side-effecting tool
|
|
5
|
+
* call. These pure helpers decide whether to replay, reuse, query, or block.
|
|
6
|
+
*
|
|
7
|
+
* See peer-knowledge/knowledge/architecture/24-goal-runner-context-checkpoint-and-seamless-resume.md
|
|
8
|
+
*/
|
|
9
|
+
import { sha256Hex } from "./iso-crypto.js";
|
|
10
|
+
export const GOAL_TOOL_REPLAY_POLICIES = Object.freeze([
|
|
11
|
+
'never',
|
|
12
|
+
'query_status',
|
|
13
|
+
'safe_retry',
|
|
14
|
+
'ask_user',
|
|
15
|
+
'reuse_completed',
|
|
16
|
+
]);
|
|
17
|
+
const READ_ONLY_TOOLS = new Set([
|
|
18
|
+
'read_file',
|
|
19
|
+
'list_files',
|
|
20
|
+
'search_files',
|
|
21
|
+
'batch_search',
|
|
22
|
+
'goal_get_plan',
|
|
23
|
+
'web_fetch',
|
|
24
|
+
'browser_read_dom',
|
|
25
|
+
'browser_screenshot',
|
|
26
|
+
'bash', // treated carefully below based on command shape when possible
|
|
27
|
+
]);
|
|
28
|
+
const IDEMPOTENT_WRITE_TOOLS = new Set([
|
|
29
|
+
'write_file',
|
|
30
|
+
'goal_update_task',
|
|
31
|
+
'goal_create_plan',
|
|
32
|
+
]);
|
|
33
|
+
const NON_IDEMPOTENT_WRITE_TOOLS = new Set([
|
|
34
|
+
'edit_file',
|
|
35
|
+
'shell_stop',
|
|
36
|
+
'browser_click',
|
|
37
|
+
'browser_type',
|
|
38
|
+
'browser_navigate',
|
|
39
|
+
'request_explorer',
|
|
40
|
+
'request_user_input',
|
|
41
|
+
]);
|
|
42
|
+
function asString(value, fallback = '') {
|
|
43
|
+
if (typeof value !== 'string')
|
|
44
|
+
return fallback;
|
|
45
|
+
return value.trim();
|
|
46
|
+
}
|
|
47
|
+
function stableStringify(value) {
|
|
48
|
+
if (value === null || typeof value !== 'object') {
|
|
49
|
+
return JSON.stringify(value);
|
|
50
|
+
}
|
|
51
|
+
if (Array.isArray(value)) {
|
|
52
|
+
return `[${value.map((item) => stableStringify(item)).join(',')}]`;
|
|
53
|
+
}
|
|
54
|
+
const record = value;
|
|
55
|
+
const keys = Object.keys(record).sort();
|
|
56
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
|
|
57
|
+
}
|
|
58
|
+
function normalizeArgsForKey(args) {
|
|
59
|
+
if (args == null)
|
|
60
|
+
return '';
|
|
61
|
+
if (typeof args === 'string') {
|
|
62
|
+
const trimmed = args.trim();
|
|
63
|
+
if (!trimmed)
|
|
64
|
+
return '';
|
|
65
|
+
try {
|
|
66
|
+
return stableStringify(JSON.parse(trimmed));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return trimmed;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return stableStringify(args);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Deterministic idempotency key for a Goal tool attempt.
|
|
76
|
+
* planId + runId + taskId + toolName + normalizedArgs + intent
|
|
77
|
+
*/
|
|
78
|
+
export function buildGoalIdempotencyKey(input) {
|
|
79
|
+
const planId = asString(input.planId);
|
|
80
|
+
const runId = asString(input.runId);
|
|
81
|
+
const taskId = asString(input.taskId);
|
|
82
|
+
const toolName = asString(input.toolName);
|
|
83
|
+
const intent = asString(input.intent, 'execute');
|
|
84
|
+
const argsKey = normalizeArgsForKey(input.args);
|
|
85
|
+
const material = [planId, runId, taskId, toolName, argsKey, intent].join('\u0001');
|
|
86
|
+
return sha256Hex(material);
|
|
87
|
+
}
|
|
88
|
+
export function classifyGoalToolMutation(toolName, args = null) {
|
|
89
|
+
const name = asString(toolName);
|
|
90
|
+
if (!name)
|
|
91
|
+
return 'unknown';
|
|
92
|
+
if (name === 'bash') {
|
|
93
|
+
const command = typeof args === 'object' && args && 'command' in args
|
|
94
|
+
? asString(args.command)
|
|
95
|
+
: typeof args === 'string'
|
|
96
|
+
? args
|
|
97
|
+
: '';
|
|
98
|
+
// Heuristic: pure inspection commands are treated as read_only.
|
|
99
|
+
if (/^\s*(ls|pwd|cat|head|tail|rg|grep|find|sed -n|node --test|pnpm (test|typecheck|build)|git (status|diff|log|show))\b/i.test(command)) {
|
|
100
|
+
return 'read_only';
|
|
101
|
+
}
|
|
102
|
+
if (/\b(rm|mv|cp|chmod|chown|kill|reboot|shutdown|dd|mkfs|git (push|commit|reset|clean)|pnpm (publish|add|remove))\b/i.test(command)) {
|
|
103
|
+
return 'non_idempotent_write';
|
|
104
|
+
}
|
|
105
|
+
return 'unknown';
|
|
106
|
+
}
|
|
107
|
+
if (READ_ONLY_TOOLS.has(name))
|
|
108
|
+
return 'read_only';
|
|
109
|
+
if (IDEMPOTENT_WRITE_TOOLS.has(name))
|
|
110
|
+
return 'idempotent_write';
|
|
111
|
+
if (NON_IDEMPOTENT_WRITE_TOOLS.has(name))
|
|
112
|
+
return 'non_idempotent_write';
|
|
113
|
+
if (name.startsWith('mcp__') || name.startsWith('browser_'))
|
|
114
|
+
return 'non_idempotent_write';
|
|
115
|
+
return 'unknown';
|
|
116
|
+
}
|
|
117
|
+
export function defaultReplayPolicyForMutation(mutationClass) {
|
|
118
|
+
switch (mutationClass) {
|
|
119
|
+
case 'read_only':
|
|
120
|
+
return 'safe_retry';
|
|
121
|
+
case 'idempotent_write':
|
|
122
|
+
return 'safe_retry';
|
|
123
|
+
case 'non_idempotent_write':
|
|
124
|
+
return 'query_status';
|
|
125
|
+
default:
|
|
126
|
+
return 'ask_user';
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export function decideGoalToolReplay(input) {
|
|
130
|
+
const mutationClass = classifyGoalToolMutation(input.toolName, input.args);
|
|
131
|
+
const policy = defaultReplayPolicyForMutation(mutationClass);
|
|
132
|
+
const idempotencyKey = buildGoalIdempotencyKey({
|
|
133
|
+
planId: input.planId,
|
|
134
|
+
runId: input.runId,
|
|
135
|
+
taskId: input.taskId,
|
|
136
|
+
toolName: input.toolName,
|
|
137
|
+
args: input.args,
|
|
138
|
+
intent: input.intent,
|
|
139
|
+
});
|
|
140
|
+
const ledgerHit = input.completedLedger?.get(idempotencyKey) ?? null;
|
|
141
|
+
if (ledgerHit && (ledgerHit.status === 'completed' || ledgerHit.status === 'succeeded')) {
|
|
142
|
+
return {
|
|
143
|
+
action: 'reuse',
|
|
144
|
+
reason: 'idempotency_ledger_hit',
|
|
145
|
+
policy: 'reuse_completed',
|
|
146
|
+
mutationClass,
|
|
147
|
+
idempotencyKey,
|
|
148
|
+
matchedCall: {
|
|
149
|
+
toolCallId: ledgerHit.toolCallId,
|
|
150
|
+
toolName: input.toolName,
|
|
151
|
+
status: ledgerHit.status,
|
|
152
|
+
resultEvidenceRefs: ledgerHit.evidenceRefs ?? [],
|
|
153
|
+
replayPolicy: 'reuse_completed',
|
|
154
|
+
idempotencyKey,
|
|
155
|
+
},
|
|
156
|
+
evidenceRefs: ledgerHit.evidenceRefs ?? [],
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
const openCalls = Array.isArray(input.openToolCalls) ? input.openToolCalls : [];
|
|
160
|
+
const matched = openCalls.find((call) => asString(call.idempotencyKey) === idempotencyKey)
|
|
161
|
+
|| openCalls.find((call) => (asString(call.toolName) === asString(input.toolName)
|
|
162
|
+
&& (call.status === 'running' || call.status === 'requested' || call.status === 'completed')))
|
|
163
|
+
|| null;
|
|
164
|
+
if (matched?.status === 'completed' && (matched.resultEvidenceRefs?.length ?? 0) > 0) {
|
|
165
|
+
return {
|
|
166
|
+
action: 'reuse',
|
|
167
|
+
reason: 'open_tool_call_completed',
|
|
168
|
+
policy: 'reuse_completed',
|
|
169
|
+
mutationClass,
|
|
170
|
+
idempotencyKey,
|
|
171
|
+
matchedCall: matched,
|
|
172
|
+
evidenceRefs: matched.resultEvidenceRefs ?? [],
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
if (matched?.status === 'running' || matched?.status === 'requested') {
|
|
176
|
+
if (policy === 'safe_retry' && mutationClass === 'read_only') {
|
|
177
|
+
return {
|
|
178
|
+
action: 'execute',
|
|
179
|
+
reason: 'read_only_safe_retry',
|
|
180
|
+
policy,
|
|
181
|
+
mutationClass,
|
|
182
|
+
idempotencyKey,
|
|
183
|
+
matchedCall: matched,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
action: mutationClass === 'non_idempotent_write' ? 'query_status' : 'block',
|
|
188
|
+
reason: matched.status === 'running' ? 'tool_still_running' : 'tool_requested_unsettled',
|
|
189
|
+
policy: mutationClass === 'non_idempotent_write' ? 'query_status' : policy,
|
|
190
|
+
mutationClass,
|
|
191
|
+
idempotencyKey,
|
|
192
|
+
matchedCall: matched,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
if (mutationClass === 'unknown') {
|
|
196
|
+
return {
|
|
197
|
+
action: 'ask_user',
|
|
198
|
+
reason: 'unknown_mutation_class',
|
|
199
|
+
policy: 'ask_user',
|
|
200
|
+
mutationClass,
|
|
201
|
+
idempotencyKey,
|
|
202
|
+
matchedCall: matched,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
action: 'execute',
|
|
207
|
+
reason: 'no_prior_attempt',
|
|
208
|
+
policy,
|
|
209
|
+
mutationClass,
|
|
210
|
+
idempotencyKey,
|
|
211
|
+
matchedCall: matched,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
function createLedgerEntry(input) {
|
|
215
|
+
return {
|
|
216
|
+
status: asString(input.status, 'completed'),
|
|
217
|
+
evidenceRefs: Array.isArray(input.evidenceRefs)
|
|
218
|
+
? input.evidenceRefs.map((ref) => asString(ref)).filter(Boolean)
|
|
219
|
+
: [],
|
|
220
|
+
toolCallId: asString(input.toolCallId) || undefined,
|
|
221
|
+
toolName: asString(input.toolName) || undefined,
|
|
222
|
+
updatedAt: new Date().toISOString(),
|
|
223
|
+
planId: asString(input.planId) || undefined,
|
|
224
|
+
runId: asString(input.runId) || undefined,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Process-local ledger (tests / fallback when no durable storeDir is available).
|
|
229
|
+
*/
|
|
230
|
+
export function createGoalIdempotencyLedger() {
|
|
231
|
+
const entries = new Map();
|
|
232
|
+
return {
|
|
233
|
+
get(key) {
|
|
234
|
+
return entries.get(key) ?? null;
|
|
235
|
+
},
|
|
236
|
+
remember(input) {
|
|
237
|
+
const key = asString(input.idempotencyKey);
|
|
238
|
+
if (!key)
|
|
239
|
+
return null;
|
|
240
|
+
const next = createLedgerEntry(input);
|
|
241
|
+
entries.set(key, next);
|
|
242
|
+
return next;
|
|
243
|
+
},
|
|
244
|
+
snapshot() {
|
|
245
|
+
return new Map(entries);
|
|
246
|
+
},
|
|
247
|
+
clear() {
|
|
248
|
+
entries.clear();
|
|
249
|
+
},
|
|
250
|
+
get filePath() {
|
|
251
|
+
return null;
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal-mode bounded keep policy.
|
|
3
|
+
*
|
|
4
|
+
* Goal compaction must preserve a *bounded* executable scene, not the entire
|
|
5
|
+
* current-turn tool tail. Plan/checkpoint own long-term progress; keep only
|
|
6
|
+
* owns protocol locality for the next recovery turn.
|
|
7
|
+
*
|
|
8
|
+
* See peer-knowledge/knowledge/architecture/24-goal-runner-context-checkpoint-and-seamless-resume.md
|
|
9
|
+
*/
|
|
10
|
+
import { type CompactionMessage } from './context-compaction.ts';
|
|
11
|
+
export interface GoalKeepPolicyConfig {
|
|
12
|
+
readonly maxRecentUserTurns: number;
|
|
13
|
+
readonly maxRecentMessages: number;
|
|
14
|
+
readonly maxCompletedToolResults: number;
|
|
15
|
+
readonly minKeepTokens: number;
|
|
16
|
+
readonly maxKeepTokens: number;
|
|
17
|
+
readonly keepContextRatio: number;
|
|
18
|
+
readonly checkpointMaxTokens: number;
|
|
19
|
+
readonly continuityMaxTokens: number;
|
|
20
|
+
readonly targetRequestRatio: number;
|
|
21
|
+
readonly softTriggerRatio: number;
|
|
22
|
+
readonly hardTriggerRatio: number;
|
|
23
|
+
readonly largeToolPreviewChars: number;
|
|
24
|
+
readonly largeToolTailChars: number;
|
|
25
|
+
readonly largeToolTriggerChars: number;
|
|
26
|
+
}
|
|
27
|
+
export declare const GOAL_KEEP_POLICY: GoalKeepPolicyConfig;
|
|
28
|
+
export type GoalKeepRecoveryLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
|
29
|
+
export interface GoalKeepBudget {
|
|
30
|
+
readonly contextWindow: number | null;
|
|
31
|
+
readonly keepBudgetTokens: number;
|
|
32
|
+
readonly targetRequestTokens: number | null;
|
|
33
|
+
readonly softTriggerTokens: number | null;
|
|
34
|
+
readonly hardTriggerTokens: number | null;
|
|
35
|
+
readonly maxRecentUserTurns: number;
|
|
36
|
+
readonly maxRecentMessages: number;
|
|
37
|
+
readonly maxCompletedToolResults: number;
|
|
38
|
+
}
|
|
39
|
+
export interface GoalKeepSelectionResult<TMessage extends CompactionMessage = CompactionMessage> {
|
|
40
|
+
readonly systemMessages: TMessage[];
|
|
41
|
+
readonly oldMessages: TMessage[];
|
|
42
|
+
readonly keepMessages: TMessage[];
|
|
43
|
+
readonly keepBudgetTokens: number;
|
|
44
|
+
readonly keepTokens: number;
|
|
45
|
+
readonly recoveryLevel: GoalKeepRecoveryLevel;
|
|
46
|
+
readonly degraded: boolean;
|
|
47
|
+
readonly reason: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Convert oversized tool-result payloads in keep to short previews / refs.
|
|
51
|
+
* Structure (role, tool_call_id, call/result pairing) is preserved.
|
|
52
|
+
*/
|
|
53
|
+
export declare function skeletonizeKeepToolResults<TMessage extends CompactionMessage>(keepMessages: readonly TMessage[], options?: {
|
|
54
|
+
readonly headChars?: number;
|
|
55
|
+
readonly tailChars?: number;
|
|
56
|
+
readonly triggerChars?: number;
|
|
57
|
+
}): {
|
|
58
|
+
messages: TMessage[];
|
|
59
|
+
changed: boolean;
|
|
60
|
+
};
|
|
61
|
+
export declare function resolveGoalKeepBudget(contextWindow: number | null | undefined, config?: Partial<GoalKeepPolicyConfig>): GoalKeepBudget;
|
|
62
|
+
/**
|
|
63
|
+
* Select a Goal-mode keep window with hard bounds.
|
|
64
|
+
*
|
|
65
|
+
* recoveryLevel:
|
|
66
|
+
* - 0/1/2: normal bounded keep (turn/message/token limits)
|
|
67
|
+
* - 3: aggressive tool microcompact/skeletonize inside keep
|
|
68
|
+
* - 4: closed tool results → skeleton only (same pass, more aggressive)
|
|
69
|
+
* - 5: shrink to latest human anchor + open tool skeleton
|
|
70
|
+
* - 6+: same as 5 (further levels belong to tools/system projection outside keep)
|
|
71
|
+
*/
|
|
72
|
+
export declare function selectGoalKeepMessages<TMessage extends CompactionMessage>(messages: readonly TMessage[], options?: {
|
|
73
|
+
readonly contextWindow?: number | null;
|
|
74
|
+
readonly recoveryLevel?: GoalKeepRecoveryLevel;
|
|
75
|
+
readonly config?: Partial<GoalKeepPolicyConfig>;
|
|
76
|
+
}): GoalKeepSelectionResult<TMessage>;
|
|
77
|
+
export declare function estimateGoalKeepTokens(messages: readonly CompactionMessage[]): number;
|
|
78
|
+
export declare function estimateGoalKeepTextTokens(text: unknown): number;
|