@howaboua/pi-shepherdr 0.2.12 → 0.2.13

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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.13
4
+
5
+ - Added Remote notes and history to existing-agent attachment, including mixed Local, Tree and Remote storage.
6
+
3
7
  ## 0.2.12
4
8
 
5
9
  - Manage orchestration, board defaults and SSH connections in `/herdr`, and attach existing agents without replacing their context.
package/README.md CHANGED
@@ -99,17 +99,19 @@ await tools.agents({ action: "attach", target: "<target from find>", context: tr
99
99
 
100
100
  Supply both booleans and enable at least one. `context` shares notes and history through aliases without changing either session's original context identity or moving its notes. `contextAgent` addresses the target from the controller; `controllerContextAgent` addresses the controller from the target. Use these paths as `history`'s `agent_name` or as `<agent>/notes/<path>` for notes. Each agent's relative note paths remain its own. The target receives its controller alias without starting a turn.
101
101
 
102
- Context attachment requires updated Codex Conversion on both agents with Local or Tree storage. Attached context owners must keep Local or Tree storage. Switching to Remote is rejected instead of redirecting alias operations to a different store. Remote context attachment is unsupported and fails explicitly. This differs from Remote sharing for newly spawned agents. The explicit `context: true` choice does not depend on the controller's spawn-sharing setting.
102
+ Context attachment requires updated Codex Conversion with Local, Tree or Remote storage. Each owner keeps its original context identity and storage, including when the two agents use different stores. Remote access uses the reader's active Codex transport and requires the original account and backend, regardless of provider name. The explicit `context: true` choice does not depend on the controller's spawn-sharing setting. Use Code or Notebook with ordinary query and text for mixed-storage search and writes. Direct sensitive calls cannot cross between encrypted Remote arguments and ordinary Local or Tree arguments. If attachment changes context access during an exec cell, start a new cell before using notes or history.
103
+
104
+ An account mismatch rejects context sharing. Each agent keeps its own notes and history. If the account changes after attachment, pinned Remote notes become unavailable, including native Remote notes. Notes do not move to a new account or another store. Use messages to exchange the context the other agent needs.
103
105
 
104
106
  `board: true` joins the controller's enabled board and returns `boardAgent` for subscriptions and notifications. The target's previous board archive stays untouched. If the folders differ, that archive remains in its original folder rather than becoming part of the controller's archive. Board-only attachment works without Codex Conversion and with Remote context storage.
105
107
 
106
108
  The target must be idle and both Pi sessions must be saved. Existing shared-context members and controllers with context children cannot be context targets. Existing board members and roots with board children cannot switch boards. A target supports one controller and one fixed set of attachment choices. Attachment starts no task or watch; `assign` and `send` never attach implicitly.
107
109
 
108
- Attachments survive resume, not forks. Live access needs the owning Pi processes and machine connections. After an interrupted attachment, resume the original sessions and retry the same target and choices. The target may already have joined even when the controller reports failure; retries reuse the original aliases and membership rather than creating duplicates.
110
+ Attachments survive resume, not forks. Local and Tree live access needs the owning Pi processes and machine connections. Remote access uses authenticated backend references rather than the owner's running process. After an interrupted attachment, resume the original sessions and retry the same target and choices. The target may already have joined even when the controller reports failure; retries reuse the original aliases and membership rather than creating duplicates.
109
111
 
110
- To detach, call `agents` with `action: "detach"`, the same target, and both booleans. Enable each membership you want to leave. Context detach saves both agents' latest counterpart notes under their existing aliases as read-only checkpoints. Native notes and history keep their original identities. Board detach restores the target's previous board and stops its shared-board notifications without deleting either archive. Board members with children cannot detach. Reattachment is unsupported.
112
+ To detach, call `agents` with `action: "detach"`, the same target, and both booleans. Enable each membership you want to leave. Context detach retains counterpart notes under the existing aliases read-only. Local and Tree notes use captured checkpoints. Remote notes retain an authenticated reference to the original owner's saved backend notes, not a frozen plaintext snapshot. Counterpart history and writes stop at detach. Native notes and history keep their original identities. Board detach restores the target's previous board and stops its shared-board notifications without deleting either archive. Board members with children cannot detach. Reattachment is unsupported.
111
113
 
112
- If an attached owner closes or dies, notes reads first use its latest saved Local or Tree checkpoints when the source machine and session file remain reachable. This needs no running owner process and never writes to its session file. If the source is unavailable, reads return the timestamped snapshot captured at attachment, explicitly marked stale with the access failure. No latest-checkpoint guarantee is possible for a disconnected source machine or unsaved notes. Counterpart history still requires the live attachment. Explicit detach refreshes notes before severing access; an incomplete detach fails with a retry instruction rather than claiming success.
114
+ If an attached owner closes or dies, Local and Tree notes reads first use its latest saved checkpoints when the source machine and session file remain reachable. This needs no running owner process and never writes to its session file. If the source is unavailable, reads return the timestamped snapshot captured at attachment, explicitly marked stale with the access failure. No latest-checkpoint guarantee is possible for a disconnected source machine or unsaved notes. Local and Tree counterpart history still requires its live owner. Remote notes and history remain reachable through the backend with the original account and backend. Backend failures stay visible without a local fallback. An incomplete detach fails with a retry instruction rather than claiming success.
113
115
 
114
116
  ## Message board
115
117
 
@@ -155,7 +157,7 @@ Pi creates each worker session normally. The worker records its shared identity
155
157
 
156
158
  Remote sharing requires Remote storage and the same Codex account on both ends. Local and Tree route through the owning Pi sessions and existing SSH connections. Those owners and intermediate controllers must be running; unavailable routes fail explicitly. Resume the owner and reconnect under `/herdr` → **Status** after a connection loss. No note store is copied or silently substituted.
157
159
 
158
- Both extensions work independently. A target without active context support still starts, with a warning that its context is not shared. A conflicting storage mode or account rejects the shared spawn before task delivery. Profiles that select or resume an existing session cannot participate in shared `spawn`; use `attach` for Local or Tree context access, then `assign`.
160
+ Both extensions work independently. A target without active context support still starts, with a warning that its context is not shared. A conflicting storage mode or account rejects the shared spawn before task delivery. Profiles that select or resume an existing session cannot participate in shared `spawn`; use `attach` for context access, then `assign`.
159
161
 
160
162
  ## Profiles
161
163
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.2.12",
3
+ "version": "0.2.13",
4
4
  "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "pack:dry": "npm pack --dry-run"
44
44
  },
45
45
  "peerDependencies": {
46
- "@howaboua/pi-codex-conversion": ">=3.0.44",
46
+ "@howaboua/pi-codex-conversion": ">=3.0.45",
47
47
  "@earendil-works/pi-ai": ">=1.0.0",
48
48
  "@earendil-works/pi-coding-agent": ">=1.0.0",
49
49
  "@earendil-works/pi-tui": ">=1.0.0",
@@ -58,7 +58,7 @@
58
58
  "unicode-case-folding": "1.1.2"
59
59
  },
60
60
  "devDependencies": {
61
- "@howaboua/pi-codex-conversion": "3.0.44",
61
+ "@howaboua/pi-codex-conversion": "3.0.45",
62
62
  "@biomejs/biome": "^2.5.10",
63
63
  "@earendil-works/pi-ai": "1.0.1",
64
64
  "@earendil-works/pi-coding-agent": "1.0.1",
@@ -51,7 +51,7 @@ export async function agentsHelp(): Promise<Record<string, unknown>> {
51
51
  send: "Only for a needed answer or to change the recipient's current work. No courtesy updates, acknowledgements or completion echoes. Can wake idle agents; no wait/watch",
52
52
  assign: "Delegate a task to an existing agent",
53
53
  attach:
54
- "Idle target; context/board booleans choose shared access and board membership independently. Local/Tree context only; no task/watch",
54
+ "Idle target; context/board booleans choose shared access and board membership independently; no task/watch",
55
55
  detach:
56
56
  "Stop selected membership; retain counterpart checkpoints read-only; idle target",
57
57
  blocking:
@@ -24,17 +24,66 @@ export class AttachmentNotes {
24
24
  export: service.exportAttachmentNotes,
25
25
  parse: service.parseAttachmentNotes,
26
26
  read: service.readAttachmentNotes,
27
+ validate: service.validateAttachmentNotes,
28
+ verify: service.verifyAttachmentAccess,
29
+ remote: service.executeRemoteAttachment,
27
30
  };
28
31
  }
29
32
  export(ctx: ExtensionContext) {
30
33
  return this.service().export(ctx);
31
34
  }
32
35
  validate(snapshot: unknown, identity: ContextAgentIdentity) {
36
+ const service = this.service();
37
+ if (service.validate) return service.validate(snapshot, identity);
38
+ if (identity.storage === "remote")
39
+ throw new Error("Update Codex Conversion to retain Remote checkpoints");
33
40
  this.service().read(snapshot, {
34
41
  action: "list_files_by_prefix",
35
42
  prefix: `${identity.agentName}/notes`,
36
43
  });
37
44
  }
45
+ async verify(
46
+ ctx: ExtensionContext,
47
+ snapshot: unknown,
48
+ identity: ContextAgentIdentity,
49
+ alreadyShared = false,
50
+ ) {
51
+ this.validate(snapshot, identity);
52
+ if (identity.storage === "remote") {
53
+ const verify = this.service().verify;
54
+ if (!verify)
55
+ throw new Error(
56
+ "Update Codex Conversion to authenticate Remote attachments",
57
+ );
58
+ try {
59
+ await verify(ctx, snapshot);
60
+ } catch (error) {
61
+ if (
62
+ !alreadyShared &&
63
+ error instanceof Error &&
64
+ error.message.startsWith("Account mismatch.")
65
+ )
66
+ throw new Error(
67
+ "Account mismatch. Context was not shared. Each agent keeps its own notes and history. Use messages to exchange the context you need.",
68
+ { cause: error },
69
+ );
70
+ throw error;
71
+ }
72
+ }
73
+ }
74
+ async remote(
75
+ ctx: ExtensionContext,
76
+ reference: unknown,
77
+ request: SharedContextRequest,
78
+ signal?: AbortSignal,
79
+ ) {
80
+ const execute = this.service().remote;
81
+ if (!execute)
82
+ throw new Error(
83
+ "Update Codex Conversion to read attached Remote context",
84
+ );
85
+ return execute(ctx, reference, request, signal);
86
+ }
38
87
  checkTransport(value: unknown) {
39
88
  if (Buffer.byteLength(JSON.stringify(value), "utf8") > 7 * 1024 * 1024)
40
89
  throw new Error(
@@ -12,7 +12,9 @@ export const Identity = Type.Object({
12
12
  sessionId: Type.String({ minLength: 1 }),
13
13
  threadId: Type.String({ minLength: 1 }),
14
14
  agentName: AgentPath,
15
- storage: Type.Literal("session"),
15
+ storage: Type.Union([Type.Literal("session"), Type.Literal("remote")]),
16
+ accountScope: Type.Optional(Type.String({ pattern: "^[a-f0-9]{64}$" })),
17
+ backendUrl: Type.Optional(Type.String({ minLength: 1 })),
16
18
  routing: Type.Optional(Type.Unknown()),
17
19
  });
18
20
  const ContextLink = Type.Object({
@@ -109,6 +111,17 @@ export function remapResult(
109
111
  from: string,
110
112
  to: string,
111
113
  ): SharedContextResult {
114
+ if (
115
+ typeof result.details.codexHistoryNotes["encrypted_output"] === "string"
116
+ ) {
117
+ const hint = `Source ${from}, access through ${to}. Use ${to}/notes for note paths and ${to} for history agent_name`;
118
+ // Ciphertext paths cannot be remapped. Preserve host-only provenance on the original details.
119
+ result.details.codexHistoryNotes["attachment_hint"] = hint;
120
+ return {
121
+ ...result,
122
+ content: [{ type: "text", text: hint }, ...result.content],
123
+ };
124
+ }
112
125
  const details = JSON.parse(
113
126
  JSON.stringify(result.details.codexHistoryNotes),
114
127
  (key, value: unknown) =>
@@ -40,12 +40,7 @@ export class AttachmentRouting {
40
40
  signal?: AbortSignal,
41
41
  ): Promise<SharedContextResult | undefined> {
42
42
  const native = this.getService()?.describe(ctx);
43
- if (
44
- !native ||
45
- native.storage !== "session" ||
46
- request.sessionId !== native.sessionId
47
- )
48
- return undefined;
43
+ if (!native || request.sessionId !== native.sessionId) return undefined;
49
44
  const child = attachmentRoutes(ctx).find(
50
45
  (route) =>
51
46
  route.phase === "ready" &&
@@ -56,7 +51,7 @@ export class AttachmentRouting {
56
51
  const link = child.plan.context;
57
52
  if (!isDeepStrictEqual(native, link.controller))
58
53
  throw new Error(
59
- "Attached controller context changed; restore its original storage",
54
+ "Shared notes are unavailable. Use messages to exchange the context you need.",
60
55
  );
61
56
  const next = {
62
57
  ...request,
@@ -65,7 +60,18 @@ export class AttachmentRouting {
65
60
  params: remapParams(request.params, link.alias, link.target.agentName),
66
61
  };
67
62
  let result: SharedContextResult;
68
- if (!child.detached?.context) {
63
+ if (link.target.storage === "remote") {
64
+ if (child.detached?.context && !this.notes.canRead(next))
65
+ throw new Error(
66
+ "Detached counterpart checkpoints are read-only; native history is unchanged",
67
+ );
68
+ result = await this.notes.remote(
69
+ ctx,
70
+ child.detached?.context ?? link.targetNotes,
71
+ next,
72
+ signal,
73
+ );
74
+ } else if (!child.detached?.context) {
69
75
  try {
70
76
  result = (await send(child, {
71
77
  operation: "context",
@@ -104,7 +110,7 @@ export class AttachmentRouting {
104
110
  if (owner && link && inside(request.agentName, link.controllerAlias)) {
105
111
  if (!isDeepStrictEqual(native, link.target))
106
112
  throw new Error(
107
- "Attached target context changed; restore its original storage",
113
+ "Shared notes are unavailable. Use messages to exchange the context you need.",
108
114
  );
109
115
  const next = {
110
116
  ...request,
@@ -122,7 +128,18 @@ export class AttachmentRouting {
122
128
  };
123
129
  const detached = detachment(ctx, owner)?.context;
124
130
  let result: SharedContextResult;
125
- if (!detached) {
131
+ if (link.controller.storage === "remote") {
132
+ if (detached && !this.notes.canRead(next))
133
+ throw new Error(
134
+ "Detached counterpart checkpoints are read-only; native history is unchanged",
135
+ );
136
+ result = await this.notes.remote(
137
+ ctx,
138
+ detached ?? link.controllerNotes,
139
+ next,
140
+ signal,
141
+ );
142
+ } else if (!detached) {
126
143
  try {
127
144
  result = (await requestContext(
128
145
  owner.upstream,
@@ -40,16 +40,14 @@ export class AttachmentTarget {
40
40
  this.getService = getService;
41
41
  this.notes = notes;
42
42
  }
43
- context(ctx: ExtensionContext, target: boolean) {
43
+ async context(ctx: ExtensionContext, target: boolean) {
44
44
  const service = this.getService();
45
45
  if (!service?.inspectAttachment || !service.retainAttachmentIdentity)
46
46
  throw new Error("Update Codex Conversion to attach existing context");
47
- const identity = target
48
- ? service.inspectAttachment(ctx)
49
- : service.describe(ctx);
47
+ const identity = await service.inspectAttachment(ctx, target);
50
48
  if (!identity || !Check(Identity, identity))
51
49
  throw new Error(
52
- "Context attachment requires Local or Tree on both agents; Remote attachment is unsupported",
50
+ "Context attachment requires notes-based continuity on both agents",
53
51
  );
54
52
  return identity as Static<typeof Identity>;
55
53
  }
@@ -59,9 +57,9 @@ export class AttachmentTarget {
59
57
  throw new Error(
60
58
  "Context attachment support became unavailable; reload and retry",
61
59
  );
62
- service.retainAttachmentIdentity(ctx);
60
+ return service.retainAttachmentIdentity(ctx);
63
61
  }
64
- private inspect(ctx: ExtensionContext) {
62
+ private async inspect(ctx: ExtensionContext) {
65
63
  if (!ctx.isIdle()) throw new Error("Attach only after the target settles");
66
64
  if (!ctx.sessionManager.getSessionFile())
67
65
  throw new Error("Attachment requires a saved target session");
@@ -69,7 +67,7 @@ export class AttachmentTarget {
69
67
  let contextError: string | undefined;
70
68
  let boardError: string | undefined;
71
69
  try {
72
- context = this.context(ctx, true);
70
+ context = await this.context(ctx, true);
73
71
  if (
74
72
  attachmentRoutes(ctx).some((route) => route.plan.context) ||
75
73
  ctx.sessionManager
@@ -95,12 +93,17 @@ export class AttachmentTarget {
95
93
  return {
96
94
  sessionId: ctx.sessionManager.getSessionId(),
97
95
  board: binding(ctx),
98
- ...(context ? { context, notes: this.notes.export(ctx) } : {}),
96
+ ...(context ? { context, notes: await this.notes.export(ctx) } : {}),
99
97
  ...(contextError ? { contextError } : {}),
100
98
  ...(boardError ? { boardError } : {}),
101
99
  };
102
100
  }
103
- async handle(ctx: ExtensionContext, input: unknown): Promise<unknown> {
101
+ async handle(
102
+ ctx: ExtensionContext,
103
+ input: unknown,
104
+ signal?: AbortSignal,
105
+ ): Promise<unknown> {
106
+ signal?.throwIfAborted();
104
107
  if (!input || typeof input !== "object" || !("operation" in input))
105
108
  throw new Error("Invalid attachment request");
106
109
  if (input.operation === "attach-inspect") return this.inspect(ctx);
@@ -114,7 +117,7 @@ export class AttachmentTarget {
114
117
  return this.notes.export(ctx);
115
118
  }
116
119
  if (input.operation === "detach-commit")
117
- return this.commitDetach(ctx, input);
120
+ return this.commitDetach(ctx, input, signal);
118
121
  if (
119
122
  input.operation !== "attach-commit" ||
120
123
  !("plan" in input) ||
@@ -162,7 +165,7 @@ export class AttachmentTarget {
162
165
  "Target is already attached; another controller or different attachment choices are unsupported",
163
166
  );
164
167
  if (!owner) {
165
- const current = this.inspect(ctx);
168
+ const current = await this.inspect(ctx);
166
169
  if (
167
170
  plan.context &&
168
171
  (!current.context ||
@@ -174,15 +177,37 @@ export class AttachmentTarget {
174
177
  if (plan.board && current.boardError) throw new Error(current.boardError);
175
178
  if (plan.board && !isDeepStrictEqual(current.board, plan.board.previous))
176
179
  throw new Error("Target board changed during attachment");
177
- // All checks precede either mutation; no await between the two commits.
180
+ // Authentication completes before either membership mutation.
178
181
  if (plan.context) {
179
- this.notes.validate(
182
+ await this.notes.verify(
183
+ ctx,
180
184
  plan.context.controllerNotes,
181
185
  plan.context.controller,
182
186
  );
183
187
  this.notes.validate(plan.context.targetNotes, plan.context.target);
184
188
  }
185
- if (plan.context) this.retainIdentity(ctx);
189
+ if (plan.context) {
190
+ const identity = await this.context(ctx, true);
191
+ signal?.throwIfAborted();
192
+ if (
193
+ !ctx.isIdle() ||
194
+ ctx.sessionManager.getSessionId() !== plan.targetSessionId ||
195
+ !isDeepStrictEqual(identity, plan.context.target) ||
196
+ (plan.board && !isDeepStrictEqual(binding(ctx), plan.board.previous))
197
+ )
198
+ throw new Error(
199
+ "Target changed during attachment authentication; retry after it settles",
200
+ );
201
+ this.retainIdentity(ctx);
202
+ }
203
+ signal?.throwIfAborted();
204
+ if (
205
+ !ctx.isIdle() ||
206
+ ctx.sessionManager.getSessionId() !== plan.targetSessionId
207
+ )
208
+ throw new Error(
209
+ "Target changed during attachment; retry after it settles",
210
+ );
186
211
  if (plan.board)
187
212
  this.board.membership.commitAttachment(
188
213
  ctx,
@@ -201,9 +226,11 @@ export class AttachmentTarget {
201
226
  } else {
202
227
  if (
203
228
  plan.context &&
204
- !isDeepStrictEqual(this.context(ctx, false), plan.context.target)
229
+ !isDeepStrictEqual(await this.context(ctx, false), plan.context.target)
205
230
  )
206
- throw new Error("Attached context changed; restore Local or Tree");
231
+ throw new Error(
232
+ "Shared notes are unavailable. Use messages to exchange the context you need.",
233
+ );
207
234
  if (
208
235
  plan.board &&
209
236
  !isDeepStrictEqual(binding(ctx), {
@@ -220,7 +247,11 @@ export class AttachmentTarget {
220
247
  );
221
248
  return plan;
222
249
  }
223
- private async commitDetach(ctx: ExtensionContext, input: unknown) {
250
+ private async commitDetach(
251
+ ctx: ExtensionContext,
252
+ input: unknown,
253
+ signal?: AbortSignal,
254
+ ) {
224
255
  if (!Check(Detachment, input)) throw new Error("Invalid detach request");
225
256
  const requested = input as Static<typeof Detachment>;
226
257
  const { plan } = requested;
@@ -238,12 +269,31 @@ export class AttachmentTarget {
238
269
  throw new Error("Invalid detach choices");
239
270
  const previous = detachment(ctx, plan);
240
271
  if (requested.context && plan.context) {
241
- if (!isDeepStrictEqual(this.context(ctx, false), plan.context.target))
272
+ if (
273
+ !isDeepStrictEqual(await this.context(ctx, false), plan.context.target)
274
+ )
242
275
  throw new Error("Target context changed before detach");
243
276
  this.notes.validate(requested.context, plan.context.controller);
277
+ await this.notes.verify(
278
+ ctx,
279
+ requested.context,
280
+ plan.context.controller,
281
+ true,
282
+ );
244
283
  }
245
- const ownNotes = requested.context ? this.notes.export(ctx) : undefined;
284
+ const ownNotes = requested.context
285
+ ? await this.notes.export(ctx)
286
+ : undefined;
246
287
  if (ownNotes) this.notes.checkTransport(ownNotes);
288
+ signal?.throwIfAborted();
289
+ if (
290
+ !ctx.isIdle() ||
291
+ ctx.sessionManager.getSessionId() !== plan.targetSessionId ||
292
+ !isDeepStrictEqual(attachmentOwner(ctx), plan)
293
+ )
294
+ throw new Error(
295
+ "Target changed during detach authentication; retry after it settles",
296
+ );
247
297
  if (requested.board && plan.board && !previous?.board)
248
298
  this.board.membership.detachTarget(
249
299
  ctx,
package/src/attachment.ts CHANGED
@@ -64,18 +64,18 @@ export class AgentAttachment {
64
64
  const context = params.context === true;
65
65
  const useBoard = params.board === true;
66
66
  const controllerContext = context
67
- ? this.target.context(ctx, false)
67
+ ? await this.target.context(ctx, false)
68
68
  : undefined;
69
69
  const controllerBoard = useBoard ? binding(ctx) : undefined;
70
- const check = () => {
70
+ const check = async () => {
71
+ const currentContext = controllerContext
72
+ ? await this.target.context(ctx, false)
73
+ : undefined;
71
74
  signal.throwIfAborted();
72
75
  if (
73
76
  ctx.sessionManager.getSessionId() !== controllerSessionId ||
74
77
  (controllerContext &&
75
- !isDeepStrictEqual(
76
- this.target.context(ctx, false),
77
- controllerContext,
78
- )) ||
78
+ !isDeepStrictEqual(currentContext, controllerContext)) ||
79
79
  (controllerBoard && !isDeepStrictEqual(binding(ctx), controllerBoard))
80
80
  )
81
81
  throw new Error(
@@ -102,7 +102,7 @@ export class AgentAttachment {
102
102
  { operation: "attach-inspect" },
103
103
  signal,
104
104
  );
105
- check();
105
+ await check();
106
106
  if (!Check(Snapshot, snapshot))
107
107
  throw new Error(
108
108
  "Target does not support attachment; update and reload Shepherdr",
@@ -113,6 +113,10 @@ export class AgentAttachment {
113
113
  current.contextError ?? "Target context is unavailable",
114
114
  );
115
115
  if (useBoard && current.boardError) throw new Error(current.boardError);
116
+ if (controllerContext && current.context) {
117
+ await this.notes.verify(ctx, current.notes, current.context);
118
+ await check();
119
+ }
116
120
  const upstream = runtime.local
117
121
  ? sessionContextPath(controllerFile)
118
122
  : runtime.client.contextRelayPath();
@@ -129,7 +133,7 @@ export class AgentAttachment {
129
133
  alias: `${controllerContext.agentName}/${segment}`,
130
134
  controllerAlias: `${current.context.agentName}/controller-${randomUUID()}`,
131
135
  ...(runtime.local ? { controllerFile } : {}),
132
- controllerNotes: this.notes.export(ctx),
136
+ controllerNotes: await this.notes.export(ctx),
133
137
  targetNotes: current.notes,
134
138
  },
135
139
  }
@@ -148,6 +152,7 @@ export class AgentAttachment {
148
152
  }
149
153
  : {}),
150
154
  };
155
+ await check();
151
156
  route = { plan, machine: runtime.machine, sessionFile, phase: "pending" };
152
157
  this.notes.checkTransport({ operation: "attach-commit", plan });
153
158
  // A retry after a lost response reuses the same aliases and board identity.
@@ -159,7 +164,7 @@ export class AgentAttachment {
159
164
  { operation: "attach-commit", plan: route.plan },
160
165
  signal,
161
166
  );
162
- check();
167
+ await check();
163
168
  if (!isDeepStrictEqual(accepted, route.plan))
164
169
  throw new Error("Target did not accept the requested attachment");
165
170
  if (route.plan.board)
@@ -173,7 +178,7 @@ export class AgentAttachment {
173
178
  },
174
179
  route.plan.board.controller,
175
180
  );
176
- check();
181
+ await check();
177
182
  if (route.plan.context) this.target.retainIdentity(ctx);
178
183
  if (route.phase !== "ready")
179
184
  this.pi.appendEntry(ROUTE, { ...route, phase: "ready" });
@@ -220,24 +225,46 @@ export class AgentAttachment {
220
225
  const { plan } = route;
221
226
  if ((params.context && !plan.context) || (params.board && !plan.board))
222
227
  throw new Error("Cannot detach a choice that was not attached");
223
- const check = () => {
228
+ const controllerBoard = params.board ? binding(ctx) : undefined;
229
+ const check = async (checkRoute = true) => {
230
+ const currentContext =
231
+ params.context && plan.context
232
+ ? await this.target.context(ctx, false)
233
+ : undefined;
224
234
  signal.throwIfAborted();
225
235
  if (
226
236
  ctx.sessionManager.getSessionId() !== plan.controllerSessionId ||
237
+ (checkRoute &&
238
+ !isDeepStrictEqual(
239
+ attachmentRoutes(ctx).find(
240
+ (entry) =>
241
+ entry.machine === route.machine &&
242
+ entry.sessionFile === route.sessionFile,
243
+ ),
244
+ route,
245
+ )) ||
227
246
  (params.context &&
228
247
  plan.context &&
229
- !isDeepStrictEqual(
230
- this.target.context(ctx, false),
231
- plan.context.controller,
232
- ))
248
+ !isDeepStrictEqual(currentContext, plan.context.controller)) ||
249
+ (controllerBoard && !isDeepStrictEqual(binding(ctx), controllerBoard))
233
250
  )
234
251
  throw new Error(
235
252
  "Controller changed during detach; resume it and retry",
236
253
  );
237
254
  };
238
- check();
255
+ await check();
239
256
  try {
240
- const context = params.context ? this.notes.export(ctx) : undefined;
257
+ if (params.context && plan.context) {
258
+ await this.notes.verify(
259
+ ctx,
260
+ route.detached?.context ?? plan.context.targetNotes,
261
+ plan.context.target,
262
+ true,
263
+ );
264
+ await check();
265
+ }
266
+ const context = params.context ? await this.notes.export(ctx) : undefined;
267
+ await check();
241
268
  this.notes.checkTransport({
242
269
  operation: "detach-commit",
243
270
  plan,
@@ -254,7 +281,7 @@ export class AgentAttachment {
254
281
  },
255
282
  signal,
256
283
  );
257
- check();
284
+ await check();
258
285
  if (
259
286
  !result ||
260
287
  typeof result !== "object" ||
@@ -266,7 +293,8 @@ export class AgentAttachment {
266
293
  if (params.context && plan.context) {
267
294
  if (!("notes" in result))
268
295
  throw new Error("Target checkpoints were not retained");
269
- this.notes.validate(result.notes, plan.context.target);
296
+ await this.notes.verify(ctx, result.notes, plan.context.target, true);
297
+ await check();
270
298
  notes = result.notes;
271
299
  }
272
300
  this.pi.appendEntry(ROUTE, {
@@ -282,7 +310,7 @@ export class AgentAttachment {
282
310
  ...plan.board.desired,
283
311
  sessionId: plan.targetSessionId,
284
312
  });
285
- check();
313
+ await check(false);
286
314
  } catch (error) {
287
315
  throw new Error(
288
316
  `Detach incomplete; retry from the same controller and target with the same choices. ${String(error)}`,
@@ -10,7 +10,11 @@ import type {
10
10
  } from "@howaboua/pi-codex-conversion/context-sharing";
11
11
  import { Check } from "typebox/value";
12
12
  import { AgentAttachment } from "./attachment.js";
13
- import { Identity } from "./attachment-protocol.js";
13
+ import {
14
+ attachmentOwner,
15
+ attachmentRoutes,
16
+ Identity,
17
+ } from "./attachment-protocol.js";
14
18
  import type { AgentBoard } from "./board/host.js";
15
19
  import { isBoardEnvelope } from "./board/protocol.js";
16
20
  import type { AgentFleet, ConnectedMachine } from "./fleet.js";
@@ -82,7 +86,7 @@ export class SharedAgentContext {
82
86
  value.operation === "attachment-export-notes" ||
83
87
  value.operation === "detach-commit")
84
88
  )
85
- return this.attachment.target.handle(ctx, value);
89
+ return this.attachment.target.handle(ctx, value, signal);
86
90
  const service = this.getService();
87
91
  const identity = service?.describe(ctx);
88
92
  if (
@@ -311,12 +315,46 @@ export async function registerSharedAgentContext(
311
315
  close = undefined;
312
316
  unregister?.();
313
317
  unregister = connection?.service?.registerRouter(
314
- async (context, request, signal) =>
315
- shared.handle(
316
- context,
317
- { operation: "context", request, visited: [] },
318
- signal,
319
- ) as Promise<SharedContextResult>,
318
+ Object.assign(
319
+ async (
320
+ context: ExtensionContext,
321
+ request: SharedContextRequest,
322
+ signal?: AbortSignal,
323
+ ) => {
324
+ const attached = await shared.attachment.routing.route(
325
+ context,
326
+ request,
327
+ [],
328
+ (route, next) =>
329
+ fleet
330
+ .connected(route.machine)
331
+ .client.requestContext(
332
+ sessionContextPath(route.sessionFile),
333
+ next,
334
+ signal,
335
+ ),
336
+ signal,
337
+ );
338
+ if (attached) return attached;
339
+ if (connection?.service?.describe(context)?.storage === "remote")
340
+ return undefined;
341
+ return shared.handle(
342
+ context,
343
+ { operation: "context", request, visited: [] },
344
+ signal,
345
+ ) as Promise<SharedContextResult>;
346
+ },
347
+ {
348
+ requiresRemoteScope: (context: ExtensionContext) =>
349
+ attachmentOwner(context)?.context?.controller.storage ===
350
+ "remote" ||
351
+ attachmentRoutes(context).some(
352
+ (route) =>
353
+ route.phase === "ready" &&
354
+ route.plan.context?.target.storage === "remote",
355
+ ),
356
+ },
357
+ ),
320
358
  );
321
359
  const file = ctx.sessionManager.getSessionFile();
322
360
  if (file)