opencode-codex-memory 0.8.4 → 0.9.2
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/README.md +2 -2
- package/dist/src/capture.js +4 -0
- package/dist/src/claude-import.js +53 -27
- package/dist/src/git-baseline.d.ts +11 -1
- package/dist/src/git-baseline.js +39 -6
- package/dist/src/llm.js +13 -8
- package/dist/src/phase2.js +13 -2
- package/dist/src/ratelimit.js +10 -2
- package/dist/src/redact.js +12 -1
- package/dist/src/source.js +13 -8
- package/dist/src/store.d.ts +6 -2
- package/dist/src/store.js +35 -9
- package/dist/src/templates/read_path_v2.md +3 -1
- package/dist/src/v2/plugin.js +116 -12
- package/dist/src/v2/service.js +2 -1
- package/dist/src/v2/shim.js +71 -64
- package/dist/src/v2/status-rpc.d.ts +26 -0
- package/dist/src/v2/status-rpc.js +15 -0
- package/dist/src/v2/tools.d.ts +11 -1
- package/dist/src/v2/tools.js +25 -15
- package/dist/src/v2/tui.js +41 -3
- package/dist/src/workspace.js +2 -1
- package/dist/tools/control.d.ts +8 -0
- package/dist/tools/control.js +60 -29
- package/package.json +2 -2
- package/dist/src/local-session-times.d.ts +0 -6
- package/dist/src/local-session-times.js +0 -59
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
|
|
|
35
35
|
{
|
|
36
36
|
"$schema": "https://opencode.ai/config.json",
|
|
37
37
|
"plugins": [
|
|
38
|
-
{ "package": "opencode-codex-memory@0.
|
|
38
|
+
{ "package": "opencode-codex-memory@0.9.2" }
|
|
39
39
|
]
|
|
40
40
|
}
|
|
41
41
|
```
|
|
@@ -45,7 +45,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
|
|
|
45
45
|
```json
|
|
46
46
|
{
|
|
47
47
|
"$schema": "https://opencode.ai/config.json",
|
|
48
|
-
"plugin": ["opencode-codex-memory@0.
|
|
48
|
+
"plugin": ["opencode-codex-memory@0.9.2"]
|
|
49
49
|
}
|
|
50
50
|
```
|
|
51
51
|
|
package/dist/src/capture.js
CHANGED
|
@@ -96,6 +96,10 @@ export async function loadTranscript(sessionId) {
|
|
|
96
96
|
const out = [];
|
|
97
97
|
for (const row of rows) {
|
|
98
98
|
const role = row?.info?.role;
|
|
99
|
+
// Compaction summaries restate messages opencode still keeps; codex drops
|
|
100
|
+
// Compacted items from memory transcripts (rollout policy / phase1.rs).
|
|
101
|
+
if (row?.info?.summary === true)
|
|
102
|
+
continue;
|
|
99
103
|
for (const part of row?.parts ?? []) {
|
|
100
104
|
const question = part;
|
|
101
105
|
const answer = question?.state?.output;
|
|
@@ -99,41 +99,67 @@ export function projectCwdFromSessions(projectRoot) {
|
|
|
99
99
|
})
|
|
100
100
|
.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
101
101
|
for (const { full } of sessions) {
|
|
102
|
-
let content;
|
|
103
102
|
try {
|
|
104
|
-
|
|
103
|
+
for (const line of readLines(full)) {
|
|
104
|
+
const trimmed = line.trim();
|
|
105
|
+
if (!trimmed)
|
|
106
|
+
continue;
|
|
107
|
+
let record;
|
|
108
|
+
try {
|
|
109
|
+
record = JSON.parse(trimmed);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (!record || typeof record !== "object")
|
|
115
|
+
continue;
|
|
116
|
+
const cwd = record.cwd;
|
|
117
|
+
if (typeof cwd !== "string" || !path.isAbsolute(cwd))
|
|
118
|
+
continue;
|
|
119
|
+
try {
|
|
120
|
+
const canonical = fs.realpathSync.native(cwd);
|
|
121
|
+
if (fs.statSync(canonical).isDirectory())
|
|
122
|
+
return canonical;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
105
128
|
}
|
|
106
129
|
catch {
|
|
107
130
|
continue;
|
|
108
131
|
}
|
|
109
|
-
for (const line of content.split(/\r?\n/)) {
|
|
110
|
-
const trimmed = line.trim();
|
|
111
|
-
if (!trimmed)
|
|
112
|
-
continue;
|
|
113
|
-
let record;
|
|
114
|
-
try {
|
|
115
|
-
record = JSON.parse(trimmed);
|
|
116
|
-
}
|
|
117
|
-
catch {
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
if (!record || typeof record !== "object")
|
|
121
|
-
continue;
|
|
122
|
-
const cwd = record.cwd;
|
|
123
|
-
if (typeof cwd !== "string" || !path.isAbsolute(cwd))
|
|
124
|
-
continue;
|
|
125
|
-
try {
|
|
126
|
-
const canonical = fs.realpathSync.native(cwd);
|
|
127
|
-
if (fs.statSync(canonical).isDirectory())
|
|
128
|
-
return canonical;
|
|
129
|
-
}
|
|
130
|
-
catch {
|
|
131
|
-
continue;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
132
|
}
|
|
135
133
|
return null;
|
|
136
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Stream a file's lines in fixed chunks (codex reads through a BufReader).
|
|
137
|
+
* Session transcripts can be hundreds of MB and the cwd sits near the top;
|
|
138
|
+
* stopping iteration closes the file without reading the rest.
|
|
139
|
+
*/
|
|
140
|
+
function* readLines(file) {
|
|
141
|
+
const fd = fs.openSync(file, "r");
|
|
142
|
+
try {
|
|
143
|
+
const decoder = new TextDecoder();
|
|
144
|
+
const chunk = Buffer.allocUnsafe(64 * 1024);
|
|
145
|
+
let pending = "";
|
|
146
|
+
for (;;) {
|
|
147
|
+
const read = fs.readSync(fd, chunk, 0, chunk.length, null);
|
|
148
|
+
if (read === 0)
|
|
149
|
+
break;
|
|
150
|
+
pending += decoder.decode(chunk.subarray(0, read), { stream: true });
|
|
151
|
+
const parts = pending.split(/\r?\n/);
|
|
152
|
+
pending = parts.pop() ?? "";
|
|
153
|
+
yield* parts;
|
|
154
|
+
}
|
|
155
|
+
pending += decoder.decode();
|
|
156
|
+
if (pending)
|
|
157
|
+
yield pending;
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
fs.closeSync(fd);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
137
163
|
function collectMarkdownFiles(sourceRoot, currentDir, projectKey, projectCwd, out) {
|
|
138
164
|
// A partial scan is not a deletion signal. Codex propagates discovery errors
|
|
139
165
|
// before replacing/pruning any imported project.
|
|
@@ -6,6 +6,12 @@ export interface WorkspaceChange {
|
|
|
6
6
|
export interface WorkspaceDiff {
|
|
7
7
|
changes: WorkspaceChange[];
|
|
8
8
|
unifiedDiff: string;
|
|
9
|
+
/**
|
|
10
|
+
* Content hash of every `extensions/` file at capture time. Notes written
|
|
11
|
+
* while the consolidator runs are not in this diff; resetBaseline keeps
|
|
12
|
+
* them out of the new baseline so the next run still sees them.
|
|
13
|
+
*/
|
|
14
|
+
extensionSnapshot?: ReadonlyMap<string, string>;
|
|
9
15
|
}
|
|
10
16
|
/**
|
|
11
17
|
* Mirrors codex prepare_memory_workspace: an existing baseline is preserved
|
|
@@ -20,5 +26,9 @@ export declare function captureWorkspaceDiff(): Promise<WorkspaceDiff>;
|
|
|
20
26
|
* Mirrors codex reset_git_repository: delete .git and re-create a fresh
|
|
21
27
|
* single-commit baseline so deleted/redacted memory content is not retained
|
|
22
28
|
* in unreachable git objects (history is intentionally dropped).
|
|
29
|
+
*
|
|
30
|
+
* Divergence: `extensions/` files added or edited after `captured` (e.g. a
|
|
31
|
+
* memory_add_note during the consolidator turn) stay out of the baseline, so
|
|
32
|
+
* they appear as added in the next diff instead of never being consolidated.
|
|
23
33
|
*/
|
|
24
|
-
export declare function resetBaseline(): Promise<boolean>;
|
|
34
|
+
export declare function resetBaseline(captured?: ReadonlyMap<string, string>): Promise<boolean>;
|
package/dist/src/git-baseline.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from "crypto";
|
|
1
2
|
import fs from "fs";
|
|
2
3
|
import path from "path";
|
|
3
4
|
import { memoryRoot } from "./paths.js";
|
|
@@ -18,6 +19,16 @@ export const DIFF_ARTIFACT = "phase2_workspace_diff.md";
|
|
|
18
19
|
function isHiddenBaselinePath(filepath) {
|
|
19
20
|
return filepath.split("/").some((part) => part.startsWith("."));
|
|
20
21
|
}
|
|
22
|
+
const EXTENSIONS_PREFIX = "extensions/";
|
|
23
|
+
function workdirHash(dir, filepath) {
|
|
24
|
+
try {
|
|
25
|
+
const content = readRegularFileNoFollow(safeResolveUnderRoot(dir, filepath)).content;
|
|
26
|
+
return createHash("sha1").update(content).digest("hex");
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
21
32
|
function removeDiffArtifact(dir) {
|
|
22
33
|
try {
|
|
23
34
|
fs.unlinkSync(path.join(dir, DIFF_ARTIFACT));
|
|
@@ -52,7 +63,7 @@ function gitMetadataUnusable(gitDir) {
|
|
|
52
63
|
}
|
|
53
64
|
// statusMatrix rows are [filepath, head, workdir, stage]; head !== workdir
|
|
54
65
|
// means the working tree differs from HEAD (added, modified, or deleted).
|
|
55
|
-
async function stageAll(dir) {
|
|
66
|
+
async function stageAll(dir, skip) {
|
|
56
67
|
const matrix = await isogit.statusMatrix({ fs, dir });
|
|
57
68
|
let changes = 0;
|
|
58
69
|
for (const [filepath, head, workdir, stage] of matrix) {
|
|
@@ -60,6 +71,8 @@ async function stageAll(dir) {
|
|
|
60
71
|
continue;
|
|
61
72
|
if (head === 1 && workdir === 1 && stage === 1)
|
|
62
73
|
continue;
|
|
74
|
+
if (workdir !== 0 && skip?.(filepath))
|
|
75
|
+
continue;
|
|
63
76
|
if (workdir === 0) {
|
|
64
77
|
// isogit.add throws on deleted files; they must be staged via remove
|
|
65
78
|
await isogit.remove({ fs, dir, filepath });
|
|
@@ -81,8 +94,8 @@ async function hasHeadCommit(dir) {
|
|
|
81
94
|
return false;
|
|
82
95
|
}
|
|
83
96
|
}
|
|
84
|
-
async function commitBaseline(dir) {
|
|
85
|
-
await stageAll(dir);
|
|
97
|
+
async function commitBaseline(dir, skip) {
|
|
98
|
+
await stageAll(dir, skip);
|
|
86
99
|
return isogit.commit({ fs, dir, message: "memory baseline", author: AUTHOR });
|
|
87
100
|
}
|
|
88
101
|
/**
|
|
@@ -163,20 +176,40 @@ export async function captureWorkspaceDiff() {
|
|
|
163
176
|
// on the global 4 MiB truncation in writeWorkspaceDiff.
|
|
164
177
|
patches.push(createPatch(filepath, oldText, newText));
|
|
165
178
|
}
|
|
166
|
-
|
|
179
|
+
const extensionSnapshot = new Map();
|
|
180
|
+
for (const [filepath, , workdir] of matrix) {
|
|
181
|
+
if (workdir === 0 || !filepath.startsWith(EXTENSIONS_PREFIX) || isHiddenBaselinePath(filepath))
|
|
182
|
+
continue;
|
|
183
|
+
const hash = workdirHash(dir, filepath);
|
|
184
|
+
if (hash)
|
|
185
|
+
extensionSnapshot.set(filepath, hash);
|
|
186
|
+
}
|
|
187
|
+
return { changes, unifiedDiff: patches.join("\n"), extensionSnapshot };
|
|
167
188
|
}
|
|
168
189
|
/**
|
|
169
190
|
* Mirrors codex reset_git_repository: delete .git and re-create a fresh
|
|
170
191
|
* single-commit baseline so deleted/redacted memory content is not retained
|
|
171
192
|
* in unreachable git objects (history is intentionally dropped).
|
|
193
|
+
*
|
|
194
|
+
* Divergence: `extensions/` files added or edited after `captured` (e.g. a
|
|
195
|
+
* memory_add_note during the consolidator turn) stay out of the baseline, so
|
|
196
|
+
* they appear as added in the next diff instead of never being consolidated.
|
|
172
197
|
*/
|
|
173
|
-
export async function resetBaseline() {
|
|
198
|
+
export async function resetBaseline(captured) {
|
|
174
199
|
try {
|
|
175
200
|
const dir = memoryRoot();
|
|
176
201
|
removeDiffArtifact(dir);
|
|
177
202
|
fs.rmSync(path.join(dir, ".git"), { recursive: true, force: true });
|
|
178
203
|
await isogit.init({ fs, dir });
|
|
179
|
-
|
|
204
|
+
const skip = captured
|
|
205
|
+
? (filepath) => {
|
|
206
|
+
if (!filepath.startsWith(EXTENSIONS_PREFIX))
|
|
207
|
+
return false;
|
|
208
|
+
const hash = workdirHash(dir, filepath);
|
|
209
|
+
return hash !== null && captured.get(filepath) !== hash;
|
|
210
|
+
}
|
|
211
|
+
: undefined;
|
|
212
|
+
await commitBaseline(dir, skip);
|
|
180
213
|
return true;
|
|
181
214
|
}
|
|
182
215
|
catch (err) {
|
package/dist/src/llm.js
CHANGED
|
@@ -5,8 +5,9 @@ import { hostListSessionsGlobal, hostProviderList, hostSessionCreate, hostSessio
|
|
|
5
5
|
import { catalogVariantKeys, nearestReasoningVariant } from "./reasoning-variant.js";
|
|
6
6
|
import { isPluginShuttingDown, pluginShutdownSignal } from "./lifecycle.js";
|
|
7
7
|
import { currentMemoryVersion } from "./memory-version.js";
|
|
8
|
-
import { SCAN_LIMIT } from "./store.js";
|
|
8
|
+
import { SCAN_LIMIT, STAGE1_LEASE_SECONDS } from "./store.js";
|
|
9
9
|
import { isProviderCapacityError, ProviderCapacityError } from "./ratelimit.js";
|
|
10
|
+
const EXTRACTION_TIMEOUT_MS = (STAGE1_LEASE_SECONDS - 600) * 1000;
|
|
10
11
|
let inputRef = null;
|
|
11
12
|
let inputGeneration = 0;
|
|
12
13
|
let subSessionDirectoryOverride = null;
|
|
@@ -379,7 +380,8 @@ const EXTRACTION_SCHEMA = {
|
|
|
379
380
|
properties: {
|
|
380
381
|
raw_memory: { type: "string" },
|
|
381
382
|
rollout_summary: { type: "string" },
|
|
382
|
-
|
|
383
|
+
// codex phase1_output.rs V1: nullable slug (V2 keeps a plain string).
|
|
384
|
+
rollout_slug: { type: ["string", "null"] },
|
|
383
385
|
},
|
|
384
386
|
required: ["raw_memory", "rollout_summary", "rollout_slug"],
|
|
385
387
|
};
|
|
@@ -409,10 +411,11 @@ export async function extractViaSubagent(sessionId, transcript, opts = {}) {
|
|
|
409
411
|
// extract_model option > opencode small_model > session default.
|
|
410
412
|
const model = await resolveExtractionModel(opts.model);
|
|
411
413
|
const data = await runPrompt(subId, prompt, agent, {
|
|
412
|
-
//
|
|
413
|
-
//
|
|
414
|
-
//
|
|
415
|
-
|
|
414
|
+
// Bounded by the stage-1 job lease (1h), minus headroom for transcript
|
|
415
|
+
// load, session creation, and model lookups before the prompt starts.
|
|
416
|
+
// Codex has no per-request timeout; a timeout past the lease lets
|
|
417
|
+
// another process reclaim the job and silently drop this paid result.
|
|
418
|
+
timeoutMs: opts.timeoutMs ?? EXTRACTION_TIMEOUT_MS,
|
|
416
419
|
system: readTemplate(version === "v2" ? "stage_one_system_v2.md" : "stage_one_system.md"),
|
|
417
420
|
model,
|
|
418
421
|
signal: opts.signal ?? pluginShutdownSignal(),
|
|
@@ -608,8 +611,10 @@ async function deleteSession(id, input = getPluginInput(), timeoutMs = SUBSESSIO
|
|
|
608
611
|
// the HTTP route still returns success. Only a confirmed 404 proves the
|
|
609
612
|
// session is gone; otherwise retain ownership so hooks keep skipping it.
|
|
610
613
|
// codex runtime.rs drops the thread from its manager the same way: only
|
|
611
|
-
// after shutdown succeeded.
|
|
612
|
-
|
|
614
|
+
// after shutdown succeeded. Hosts without session.get cannot confirm;
|
|
615
|
+
// the successful delete is all the evidence there is.
|
|
616
|
+
const canConfirm = typeof input.client.session?.get === "function";
|
|
617
|
+
if (!canConfirm || await hostSessionDeletionConfirmed(input.client, id, SUBSESSION_CONFIRM_TIMEOUT_MS)) {
|
|
613
618
|
activeSubSessions.delete(id);
|
|
614
619
|
}
|
|
615
620
|
return true;
|
package/dist/src/phase2.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PHASE2_HEARTBEAT_SECONDS } from "./store.js";
|
|
1
2
|
import { checkRateLimit, isProviderCapacityError, noteProviderCapacityExhausted } from "./ratelimit.js";
|
|
2
3
|
import { ensureLayout, rebuildRawMemories, writeRolloutSummaries, pruneExtensionResources, writeWorkspaceDiff, validateConsolidationArtifactsForVersion, removeMemorySymlinks, } from "./workspace.js";
|
|
3
4
|
import { ensureBaseline, captureWorkspaceDiff, resetBaseline, DIFF_ARTIFACT } from "./git-baseline.js";
|
|
@@ -117,6 +118,16 @@ async function runVersionPhase2(store, opts) {
|
|
|
117
118
|
const rl = await checkRateLimit("phase2", consolidationModel);
|
|
118
119
|
if (!rl.ok)
|
|
119
120
|
return { status: "skipped_rate_limit" };
|
|
121
|
+
// Boot sweeps alone would wait out a whole lease when the host restarts
|
|
122
|
+
// within the heartbeat-staleness window of a crash.
|
|
123
|
+
try {
|
|
124
|
+
if (store.releaseOrphanedPhase2Job()) {
|
|
125
|
+
console.warn(`[opencode-codex-memory] released orphaned ${store.version} consolidation lease`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
console.warn("[opencode-codex-memory] orphaned phase2 sweep failed:", err);
|
|
130
|
+
}
|
|
120
131
|
const claim = store.claimGlobalPhase2Job({ bypassCooldown: opts.bypassCooldown });
|
|
121
132
|
if (claim.type !== "claimed")
|
|
122
133
|
return { status: claim.type };
|
|
@@ -230,7 +241,7 @@ async function runVersionPhase2(store, opts) {
|
|
|
230
241
|
if (releaseIfShuttingDown(store, claim.ownershipToken)) {
|
|
231
242
|
return { status: "shutting_down" };
|
|
232
243
|
}
|
|
233
|
-
const heartbeat = setInterval(heartbeatOnce, opts.heartbeatIntervalMs ??
|
|
244
|
+
const heartbeat = setInterval(heartbeatOnce, opts.heartbeatIntervalMs ?? PHASE2_HEARTBEAT_SECONDS * 1000);
|
|
234
245
|
try {
|
|
235
246
|
await consolidateViaSubagent(memoryRoot(), DIFF_ARTIFACT, consolidationModel, consolidationSignal);
|
|
236
247
|
}
|
|
@@ -280,7 +291,7 @@ async function runVersionPhase2(store, opts) {
|
|
|
280
291
|
store.markPhase2Failed(claim.ownershipToken, `failed_invalid_artifacts: ${artifacts.reason}`);
|
|
281
292
|
return { status: "failed_invalid_artifacts" };
|
|
282
293
|
}
|
|
283
|
-
if (!await withHostTimeout(resetBaseline(), GIT_TIMEOUT_MS, "resetBaseline")) {
|
|
294
|
+
if (!await withHostTimeout(resetBaseline(diff.extensionSnapshot), GIT_TIMEOUT_MS, "resetBaseline")) {
|
|
284
295
|
store.markPhase2Failed(claim.ownershipToken, "baseline reset failed");
|
|
285
296
|
return { status: "baseline_reset_failed" };
|
|
286
297
|
}
|
package/dist/src/ratelimit.js
CHANGED
|
@@ -32,7 +32,12 @@ const lastPhase1Work = new Map();
|
|
|
32
32
|
const providerCapacityUntil = new Map();
|
|
33
33
|
const MIN_PHASE1_INTERVAL_MS = 30_000;
|
|
34
34
|
export const PROVIDER_CAPACITY_BACKOFF_MS = 3_600_000;
|
|
35
|
-
const PROVIDER_CAPACITY_RE = /usage limit|free usage exceeded|provider capacity exhausted|rate[\s_-]?limit|quota
|
|
35
|
+
const PROVIDER_CAPACITY_RE = /usage limit|free usage exceeded|provider capacity exhausted|rate[\s_-]?limit|quota\s+(?:exceeded|exhausted|reached)|exceeded (?:your|the) (?:current )?quota|too many requests|\b429\b|resource_exhausted|insufficient_quota|billing.?hard.?limit/i;
|
|
36
|
+
// A single request larger than the per-minute budget (OpenAI "Request too
|
|
37
|
+
// large … tokens per min", sent as 429) never succeeds on retry; treating it
|
|
38
|
+
// as capacity would keep that session pending forever and trip the breaker
|
|
39
|
+
// for every other extraction on each attempt.
|
|
40
|
+
const REQUEST_SIZE_RE = /request too large|context[\s_-]?length|maximum context|prompt is too long|too many tokens/i;
|
|
36
41
|
function errorRecord(error) {
|
|
37
42
|
return error && typeof error === "object" ? error : null;
|
|
38
43
|
}
|
|
@@ -66,9 +71,12 @@ export function providerCapacityMessage(error) {
|
|
|
66
71
|
export function isProviderCapacityError(error) {
|
|
67
72
|
if (error instanceof ProviderCapacityError)
|
|
68
73
|
return true;
|
|
74
|
+
const message = providerCapacityMessage(error);
|
|
75
|
+
if (REQUEST_SIZE_RE.test(message))
|
|
76
|
+
return false;
|
|
69
77
|
if (providerCapacityStatusCode(error) === 429)
|
|
70
78
|
return true;
|
|
71
|
-
return PROVIDER_CAPACITY_RE.test(
|
|
79
|
+
return PROVIDER_CAPACITY_RE.test(message);
|
|
72
80
|
}
|
|
73
81
|
function providerCapacityScope(phase, model) {
|
|
74
82
|
return model ? `model:${model}` : `phase:${phase}:default`;
|
package/dist/src/redact.js
CHANGED
|
@@ -57,8 +57,10 @@ function scanAssignmentValue(text, start, keyQuote, separator, flowCollection, e
|
|
|
57
57
|
valueStart++;
|
|
58
58
|
}
|
|
59
59
|
const first = text[valueStart];
|
|
60
|
-
if (!first
|
|
60
|
+
if (!first)
|
|
61
61
|
return null;
|
|
62
|
+
if (first === "\r" || first === "\n")
|
|
63
|
+
return flowCollection ? null : scanNextLineValue(text, valueStart);
|
|
62
64
|
if (first === '"' || first === "'") {
|
|
63
65
|
const end = scanQuoted(text, valueStart, first) ?? plainValueEnd(text, valueStart, flowCollection);
|
|
64
66
|
return end > valueStart ? { start: valueStart, end, replacement: `${first}[REDACTED]${first}` } : null;
|
|
@@ -75,6 +77,15 @@ function scanAssignmentValue(text, start, keyQuote, separator, flowCollection, e
|
|
|
75
77
|
const end = plainValueEnd(text, valueStart, flowCollection);
|
|
76
78
|
return end > valueStart ? { start: valueStart, end, replacement: '"[REDACTED]"' } : null;
|
|
77
79
|
}
|
|
80
|
+
// Codex's separator is `\s*`, so a value on the following line still redacts
|
|
81
|
+
// under its `(["']?)[^\s"']{8,}` value rule. Short YAML block keys stay intact.
|
|
82
|
+
function scanNextLineValue(text, start) {
|
|
83
|
+
const match = /^\s*["']?([^\s"']{8,})/.exec(text.slice(start));
|
|
84
|
+
if (!match)
|
|
85
|
+
return null;
|
|
86
|
+
const end = start + match[0].length;
|
|
87
|
+
return { start: end - match[1].length, end, replacement: "[REDACTED]" };
|
|
88
|
+
}
|
|
78
89
|
function scanEnclosingQuote(text, start, quote) {
|
|
79
90
|
for (let i = start; i < text.length; i++) {
|
|
80
91
|
if (quote === '"' && text[i] === "\\") {
|
package/dist/src/source.js
CHANGED
|
@@ -18,7 +18,8 @@ const SEARCH_STEP_TOOLS = `2. Search {{ base_path }}/MEMORY.md for those keyword
|
|
|
18
18
|
pass \`since\`/\`until\` to \`memory_search\` — with a query it searches only that
|
|
19
19
|
period's sessions/notes; without a query it lists them chronologically.`;
|
|
20
20
|
const SEARCH_STEP_FILES = `2. Search {{ base_path }}/MEMORY.md using those keywords.`;
|
|
21
|
-
const SEARCH_STEP_TOOLS_V2 = `
|
|
21
|
+
const SEARCH_STEP_TOOLS_V2 = `Call \`memory_search\`, \`memory_read\`, \`memory_list\`, and \`memory_add_note\` directly. They are normal tools in this chat, not tools inside \`execute\`.
|
|
22
|
+
Search {{ base_path }}/rollout_summaries/ with the \`memory_search\`
|
|
22
23
|
tool, or read a recap with \`memory_read\`, when extra evidence, wording,
|
|
23
24
|
chronology, or uncertainty could change your answer.
|
|
24
25
|
- For time-scoped recall ("what was I working on last week / around date X"),
|
|
@@ -35,10 +36,16 @@ const UPDATE_INSTRUCTIONS_FILES = `- Write your update in {{ base_path }}/extens
|
|
|
35
36
|
- Do not edit the other memory files yourself; the consolidation pass will
|
|
36
37
|
integrate the note.`;
|
|
37
38
|
const cache = new Map();
|
|
39
|
+
// Shipped templates never change while the plugin runs; read once per version.
|
|
40
|
+
const templates = new Map();
|
|
38
41
|
function readTemplate() {
|
|
39
42
|
const name = currentMemoryVersion() === "v2" ? READ_PATH_TEMPLATE_V2 : READ_PATH_TEMPLATE;
|
|
40
|
-
|
|
41
|
-
|
|
43
|
+
let template = templates.get(name);
|
|
44
|
+
if (template === undefined) {
|
|
45
|
+
template = fs.readFileSync(path.join(import.meta.dirname, "templates", name), "utf8");
|
|
46
|
+
templates.set(name, template);
|
|
47
|
+
}
|
|
48
|
+
return template;
|
|
42
49
|
}
|
|
43
50
|
function readMemorySummary() {
|
|
44
51
|
try {
|
|
@@ -46,18 +53,16 @@ function readMemorySummary() {
|
|
|
46
53
|
// neither the root nor memory_summary.md may redirect outside the workspace.
|
|
47
54
|
const summaryPath = safeResolveMemoryPath("memory_summary.md");
|
|
48
55
|
return withRegularFileNoFollow(summaryPath, fs.constants.O_RDONLY, (fd, stat) => {
|
|
56
|
+
const identity = `${stat.mtimeMs}:${stat.size}:${stat.ino}`;
|
|
49
57
|
const cached = cache.get(summaryPath);
|
|
50
|
-
if (cached && cached.
|
|
58
|
+
if (cached && cached.identity === identity) {
|
|
51
59
|
return cached.content;
|
|
52
60
|
}
|
|
53
61
|
const raw = fs.readFileSync(fd, "utf8").trim();
|
|
54
62
|
if (!raw)
|
|
55
63
|
return null;
|
|
56
64
|
const truncated = truncateToTokens(raw, MEMORY_SUMMARY_TOKEN_LIMIT);
|
|
57
|
-
cache.set(summaryPath, {
|
|
58
|
-
content: truncated,
|
|
59
|
-
mtime: stat.mtimeMs,
|
|
60
|
-
});
|
|
65
|
+
cache.set(summaryPath, { content: truncated, identity });
|
|
61
66
|
return truncated;
|
|
62
67
|
});
|
|
63
68
|
}
|
package/dist/src/store.d.ts
CHANGED
|
@@ -44,6 +44,7 @@ export type Phase2ClaimResult = {
|
|
|
44
44
|
export declare function clearAllVersionMemoryData(): void;
|
|
45
45
|
/** Include inactive existing stores for deletion, reset guards and diagnostics. */
|
|
46
46
|
export declare function existingMemoryStores(): MemoryStore[];
|
|
47
|
+
export declare const PHASE2_HEARTBEAT_SECONDS = 90;
|
|
47
48
|
export declare class MemoryStore {
|
|
48
49
|
private db;
|
|
49
50
|
private meta;
|
|
@@ -128,9 +129,11 @@ export declare class MemoryStore {
|
|
|
128
129
|
* so the next process can reclaim immediately. Ownership-token guarded.
|
|
129
130
|
*/
|
|
130
131
|
/**
|
|
131
|
-
*
|
|
132
|
+
* Orphan sweep: a `running` global row whose owning pid is dead can never
|
|
132
133
|
* be finished by anyone; release it so the next pass can reclaim instead of
|
|
133
|
-
* waiting the full lease out. Rows from live pids (a peer instance)
|
|
134
|
+
* waiting the full lease out. Rows from live pids (a peer instance), rows
|
|
135
|
+
* from another host, rows with a fresh heartbeat (the owner may sit in
|
|
136
|
+
* another pid namespace, e.g. a sandbox sharing memory.db), and rows
|
|
134
137
|
* without a pid tag (older schema) are left alone.
|
|
135
138
|
*/
|
|
136
139
|
releaseOrphanedPhase2Job(): boolean;
|
|
@@ -172,6 +175,7 @@ export declare class MemoryStore {
|
|
|
172
175
|
stampMemoryModeIfAbsent(sessionId: string, mode: "enabled" | "disabled"): void;
|
|
173
176
|
getMemoryMode(sessionId: string): "enabled" | "disabled" | "polluted" | null;
|
|
174
177
|
markPolluted(sessionId: string): void;
|
|
178
|
+
private enqueueIfSelected;
|
|
175
179
|
isPolluted(sessionId: string): boolean;
|
|
176
180
|
/**
|
|
177
181
|
* Stage-1 job counts + recent failures for memory_inspect. Helps diagnose
|
package/dist/src/store.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
|
+
import os from "os";
|
|
2
3
|
import { openDb, openSessionMetaDb, openTransientDb } from "./db.js";
|
|
3
4
|
import { allJobDbPaths, sessionMetaDbPath, memoryDbPath } from "./paths.js";
|
|
4
5
|
import { currentMemoryVersion, MEMORY_VERSIONS, withMemoryVersion } from "./memory-version.js";
|
|
@@ -48,10 +49,11 @@ function newId() {
|
|
|
48
49
|
return crypto.randomUUID();
|
|
49
50
|
}
|
|
50
51
|
/**
|
|
51
|
-
* Phase-2 worker ids embed the owning pid so a later boot can tell a
|
|
52
|
-
* peer's lease from one orphaned by a hard kill (host auto-update/restart).
|
|
52
|
+
* Phase-2 worker ids embed the owning pid and host so a later boot can tell a
|
|
53
|
+
* live peer's lease from one orphaned by a hard kill (host auto-update/restart).
|
|
53
54
|
*/
|
|
54
|
-
const PHASE2_WORKER_PREFIX = `pid:${process.pid}:`;
|
|
55
|
+
const PHASE2_WORKER_PREFIX = `pid:${process.pid}@${os.hostname()}:`;
|
|
56
|
+
export const PHASE2_HEARTBEAT_SECONDS = 90;
|
|
55
57
|
function phase2WorkerId() {
|
|
56
58
|
return `${PHASE2_WORKER_PREFIX}${crypto.randomUUID()}`;
|
|
57
59
|
}
|
|
@@ -111,17 +113,22 @@ export class MemoryStore {
|
|
|
111
113
|
*/
|
|
112
114
|
pruneStage1Outputs(maxUnusedDays) {
|
|
113
115
|
const cutoff = now() - maxUnusedDays * 24 * 60 * 60 * 1000;
|
|
114
|
-
|
|
116
|
+
const pruned = this.db
|
|
115
117
|
.prepare(`DELETE FROM memory_stage1_outputs
|
|
116
118
|
WHERE rowid IN (
|
|
117
119
|
SELECT rowid FROM memory_stage1_outputs
|
|
118
120
|
WHERE selected_for_phase2 = 0
|
|
119
121
|
AND ((last_usage IS NOT NULL AND last_usage < ?)
|
|
120
122
|
OR (last_usage IS NULL AND source_updated_at < ?))
|
|
121
|
-
ORDER BY COALESCE(last_usage, source_updated_at) ASC
|
|
123
|
+
ORDER BY COALESCE(last_usage, source_updated_at) ASC, source_updated_at ASC, session_id ASC
|
|
122
124
|
LIMIT ?
|
|
123
125
|
)`)
|
|
124
126
|
.run(cutoff, cutoff, PRUNE_BATCH_SIZE).changes;
|
|
127
|
+
// db.ts opts into auto_vacuum=INCREMENTAL; free pages are only returned
|
|
128
|
+
// to the filesystem when asked.
|
|
129
|
+
if (pruned > 0)
|
|
130
|
+
this.db.run("PRAGMA incremental_vacuum");
|
|
131
|
+
return pruned;
|
|
125
132
|
}
|
|
126
133
|
upsertStage1Output(out) {
|
|
127
134
|
const existing = this.db
|
|
@@ -555,21 +562,28 @@ export class MemoryStore {
|
|
|
555
562
|
* so the next process can reclaim immediately. Ownership-token guarded.
|
|
556
563
|
*/
|
|
557
564
|
/**
|
|
558
|
-
*
|
|
565
|
+
* Orphan sweep: a `running` global row whose owning pid is dead can never
|
|
559
566
|
* be finished by anyone; release it so the next pass can reclaim instead of
|
|
560
|
-
* waiting the full lease out. Rows from live pids (a peer instance)
|
|
567
|
+
* waiting the full lease out. Rows from live pids (a peer instance), rows
|
|
568
|
+
* from another host, rows with a fresh heartbeat (the owner may sit in
|
|
569
|
+
* another pid namespace, e.g. a sandbox sharing memory.db), and rows
|
|
561
570
|
* without a pid tag (older schema) are left alone.
|
|
562
571
|
*/
|
|
563
572
|
releaseOrphanedPhase2Job() {
|
|
564
573
|
const row = this.db
|
|
565
|
-
.prepare(`SELECT worker_id FROM memory_jobs
|
|
574
|
+
.prepare(`SELECT worker_id, lease_until FROM memory_jobs
|
|
566
575
|
WHERE kind='memory_consolidate_global' AND job_key='global' AND status='running'`)
|
|
567
576
|
.get();
|
|
568
|
-
const m = row?.worker_id?.match(/^pid:(\d+)
|
|
577
|
+
const m = row?.worker_id?.match(/^pid:(\d+)(?:@([^:]*))?:/);
|
|
569
578
|
if (!m)
|
|
570
579
|
return false;
|
|
580
|
+
if (m[2] !== undefined && m[2] !== os.hostname())
|
|
581
|
+
return false;
|
|
571
582
|
if (pidAlive(Number(m[1])))
|
|
572
583
|
return false;
|
|
584
|
+
const heartbeatFreshAfter = nowSec() + PHASE2_LEASE_SECONDS - 3 * PHASE2_HEARTBEAT_SECONDS;
|
|
585
|
+
if (row.lease_until !== null && row.lease_until > heartbeatFreshAfter)
|
|
586
|
+
return false;
|
|
573
587
|
const res = this.db
|
|
574
588
|
.prepare(`UPDATE memory_jobs SET
|
|
575
589
|
status = 'pending',
|
|
@@ -692,6 +706,18 @@ export class MemoryStore {
|
|
|
692
706
|
VALUES (?, 'polluted', 1, ?)
|
|
693
707
|
ON CONFLICT(session_id) DO UPDATE SET polluted=1, memory_mode='polluted', updated_at=excluded.updated_at`)
|
|
694
708
|
.run(sessionId, now());
|
|
709
|
+
// codex mark_thread_memory_mode_polluted: a consumed output must be
|
|
710
|
+
// forgotten on the next pass, not after a pending phase-2 retry backoff.
|
|
711
|
+
// Session meta is shared, so every writer that consumed it re-queues.
|
|
712
|
+
for (const store of existingMemoryStores())
|
|
713
|
+
store.enqueueIfSelected(sessionId);
|
|
714
|
+
}
|
|
715
|
+
enqueueIfSelected(sessionId) {
|
|
716
|
+
const row = this.db
|
|
717
|
+
.prepare("SELECT selected_for_phase2 FROM memory_stage1_outputs WHERE session_id = ?")
|
|
718
|
+
.get(sessionId);
|
|
719
|
+
if (row && row.selected_for_phase2 !== 0)
|
|
720
|
+
this.enqueueGlobalConsolidation(now());
|
|
695
721
|
}
|
|
696
722
|
isPolluted(sessionId) {
|
|
697
723
|
const row = this.meta
|
|
@@ -49,7 +49,9 @@ ses_def456
|
|
|
49
49
|
Updating memories:
|
|
50
50
|
|
|
51
51
|
You may update memories **only** when explicitly asked by the user. This must
|
|
52
|
-
always come from a direct request from the user.
|
|
52
|
+
always come from a direct request from the user. For an explicit remember,
|
|
53
|
+
forget, or correction request, record the requested addition, deletion, or
|
|
54
|
+
correction as a note:
|
|
53
55
|
{{ update_instructions }}
|
|
54
56
|
Do not edit generated memory files directly; consolidation applies these notes.
|
|
55
57
|
|