@unblocklabs/unblock-codex-prompt 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.d.ts CHANGED
@@ -1,54 +1,96 @@
1
+ export declare const RUNTIMES: readonly ["codex", "claude-cli"];
2
+ export type ManagedRuntime = typeof RUNTIMES[number];
3
+ /** previousPointer is Codex's original model_instructions_file; unused by Claude-only enrollment. */
4
+ export type Enrollment = {
5
+ active: boolean;
6
+ previousPointer: string | null;
7
+ runtimes: ManagedRuntime[];
8
+ };
9
+ /** A fetched fleet policy and its provenance. Metadata (never `text`) is safe to report. */
10
+ export type PolicyReceipt = {
11
+ url: string;
12
+ revision: string;
13
+ checkedAt: number;
14
+ };
15
+ export type ClaudePolicy = PolicyReceipt & {
16
+ text: string;
17
+ };
18
+ /**
19
+ * `policy` stays "" (0.3 runtimes require the field; they read only `schema`, `policy` and
20
+ * `promptSha256`). The Codex policy is the prompt-file prefix, with `basePromptLength` and
21
+ * `remotePrompt` describing it. Claude's policy and the shared agent context live in the bundle
22
+ * itself, so Claude never reads the Codex artifact.
23
+ */
1
24
  export type FrozenBundle = {
2
25
  schema: 1;
3
26
  policy: string;
4
- sources: {
5
- name: string;
6
- sha256: string | null;
7
- }[];
8
- skillCount: number;
9
27
  basePromptLength?: number;
10
28
  remotePrompt?: {
11
29
  url: string;
12
30
  revision: string;
13
31
  checkedAt?: number;
14
32
  };
33
+ claudePolicy?: ClaudePolicy;
34
+ agentContext?: string;
15
35
  };
16
- export declare const FROZEN_CONTEXT_HEADER = "\n\n## Frozen agent context\n";
36
+ /** First heading of the agent context, the boundary after the shared policy prefix. */
37
+ export declare const MEMORY_REFERENCE_HEADER = "\n\n## Memory reference\n";
38
+ /**
39
+ * Accepted boundaries: the current first heading, then the 0.4 branch builds' `## Agent context`
40
+ * and the 0.3 `## Frozen agent context`, so their prompt files still refresh in place.
41
+ */
42
+ export declare const CONTEXT_BOUNDARY_HEADERS: readonly ["\n\n## Memory reference\n", "\n\n## Agent context\n", "\n\n## Frozen agent context\n"];
43
+ /** Strict shape check for a stored Claude policy; throws on anything else. */
44
+ export declare function parseClaudePolicy(value: unknown): ClaudePolicy;
17
45
  export type PromptTarget = {
18
46
  agentDir: string;
19
47
  prompt: string;
20
48
  bundle?: FrozenBundle;
21
49
  };
22
50
  export declare function readOptional(path: string): Promise<string | null>;
51
+ export declare function parseEnrollment(source: string | null): Enrollment | null;
52
+ /**
53
+ * Schema 1 is the format 0.3.x reads (it checks only schema, active and previousPointer).
54
+ * Every state 0.3.x can safely act on uses it: Codex enrollments (with Claude too, 0.3.x keeps
55
+ * managing Codex and registers no Claude prompt hook, so Claude falls back upstream) and paused ones.
56
+ * Active Claude-only enrollment is schema 2, which 0.3.x refuses rather than mismanaging it.
57
+ * Codex-only enrollment omits runtimes: exactly the 0.3.x shape.
58
+ */
59
+ export declare function serializeEnrollment(enrollment: Enrollment): string;
60
+ /** Disk-only enrollment for callers that select runtime components. */
61
+ export declare function readEnrollment(agentDir: string): Promise<Enrollment | null>;
23
62
  export declare function sha256(text: string): string;
