opencode-codex-memory 0.7.7 → 0.8.1
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 +64 -482
- package/dist/opencode.json +2 -2
- package/dist/src/capture.d.ts +5 -0
- package/dist/src/capture.js +8 -0
- package/dist/src/claude-import.js +25 -27
- package/dist/src/codex-interop.js +5 -0
- package/dist/src/db.d.ts +7 -1
- package/dist/src/db.js +38 -11
- package/dist/src/host-client.d.ts +5 -0
- package/dist/src/index.d.ts +12 -4
- package/dist/src/index.js +39 -61
- package/dist/src/lifecycle.js +14 -9
- package/dist/src/llm.d.ts +3 -2
- package/dist/src/llm.js +47 -11
- package/dist/src/memory-version.d.ts +5 -0
- package/dist/src/memory-version.js +16 -0
- package/dist/src/migration.d.ts +24 -0
- package/dist/src/migration.js +37 -0
- package/dist/src/options.d.ts +4 -0
- package/dist/src/options.js +2 -0
- package/dist/src/paths.d.ts +9 -3
- package/dist/src/paths.js +22 -8
- package/dist/src/phase1.js +16 -2
- package/dist/src/phase2.js +15 -9
- package/dist/src/pipeline.d.ts +3 -0
- package/dist/src/pipeline.js +74 -0
- package/dist/src/ratelimit.js +5 -4
- package/dist/src/rollout-input.d.ts +3 -2
- package/dist/src/rollout-input.js +26 -17
- package/dist/src/session-version.d.ts +9 -0
- package/dist/src/session-version.js +27 -0
- package/dist/src/source.js +21 -6
- package/dist/src/store.d.ts +10 -1
- package/dist/src/store.js +76 -24
- package/dist/src/templates/consolidation_v2.md +54 -0
- package/dist/src/templates/read_path_v2.md +58 -0
- package/dist/src/templates/stage_one_input_v2.md +21 -0
- package/dist/src/templates/stage_one_system_v2.md +53 -0
- package/dist/src/token.d.ts +2 -0
- package/dist/src/token.js +16 -0
- package/dist/src/v2/agents.d.ts +4 -2
- package/dist/src/v2/agents.js +28 -9
- package/dist/src/v2/citation-overlay.d.ts +1 -1
- package/dist/src/v2/citation-overlay.js +27 -4
- package/dist/src/v2/plugin.js +47 -76
- package/dist/src/v2/search-sandbox.d.ts +4 -0
- package/dist/src/v2/search-sandbox.js +33 -0
- package/dist/src/v2/service.d.ts +2 -0
- package/dist/src/v2/service.js +43 -4
- package/dist/src/v2/shim.d.ts +2 -2
- package/dist/src/v2/shim.js +82 -39
- package/dist/src/v2/status-rpc.d.ts +70 -1
- package/dist/src/v2/status-rpc.js +41 -2
- package/dist/src/v2/status.d.ts +1 -1
- package/dist/src/v2/status.js +28 -6
- package/dist/src/v2/tui.js +57 -2
- package/dist/src/workspace.d.ts +8 -6
- package/dist/src/workspace.js +31 -11
- package/dist/tools/control.d.ts +6 -2
- package/dist/tools/control.js +196 -164
- package/dist/tools/memory.js +11 -1
- package/opencode.json +2 -2
- package/package.json +2 -2
package/dist/src/llm.js
CHANGED
|
@@ -4,6 +4,7 @@ import { memoryRoot } from "./paths.js";
|
|
|
4
4
|
import { hostListSessionsGlobal, hostProviderList, hostSessionCreate, hostSessionDeletionConfirmed, hostSessionPrompt, hostStructuredOutput, ignoreLateRejection, pluginHttpGet, withHostTimeout, } from "./host-client.js";
|
|
5
5
|
import { catalogVariantKeys, nearestReasoningVariant } from "./reasoning-variant.js";
|
|
6
6
|
import { isPluginShuttingDown, pluginShutdownSignal } from "./lifecycle.js";
|
|
7
|
+
import { currentMemoryVersion } from "./memory-version.js";
|
|
7
8
|
import { SCAN_LIMIT } from "./store.js";
|
|
8
9
|
import { isProviderCapacityError, ProviderCapacityError } from "./ratelimit.js";
|
|
9
10
|
let inputRef = null;
|
|
@@ -93,6 +94,10 @@ async function createSession(title) {
|
|
|
93
94
|
body: {
|
|
94
95
|
title,
|
|
95
96
|
metadata: { [SUBSESSION_METADATA_KEY]: true },
|
|
97
|
+
...(title === "codex-memory-consolidate" ? { permission: [
|
|
98
|
+
{ permission: "external_directory", pattern: "*", action: "deny" },
|
|
99
|
+
{ permission: "external_directory", pattern: path.join(memoryRoot(), "*"), action: "allow" },
|
|
100
|
+
] } : {}),
|
|
96
101
|
},
|
|
97
102
|
signal: controller.signal,
|
|
98
103
|
}), createTimeoutMs, "session.create", controller);
|
|
@@ -378,6 +383,15 @@ const EXTRACTION_SCHEMA = {
|
|
|
378
383
|
},
|
|
379
384
|
required: ["raw_memory", "rollout_summary", "rollout_slug"],
|
|
380
385
|
};
|
|
386
|
+
const EXTRACTION_SCHEMA_V2 = {
|
|
387
|
+
type: "object",
|
|
388
|
+
additionalProperties: false,
|
|
389
|
+
properties: {
|
|
390
|
+
rollout_summary: { type: "string" },
|
|
391
|
+
rollout_slug: { type: "string" },
|
|
392
|
+
},
|
|
393
|
+
required: ["rollout_summary", "rollout_slug"],
|
|
394
|
+
};
|
|
381
395
|
/**
|
|
382
396
|
* Returns null when the extractor reported a no-op (nothing worth remembering).
|
|
383
397
|
*
|
|
@@ -390,7 +404,8 @@ export async function extractViaSubagent(sessionId, transcript, opts = {}) {
|
|
|
390
404
|
const agent = "memorize-extract";
|
|
391
405
|
const subId = await createSession(`codex-memory-extract-${sessionId}`);
|
|
392
406
|
try {
|
|
393
|
-
const
|
|
407
|
+
const version = currentMemoryVersion();
|
|
408
|
+
const prompt = buildExtractionInput(sessionId, opts.cwd ?? "unknown", transcript, version);
|
|
394
409
|
// extract_model option > opencode small_model > session default.
|
|
395
410
|
const model = await resolveExtractionModel(opts.model);
|
|
396
411
|
const data = await runPrompt(subId, prompt, agent, {
|
|
@@ -398,13 +413,13 @@ export async function extractViaSubagent(sessionId, transcript, opts = {}) {
|
|
|
398
413
|
// and a near-600k-char transcript on a slow model can easily exceed a
|
|
399
414
|
// short one — repeated timeouts would exhaust the job's retries.
|
|
400
415
|
timeoutMs: opts.timeoutMs ?? 3600_000,
|
|
401
|
-
system: readTemplate("stage_one_system.md"),
|
|
416
|
+
system: readTemplate(version === "v2" ? "stage_one_system_v2.md" : "stage_one_system.md"),
|
|
402
417
|
model,
|
|
403
418
|
signal: opts.signal ?? pluginShutdownSignal(),
|
|
404
419
|
// opencode enforces json_schema output via a forced StructuredOutput tool
|
|
405
420
|
// call (toolChoice: required) — which is why memorize-extract must allow
|
|
406
421
|
// that one otherwise-denied tool.
|
|
407
|
-
format: { type: "json_schema", schema: EXTRACTION_SCHEMA },
|
|
422
|
+
format: { type: "json_schema", schema: version === "v2" ? EXTRACTION_SCHEMA_V2 : EXTRACTION_SCHEMA },
|
|
408
423
|
// Codex extraction ReasoningEffort::Low. Host maps variant → reasoningEffort.
|
|
409
424
|
// If the model has no `low`, pick the nearest listed effort (host-only).
|
|
410
425
|
variant: await resolveReasoningVariant(EXTRACT_VARIANT, model),
|
|
@@ -415,9 +430,9 @@ export async function extractViaSubagent(sessionId, transcript, opts = {}) {
|
|
|
415
430
|
// without the feature, or a model that emitted JSON as plain text).
|
|
416
431
|
const structured = hostStructuredOutput(data);
|
|
417
432
|
if (structured) {
|
|
418
|
-
return validateExtraction(structured);
|
|
433
|
+
return validateExtraction(structured, version);
|
|
419
434
|
}
|
|
420
|
-
return parseExtraction(extractAssistantText(data));
|
|
435
|
+
return parseExtraction(extractAssistantText(data), version);
|
|
421
436
|
}
|
|
422
437
|
finally {
|
|
423
438
|
// Fire-and-forget on purpose (unlike consolidation): stage 1 has no codex
|
|
@@ -621,7 +636,15 @@ export function fillTemplate(tmpl, vars) {
|
|
|
621
636
|
}
|
|
622
637
|
return out;
|
|
623
638
|
}
|
|
624
|
-
function buildExtractionInput(sessionId, cwd, transcript) {
|
|
639
|
+
function buildExtractionInput(sessionId, cwd, transcript, version) {
|
|
640
|
+
if (version === "v2") {
|
|
641
|
+
return fillTemplate(readTemplate("stage_one_input_v2.md"), {
|
|
642
|
+
session_id: sessionId,
|
|
643
|
+
session_cwd: cwd,
|
|
644
|
+
session_git_branch: "unknown",
|
|
645
|
+
transcript,
|
|
646
|
+
});
|
|
647
|
+
}
|
|
625
648
|
return fillTemplate(readTemplate("stage_one_input.md"), {
|
|
626
649
|
session_id: sessionId,
|
|
627
650
|
session_cwd: cwd,
|
|
@@ -663,7 +686,8 @@ export function buildConsolidationPrompt(memoryRoot, diffFileName) {
|
|
|
663
686
|
}
|
|
664
687
|
catch { }
|
|
665
688
|
const blockVars = { memory_extensions_root: extensionsRoot };
|
|
666
|
-
|
|
689
|
+
const template = currentMemoryVersion() === "v2" ? "consolidation_v2.md" : "consolidation.md";
|
|
690
|
+
return fillTemplate(readTemplate(template), {
|
|
667
691
|
memory_root: memoryRoot,
|
|
668
692
|
phase2_workspace_diff_file: diffFileName,
|
|
669
693
|
memory_extensions_folder_structure: extensionsExist ? fillTemplate(EXTENSIONS_FOLDER_STRUCTURE, blockVars) : "",
|
|
@@ -678,8 +702,20 @@ function readTemplate(name) {
|
|
|
678
702
|
* all-empty no-op. Shared by the structured-output path (AssistantMessage.
|
|
679
703
|
* structured) and the text parser below.
|
|
680
704
|
*/
|
|
681
|
-
export function validateExtraction(obj) {
|
|
682
|
-
if (typeof obj.
|
|
705
|
+
export function validateExtraction(obj, version = currentMemoryVersion()) {
|
|
706
|
+
if (typeof obj.rollout_summary !== "string") {
|
|
707
|
+
throw new Error("extraction response missing required fields");
|
|
708
|
+
}
|
|
709
|
+
if (version === "v2") {
|
|
710
|
+
if (!obj.rollout_summary.trim())
|
|
711
|
+
return null;
|
|
712
|
+
return {
|
|
713
|
+
raw_memory: "",
|
|
714
|
+
rollout_summary: obj.rollout_summary,
|
|
715
|
+
rollout_slug: typeof obj.rollout_slug === "string" && obj.rollout_slug.trim() ? obj.rollout_slug : null,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
if (typeof obj.raw_memory !== "string") {
|
|
683
719
|
throw new Error("extraction response missing required fields");
|
|
684
720
|
}
|
|
685
721
|
// codex phase1: either field empty → SucceededNoOutput (not a partial upsert).
|
|
@@ -705,12 +741,12 @@ export function validateExtraction(obj) {
|
|
|
705
741
|
* Parses stage-1 JSON from assistant text. Fallback for when structured output
|
|
706
742
|
* is unavailable; the primary path reads AssistantMessage.structured directly.
|
|
707
743
|
*/
|
|
708
|
-
export function parseExtraction(raw) {
|
|
744
|
+
export function parseExtraction(raw, version = currentMemoryVersion()) {
|
|
709
745
|
const cleaned = raw.replace(/^```(?:json)?/gim, "").replace(/```$/gim, "").trim();
|
|
710
746
|
const start = cleaned.indexOf("{");
|
|
711
747
|
const end = cleaned.lastIndexOf("}");
|
|
712
748
|
if (start === -1 || end === -1 || end <= start) {
|
|
713
749
|
throw new Error("extraction response contained no JSON object");
|
|
714
750
|
}
|
|
715
|
-
return validateExtraction(JSON.parse(cleaned.slice(start, end + 1)));
|
|
751
|
+
return validateExtraction(JSON.parse(cleaned.slice(start, end + 1)), version);
|
|
716
752
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type MemoryVersion } from "./options.js";
|
|
2
|
+
export declare const MEMORY_VERSIONS: readonly ["v1", "v2"];
|
|
3
|
+
export declare function currentMemoryVersion(): MemoryVersion;
|
|
4
|
+
export declare function withMemoryVersion<T>(version: MemoryVersion, run: () => T): T;
|
|
5
|
+
export declare function writeMemoryVersions(): readonly MemoryVersion[];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { pluginOptions } from "./options.js";
|
|
3
|
+
// Codex clones the config for each pipeline. Async-local routing gives every
|
|
4
|
+
// awaited filesystem/model operation the same immutable namespace, without
|
|
5
|
+
// mutating the process-wide read-version option while both writers run.
|
|
6
|
+
const scope = new AsyncLocalStorage();
|
|
7
|
+
export const MEMORY_VERSIONS = ["v1", "v2"];
|
|
8
|
+
export function currentMemoryVersion() {
|
|
9
|
+
return scope.getStore() ?? pluginOptions.version;
|
|
10
|
+
}
|
|
11
|
+
export function withMemoryVersion(version, run) {
|
|
12
|
+
return scope.run(version, run);
|
|
13
|
+
}
|
|
14
|
+
export function writeMemoryVersions() {
|
|
15
|
+
return pluginOptions.dual_write ? MEMORY_VERSIONS : [pluginOptions.version];
|
|
16
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export declare const DEFAULT_MIN_CONSOLIDATED_THREADS = 20;
|
|
2
|
+
/** Codex memory/status: high-water progress AND a currently valid V2 summary. */
|
|
3
|
+
export declare function readMigrationStatus(minConsolidatedThreads?: number): {
|
|
4
|
+
v2ConsolidatedThreads: number;
|
|
5
|
+
v2Ready: boolean;
|
|
6
|
+
minConsolidatedThreads: number;
|
|
7
|
+
};
|
|
8
|
+
export declare function memoryPipelineSnapshots(): {
|
|
9
|
+
version: import("./options.js").MemoryVersion;
|
|
10
|
+
root: string;
|
|
11
|
+
stage1Count: number;
|
|
12
|
+
stage1Jobs: Record<string, number>;
|
|
13
|
+
phase2: {
|
|
14
|
+
status: string;
|
|
15
|
+
last_error: string | null;
|
|
16
|
+
started_at: number | null;
|
|
17
|
+
finished_at: number | null;
|
|
18
|
+
retry_at: number | null;
|
|
19
|
+
lease_until: number | null;
|
|
20
|
+
success_finished_at: number | null;
|
|
21
|
+
last_success_watermark: number | null;
|
|
22
|
+
} | null;
|
|
23
|
+
maxConsolidatedThreads: number;
|
|
24
|
+
}[];
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { memoryDbPath, memoryRoot } from "./paths.js";
|
|
3
|
+
import { MemoryStore, existingMemoryStores } from "./store.js";
|
|
4
|
+
import { withMemoryVersion } from "./memory-version.js";
|
|
5
|
+
import { isValidV2Summary } from "./workspace.js";
|
|
6
|
+
import { safeResolveUnderRoot, readRegularFileNoFollow } from "./path-guard.js";
|
|
7
|
+
export const DEFAULT_MIN_CONSOLIDATED_THREADS = 20;
|
|
8
|
+
/** Codex memory/status: high-water progress AND a currently valid V2 summary. */
|
|
9
|
+
export function readMigrationStatus(minConsolidatedThreads = DEFAULT_MIN_CONSOLIDATED_THREADS) {
|
|
10
|
+
if (!Number.isInteger(minConsolidatedThreads) || minConsolidatedThreads < 1 || minConsolidatedThreads > 4096) {
|
|
11
|
+
throw new Error("minConsolidatedThreads must be between 1 and 4096");
|
|
12
|
+
}
|
|
13
|
+
const v2ConsolidatedThreads = fs.existsSync(memoryDbPath("v2"))
|
|
14
|
+
? withMemoryVersion("v2", () => new MemoryStore().maxConsolidatedThreadCount())
|
|
15
|
+
: 0;
|
|
16
|
+
let valid = false;
|
|
17
|
+
try {
|
|
18
|
+
const file = safeResolveUnderRoot(memoryRoot("v2"), "memory_summary.md");
|
|
19
|
+
valid = isValidV2Summary(readRegularFileNoFollow(file).content.toString("utf8"));
|
|
20
|
+
}
|
|
21
|
+
catch { /* Missing or unsafe summary is not ready. */ }
|
|
22
|
+
return {
|
|
23
|
+
v2ConsolidatedThreads,
|
|
24
|
+
v2Ready: valid && v2ConsolidatedThreads >= minConsolidatedThreads,
|
|
25
|
+
minConsolidatedThreads,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function memoryPipelineSnapshots() {
|
|
29
|
+
return existingMemoryStores().map((store) => ({
|
|
30
|
+
version: store.version,
|
|
31
|
+
root: memoryRoot(store.version),
|
|
32
|
+
stage1Count: store.stage1OutputCount(),
|
|
33
|
+
stage1Jobs: store.stage1JobSnapshot().by_status,
|
|
34
|
+
phase2: store.phase2JobSnapshot(),
|
|
35
|
+
maxConsolidatedThreads: store.maxConsolidatedThreadCount(),
|
|
36
|
+
}));
|
|
37
|
+
}
|
package/dist/src/options.d.ts
CHANGED
|
@@ -11,11 +11,15 @@ import type { ClaudeImportOptions } from "./claude-import.js";
|
|
|
11
11
|
* claude_import, and home are opencode-facing knobs (Codex has no equivalent
|
|
12
12
|
* of relocating just the memory files away from the host data dir).
|
|
13
13
|
*/
|
|
14
|
+
/** Codex MemoriesToml.version. Default v1; v2 is opt-in. */
|
|
15
|
+
export type MemoryVersion = "v1" | "v2";
|
|
14
16
|
export interface PluginOptionsState {
|
|
15
17
|
generate_memories: boolean;
|
|
16
18
|
use_memories: boolean;
|
|
17
19
|
dedicated_tools: boolean;
|
|
18
20
|
disable_on_external_context: boolean;
|
|
21
|
+
version: MemoryVersion;
|
|
22
|
+
dual_write: boolean;
|
|
19
23
|
extract_model?: string;
|
|
20
24
|
consolidation_model?: string;
|
|
21
25
|
/** Resolved absolute plugin home (parent of memory.db + memories/). Unset = default. */
|
package/dist/src/options.js
CHANGED
package/dist/src/paths.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { MemoryVersion } from "./options.js";
|
|
1
2
|
export type MemoryHomeSource = "test" | "option" | "env" | "default";
|
|
2
3
|
/**
|
|
3
4
|
* Memory lives under a dedicated home, mirroring codex's
|
|
@@ -25,6 +26,11 @@ export declare function resolveHomePath(raw: string): string | null;
|
|
|
25
26
|
export declare function setConfiguredHome(home: string | undefined): void;
|
|
26
27
|
export declare function dataRoot(): string;
|
|
27
28
|
export declare function memoryHomeSource(): MemoryHomeSource;
|
|
28
|
-
export declare function memoryRoot(): string;
|
|
29
|
-
|
|
30
|
-
export declare function
|
|
29
|
+
export declare function memoryRoot(version?: MemoryVersion): string;
|
|
30
|
+
/** Jobs/outputs DB for the selected version. Session mode/pollution lives in sessionMetaDbPath. */
|
|
31
|
+
export declare function memoryDbPath(version?: MemoryVersion): string;
|
|
32
|
+
/** Shared catalog (memory_session_meta). Always the v1 db file, like Codex sharing the thread DB. */
|
|
33
|
+
export declare function sessionMetaDbPath(): string;
|
|
34
|
+
export declare function allMemoryRoots(): string[];
|
|
35
|
+
export declare function allJobDbPaths(): string[];
|
|
36
|
+
export declare function memorySummaryPath(version?: MemoryVersion): string;
|
package/dist/src/paths.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import path from "path";
|
|
2
2
|
import os from "os";
|
|
3
3
|
import { xdgData } from "xdg-basedir";
|
|
4
|
-
|
|
5
|
-
const
|
|
4
|
+
import { currentMemoryVersion } from "./memory-version.js";
|
|
5
|
+
const MEMORY_DIR_V1 = "memories";
|
|
6
|
+
const MEMORY_DIR_V2 = "memories_v2";
|
|
7
|
+
const MEMORY_DB_V1 = "memory.db";
|
|
8
|
+
const MEMORY_DB_V2 = "memory_v2.db";
|
|
6
9
|
const TEST_ROOT_ENV = "OPENCODE_CODEX_MEMORY_TEST_ROOT";
|
|
7
10
|
const HOME_ENV = "OPENCODE_CODEX_MEMORY_HOME";
|
|
8
11
|
const OPENCODE_APP_DIR = "opencode";
|
|
@@ -74,12 +77,23 @@ export function memoryHomeSource() {
|
|
|
74
77
|
return "env";
|
|
75
78
|
return "default";
|
|
76
79
|
}
|
|
77
|
-
export function memoryRoot() {
|
|
78
|
-
return path.join(dataRoot(),
|
|
80
|
+
export function memoryRoot(version = currentMemoryVersion()) {
|
|
81
|
+
return path.join(dataRoot(), version === "v2" ? MEMORY_DIR_V2 : MEMORY_DIR_V1);
|
|
79
82
|
}
|
|
80
|
-
|
|
81
|
-
|
|
83
|
+
/** Jobs/outputs DB for the selected version. Session mode/pollution lives in sessionMetaDbPath. */
|
|
84
|
+
export function memoryDbPath(version = currentMemoryVersion()) {
|
|
85
|
+
return path.join(dataRoot(), version === "v2" ? MEMORY_DB_V2 : MEMORY_DB_V1);
|
|
82
86
|
}
|
|
83
|
-
|
|
84
|
-
|
|
87
|
+
/** Shared catalog (memory_session_meta). Always the v1 db file, like Codex sharing the thread DB. */
|
|
88
|
+
export function sessionMetaDbPath() {
|
|
89
|
+
return path.join(dataRoot(), MEMORY_DB_V1);
|
|
90
|
+
}
|
|
91
|
+
export function allMemoryRoots() {
|
|
92
|
+
return [path.join(dataRoot(), MEMORY_DIR_V1), path.join(dataRoot(), MEMORY_DIR_V2)];
|
|
93
|
+
}
|
|
94
|
+
export function allJobDbPaths() {
|
|
95
|
+
return [path.join(dataRoot(), MEMORY_DB_V1), path.join(dataRoot(), MEMORY_DB_V2)];
|
|
96
|
+
}
|
|
97
|
+
export function memorySummaryPath(version = currentMemoryVersion()) {
|
|
98
|
+
return path.join(memoryRoot(version), "memory_summary.md");
|
|
85
99
|
}
|
package/dist/src/phase1.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { STAGE1_CONCURRENCY } from "./store.js";
|
|
2
2
|
import { loadTranscript, selectEligibleSessions } from "./capture.js";
|
|
3
|
+
import { serializeTieredInput } from "./rollout-input.js";
|
|
3
4
|
import { redact, isMemoryExcludedFragment } from "./redact.js";
|
|
4
5
|
import { stripCitations } from "./citation.js";
|
|
5
6
|
import { extractViaSubagent, SubagentCancelledError } from "./llm.js";
|
|
6
7
|
import { checkRateLimit, isProviderCapacityBlocked, isProviderCapacityError, markRateLimitUsed, noteProviderCapacityExhausted, ProviderCapacityError, } from "./ratelimit.js";
|
|
7
8
|
import { isPluginShuttingDown } from "./lifecycle.js";
|
|
8
9
|
import { recordDiagnostic } from "./diagnostics.js";
|
|
10
|
+
import { currentMemoryVersion, withMemoryVersion } from "./memory-version.js";
|
|
11
|
+
import { truncateToBytes } from "./token.js";
|
|
12
|
+
const V2_SUMMARY_MAX_BYTES = 9_000;
|
|
9
13
|
export const DEFAULT_PHASE1_OPTIONS = {
|
|
10
14
|
maxAgeDays: 10,
|
|
11
15
|
minIdleHours: 6,
|
|
@@ -22,6 +26,9 @@ const TRANSCRIPT_MAX_CHARS = 600_000;
|
|
|
22
26
|
const TRANSCRIPT_HEAD_CHARS = 300_000;
|
|
23
27
|
const TRANSCRIPT_TAIL_CHARS = 300_000;
|
|
24
28
|
export async function runPhase1(store, opts = DEFAULT_PHASE1_OPTIONS, rateLimitCheck = checkRateLimit) {
|
|
29
|
+
return withMemoryVersion(store.version, () => runVersionPhase1(store, opts, rateLimitCheck));
|
|
30
|
+
}
|
|
31
|
+
async function runVersionPhase1(store, opts, rateLimitCheck) {
|
|
25
32
|
if (isPluginShuttingDown())
|
|
26
33
|
return;
|
|
27
34
|
// Prune first (no tokens), matching codex start.rs ordering before the gate.
|
|
@@ -97,11 +104,14 @@ export async function runPhase1(store, opts = DEFAULT_PHASE1_OPTIONS, rateLimitC
|
|
|
97
104
|
store.markStage1SucceededNoOutput(sid, claim.ownershipToken, sourceUpdatedAt);
|
|
98
105
|
return;
|
|
99
106
|
}
|
|
107
|
+
const summary = currentMemoryVersion() === "v2"
|
|
108
|
+
? truncateToBytes(redact(result.rollout_summary), V2_SUMMARY_MAX_BYTES)
|
|
109
|
+
: redact(result.rollout_summary);
|
|
100
110
|
store.markStage1Succeeded(sid, claim.ownershipToken, {
|
|
101
111
|
session_id: sid,
|
|
102
112
|
source_updated_at: sourceUpdatedAt,
|
|
103
|
-
raw_memory: redact(result.raw_memory),
|
|
104
|
-
rollout_summary:
|
|
113
|
+
raw_memory: currentMemoryVersion() === "v2" ? "" : redact(result.raw_memory),
|
|
114
|
+
rollout_summary: summary,
|
|
105
115
|
// codex redacts the slug too — it becomes a filename.
|
|
106
116
|
rollout_slug: result.rollout_slug ? redact(result.rollout_slug) : result.rollout_slug,
|
|
107
117
|
cwd: session?.directory ?? null,
|
|
@@ -126,6 +136,10 @@ export async function buildTranscript(sessionId) {
|
|
|
126
136
|
const msgs = await loadTranscript(sessionId);
|
|
127
137
|
if (msgs.length === 0)
|
|
128
138
|
return "";
|
|
139
|
+
if (currentMemoryVersion() === "v2") {
|
|
140
|
+
const tiered = serializeTieredInput(msgs, TRANSCRIPT_MAX_CHARS);
|
|
141
|
+
return redact(stripCitations(tiered));
|
|
142
|
+
}
|
|
129
143
|
const lines = [];
|
|
130
144
|
for (const m of msgs) {
|
|
131
145
|
if (m.type === "system")
|
package/dist/src/phase2.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { checkRateLimit, isProviderCapacityError, noteProviderCapacityExhausted } from "./ratelimit.js";
|
|
2
|
-
import { ensureLayout, rebuildRawMemories, writeRolloutSummaries, pruneExtensionResources, writeWorkspaceDiff,
|
|
2
|
+
import { ensureLayout, rebuildRawMemories, writeRolloutSummaries, pruneExtensionResources, writeWorkspaceDiff, validateConsolidationArtifactsForVersion, removeMemorySymlinks, } from "./workspace.js";
|
|
3
3
|
import { ensureBaseline, captureWorkspaceDiff, resetBaseline, DIFF_ARTIFACT } from "./git-baseline.js";
|
|
4
4
|
import { consolidateViaSubagent, getPluginInput, SubagentCancelledError, SubagentShutdownError, } from "./llm.js";
|
|
5
5
|
import { hostSessionLiveness, withHostTimeout } from "./host-client.js";
|
|
6
6
|
import { invalidateCache } from "./source.js";
|
|
7
|
+
import { withMemoryVersion } from "./memory-version.js";
|
|
7
8
|
import { memoryRoot } from "./paths.js";
|
|
8
9
|
import { abortPhase2Consolidation, beginPhase2AbortScope, endPhase2AbortScope, isPluginShuttingDown, } from "./lifecycle.js";
|
|
9
10
|
import { resolveCodexInterop, syncCodexImport, exportToCodexMemory } from "./codex-interop.js";
|
|
@@ -79,10 +80,10 @@ function maybeExportToCodex(interop) {
|
|
|
79
80
|
console.warn("[opencode-codex-memory] codex export failed:", err);
|
|
80
81
|
}
|
|
81
82
|
}
|
|
82
|
-
|
|
83
|
+
const phase2InFlight = new Set();
|
|
83
84
|
/** True while THIS process runs a consolidation (memory_reset refuses then). */
|
|
84
85
|
export function isPhase2InFlight() {
|
|
85
|
-
return phase2InFlight;
|
|
86
|
+
return phase2InFlight.size > 0;
|
|
86
87
|
}
|
|
87
88
|
/** Release the claim when dispose raced the prep path; return true if released. */
|
|
88
89
|
function releaseIfShuttingDown(store, ownershipToken) {
|
|
@@ -100,11 +101,15 @@ function sweepMemorySymlinksBestEffort() {
|
|
|
100
101
|
}
|
|
101
102
|
}
|
|
102
103
|
export async function runPhase2(store, opts = DEFAULT_PHASE2_OPTIONS) {
|
|
104
|
+
return withMemoryVersion(store.version, () => runVersionPhase2(store, opts));
|
|
105
|
+
}
|
|
106
|
+
async function runVersionPhase2(store, opts) {
|
|
103
107
|
if (isPluginShuttingDown())
|
|
104
108
|
return { status: "shutting_down" };
|
|
105
|
-
|
|
109
|
+
const root = memoryRoot();
|
|
110
|
+
if (phase2InFlight.has(root))
|
|
106
111
|
return { status: "already_running" };
|
|
107
|
-
phase2InFlight
|
|
112
|
+
phase2InFlight.add(root);
|
|
108
113
|
try {
|
|
109
114
|
// No 30s process gate: codex serializes phase 2 only via the DB claim.
|
|
110
115
|
// An observed quota stamp still skips both phases (Codex start.rs).
|
|
@@ -141,7 +146,8 @@ export async function runPhase2(store, opts = DEFAULT_PHASE2_OPTIONS) {
|
|
|
141
146
|
return { status: "shutting_down" };
|
|
142
147
|
}
|
|
143
148
|
const outputs = await selectLivePhase2Inputs(store, opts.maxRaw, opts.maxUnusedDays);
|
|
144
|
-
|
|
149
|
+
if (store.version === "v1")
|
|
150
|
+
rebuildRawMemories(outputs);
|
|
145
151
|
writeRolloutSummaries(outputs);
|
|
146
152
|
pruneExtensionResources(opts.extensionRetentionDays);
|
|
147
153
|
// External-agent imports (Codex consolidated memory + Claude project
|
|
@@ -180,7 +186,7 @@ export async function runPhase2(store, opts = DEFAULT_PHASE2_OPTIONS) {
|
|
|
180
186
|
// already valid. Invalid/empty summary (e.g. ensureLayout's empty file)
|
|
181
187
|
// falls through so the consolidator can INIT/repair.
|
|
182
188
|
if (diff.changes.length === 0) {
|
|
183
|
-
const valid =
|
|
189
|
+
const valid = validateConsolidationArtifactsForVersion(root, store.version);
|
|
184
190
|
if (valid.ok) {
|
|
185
191
|
store.markPhase2Succeeded(claim.ownershipToken, outputs);
|
|
186
192
|
maybeExportToCodex(interop);
|
|
@@ -269,7 +275,7 @@ export async function runPhase2(store, opts = DEFAULT_PHASE2_OPTIONS) {
|
|
|
269
275
|
}
|
|
270
276
|
// codex failed_invalid_artifacts: do not reset baseline on bad output so
|
|
271
277
|
// the next run still sees a diff / can re-INIT.
|
|
272
|
-
const artifacts =
|
|
278
|
+
const artifacts = validateConsolidationArtifactsForVersion(root, store.version);
|
|
273
279
|
if (!artifacts.ok) {
|
|
274
280
|
store.markPhase2Failed(claim.ownershipToken, `failed_invalid_artifacts: ${artifacts.reason}`);
|
|
275
281
|
return { status: "failed_invalid_artifacts" };
|
|
@@ -299,6 +305,6 @@ export async function runPhase2(store, opts = DEFAULT_PHASE2_OPTIONS) {
|
|
|
299
305
|
}
|
|
300
306
|
}
|
|
301
307
|
finally {
|
|
302
|
-
phase2InFlight
|
|
308
|
+
phase2InFlight.delete(root);
|
|
303
309
|
}
|
|
304
310
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { MemoryStore } from "./store.js";
|
|
2
|
+
import { runPhase1 } from "./phase1.js";
|
|
3
|
+
import { runPhase2 } from "./phase2.js";
|
|
4
|
+
import { pluginOptions } from "./options.js";
|
|
5
|
+
import { memoryDbPath } from "./paths.js";
|
|
6
|
+
import { withMemoryVersion, writeMemoryVersions } from "./memory-version.js";
|
|
7
|
+
import { isPluginShuttingDown } from "./lifecycle.js";
|
|
8
|
+
import { recordDiagnostic } from "./diagnostics.js";
|
|
9
|
+
const extracting = new Set();
|
|
10
|
+
async function consolidate(store, bypassCooldown) {
|
|
11
|
+
try {
|
|
12
|
+
const result = await runPhase2(store, {
|
|
13
|
+
maxRaw: pluginOptions.max_raw_memories_for_consolidation,
|
|
14
|
+
maxUnusedDays: pluginOptions.max_unused_days,
|
|
15
|
+
extensionRetentionDays: 7,
|
|
16
|
+
consolidationModel: pluginOptions.consolidation_model,
|
|
17
|
+
codexInterop: pluginOptions.codex_interop,
|
|
18
|
+
claudeImport: pluginOptions.claude_import,
|
|
19
|
+
bypassCooldown,
|
|
20
|
+
});
|
|
21
|
+
if (!["already_running", "skipped_cooldown", "skipped_running"].includes(result.status)) {
|
|
22
|
+
recordDiagnostic(["succeeded", "no_workspace_changes"].includes(result.status) ? "info" : "warn", "phase2", `${store.version}: ${result.status}`);
|
|
23
|
+
}
|
|
24
|
+
return result.status;
|
|
25
|
+
}
|
|
26
|
+
catch (err) {
|
|
27
|
+
recordDiagnostic("error", "phase2", `${store.version}: ${String(err)}`);
|
|
28
|
+
return "failed";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Codex start.rs: independently run phase 1 then phase 2 for each write version. */
|
|
32
|
+
export async function runMemoryPipeline(currentSessionId, bypassCooldown = false) {
|
|
33
|
+
if (!pluginOptions.generate_memories)
|
|
34
|
+
return ["generation_disabled"];
|
|
35
|
+
if (isPluginShuttingDown())
|
|
36
|
+
return ["shutting_down"];
|
|
37
|
+
return Promise.all(writeMemoryVersions().map((version) => withMemoryVersion(version, async () => {
|
|
38
|
+
const key = memoryDbPath();
|
|
39
|
+
if (extracting.has(key))
|
|
40
|
+
return "already_running";
|
|
41
|
+
const store = new MemoryStore();
|
|
42
|
+
extracting.add(key);
|
|
43
|
+
try {
|
|
44
|
+
await runPhase1(store, {
|
|
45
|
+
maxAgeDays: pluginOptions.max_rollout_age_days,
|
|
46
|
+
minIdleHours: pluginOptions.min_rollout_idle_hours,
|
|
47
|
+
maxClaimed: pluginOptions.max_rollouts_per_startup,
|
|
48
|
+
maxUnusedDays: pluginOptions.max_unused_days,
|
|
49
|
+
excludeSession: currentSessionId,
|
|
50
|
+
extractModel: pluginOptions.extract_model,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
recordDiagnostic("error", "phase1", `${version}: ${String(err)}`);
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
extracting.delete(key);
|
|
58
|
+
}
|
|
59
|
+
return consolidate(store, bypassCooldown);
|
|
60
|
+
}).catch((err) => {
|
|
61
|
+
recordDiagnostic("error", "pipeline", `${version}: ${String(err)}`);
|
|
62
|
+
return "failed";
|
|
63
|
+
})));
|
|
64
|
+
}
|
|
65
|
+
export async function runMemoryConsolidation() {
|
|
66
|
+
if (!pluginOptions.generate_memories)
|
|
67
|
+
return ["generation_disabled"];
|
|
68
|
+
if (isPluginShuttingDown())
|
|
69
|
+
return ["shutting_down"];
|
|
70
|
+
return Promise.all(writeMemoryVersions().map((version) => withMemoryVersion(version, async () => consolidate(new MemoryStore(), false)).catch((err) => {
|
|
71
|
+
recordDiagnostic("error", "pipeline", `${version}: ${String(err)}`);
|
|
72
|
+
return "failed";
|
|
73
|
+
})));
|
|
74
|
+
}
|
package/dist/src/ratelimit.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { pluginOptions } from "./options.js";
|
|
2
|
+
import { memoryDbPath } from "./paths.js";
|
|
2
3
|
export class ProviderCapacityError extends Error {
|
|
3
4
|
statusCode;
|
|
4
5
|
constructor(message, statusCode) {
|
|
@@ -27,7 +28,7 @@ export class ProviderCapacityError extends Error {
|
|
|
27
28
|
* - phase 2 has no 30s timer; the DB claim + 6h cooldown serialize it.
|
|
28
29
|
* The observed-quota stamp still skips phase 2 (Codex start.rs skips both).
|
|
29
30
|
*/
|
|
30
|
-
|
|
31
|
+
const lastPhase1Work = new Map();
|
|
31
32
|
const providerCapacityUntil = new Map();
|
|
32
33
|
const MIN_PHASE1_INTERVAL_MS = 30_000;
|
|
33
34
|
export const PROVIDER_CAPACITY_BACKOFF_MS = 3_600_000;
|
|
@@ -105,7 +106,7 @@ export async function checkRateLimit(kind = "phase1", model) {
|
|
|
105
106
|
if (pluginOptions.test)
|
|
106
107
|
return { ok: true };
|
|
107
108
|
const now = Date.now();
|
|
108
|
-
if (now - lastPhase1Work < MIN_PHASE1_INTERVAL_MS) {
|
|
109
|
+
if (now - (lastPhase1Work.get(memoryDbPath()) ?? 0) < MIN_PHASE1_INTERVAL_MS) {
|
|
109
110
|
return { ok: false, reason: "phase1 rate limit (30s since last claimed work)" };
|
|
110
111
|
}
|
|
111
112
|
return { ok: true };
|
|
@@ -113,10 +114,10 @@ export async function checkRateLimit(kind = "phase1", model) {
|
|
|
113
114
|
/** Call after a phase-1 pass claimed at least one job (token-using work started). */
|
|
114
115
|
export function markRateLimitUsed(kind = "phase1") {
|
|
115
116
|
if (kind === "phase1")
|
|
116
|
-
lastPhase1Work
|
|
117
|
+
lastPhase1Work.set(memoryDbPath(), Date.now());
|
|
117
118
|
}
|
|
118
119
|
/** Test seam: reset the process-local stamps. */
|
|
119
120
|
export function resetRateLimitForTest() {
|
|
120
|
-
lastPhase1Work
|
|
121
|
+
lastPhase1Work.clear();
|
|
121
122
|
providerCapacityUntil.clear();
|
|
122
123
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { TranscriptMessage } from "./capture.js";
|
|
2
2
|
/**
|
|
3
3
|
* Human-first extract input. OpenCode parts, not Codex RolloutItem:
|
|
4
|
-
*
|
|
4
|
+
* question-tool replies retain their question; host transcripts expose no
|
|
5
|
+
* Codex MessagePhase::Commentary or internal content-item provenance.
|
|
5
6
|
*/
|
|
6
|
-
export declare function serializeTieredInput(items: TranscriptMessage[],
|
|
7
|
+
export declare function serializeTieredInput(items: TranscriptMessage[], byteLimit?: number): string;
|