Skip to content

Commit 53335d0

Browse files
committed
feat(bot): preserve original text in bounded protected blocks
1 parent 1293876 commit 53335d0

8 files changed

Lines changed: 155 additions & 22 deletions

File tree

‎apps/bot/README.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,3 +451,33 @@ Exit code zero means the snapshot was read successfully, not that the mission
451451
finished or it is safe to retry. The summary can become stale immediately. Keep
452452
checkpoint/lock recovery and new-call authorization separate; inspection never
453453
changes or bypasses either gate.
454+
455+
456+
### Preserve other text blocks while editing one target
457+
458+
`run --planning-path '[1]' --protect-text '[[2],[3,0]]'` adds opt-in, identity-bound
459+
text preservation to the existing bounded writer. Provide the usual explicit URL,
460+
document and mission options. API callers use `protectedText: [[2], [3, 0]]`.
461+
The 1–16 protected canonical model paths must differ from the editing target. Each
462+
must resolve to a stored plain-text block of at most 8192 UTF-16 units. Empty text
463+
is valid. Inline objects and structured spans are not silently flattened.
464+
465+
The first settled capture saves original text, block identity, node type, placement,
466+
epoch and schema binding in the private mission. Later checks and profile resume
467+
compare against that original, never adopt a changed peer value or restore the old
468+
text. Missing evidence, peer text edits, replacement, movement or schema changes
469+
stop for inspection. The planner still receives only the bounded editing target,
470+
not these additional captured texts. Private mission retention includes the original
471+
protected text; treat the mission file accordingly.
472+
473+
This protects exact text only: mark changes and equivalent plain-run segmentation
474+
are permitted, and unrelated attributes are not checked. Use `--protect-attributes`
475+
separately for supported scalar attributes. Both options can coexist. Checks occur
476+
before planning and at authoritative completion; normal conditional edit fences
477+
still apply. This is not continuous monitoring, a server permission boundary,
478+
general structural preservation or a guarantee that people cannot edit the text.
479+
Never overwrite a person's changed content to make a preservation check pass.
480+
481+
Recovery alone validates saved capture structure; comparison with the current
482+
document occurs before resumed planning and at completion, not merely by inspecting
483+
or reconciling a mission.