24
- /** Disk state only: this cannot attest to instructions retained by a live Codex thread. */
63
+ /** Disk state only: this cannot attest to instructions retained by a live Codex thread or Claude process. */
25
64
  export declare function promptStatus(target: PromptTarget): Promise<{
26
65
  enrolled: boolean;
27
66
  restored: boolean;
67
+ runtimes: ("codex" | "claude-cli")[];
28
68
  configPath: string;
29
69
  promptPath: string;
30
- pointerMatches: boolean;
31
- promptMatches: boolean;
32
- expectedSha256: string;
70
+ pointerMatches: boolean | null;
33
71
  actualSha256: string | null;
34
72
  runtimeVerified: boolean;
35
73
  }>;
36
74
  export declare function replaceFile(path: string, previous: string | null, contents: string): Promise<boolean>;
37
75
  export declare function withLock<T>(target: PromptTarget, operation: () => Promise<T>): Promise<T>;
76
+ export declare const ACTIVATION: Record<ManagedRuntime, string>;
38
77
  export declare function syncPrompt(target: PromptTarget, options?: {
39
78
  adopt?: boolean;
40
79
  automatic?: boolean;
80
+ runtimes?: readonly ManagedRuntime[];
41
81
  }): Promise<{
42
82
  changed: boolean;
43
83
  restored: boolean;
44
84
  promptChanged?: never;
45
85
  configChanged?: never;
86
+ runtimes?: never;
46
87
  sha256?: never;
47
88
  activation?: never;
48
89
  } | {
49
90
  changed: boolean;
50
91
  promptChanged: boolean;
51
92
  configChanged: boolean;
93
+ runtimes: ("codex" | "claude-cli")[];
52
94
  sha256: string;
53
95
  activation: string;
54
96
  restored?: never;
@@ -56,25 +98,37 @@ export declare function syncPrompt(target: PromptTarget, options?: {
56
98
  export declare function restorePrompt(target: PromptTarget): Promise<{
57
99
  changed: boolean;
58
100
  restored: boolean;
101
+ runtimes: ("codex" | "claude-cli")[];
59
102
  retainedPromptPath: string;
60
103
  }>;
61
- /** Replace only the shared prefix; never reread workspace documents or skills. */
62
- export declare function refreshSharedPrompt(agentDir: string, fetchBase: () => Promise<{
104
+ export type FetchedPolicy = () => Promise<{
63
105
  prompt: string;
64
106
  source: {
65
107
  url: string;
66
108
  revision: string;
67
109
  };
68
- }>, now?: number): Promise<{
110
+ }>;
111
+ /**
112
+ * Daily/explicit refresh of each enrolled runtime's fleet policy; it never rereads the agent
113
+ * context. Every enrolled runtime is fetched before anything is written, so one failure leaves
114
+ * all local state untouched. Then, in one locked write:
115
+ * - Codex: only the policy prefix of the prompt file is replaced (the file keeps its inode when
116
+ * unchanged). Everything after `basePromptLength` is kept byte-for-byte, so a snapshot from an
117
+ * older sync keeps its frozen skills catalog tail until the next sync rewrites the file;
118
+ * - Claude: only `claudePolicy` in the bundle is replaced; the prompt file is not touched for it.
119
+ */
120
+ export declare function refreshSharedPrompt(agentDir: string, fetchers: {
121
+ codex?: FetchedPolicy;
122
+ claude?: FetchedPolicy;
123
+ }, now?: number): Promise<{
69
124
  changed: boolean;
70
125
  skipped: boolean;
71
- revision?: never;
72
- checkedAt?: never;
73
- newSessionRequired?: never;
74
126
  } | {
127
+ claudeRevision?: string;
128
+ nextClaudeProcess?: boolean;
129
+ revision?: string;
130
+ nextCodexTurn?: boolean;
75
131
  changed: boolean;
76
- revision: string;
77
132
  checkedAt: number;
78
- newSessionRequired: boolean;
79
133
  skipped?: never;
80
134
  }>;
package/dist/manager.js CHANGED
@@ -2,7 +2,23 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { lstat, mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { readPromptPointer, setPromptPointer } from "./toml.js";
5
- export const FROZEN_CONTEXT_HEADER = "\n\n## Frozen agent context\n";
5
+ export const RUNTIMES = ["codex", "claude-cli"];
6
+ /** First heading of the agent context, the boundary after the shared policy prefix. */
7
+ export const MEMORY_REFERENCE_HEADER = "\n\n## Memory reference\n";
8
+ /**
9
+ * Accepted boundaries: the current first heading, then the 0.4 branch builds' `## Agent context`
10
+ * and the 0.3 `## Frozen agent context`, so their prompt files still refresh in place.
11
+ */
12
+ export const CONTEXT_BOUNDARY_HEADERS = [MEMORY_REFERENCE_HEADER, "\n\n## Agent context\n", "\n\n## Frozen agent context\n"];
13
+ function record(value) { return !!value && typeof value === "object" && !Array.isArray(value); }
14
+ /** Strict shape check for a stored Claude policy; throws on anything else. */
15
+ export function parseClaudePolicy(value) {
16
+ if (!record(value) || typeof value.text !== "string" || !value.text.trim() || typeof value.url !== "string" || !value.url ||
17
+ typeof value.revision !== "string" || !value.revision || typeof value.checkedAt !== "number" || !Number.isFinite(value.checkedAt)) {
18
+ throw new Error("Claude policy missing or invalid; run codex-prompt sync");
19
+ }
20
+ return { text: value.text, url: value.url, revision: value.revision, checkedAt: value.checkedAt };
21
+ }
6
22
  function paths(target) {
7
23
  const home = join(resolve(target.agentDir), "codex-home");
8
24
  return {
@@ -43,7 +59,7 @@ export async function readOptional(path) {
43
59
  throw new Error(`Refusing non-regular, linked, or shared file: ${path}`);
44
60
  return readFile(path, "utf8");
45
61
  }
46
- function parseEnrollment(source) {
62
+ export function parseEnrollment(source) {
47
63
  if (source === null)
48
64
  return null;
49
65
  let value;
@@ -53,12 +69,34 @@ function parseEnrollment(source) {
53
69
  catch {
54
70
  throw new Error("Invalid prompt enrollment state");
55
71
  }
56
- if (!value || typeof value !== "object" || !("schema" in value) || value.schema !== 1 ||
72
+ if (!value || typeof value !== "object" || !("schema" in value) || (value.schema !== 1 && value.schema !== 2) ||
57
73
  !("active" in value) || typeof value.active !== "boolean" || !("previousPointer" in value) ||
58
74
  (value.previousPointer !== null && typeof value.previousPointer !== "string")) {
59
75
  throw new Error("Invalid prompt enrollment state");
60
76
  }
61
- return { schema: 1, active: value.active, previousPointer: value.previousPointer };
77
+ // Schema 1 without runtimes is the pre-0.4 Codex enrollment.
78
+ if (value.schema === 1 && !("runtimes" in value))
79
+ return { active: value.active, previousPointer: value.previousPointer, runtimes: ["codex"] };
80
+ const runtimes = "runtimes" in value ? value.runtimes : undefined;
81
+ if (!Array.isArray(runtimes) || !runtimes.length || new Set(runtimes).size !== runtimes.length ||
82
+ runtimes.some(runtime => !RUNTIMES.includes(runtime)))
83
+ throw new Error("Invalid prompt enrollment state");
84
+ return { active: value.active, previousPointer: value.previousPointer, runtimes: sortRuntimes(runtimes) };
85
+ }
86
+ function sortRuntimes(runtimes) { return RUNTIMES.filter(runtime => runtimes.includes(runtime)); }
87
+ /**
88
+ * Schema 1 is the format 0.3.x reads (it checks only schema, active and previousPointer).
89
+ * Every state 0.3.x can safely act on uses it: Codex enrollments (with Claude too, 0.3.x keeps
90
+ * managing Codex and registers no Claude prompt hook, so Claude falls back upstream) and paused ones.
91
+ * Active Claude-only enrollment is schema 2, which 0.3.x refuses rather than mismanaging it.
92
+ * Codex-only enrollment omits runtimes: exactly the 0.3.x shape.
93
+ */
94
+ export function serializeEnrollment(enrollment) {
95
+ const runtimes = sortRuntimes(enrollment.runtimes);
96
+ const codexOnly = runtimes.length === 1 && runtimes[0] === "codex";
97
+ const value = { schema: enrollment.active && !runtimes.includes("codex") ? 2 : 1, active: enrollment.active,
98
+ previousPointer: enrollment.previousPointer, ...codexOnly ? {} : { runtimes } };
99
+ return `${JSON.stringify(value, null, 2)}\n`;
62
100
  }
63
101
  async function snapshot(target) {
64
102
  const files = paths(target);
@@ -66,20 +104,27 @@ async function snapshot(target) {
66
104
  const [config, prompt, state] = await Promise.all([
67
105
  readOptional(files.config), readOptional(files.prompt), readOptional(files.state),
68
106
  ]);
69
- return { files, config, prompt, state, pointer: readPromptPointer(config ?? ""), enrollment: parseEnrollment(state) };
107
+ const enrollment = parseEnrollment(state);
108
+ // Claude-only enrollment never parses or edits Codex configuration.
109
+ const pointer = () => readPromptPointer(config ?? "");
110
+ return { files, config, prompt, state, pointer, enrollment };
111
+ }
112
+ /** Disk-only enrollment for callers that select runtime components. */
113
+ export async function readEnrollment(agentDir) {
114
+ return (await snapshot({ agentDir, prompt: "" })).enrollment;
70
115
  }
71
116
  export function sha256(text) { return createHash("sha256").update(text).digest("hex"); }
72
- /** Disk state only: this cannot attest to instructions retained by a live Codex thread. */
117
+ /** Disk state only: this cannot attest to instructions retained by a live Codex thread or Claude process. */
73
118
  export async function promptStatus(target) {
74
119
  const s = await snapshot(target);
120
+ const codex = s.enrollment?.runtimes.includes("codex") ?? true;
75
121
  return {
76
122
  enrolled: s.enrollment?.active === true,
77
123
  restored: s.enrollment?.active === false,
124
+ runtimes: s.enrollment?.runtimes ?? [],
78
125
  configPath: s.files.config,
79
126
  promptPath: s.files.prompt,
80
- pointerMatches: s.pointer === s.files.prompt,
81
- promptMatches: s.prompt === target.prompt,
82
- expectedSha256: sha256(target.prompt),
127
+ pointerMatches: codex ? s.pointer() === s.files.prompt : null,
83
128
  actualSha256: s.prompt === null ? null : sha256(s.prompt),
84
129
  runtimeVerified: false,
85
130
  };
@@ -126,31 +171,45 @@ export async function withLock(target, operation) {
126
171
  await rmdir(files.lock);
127
172
  }
128
173
  }
174
+ export const ACTIVATION = {
175
+ codex: "Restart the managed app-server and use a new Codex session; existing threads may retain old instructions.",
176
+ "claude-cli": "No restart is needed once the Gateway has loaded this plugin version: the plugin builds the Claude CLI prompt on every turn, so the target agent's next Claude turn uses it. A plugin install or update needs a Gateway restart to load the plugin. The new prompt starts a new Claude CLI process that may resume the existing conversation, whose earlier history is not cleaned.",
177
+ };
129
178
  export async function syncPrompt(target, options = {}) {
130
179
  if (!target.prompt.trim())
131
180
  throw new Error("Refusing an empty base prompt");
181
+ const requested = sortRuntimes(options.runtimes ?? ["codex"]);
182
+ if (!requested.length)
183
+ throw new Error("Select at least one managed runtime");
132
184
  // Reject invalid state before creating even the lock directory.
133
185
  await snapshot(target);
134
186
  return withLock(target, async () => {
135
187
  const s = await snapshot(target);
136
188
  if (s.enrollment?.active === false && options.automatic)
137
189
  return { changed: false, restored: true };
138
- if (s.pointer !== null && s.pointer !== s.files.prompt && !options.adopt) {
190
+ const current = s.enrollment?.active ? s.enrollment : null;
191
+ // Sync adds components; removing one requires restore so its owned edits are reverted.
192
+ const runtimes = sortRuntimes([...current?.runtimes ?? [], ...requested]);
193
+ const codex = runtimes.includes("codex");
194
+ const pointer = codex ? s.pointer() : null;
195
+ const addingCodex = codex && !current?.runtimes.includes("codex");
196
+ if (codex && pointer !== null && pointer !== s.files.prompt && !options.adopt) {
139
197
  throw new Error("A different model_instructions_file is configured. Review it, then run openclaw codex-prompt sync --adopt to take ownership.");
140
198
  }
141
- if (!s.enrollment && (s.prompt !== null || s.pointer === s.files.prompt)) {
199
+ if (!s.enrollment && (s.prompt !== null || pointer === s.files.prompt)) {
142
200
  throw new Error("Managed prompt exists without enrollment state; recover the state before syncing");
143
201
  }
144
- const enrollment = s.enrollment?.active ? s.enrollment : {
145
- schema: 1, active: true, previousPointer: s.pointer,
202
+ const enrollment = {
203
+ active: true, runtimes,
204
+ previousPointer: addingCodex ? pointer : current?.previousPointer ?? null,
146
205
  };
147
- const nextConfig = setPromptPointer(s.config ?? "", s.files.prompt);
148
206
  // Save rollback information first; point Codex at the file only after it exists.
149
- const stateChanged = await replaceFile(s.files.state, s.state, `${JSON.stringify(enrollment, null, 2)}\n`);
207
+ const stateChanged = await replaceFile(s.files.state, s.state, serializeEnrollment(enrollment));
150
208
  const promptChanged = await replaceFile(s.files.prompt, s.prompt, target.prompt);
151
209
  const bundleChanged = target.bundle ? await replaceFile(s.files.bundle, await readOptional(s.files.bundle), `${JSON.stringify({ ...target.bundle, promptSha256: sha256(target.prompt) }, null, 2)}\n`) : false;
152
- const configChanged = await replaceFile(s.files.config, s.config, nextConfig);
153
- return { changed: stateChanged || promptChanged || configChanged || bundleChanged, promptChanged, configChanged, sha256: sha256(target.prompt), activation: "Restart the managed app-server and use a new Codex session; existing threads may retain old instructions." };
210
+ const configChanged = codex ? await replaceFile(s.files.config, s.config, setPromptPointer(s.config ?? "", s.files.prompt)) : false;
211
+ return { changed: stateChanged || promptChanged || configChanged || bundleChanged, promptChanged, configChanged, runtimes,
212
+ sha256: sha256(target.prompt), activation: runtimes.map(runtime => ACTIVATION[runtime]).join(" ") };
154
213
  });
155
214
  }
156
215
  export async function restorePrompt(target) {
@@ -161,48 +220,75 @@ export async function restorePrompt(target) {
161
220
  const s = await snapshot(target);
162
221
  if (!s.enrollment)
163
222
  throw new Error("Enrollment disappeared during restore");
164
- if (s.pointer !== s.files.prompt && s.pointer !== s.enrollment.previousPointer) {
223
+ const codex = s.enrollment.runtimes.includes("codex");
224
+ const pointer = codex ? s.pointer() : null;
225
+ if (codex && pointer !== s.files.prompt && pointer !== s.enrollment.previousPointer) {
165
226
  throw new Error("Prompt pointer was changed by another writer; refusing to restore over it");
166
227
  }
167
- const nextConfig = setPromptPointer(s.config ?? "", s.enrollment.previousPointer);
168
228
  // A restart must not re-enroll while a restore is in progress.
169
- await replaceFile(s.files.state, s.state, `${JSON.stringify({ ...s.enrollment, active: false }, null, 2)}\n`);
170
- const changed = await replaceFile(s.files.config, s.config, nextConfig);
171
- return { changed, restored: true, retainedPromptPath: s.files.prompt };
229
+ await replaceFile(s.files.state, s.state, serializeEnrollment({ ...s.enrollment, active: false }));
230
+ const changed = codex ? await replaceFile(s.files.config, s.config, setPromptPointer(s.config ?? "", s.enrollment.previousPointer)) : false;
231
+ return { changed, restored: true, runtimes: s.enrollment.runtimes, retainedPromptPath: s.files.prompt };
172
232
  });
173
233
  }
174
- /** Replace only the shared prefix; never reread workspace documents or skills. */
175
- export async function refreshSharedPrompt(agentDir, fetchBase, now = Date.now()) {
234
+ /**
235
+ * Daily/explicit refresh of each enrolled runtime's fleet policy; it never rereads the agent
236
+ * context. Every enrolled runtime is fetched before anything is written, so one failure leaves
237
+ * all local state untouched. Then, in one locked write:
238
+ * - Codex: only the policy prefix of the prompt file is replaced (the file keeps its inode when
239
+ * unchanged). Everything after `basePromptLength` is kept byte-for-byte, so a snapshot from an
240
+ * older sync keeps its frozen skills catalog tail until the next sync rewrites the file;
241
+ * - Claude: only `claudePolicy` in the bundle is replaced; the prompt file is not touched for it.
242
+ */
243
+ export async function refreshSharedPrompt(agentDir, fetchers, now = Date.now()) {
176
244
  const target = { agentDir, prompt: "" };
177
245
  return withLock(target, async () => {
178
246
  const s = await snapshot(target);
179
247
  if (!s.enrollment?.active)
180
248
  return { changed: false, skipped: true };
181
- if (s.pointer !== s.files.prompt || s.prompt === null)
249
+ const codex = s.enrollment.runtimes.includes("codex");
250
+ const claude = s.enrollment.runtimes.includes("claude-cli");
251
+ if ((codex && s.pointer() !== s.files.prompt) || s.prompt === null)
182
252
  throw new Error("Managed prompt pointer missing or changed; refusing refresh");
183
253
  const previousBundle = await readOptional(s.files.bundle);
184
254
  const bundle = JSON.parse(previousBundle ?? "null");
185
- if (!bundle || typeof bundle !== "object" || !("schema" in bundle) || bundle.schema !== 1 ||
186
- !("promptSha256" in bundle) || bundle.promptSha256 !== sha256(s.prompt) ||
187
- !("policy" in bundle) || typeof bundle.policy !== "string" ||
188
- !("remotePrompt" in bundle) || !bundle.remotePrompt) {
255
+ if (!record(bundle) || bundle.schema !== 1 || bundle.promptSha256 !== sha256(s.prompt) || typeof bundle.policy !== "string" ||
256
+ (codex && !bundle.remotePrompt)) {
189
257
  throw new Error("Valid enrolled remote snapshot required; run codex-prompt sync");
190
258
  }
191
- // Legacy snapshots can migrate only when the compiler boundary is unambiguous.
192
- const boundary = "basePromptLength" in bundle ? bundle.basePromptLength : s.prompt.indexOf(FROZEN_CONTEXT_HEADER);
193
- if (typeof boundary !== "number" || !Number.isInteger(boundary) || boundary <= 0 ||
194
- !s.prompt.slice(boundary).startsWith(FROZEN_CONTEXT_HEADER) ||
195
- (!("basePromptLength" in bundle) && boundary !== s.prompt.lastIndexOf(FROZEN_CONTEXT_HEADER))) {
259
+ let previousClaude;
260
+ if (claude) {
261
+ try {
262
+ previousClaude = parseClaudePolicy(bundle.claudePolicy);
263
+ }
264
+ catch {
265
+ throw new Error("Valid enrolled remote snapshot required; run codex-prompt sync");
266
+ }
267
+ if (typeof bundle.agentContext !== "string" || !bundle.agentContext.trim())
268
+ throw new Error("Valid enrolled remote snapshot required; run codex-prompt sync");
269
+ }
270
+ // Every remote snapshot records its prefix length (0.1.0 onwards); the agent context after it
271
+ // starts with one of the accepted boundary headings (current, 0.4 branch or 0.3).
272
+ const boundary = bundle.basePromptLength;
273
+ if (codex && (typeof boundary !== "number" || !Number.isInteger(boundary) || boundary <= 0 ||
274
+ !CONTEXT_BOUNDARY_HEADERS.some(header => s.prompt.slice(boundary).startsWith(header)))) {
196
275
  throw new Error("Frozen context boundary is ambiguous; run codex-prompt sync");
197
276
  }
198
- const remote = await fetchBase();
199
- if (!remote.prompt.trim() || remote.source.revision !== sha256(remote.prompt))
277
+ const [codexRemote, claudeRemote] = await Promise.all([codex ? fetchers.codex?.() : undefined, claude ? fetchers.claude?.() : undefined]);
278
+ if ((codex && !codexRemote) || (claude && !claudeRemote))
200
279
  throw new Error("Invalid shared prompt revision");
280
+ for (const remote of [codexRemote, claudeRemote]) {
281
+ if (remote && (!remote.prompt.trim() || remote.source.revision !== sha256(remote.prompt)))
282
+ throw new Error("Invalid shared prompt revision");
283
+ }
201
284
  if (await readOptional(s.files.config) !== s.config || await readOptional(s.files.state) !== s.state)
202
285
  throw new Error("Enrollment or configuration changed during refresh");
203
- const prompt = remote.prompt.trim() + s.prompt.slice(boundary);
204
- const nextBundle = `${JSON.stringify({ ...bundle, basePromptLength: remote.prompt.trim().length,
205
- remotePrompt: { ...remote.source, checkedAt: now }, promptSha256: sha256(prompt) }, null, 2)}\n`;
286
+ const prompt = codexRemote ? codexRemote.prompt.trim() + s.prompt.slice(boundary) : s.prompt;
287
+ const claudePolicy = claudeRemote ? { text: claudeRemote.prompt.trim(), url: claudeRemote.source.url,
288
+ revision: claudeRemote.source.revision, checkedAt: now } : undefined;
289
+ const nextBundle = `${JSON.stringify({ ...bundle,
290
+ ...codexRemote ? { basePromptLength: codexRemote.prompt.trim().length, remotePrompt: { ...codexRemote.source, checkedAt: now } } : {},
291
+ ...claudePolicy ? { claudePolicy } : {}, promptSha256: sha256(prompt) }, null, 2)}\n`;
206
292
  const changed = await replaceFile(s.files.prompt, s.prompt, prompt);
207
293
  try {
208
294
  await replaceFile(s.files.bundle, previousBundle, nextBundle);
@@ -213,6 +299,11 @@ export async function refreshSharedPrompt(agentDir, fetchBase, now = Date.now())
213
299
  await replaceFile(s.files.prompt, prompt, s.prompt);
214
300
  throw error;
215
301
  }
216
- return { changed, revision: remote.source.revision, checkedAt: now, newSessionRequired: changed };
302
+ const claudeChanged = claudePolicy !== undefined && claudePolicy.text !== previousClaude?.text;
303
+ // Codex's reviewed bridge resends the base file as each thread's base instructions, so a change
304
+ // re-syncs existing threads on their next turn; Claude's prompt hook reads the policy every turn.
305
+ return { changed: changed || claudeChanged, checkedAt: now,
306
+ ...codexRemote ? { revision: codexRemote.source.revision, nextCodexTurn: changed } : {},
307
+ ...claudeRemote ? { claudeRevision: claudeRemote.source.revision, nextClaudeProcess: claudeChanged } : {} };
217
308
  });
218
309
  }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The patched-file-set lifecycle both adapters share: receipt ownership, prepare, install,
3
+ * status and restore. Each adapter keeps its own discovery, fingerprints, patch rendering,
4
+ * receipt format and install identity (Codex package or OpenClaw root).
5
+ */
6
+ /** A receipt's file entry; the field names are the on-disk receipt format. */
7
+ export type PatchedFile = {
8
+ path: string;
9
+ originalSha256: string;
10
+ patchedSha256: string;
11
+ previousPatchedSha256?: string;
12
+ };
13
+ /**
14
+ * What a receipt's files show on disk. Only "patched" (any recorded file still holding this
15
+ * adapter's bytes, including a partial restore) is ownership. "restored" (every file original)
16
+ * and "superseded" (every non-original file gone, or the recorded install version replaced)
17
+ * leave only rollback evidence. "changed" is anything else.
18
+ */
19
+ export type Ownership = "none" | "patched" | "restored" | "superseded" | "changed";
20
+ export type PatchedFilesState = "absent" | "patched" | "partial" | "original" | "missing" | "changed";
21
+ /** A parsed receipt, reduced to what the shared lifecycle needs. */
22
+ export type RecordedFiles = {
23
+ /** Install identity recorded at patch time: the Codex package or the OpenClaw root. */
24
+ root: string;
25
+ /** Install version recorded at patch time; receipts before 0.4 may lack it. */
26
+ version?: string;
27
+ files: PatchedFile[];
28
+ /** Where this receipt kept a file's original bytes. */
29
+ backupPath(file: PatchedFile): string;
30
+ };
31
+ export type PatchedFileSet = {
32
+ receiptPath: string;
33
+ parseReceipt(source: string): RecordedFiles;
34
+ /** The version installed at a recorded root now; null when it cannot be read. */
35
+ installedVersion(root: string): Promise<string | null>;
36
+ /** Where a new install keeps a file's original bytes. */
37
+ backupPath(path: string): string;
38
+ messages: {
39
+ installChanged: string;
40
+ changed: string;
41
+ missing: string;
42
+ prepareBackupInvalid: string;
43
+ moved: string;
44
+ foreignBackup: string;
45
+ concurrent: string;
46
+ foreignEdit: string;
47
+ backupInvalid: string;
48
+ };
49
+ };
50
+ export declare function patchedFilesOwnership(set: PatchedFileSet): Promise<Ownership>;
51
+ /** The previous receipt, its ownership, and the root a new install may default to. */
52
+ export declare function openPatchedFiles(set: PatchedFileSet): Promise<{
53
+ previousReceipt: string | null;
54
+ recorded: RecordedFiles | null;
55
+ ownership: Ownership;
56
+ }>;
57
+ export type PreparedFile = {
58
+ path: string;
59
+ current: string;
60
+ original: string;
61
+ patched: string;
62
+ };
63
+ /**
64
+ * Start a patch at `root`. A restored or superseded receipt counts as cleared: any root is
65
+ * allowed and its backups may be replaced. Otherwise every recorded file must still hold this
66
+ * adapter's bytes (an interrupted re-patch is recognized by previousPatchedSha256) unless it
67
+ * is missing or the recorded version was replaced; the adapter then reads originals through
68
+ * `read` (backups for owned files) and hands its patched sources to `finish`.
69
+ */
70
+ export declare function beginPatch(set: PatchedFileSet, opened: Awaited<ReturnType<typeof openPatchedFiles>>, root: string): Promise<{
71
+ read: (path: string) => Promise<string>;
72
+ finish: (patched: Map<string, string>) => {
73
+ files: PreparedFile[];
74
+ entries: PatchedFile[];
75
+ previousReceipt: string | null;
76
+ staleBackups: Set<string>;
77
+ };
78
+ }>;
79
+ export type PatchPlan = {
80
+ files: PreparedFile[];
81
+ previousReceipt: string | null;
82
+ staleBackups: Set<string>;
83
+ };
84
+ /** Validates every target before any change; keeps exact original backups, then the receipt, then the files. */
85
+ export declare function installPatch(set: PatchedFileSet, plan: PatchPlan, receipt: string): Promise<{
86
+ adapterChanged: boolean;
87
+ restartRequired: boolean;
88
+ }>;
89
+ /** Disk state of every recorded file; distinguishes missing files (an update) from foreign edits. */
90
+ export declare function patchedFilesStatus(set: PatchedFileSet): Promise<{
91
+ recorded: RecordedFiles;
92
+ state: "changed" | "patched" | "partial" | "original" | "missing";
93
+ installed: boolean;
94
+ paths: string[];
95
+ } | null>;
96
+ /**
97
+ * Validates the whole restore before any write, and plans nothing unless this adapter's bytes
98
+ * are installed. Files holding them are restored; missing files are superseded; foreign bytes
99
+ * are superseded only after the recorded version was replaced, otherwise refused. Backups are
100
+ * checked only for files that will be written.
101
+ */
102
+ export type RestorePlan = {
103
+ ownership: Ownership;
104
+ files: {
105
+ path: string;
106
+ current: string;
107
+ original: string;
108
+ }[];
109
+ superseded: string[];
110
+ };
111
+ export declare function planPatchedRestore(set: PatchedFileSet): Promise<RestorePlan>;
112
+ export declare function applyPatchedRestore(plan: RestorePlan): Promise<{
113
+ ownership: Ownership;
114
+ files: string[];
115
+ superseded: string[];
116
+ restartRequired: boolean;
117
+ }>;