my-durable 0.0.66 → 0.0.68

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.
@@ -25,6 +25,11 @@ export interface GcIo {
25
25
  readFile: (path: string) => string;
26
26
  homedir: () => string;
27
27
  now: () => number;
28
+ /** R13 P3-1: the pending-sweep marker's writer — optional so test fakes can
29
+ * omit it (a missing writer just means the retry hint degrades to the
30
+ * message, never a crash). */
31
+ writeFile?: (path: string, data: string) => void;
32
+ remove?: (path: string) => void;
28
33
  }
29
34
 
30
35
  export const defaultGcIo = (): GcIo => ({
@@ -39,10 +44,13 @@ export const defaultGcIo = (): GcIo => ({
39
44
  const HELP = `dpi gc — retention for archived sessions
40
45
 
41
46
  dpi gc --closed-before 30d [--dry-run | --yes] [--home <dir>] [--data-dir <dir>]
47
+ dpi gc --sweep [--home <dir>] [--data-dir <dir>]
42
48
 
43
49
  --closed-before D age cutoff: 90m, 12h, 30d, 2w
44
50
  --dry-run show what would be deleted (the default)
45
51
  --yes actually delete it
52
+ --sweep retry a pending dangling-ref sweep (after a delete whose
53
+ sweep failed — deletes nothing by itself)
46
54
  --home <dir> device home (default: $DPI_HOME, else ~/.dpi)
47
55
  --data-dir <dir> device data dir (default: <home>/backend)
48
56
 
@@ -88,7 +96,7 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
88
96
  io.print(HELP);
89
97
  return 0;
90
98
  }
91
- const known = new Set(["--closed-before", "--dry-run", "--yes", "--home", "--data-dir"]);
99
+ const known = new Set(["--closed-before", "--dry-run", "--yes", "--sweep", "--home", "--data-dir"]);
92
100
  for (const arg of argv) {
93
101
  if (arg.startsWith("-") && !known.has(arg)) {
94
102
  io.printErr(`dpi gc: unknown flag '${arg}'\n\n${HELP}`);
@@ -96,6 +104,34 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
96
104
  }
97
105
  }
98
106
  const at = argv.indexOf("--closed-before");
107
+ // R13 P3-1: `--sweep` is a standalone retry of a pending ref sweep — it
108
+ // needs no cutoff (it deletes nothing; it only clears refs left behind by
109
+ // an earlier delete-ok/sweep-fail pass).
110
+ if (argv.includes("--sweep")) {
111
+ let dataDir0: string;
112
+ try {
113
+ dataDir0 = resolveDataDir(argv, io);
114
+ } catch (e) {
115
+ io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
116
+ return 1;
117
+ }
118
+ const pending0 = readPendingIds(io, pendingSweepPath(dataDir0));
119
+ if (!pending0.length) {
120
+ io.print("no pending ref sweep.");
121
+ return 0;
122
+ }
123
+ try {
124
+ await sweepRefs(dataDir0, pending0, io, deviceToken(io));
125
+ io.remove?.(pendingSweepPath(dataDir0));
126
+ io.print(`swept ${pending0.length} pending ref id(s); marker cleared.`);
127
+ return 0;
128
+ } catch (e) {
129
+ io.printErr(
130
+ `dpi gc: pending sweep failed: ${e instanceof Error ? e.message : String(e)} (marker kept — retry with --sweep)`,
131
+ );
132
+ return 1;
133
+ }
134
+ }
99
135
  if (at < 0 || !argv[at + 1]) {
100
136
  io.printErr(`dpi gc: --closed-before DURATION is required (e.g. 30d)\n\n${HELP}`);
101
137
  return 2;
@@ -118,6 +154,9 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
118
154
  return 1;
119
155
  }
120
156
  const options = { closedBeforeDays: days, now: io.now() };
157
+ const dataDir = dataDirOf(archiveDir);
158
+ const pendingFile = pendingSweepPath(dataDir);
159
+ const pending = readPendingIds(io, pendingFile);
121
160
 
122
161
  // The plan/apply calls live inside the pretty-error path (R5 finding 6): a bad
123
162
  // cutoff or unreadable archive used to escape as a raw stack trace.
@@ -141,28 +180,39 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
141
180
  `sweep would clear ${plan.danglingRefs.schedules} schedule ref(s) and ${plan.danglingRefs.graphRuns} graph-run ref(s) pointing at the deletions.`,
142
181
  );
143
182
  }
183
+ if (pending.length > 0)
184
+ io.print(
185
+ `${pending.length} pending ref id(s) from an earlier failed sweep — re-run with --yes (or --sweep) to retry.`,
186
+ );
144
187
  return 0;
145
188
  }
146
189
 
147
190
  const { removed, bytes } = await gcApply(archiveDir, options);
148
191
  io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
149
192
 
150
- // R10 Design B: sweep refs pointing at what we just removed. Daemon-first
151
- // (registry mutations happen in-process, no file race); offline falls back
152
- // to the same advisory lock Store.open takes.
153
- const ids = removedSessionIds(removed);
193
+ // R10 Design B: sweep refs pointing at what we just removed — MERGED with
194
+ // any ids a previous failed sweep left behind (R13 P3-1: the retry used to
195
+ // be a dead end — a re-run with nothing to delete never swept again, so
196
+ // refs stayed dangling forever while the operator read success).
197
+ // Daemon-first (registry mutations happen in-process, no file race);
198
+ // offline falls back to the same advisory lock Store.open takes.
199
+ const ids = [...new Set([...pending, ...removedSessionIds(removed)])];
154
200
  if (ids.length > 0) {
155
201
  try {
156
- await sweepRefs(dataDirOf(archiveDir), ids, io, deviceToken(io));
202
+ await sweepRefs(dataDir, ids, io, deviceToken(io));
203
+ if (pending.length > 0) {
204
+ io.remove?.(pendingFile);
205
+ io.print(`(included ${pending.length} pending ref id(s) from an earlier failed sweep — marker cleared.)`);
206
+ }
157
207
  } catch (e) {
208
+ writePendingIds(io, pendingFile, ids);
158
209
  io.printErr(
159
210
  `dpi gc: deleted ${ids.length} session(s) but the ref sweep failed: ${
160
211
  e instanceof Error ? e.message : String(e)
161
- } (re-run later — the sweep is idempotent)`,
212
+ } (ids kept for retry: dpi gc --sweep — the sweep is idempotent)`,
162
213
  );
163
214
  // R12 P2-3: cron/scripts gate on the exit code — a failed sweep after
164
- // a real delete must not read as success (nothing retries it
165
- // otherwise; a later no-delete gc pass never sweeps).
215
+ // a real delete must not read as success.
166
216
  return 1;
167
217
  }
168
218
  }
@@ -175,6 +225,30 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
175
225
 
176
226
  const dataDirOf = (archiveDir: string) => archiveDir.slice(0, archiveDir.length - "/archive".length);
177
227
 
228
+ /** R13 P3-1: the pending-sweep marker — ids a delete-ok/sweep-fail pass left
229
+ * behind. Session UUIDs only (not secret); written best-effort, read
230
+ * tolerantly, cleared on the first successful sweep. */
231
+ const pendingSweepPath = (dataDir: string) => join(dataDir, "gc-pending-sweep.json");
232
+
233
+ const readPendingIds = (io: GcIo, path: string): string[] => {
234
+ try {
235
+ const doc = JSON.parse(io.readFile(path)) as { ids?: unknown };
236
+ return Array.isArray(doc.ids)
237
+ ? [...new Set(doc.ids.filter((id): id is string => typeof id === "string" && id.length > 0))]
238
+ : [];
239
+ } catch {
240
+ return []; // absent/corrupt — nothing pending
241
+ }
242
+ };
243
+
244
+ const writePendingIds = (io: GcIo, path: string, ids: string[]): void => {
245
+ try {
246
+ io.writeFile?.(path, `${JSON.stringify({ ids }, null, 2)}\n`);
247
+ } catch {
248
+ /* best-effort — the printed remedy still names --sweep */
249
+ }
250
+ };
251
+
178
252
  /** The device token, from the process env or the env file (DPI_ENV_FILE) —
179
253
  * only needed for the daemon-first sweep route. */
180
254
  function deviceToken(io: GcIo): string | undefined {
@@ -212,7 +286,10 @@ async function sweepRefs(dataDir: string, ids: string[], io: GcIo, token?: strin
212
286
  // anything else is a real fault; falling through to the offline path
213
287
  // would race the daemon, so surface it instead.
214
288
  if (res.status === 404)
215
- throw new Error("device predates the sweep route — upgrade it (npm i -g my-durable) and re-run dpi gc");
289
+ throw new Error(
290
+ "device predates the sweep route — upgrade it (npm i -g my-durable) and re-run dpi gc " +
291
+ "(or DPI_PORT points at another local service — check it)",
292
+ );
216
293
  if (res.status === 401)
217
294
  throw new Error("device refused the sweep token — stale DPI_TOKEN in the env file; refresh it and re-run dpi gc");
218
295
  throw new Error(`device answered ${res.status} to the sweep route`);
@@ -120,14 +120,20 @@ export function danglingRefCounts(
120
120
  let graphRuns = 0;
121
121
  try {
122
122
  const doc = JSON.parse(readFile(join(dataDir, "schedules.json"))) as {
123
- schedules?: Array<{ lastSessionId?: string; recentSessionIds?: string[] }>;
123
+ schedules?: Array<{ lastSessionId?: string; keepRuns?: unknown; recentSessionIds?: string[] }>;
124
124
  };
125
125
  // R12 P3-11: count what the sweep actually clears — the retention ring
126
126
  // too (clearSessionRefs deletes ring entries alongside lastSessionId), so
127
- // the dry-run's "would clear N" stops under-promising.
127
+ // the dry-run's "would clear N" stops under-promising. R13 P3-2: ring
128
+ // refs count ONLY when keepRuns parses in-range — the registry coercion
129
+ // DROPS junk keepRuns together with its ring (schedules.ts), so counting
130
+ // a doomed ring here would dry-run-promise what the sweep never clears.
131
+ const keepRunsParses = (v: unknown) =>
132
+ typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 100;
128
133
  for (const s of doc.schedules ?? []) {
129
134
  if (s.lastSessionId && ids.has(s.lastSessionId)) schedules += 1;
130
- else if ((s.recentSessionIds ?? []).some((id) => ids.has(id))) schedules += 1;
135
+ else if (keepRunsParses(s.keepRuns) && (s.recentSessionIds ?? []).some((id) => ids.has(id)))
136
+ schedules += 1;
131
137
  }
132
138
  } catch {
133
139
  /* absent or unreadable — nothing countable */
@@ -468,6 +468,29 @@ export class DevicePairing {
468
468
  // Offer v3: challenge the hub to prove it owns the pinned identity key.
469
469
  const hubNonce = kfp ? randomBytes(32).toString("base64url") : undefined;
470
470
 
471
+ // Synchronous slot reservation (audit run-1 HIGH, pairing TOCTOU): the busy
472
+ // gate and status() must hold from HERE — before the first await — not from
473
+ // the tail of completeChallenge, or a concurrent start() slips through the
474
+ // window between the check above and that assignment and hijacks the
475
+ // enrollment. completeChallenge upgrades the reservation in place (same
476
+ // operationId); any throw below clears it; cancel() in the window wins
477
+ // (completeChallenge refuses to resurrect a cancelled slot).
478
+ this.pending = {
479
+ operationId,
480
+ hubOrigin: origin,
481
+ code,
482
+ requestId,
483
+ deviceUid,
484
+ deviceName: this.deviceName,
485
+ keyFingerprint: keypair.fingerprint,
486
+ proof: { type: "pair.response", v: 1, enrollmentId: "", nonce: "", signature: "" },
487
+ hubId: "",
488
+ ...(kfp ? { kfp } : {}),
489
+ expiresAt: this.now() + 300_000,
490
+ startedAt: this.now(),
491
+ abort: new AbortController(),
492
+ };
493
+
471
494
  // Device-initiated enrollment (code-less): the hub mints the code and answers
472
495
  // with its challenge in ONE round trip, so the request carries the machine's
473
496
  // full identity — the shape the operator approves against.
@@ -482,18 +505,37 @@ export class DevicePairing {
482
505
  clientTime: this.now(),
483
506
  ...(hubNonce ? { hubNonce } : {}),
484
507
  };
485
- if (!code) {
486
- const ack = (await this.hubFetch(origin, "/api/pair/request", {
487
- type: "pair.device-request",
508
+ try {
509
+ if (!code) {
510
+ const ack = (await this.hubFetch(origin, "/api/pair/request", {
511
+ type: "pair.device-request",
512
+ v: 1,
513
+ ...body,
514
+ })) as { code?: string; challenge?: unknown };
515
+ if (typeof ack.code !== "string" || !ack.challenge)
516
+ throw err("invalid", `Unexpected hub response: ${JSON.stringify(ack).slice(0, 200)}`);
517
+ code = ack.code;
518
+ return this.completeChallenge(
519
+ origin,
520
+ ack.challenge as Challenge,
521
+ code,
522
+ kfp,
523
+ hubNonce,
524
+ operationId,
525
+ requestId,
526
+ deviceUid,
527
+ keypair,
528
+ );
529
+ }
530
+ const challenge = (await this.hubFetch(origin, "/api/pair/start", {
531
+ type: "pair.request",
488
532
  v: 1,
489
533
  ...body,
490
- })) as { code?: string; challenge?: unknown };
491
- if (typeof ack.code !== "string" || !ack.challenge)
492
- throw err("invalid", `Unexpected hub response: ${JSON.stringify(ack).slice(0, 200)}`);
493
- code = ack.code;
534
+ code,
535
+ })) as Challenge;
494
536
  return this.completeChallenge(
495
537
  origin,
496
- ack.challenge as Challenge,
538
+ challenge,
497
539
  code,
498
540
  kfp,
499
541
  hubNonce,
@@ -502,24 +544,15 @@ export class DevicePairing {
502
544
  deviceUid,
503
545
  keypair,
504
546
  );
547
+ } catch (e) {
548
+ // The reservation dies with this attempt unless cancel()/a rival already
549
+ // replaced it (operationId mismatch → leave the survivor alone).
550
+ if (this.pending?.operationId === operationId) {
551
+ this.pending.abort.abort();
552
+ this.pending = undefined;
553
+ }
554
+ throw e;
505
555
  }
506
- const challenge = (await this.hubFetch(origin, "/api/pair/start", {
507
- type: "pair.request",
508
- v: 1,
509
- ...body,
510
- code,
511
- })) as Challenge;
512
- return this.completeChallenge(
513
- origin,
514
- challenge,
515
- code,
516
- kfp,
517
- hubNonce,
518
- operationId,
519
- requestId,
520
- deviceUid,
521
- keypair,
522
- );
523
556
  }
524
557
 
525
558
  /**
@@ -597,6 +630,13 @@ export class DevicePairing {
597
630
  startedAt: this.now(),
598
631
  abort: new AbortController(),
599
632
  };
633
+ // cancel() may have aborted the reservation while the hub challenge was in
634
+ // flight — cancel promised to stop the LOCAL operation, so never resurrect
635
+ // the slot: abort this attempt and report the (no longer pairing) state.
636
+ if (this.pending?.operationId !== operationId) {
637
+ pending.abort.abort();
638
+ return this.status();
639
+ }
600
640
  this.pending = pending;
601
641
  void this.pollLoop(pending).catch(() => undefined);
602
642
  return this.status();
@@ -1,6 +1,7 @@
1
1
  // REST v1. Every route requires the device token (see auth.ts). Session refs are a UUID or a
2
2
  // unique name; agent refs are a numeric id, `main`, or a unique name.
3
3
  import { Router, type Request, type Response, type NextFunction } from "express";
4
+ import { isAbsolute, resolve } from "node:path";
4
5
  import { createReadStream } from "node:fs";
5
6
  import { pipeline } from "node:stream/promises";
6
7
  import type { Conversation, Harness } from "@earendil-works/pi-durable";
@@ -191,12 +192,29 @@ export function v1(
191
192
  const op = String(body.op ?? "") as GitOp;
192
193
  if (!GIT_OPS.includes(op)) throw invalid(`Unknown git op ${String(body.op ?? "")}`);
193
194
  const path = await gitPath(body.path);
195
+ // Audit run-1 (worktree-target containment): the worktree DESTINATION is an
196
+ // fs path like any other — it must pass the same start-dir choke point as
197
+ // `path` above, or worktree-add/remove plants/deletes checkouts anywhere
198
+ // the daemon user can write (routes.ts is the enforcing layer; git.ts has
199
+ // no store/start-dir context).
200
+ const rawTarget =
201
+ (op === "worktree-add" || op === "worktree-remove") && typeof body.target === "string"
202
+ ? // Relative targets keep git's own semantics — resolved against the
203
+ // REPO, not the daemon cwd — before the containment choke point.
204
+ isAbsolute(body.target)
205
+ ? body.target
206
+ : resolve(path, body.target)
207
+ : body.target;
208
+ const target =
209
+ typeof rawTarget === "string" && (op === "worktree-add" || op === "worktree-remove")
210
+ ? await store.containedPath(rawTarget)
211
+ : rawTarget;
194
212
  try {
195
213
  const out = await gitOp(path, op, {
196
214
  ref: body.ref,
197
215
  branch: body.branch,
198
216
  message: body.message,
199
- target: body.target,
217
+ target,
200
218
  files: Array.isArray(body.files) ? body.files.map(String).slice(0, 500) : undefined,
201
219
  // booleans stay booleans: gitOp validates names/refs itself.
202
220
  create: body.create === true,
@@ -2905,8 +2905,9 @@ export class Store {
2905
2905
  * archived via the existing store.archive path (abort-open → atomic rename
2906
2906
  * to archive/ → catalog row deleted — nothing deleted, restorable, ages into
2907
2907
  * the gc plan). Archive failure leaves the session live; the id is already
2908
- * gone from the ring, but the session stays restorable and the operator can
2909
- * archive it manually — at most keepRuns stragglers can overstay (bounded). */
2908
+ * gone from the ring, so a PERSISTENT failure accumulates one straggler
2909
+ * per run until recovery — unbounded while the fault lasts, which is why
2910
+ * R12 P2-1 reports the degraded episode instead of swallowing it. */
2910
2911
  /** R12 P2-1: the once-per-episode signal for a retention prune that could
2911
2912
  * not archive an evicted run — shared by the prune's own failure path and
2912
2913
  * the void-caller's outer catch. */
@@ -2946,7 +2947,10 @@ export class Store {
2946
2947
  void this.notifyEvent({
2947
2948
  kind: "schedule.ok",
2948
2949
  title: `Retention resumed: ${record.name}`,
2949
- body: `archived ${archived} evicted run(s); the window is healthy again`,
2950
+ body:
2951
+ archived > 0
2952
+ ? `archived ${archived} evicted run(s); the window is healthy again`
2953
+ : `archiving works again (the evicted run(s) were already gone); the window is healthy`,
2950
2954
  data: { scheduleId: record.id },
2951
2955
  });
2952
2956
  }
@@ -71,7 +71,15 @@ const CODE_PATTERN = /^[0-9a-f]{8}$/;
71
71
  */
72
72
  export interface TelegramUpdate {
73
73
  updateId: number;
74
- message?: { chatId: number; text: string; from?: string };
74
+ message?: {
75
+ chatId: number;
76
+ text: string;
77
+ from?: string;
78
+ /** Audit run-1: the sender's STABLE Telegram id (usernames are mutable). */
79
+ fromId?: number;
80
+ /** Audit run-1: chat.type from the wire — "private" vs group/supergroup/channel. */
81
+ chatType?: string;
82
+ };
75
83
  }
76
84
 
77
85
  /**
@@ -150,6 +158,9 @@ export interface TelegramChatBinding {
150
158
  sessionId: string;
151
159
  /** ISO. When this binding was made. */
152
160
  createdAt: string;
161
+ /** Audit run-1: the /start sender's stable Telegram id — only that sender may
162
+ * act on this binding. Absent on legacy rows (treated as chat-wide until re-bound). */
163
+ boundFromId?: number;
153
164
  }
154
165
 
155
166
  /** One minted `/start` code. `sessionId` is the session the code grants (the CLI's default is the first session). */
@@ -237,6 +248,7 @@ export function flattenUpdates(rows: readonly unknown[]): TelegramUpdate[] {
237
248
  if (typeof msg.text === "string" && typeof chatId === "number" && Number.isFinite(chatId)) {
238
249
  const from = msg.from;
239
250
  let fromName: string | undefined;
251
+ let fromId: number | undefined;
240
252
  if (from !== null && typeof from === "object") {
241
253
  const f = from as Record<string, unknown>;
242
254
  fromName =
@@ -245,8 +257,19 @@ export function flattenUpdates(rows: readonly unknown[]): TelegramUpdate[] {
245
257
  : typeof f.first_name === "string" && f.first_name
246
258
  ? f.first_name
247
259
  : undefined;
260
+ if (typeof f.id === "number" && Number.isFinite(f.id)) fromId = Math.trunc(f.id);
248
261
  }
249
- message = { chatId: Math.trunc(chatId), text: msg.text, ...(fromName ? { from: fromName } : {}) };
262
+ const chatType =
263
+ chat !== null && typeof chat === "object" && typeof (chat as Record<string, unknown>).type === "string"
264
+ ? ((chat as Record<string, unknown>).type as string)
265
+ : undefined;
266
+ message = {
267
+ chatId: Math.trunc(chatId),
268
+ text: msg.text,
269
+ ...(fromName ? { from: fromName } : {}),
270
+ ...(fromId !== undefined ? { fromId } : {}),
271
+ ...(chatType ? { chatType } : {}),
272
+ };
250
273
  }
251
274
  }
252
275
  out.push({ updateId: Math.trunc(updateId), ...(message ? { message } : {}) });
@@ -277,7 +300,16 @@ function coerceRegistry(raw: unknown, now: number): TelegramRegistryFile {
277
300
  typeof source.createdAt === "string" && Number.isFinite(Date.parse(source.createdAt))
278
301
  ? source.createdAt
279
302
  : isoTime(now);
280
- chats.push({ chatId: Math.trunc(source.chatId), sessionId: source.sessionId, createdAt });
303
+ const boundFromId =
304
+ typeof source.boundFromId === "number" && Number.isFinite(source.boundFromId)
305
+ ? Math.trunc(source.boundFromId)
306
+ : undefined;
307
+ chats.push({
308
+ chatId: Math.trunc(source.chatId),
309
+ sessionId: source.sessionId,
310
+ createdAt,
311
+ ...(boundFromId !== undefined ? { boundFromId } : {}),
312
+ });
281
313
  }
282
314
  }
283
315
 
@@ -663,7 +695,13 @@ export class TelegramBridge {
663
695
  draft.offset = Math.max(draft.offset, update.updateId + 1);
664
696
  });
665
697
  if (!update.message) return; // non-message or non-text: acknowledged, ignored
666
- await this.dispatch(update.message.chatId, update.message.from, update.message.text);
698
+ await this.dispatch(
699
+ update.message.chatId,
700
+ update.message.from,
701
+ update.message.text,
702
+ update.message.fromId,
703
+ update.message.chatType,
704
+ );
667
705
  }
668
706
 
669
707
  /**
@@ -671,7 +709,13 @@ export class TelegramBridge {
671
709
  * is plain text — including unknown `/words`, which the bound agent can
672
710
  * answer better than a canned "unknown command".
673
711
  */
674
- private async dispatch(chatId: number, _from: string | undefined, rawText: string): Promise<void> {
712
+ private async dispatch(
713
+ chatId: number,
714
+ _from: string | undefined,
715
+ rawText: string,
716
+ fromId?: number,
717
+ chatType?: string,
718
+ ): Promise<void> {
675
719
  const text = rawText.trim();
676
720
  const lower = text.toLowerCase();
677
721
 
@@ -679,20 +723,27 @@ export class TelegramBridge {
679
723
  await this.reply(chatId, CHAT_HELP);
680
724
  return;
681
725
  }
726
+ const binding = this.bindingOf(chatId);
727
+ // Audit run-1 (sender binding): a chat container is not a principal — every
728
+ // member of a group shares one chatId, including members added after the
729
+ // bind. When the binding pinned the /start sender's stable id, only that
730
+ // sender may act on it; anyone else's messages are dropped like a
731
+ // stranger's (they learn nothing and change nothing).
732
+ const senderAllowed = binding?.boundFromId === undefined || binding.boundFromId === fromId;
733
+ if (!senderAllowed) return;
682
734
  if (lower === "/stop") {
683
735
  await this.commit((draft) => {
684
- draft.chats = draft.chats.filter((binding) => binding.chatId !== chatId);
736
+ draft.chats = draft.chats.filter((row) => row.chatId !== chatId);
685
737
  });
686
738
  await this.reply(chatId, "unbound");
687
739
  return;
688
740
  }
689
741
  if (lower === "/status") {
690
- const binding = this.bindingOf(chatId);
691
742
  await this.reply(chatId, binding ? this.sessionNameOf(binding.sessionId) : "not bound");
692
743
  return;
693
744
  }
694
745
  if (lower === "/start" || lower.startsWith("/start ")) {
695
- await this.cmdStart(chatId, text);
746
+ await this.cmdStart(chatId, text, fromId, chatType);
696
747
  return;
697
748
  }
698
749
  if (lower === "/session" || lower.startsWith("/session ")) {
@@ -700,7 +751,6 @@ export class TelegramBridge {
700
751
  return;
701
752
  }
702
753
 
703
- const binding = this.bindingOf(chatId);
704
754
  if (!binding) return; // unbound chat: drop silently — a stranger learns nothing
705
755
  try {
706
756
  const { submissionId } = await this.broker.sendToSession(binding.sessionId, text);
@@ -712,7 +762,23 @@ export class TelegramBridge {
712
762
  }
713
763
 
714
764
  /** `/start <code>`: single-use, 10-minute code → bind this chat to the code's session. */
715
- private async cmdStart(chatId: number, text: string): Promise<void> {
765
+ private async cmdStart(
766
+ chatId: number,
767
+ text: string,
768
+ fromId: number | undefined,
769
+ chatType: string | undefined,
770
+ ): Promise<void> {
771
+ // Audit run-1 (chat-type gate): a non-private chat id is shared by every
772
+ // current and future member — binding it would hand all of them the
773
+ // operator's agent authority. Refuse; the operator binds from their own
774
+ // private chat with the bot.
775
+ if (chatType && chatType !== "private") {
776
+ await this.reply(
777
+ chatId,
778
+ "this is not a private chat — every member would inherit the binding; run /start from a private chat with the bot",
779
+ );
780
+ return;
781
+ }
716
782
  const code = text.slice("/start".length).trim().toLowerCase();
717
783
  const now = this.now();
718
784
  const hit = CODE_PATTERN.test(code) ? this.codes.find((row) => row.code === code && Date.parse(row.expiresAt) > now) : undefined;
@@ -725,7 +791,13 @@ export class TelegramBridge {
725
791
  draft.codes = draft.codes.filter((row) => row.code !== code); // single use, spent now
726
792
  draft.chats = [
727
793
  ...draft.chats.filter((binding) => binding.chatId !== chatId),
728
- { chatId, sessionId, createdAt: isoTime(now) },
794
+ {
795
+ chatId,
796
+ sessionId,
797
+ createdAt: isoTime(now),
798
+ // Pin the ceremony sender (audit run-1): stable id, not the mutable username.
799
+ ...(fromId !== undefined ? { boundFromId: fromId } : {}),
800
+ },
729
801
  ];
730
802
  });
731
803
  await this.reply(chatId, `bound to ${this.sessionNameOf(sessionId)}`);
@@ -757,6 +757,11 @@ export class DeviceConnector {
757
757
  // Small responses ride one frame; large ones chunk (hub reassembles).
758
758
  // Textual bodies keep the legacy UTF-8 string envelope; binaries are
759
759
  // base64-flagged so the hub can serve bytes byte-exact (R8 export).
760
+ // R13 (R9-6.3 FE): the device's idempotency replay verdict rides the
761
+ // envelope as an optional literal — old hubs ignore it (rest-response
762
+ // is de-Strict by design), new hubs surface the header so clients can
763
+ // tell a replay from a fresh create.
764
+ const replayed = res.headers.get("idempotent-replay") === "true" ? { idempotentReplay: true } : {};
760
765
  const envelope = textual
761
766
  ? ({
762
767
  type: "rest-response",
@@ -764,6 +769,7 @@ export class DeviceConnector {
764
769
  status: res.status,
765
770
  contentType: resCt,
766
771
  body: read.bytes.toString("utf8"),
772
+ ...replayed,
767
773
  } as const)
768
774
  : ({
769
775
  type: "rest-response",
@@ -773,6 +779,7 @@ export class DeviceConnector {
773
779
  body: read.bytes.toString("base64"),
774
780
  bodyEncoding: "base64",
775
781
  contentDisposition: safeHeaderValue(res.headers.get("content-disposition")),
782
+ ...replayed,
776
783
  } as const);
777
784
  const serialized = JSON.stringify(envelope);
778
785
  if (Buffer.byteLength(serialized, "utf8") <= INLINE_FRAME_MAX_BYTES) {