‎apps/bot/src/main.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ const PROPOSAL_CREATE_OPTIONS = Object.freeze(["--input"]);
2222
const PROPOSAL_DECIDE_OPTIONS = Object.freeze(["--id", "--input"]);
2323
const PROPOSAL_INSPECT_OPTIONS = Object.freeze(["--id"]);
2424
const WATCH_OPTIONS = Object.freeze(["--url", "--doc", "--mission", "--state-dir", "--model", "--interval", "--max-runs", "--checkpoint"]);
25-
const RUN_OPTIONS = Object.freeze(["--url", "--doc", "--actor", "--name", "--color", "--mission", "--state-dir", "--max-steps", "--ephemeral", "--model", "--character", "--personality", "--role", "--profile", "--brief", "--planning-path", "--protect-attributes"]);
25+
const RUN_OPTIONS = Object.freeze(["--url", "--doc", "--actor", "--name", "--color", "--mission", "--state-dir", "--max-steps", "--ephemeral", "--model", "--character", "--personality", "--role", "--profile", "--brief", "--planning-path", "--protect-attributes", "--protect-text"]);
2626
const PROFILE_CREATE_OPTIONS = Object.freeze(["--id", "--name", "--character", "--personality", "--role", "--color", "--state-dir"]);
2727
const RESUME_OPTIONS = Object.freeze(["--id","--state-dir","--model"]);
2828
const ID_STATE_OPTIONS = Object.freeze(["--id", "--state-dir"]);
@@ -136,7 +136,7 @@ async function main() {
136136
configured=await loadProfile(stateDir,profileId);actualUrl=profileUrl(url);
137137
}
138138
const actor = configured ? profileActor(configured,actualUrl,document) : options.get("--actor") ?? `bot-${randomUUID()}`;
139-
const result = await runMission({url:actualUrl, document, mission, brief, protectedAttributes:options.has("--protect-attributes")?JSON.parse(options.get("--protect-attributes")!):undefined, planningPath:options.has("--planning-path")?JSON.parse(options.get("--planning-path")!):undefined, actor, stateDir, profileId:configured?.id,
139+
const result = await runMission({url:actualUrl, document, mission, brief, protectedText:options.has("--protect-text")?JSON.parse(options.get("--protect-text")!):undefined, protectedAttributes:options.has("--protect-attributes")?JSON.parse(options.get("--protect-attributes")!):undefined, planningPath:options.has("--planning-path")?JSON.parse(options.get("--planning-path")!):undefined, actor, stateDir, profileId:configured?.id,
140140
ephemeral: options.get("--ephemeral") === "true", maxSteps: Number(options.get("--max-steps") ?? "4"),
141141
name: configured?.name ?? options.get("--name"), color: configured?.color ?? options.get("--color"), character: (configured?.character ?? options.get("--character")) as "cat" | "fox" | "owl" | "robot" | undefined,
142142
personality: (configured?.personality ?? options.get("--personality")) as "curious" | "careful" | "creative" | "concise" | undefined,

‎apps/bot/src/runner.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import {parseTextProtection,checkTextPreservation,assertTextPreservationState} from './text-preservation.ts';
2+
import type {TextPreservationCapture} from './text-preservation.ts';
13
import {parseProtection,checkPreservation,assertPreservationState} from "./preservation.ts";
24
import type {ProtectedAttribute,PreservationCapture} from "./preservation.ts";
35
import {randomUUID, createHash} from "node:crypto";
@@ -45,8 +47,8 @@ export type Plan = {action: "insert" | "delete" | "edit" | "inspect" | "finish"
4547
export type Role = "writer" | "reviewer" | "organizer";
4648
export type Personality = "curious" | "careful" | "creative" | "concise";
4749
export type Planner = (input: {mission: string; brief?: Brief; personality: Personality; role: Role; schema: unknown; document: unknown; revision: Revision; previous: string[]; lastConfirmed: {edits: EditOp[]; revision: Revision} | null; inspection: {anchor: number[]; focus: number[]} | null}) => Promise<Plan>;
48-
export type BotOptions = {protectedAttributes?:ProtectedAttribute[]; planningPath?: number[]; brief?: Brief; url: string; document: string; actor: string; mission: string; stateDir: string; maxSteps?: number; ephemeral?: boolean; name?: string; color?: string; character?: BotCharacter; personality?: Personality; role?: Role; profileId?: string};
49-
export type Mission = {protectedAttributes?:ProtectedAttribute[]; preservation?:PreservationCapture[]; planningPath?: number[]; planningBinding?: PlanningBinding; brief?: Brief; completion?: "verified" | "model_reported"; verification?: VerificationReport | {version: 1; status: "not_checked"; checkedRevision: Revision; requirements: []; reason: string}; id: string; profileId?: string; recoveryProtocol?: 1; resume?: {version:1; maxSteps:number; used:number; ready:boolean}; url: string; document: string; actor: string; mission: string; name: string; color: string; character: BotCharacter; personality: Personality; role: Role; expression: BotExpression; status: "queued" | "running" | "completed" | "needs_attention"; createdAt: string; updatedAt: string; steps: string[]; history: Array<{kind: "confirmed" | "stale"; base: Revision; plan: Plan; revision?: Revision}>; pending: {revision: Revision; plan: Plan; stepId?: string} | null; result?: string; error?: string};
50+
export type BotOptions = {protectedText?:number[][]; protectedAttributes?:ProtectedAttribute[]; planningPath?: number[]; brief?: Brief; url: string; document: string; actor: string; mission: string; stateDir: string; maxSteps?: number; ephemeral?: boolean; name?: string; color?: string; character?: BotCharacter; personality?: Personality; role?: Role; profileId?: string};
51+
export type Mission = {protectedText?:number[][]; textPreservation?:TextPreservationCapture[]; protectedAttributes?:ProtectedAttribute[]; preservation?:PreservationCapture[]; planningPath?: number[]; planningBinding?: PlanningBinding; brief?: Brief; completion?: "verified" | "model_reported"; verification?: VerificationReport | {version: 1; status: "not_checked"; checkedRevision: Revision; requirements: []; reason: string}; id: string; profileId?: string; recoveryProtocol?: 1; resume?: {version:1; maxSteps:number; used:number; ready:boolean}; url: string; document: string; actor: string; mission: string; name: string; color: string; character: BotCharacter; personality: Personality; role: Role; expression: BotExpression; status: "queued" | "running" | "completed" | "needs_attention"; createdAt: string; updatedAt: string; steps: string[]; history: Array<{kind: "confirmed" | "stale"; base: Revision; plan: Plan; revision?: Revision}>; pending: {revision: Revision; plan: Plan; stepId?: string} | null; result?: string; error?: string};
5052

5153
const mcpFile = fileURLToPath(new URL("../../mcp/src/main.ts", import.meta.url));
5254
const env = Object.fromEntries(Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined));
@@ -161,15 +163,15 @@ function planEdits(plan:Plan):EditOp[] {
161163
/** Reconcile a claimed mission without replaying or replanning any edit. */
162164
export async function recoverMission(stateDir:string,id:string):Promise<Mission> {
163165
const initial=await loadMission(stateDir,id);
164-
assertPersistedPlanningState(initial); assertPreservationState(initial);
166+
assertPersistedPlanningState(initial); assertPreservationState(initial);assertTextPreservationState(initial);
165167
if(initial.brief !== undefined)parseBrief(initial.brief);
166168
if(initial.recoveryProtocol!==1 || !initial.profileId) throw Error("Legacy mission requires manual recovery inspection");
167169
const profile=await loadProfile(stateDir,initial.profileId),url=profileUrl(initial.url);
168170
if(url!==initial.url || profileActor(profile,url,initial.document)!==initial.actor)throw Error("Mission identity does not match its profile");
169171
const release=await claimProfile(stateDir,initial.actor);
170172
try {
171173
const state=await loadMission(stateDir,id);
172-
assertPersistedPlanningState(state); assertPreservationState(state);
174+
assertPersistedPlanningState(state); assertPreservationState(state);assertTextPreservationState(state);
173175
if(state.brief !== undefined)parseBrief(state.brief);
174176
if(state.recoveryProtocol!==1 || state.profileId!==profile.id || state.actor!==initial.actor || state.url!==url || state.document!==initial.document)throw Error("Mission identity changed");
175177
if(state.resume?.ready && !state.pending && state.status==="queued")return state;
@@ -228,14 +230,15 @@ export async function resumeMission(stateDir:string,id:string,planner:Planner):P
228230
if(state.actor!==recovered.actor||state.profileId!==profile.id||state.url!==recovered.url||state.document!==recovered.document||profileActor(profile,state.url,state.document)!==state.actor||!state.resume?.ready||state.status!=="queued"||state.pending)throw Error("Mission changed before continuation");
229231
const others=await listMissions(stateDir);
230232
if(others.some(m=>m.id!==id&&m.profileId===state.profileId&&m.document===state.document&&m.url===state.url&&(m.pending||m.status==="running"||m.status==="queued")))throw Error("Another task requires recovery inspection");
231-
return await runMissionClaimed({url:state.url,document:state.document,actor:state.actor,mission:state.mission,brief:state.brief,planningPath:state.planningPath,protectedAttributes:state.protectedAttributes,stateDir,profileId:state.profileId,maxSteps:state.resume.maxSteps,name:state.name,color:state.color,character:state.character,personality:state.personality,role:state.role},planner,state);
233+
return await runMissionClaimed({url:state.url,document:state.document,actor:state.actor,mission:state.mission,brief:state.brief,planningPath:state.planningPath,protectedAttributes:state.protectedAttributes,protectedText:state.protectedText,stateDir,profileId:state.profileId,maxSteps:state.resume.maxSteps,name:state.name,color:state.color,character:state.character,personality:state.personality,role:state.role},planner,state);
232234
} finally {await release();}
233235
}
234236

235237
/** One bounded, user-requested mission; uncertain steps are retained for inspection, never replayed automatically. */
236238
export async function runMission(options: BotOptions, planner: Planner): Promise<Mission> {
237239
// Reject invalid requirements before creating state, claiming a profile, or starting a session.
238240
options = {...options, ...(options.planningPath !== undefined ? {planningPath:parsePlanningPath(options.planningPath)} : {}), ...(options.brief !== undefined ? {brief: parseBrief(options.brief)} : {})};
241+
if(options.protectedText!==undefined)options={...options,protectedText:parseTextProtection(options.protectedText,options.planningPath)};
239242
if(options.protectedAttributes!==undefined)options={...options,protectedAttributes:parseProtection(options.protectedAttributes,options.planningPath)};
240243
if (!options.profileId) return runMissionClaimed(options, planner);
241244
if (options.ephemeral) throw new Error("A profile requires durable recovery");
@@ -253,8 +256,9 @@ export async function runMission(options: BotOptions, planner: Planner): Promise
253256
async function runMissionClaimed(options: BotOptions, planner: Planner, resumed?: Mission): Promise<Mission> {
254257
const {url, document, actor, mission} = options;
255258
const brief = resumed?.brief !== undefined ? parseBrief(resumed.brief) : options.brief !== undefined ? parseBrief(options.brief) : undefined;
256-
if(resumed){assertPersistedPlanningState(resumed);assertPreservationState(resumed);}
259+
if(resumed){assertPersistedPlanningState(resumed);assertPreservationState(resumed);assertTextPreservationState(resumed);}
257260
const planningPath = resumed?.planningPath !== undefined ? parsePlanningPath(resumed.planningPath) : options.planningPath !== undefined ? parsePlanningPath(options.planningPath) : undefined;
261+
const protectedText=resumed?.protectedText??options.protectedText;
258262
const protectedAttributes=resumed?.protectedAttributes??options.protectedAttributes;
259263
validateId(document, "document ID"); validateId(actor, "actor ID");
260264
const parsed = new URL(url); if (!SERVER_URL_PROTOCOLS.includes(parsed.protocol) || parsed.username || parsed.password) throw new Error("Invalid server URL");
@@ -271,7 +275,7 @@ async function runMissionClaimed(options: BotOptions, planner: Planner, resumed?
271275
if (!/^#[0-9a-f]{6}$/i.test(color) || !name.trim() || name.length > 80) throw new Error("Invalid bot name or color");
272276
const directory = join(resolve(options.stateDir), "missions"); await mkdir(directory, {recursive: true, mode: 0o700});
273277
const id = resumed?.id ?? randomUUID(), path = join(directory, `${id}.json`), now = new Date().toISOString();
274-
const state: Mission = resumed ?? {id, ...(protectedAttributes?{protectedAttributes:structuredClone(protectedAttributes)}:{}), ...(planningPath ? {planningPath:[...planningPath]} : {}), ...(brief ? {brief} : {}), ...(options.profileId ? {profileId: options.profileId,recoveryProtocol:1 as const,resume:{version:1 as const,maxSteps,used:0,ready:false}} : {}), url, document, actor, mission, name, color, character, personality, role, expression: "thinking", status: "queued", createdAt: now, updatedAt: now, steps: [], history: [], pending: null};
278+
const state: Mission = resumed ?? {id, ...(protectedText?{protectedText:structuredClone(protectedText)}:{}), ...(protectedAttributes?{protectedAttributes:structuredClone(protectedAttributes)}:{}), ...(planningPath ? {planningPath:[...planningPath]} : {}), ...(brief ? {brief} : {}), ...(options.profileId ? {profileId: options.profileId,recoveryProtocol:1 as const,resume:{version:1 as const,maxSteps,used:0,ready:false}} : {}), url, document, actor, mission, name, color, character, personality, role, expression: "thinking", status: "queued", createdAt: now, updatedAt: now, steps: [], history: [], pending: null};
275279
const persist = async () => {state.updatedAt = new Date().toISOString(); await save(path, state);};
276280
await persist();
277281
let client: Client | null = null;
@@ -323,6 +327,7 @@ async function runMissionClaimed(options: BotOptions, planner: Planner, resumed?
323327
planningDocument=context.document;
324328
}
325329
if(protectedAttributes){state.preservation=await checkPreservation((name,args)=>callTool(client!,name,args),protectedAttributes,view.revision,server.schema as Schema,state.preservation);await persist();}
330+
if(protectedText){state.textPreservation=await checkTextPreservation((name,args)=>callTool(client!,name,args),protectedText,view.revision,server.schema as Schema,state.textPreservation);await persist();}
326331
const plan = await planner({mission, ...(brief ? {brief: structuredClone(brief)} : {}), personality, role, schema: server.schema, document: planningDocument, revision: view.revision, previous: [...state.steps], lastConfirmed, inspection: inspection ? {anchor: inspection.anchor, focus: inspection.focus} : null});
327332
checkPlan(plan);
328333
if (role === "reviewer" && MUTATING_PLANNER_ACTIONS.includes(plan.action)) throw new Error("Reviewer role cannot edit the document");
@@ -341,12 +346,13 @@ async function runMissionClaimed(options: BotOptions, planner: Planner, resumed?
341346
if (!latest.revision || !latest.sessionOnline || latest.pending || latest.conditionalPending || latest.recoveryRequired) throw new Error("Session is not settled; inspect recovery before finishing");
342347
// A settled MCP read is a local replica. Fence structured verification against
343348
// the server sequence so delayed stream delivery cannot prove stale content.
344-
const authority = (brief||protectedAttributes) ? await new NodeHttpTransport(document, actor, url).getRecoveryState() : latest.revision;
349+
const authority = (brief||protectedAttributes||protectedText) ? await new NodeHttpTransport(document, actor, url).getRecoveryState() : latest.revision;
345350
if (JSON.stringify(latest.revision) !== JSON.stringify(view.revision) ||
346351
latest.revision.epoch !== authority.epoch || latest.revision.serverSeq !== authority.serverSeq || latest.revision.schemaVersion !== authority.schemaVersion) {
347352
state.steps.push("Document changed while planning; read again before finishing."); await persist(); continue;
348353
}
349354
if(protectedAttributes)await checkPreservation((name,args)=>callTool(client!,name,args),protectedAttributes,latest.revision,server.schema as Schema,state.preservation);
355+
if(protectedText)await checkTextPreservation((name,args)=>callTool(client!,name,args),protectedText,latest.revision,server.schema as Schema,state.textPreservation);
350356
if (brief) {
351357
state.verification = verifyBrief(brief, latest.document, server.schema as Schema, latest.revision);
352358
if (state.verification.status !== "passed") {

0 commit comments

Comments
 (0)