iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

MCP client: a credential's header is a secret alone, a renewal never comes after the lapse, and a follow-up has one end

Three faults from the reviewer's read of pull #12: a header that names one
secret and writes another out passed the check; a renewal's second try
could run after the grant's lapse and subscribe anew; and the last try's
claim could write a second end beside the try's own.

Tests: none
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

Jonas Templestein, 2026-11-26 17:28 UTC · 094983d1dd4f7f1e06881ae5f342c69782fc71c2 · parent 6e19dc2

4 files changed

M core/lib/src/api.ts
@@ -1117,7 +1117,8 @@
 }
 
 /** `connectToMcp`'s options: headers every request carries (`getSecret(…)` placeholders substitute
- *  at egress). A CREDENTIAL NAMES A SECRET: `{ authorization: 'Bearer getSecret("/secrets/x")' }`.
+ *  at egress). A CREDENTIAL NAMES A SECRET, AND NOTHING BESIDE IT:
+ *  `{ authorization: 'Bearer getSecret("/secrets/x")' }`, and each pair of a `cookie` likewise.
  *  A connection with a credential that is written out, in a header or in its address, works for
  *  one script, and the context follows nothing up for it: a subscription is not renewed
  *  (`McpSubscription.notRenewed`), and the connection declares no MCP tasks, so a tool call is
@@ -1316,8 +1317,10 @@
    *  (`itx.schedules.list()`, key `["mcp-subscription", …]`) runs a script that subscribes again
    *  after two thirds of each grant, with the cursor of the grant before. When that script fails
    *  twice, two minutes apart, nothing renews the subscription any more, and this context gets
-   *  `events.iterate.com/mcp/subscription-ended` `{ server, name, arguments, error }`: subscribe
-   *  again to go on. A GRANT THAT THE CONTEXT DOES NOT RENEW says so in `notRenewed`: one that is
+   *  `events.iterate.com/mcp/subscription-ended` `{ server, name, arguments, error }`, once:
+   *  subscribe again to go on. It tries once when a second try would come after the grant's
+   *  lapse, and a renewal that begins after the lapse subscribes nothing and says that the grant
+   *  lapsed. A GRANT THAT THE CONTEXT DOES NOT RENEW says so in `notRenewed`: one that is
    *  over within two minutes, the soonest a context renews, and one of a connection with a
    *  credential that is written out (`McpConnectOptions`). When a renewal gets such a grant, the
    *  context gets `mcp/subscription-ended` too. `cursor`: where delivery begins, for a
M core/mind-worker/src/library/mcp-events.test.ts
@@ -102,8 +102,12 @@
             call: ["subscribe", "pet.adopted", { species: "beagle" }, { cursor: "7" }],
             failed: {
               type: "events.iterate.com/mcp/subscription-ended",
+              // the subscription and the moment of this renewal's setting: one end for it
+              idempotencyKey: `mcp/subscription-ended:${key[1]}:${String(NOW)}`,
               payload: { server: SHOP, name: "pet.adopted", arguments: { species: "beagle" } },
             },
+            // the grant's own end: no try of the renewal subscribes after it
+            lapsesAt: NOW + HOUR_MS,
           }),
         },
       },
@@ -168,7 +172,31 @@
   { url: SHOP, headers: { "accept-language": "en", "x-tenant": "acme" }, why: null },
   { url: `${SHOP}?api_key=getSecret("/secrets/shop")`, headers: {}, why: null },
   { url: `${SHOP}?page=2`, headers: {}, why: null },
+  {
+    url: SHOP,
+    headers: { cookie: 'a=getSecret("/secrets/a"); b=getSecret("/secrets/b", { field: "sid" })' },
+    why: null,
+  },
+  {
+    url: SHOP,
+    headers: { authorization: `Basic ${btoa('shop:getSecret("/secrets/shop")')}` },
+    why: null,
+  },
   { url: SHOP, headers: { Cookie: "sid=abc" }, why: 'header "Cookie"' },
+  // one secret by name beside one that is written out: the header as a whole is not a reference
+  {
+    url: SHOP,
+    headers: { Cookie: 'a=getSecret("/secrets/a"); sid=abc' },
+    why: 'header "Cookie"',
+  },
+  {
+    url: SHOP,
+    headers: { authorization: 'Bearer abc getSecret("/secrets/shop")' },
+    why: 'header "authorization"',
+  },
+  { url: SHOP, headers: { authorization: `Basic ${btoa("shop:hunter2")}` }, why: 'header "authorization"' },
+  { url: SHOP, headers: { "x-api-key": 'k-getSecret("/secrets/shop")' }, why: 'header "x-api-key"' },
+  { url: `${SHOP}?token=abcgetSecret("/secrets/shop")`, headers: {}, why: 'address\'s parameter "token"' },
   { url: `${SHOP}?api_key=abc`, headers: {}, why: 'address\'s parameter "api_key"' },
   { url: "https://shop:hunter2@petshop.test/mcp", headers: {}, why: "address's password" },
 ])("whyNoFollowUp of $url with $headers names $why", ({ url, headers, why }) => {
@@ -227,39 +255,87 @@
   );
   expect(context.sent.filter(({ method }) => method === "events/subscribe")).toHaveLength(3);
   // the fact names the subscription and the server's own reason, once
-  const ended = {
-    type: "events.iterate.com/mcp/subscription-ended",
-    payload: { server: SHOP, name: "pet.adopted", arguments: { species: "beagle" } },
-  };
-  expect(context.appended).toEqual([
+  const ended = [
     {
-      ...ended,
+      type: "events.iterate.com/mcp/subscription-ended",
+      idempotencyKey: expect.stringMatching(/^mcp\/subscription-ended:[0-9a-f]{32}:\d+$/),
       payload: {
-        ...ended.payload,
+        server: SHOP,
+        name: "pet.adopted",
+        arguments: { species: "beagle" },
         error: expect.stringContaining("Forbidden: access was revoked"),
       },
     },
-  ]);
-  // the last claim would have said so by itself after eleven minutes; the script took it away,
-  // and nothing subscribes again
-  expect(context.schedules.slice(2)).toEqual([
+  ];
+  expect(context.appended).toEqual(ended);
+  // the last claim is a script that would have said so by itself after eleven minutes; the try
+  // took it away, and nothing subscribes again
+  expect(context.schedules.slice(2)).toMatchObject([
     {
       set: {
         key,
         when: { afterMs: 11 * 60_000 },
-        events: [
-          {
-            ...ended,
-            payload: { ...ended.payload, error: "the last try of the follow-up did not end" },
-          },
-        ],
+        events: [{ type: "events.iterate.com/itx/run-requested" }],
       },
     },
     { cancel: key },
   ]);
+  // ONE END FOR ONE FOLLOW-UP: had the claim stayed and fired, its script writes under the same
+  // key, and the log keeps the end that the try wrote
+  await context.runScheduled(context.schedules[2]);
+  expect(context.appended).toEqual(ended);
   await mcp.close();
 });
 
+test("a renewal with no time for a second try before the grant lapses tries once", async () => {
+  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
+  onTestFinished(() => void vi.useRealTimers());
+  const context = contextOfFake({ grantMs: 3 * 60_000 });
+  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
+  await mcp.subscribe("pet.adopted");
+  const [first] = context.schedules;
+  expect(first).toMatchObject({ set: { when: { afterMs: 2 * 60_000 } } });
+  // two minutes on, with one minute of the grant left: a second try would come after the lapse
+  vi.setSystemTime(NOW + 2 * 60_000);
+  context.refuse("the shop is closed");
+  await expect(context.runScheduled(first)).rejects.toThrow("the shop is closed");
+  expect(context.appended).toMatchObject([
+    {
+      type: "events.iterate.com/mcp/subscription-ended",
+      payload: { name: "pet.adopted", error: expect.stringContaining("the shop is closed") },
+    },
+  ]);
+  // its claim was the end and not a second try, and the try took it away
+  expect(context.schedules.slice(1)).toMatchObject([
+    { set: { when: { afterMs: 11 * 60_000 } } },
+    { cancel: first?.set?.key },
+  ]);
+  await mcp.close();
+});
+
+test("a renewal that begins after the grant lapsed asks the server nothing, and tells the context", async () => {
+  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
+  onTestFinished(() => void vi.useRealTimers());
+  const context = contextOfFake({});
+  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
+  await mcp.subscribe("pet.adopted");
+  // the context was away: its schedule fires a minute after the hour's grant ended
+  vi.setSystemTime(NOW + HOUR_MS + 60_000);
+  expect(await context.runScheduled(context.schedules[0])).toBeNull();
+  expect(context.sent.filter(({ method }) => method === "events/subscribe")).toHaveLength(1);
+  expect(context.appended).toMatchObject([
+    {
+      type: "events.iterate.com/mcp/subscription-ended",
+      payload: {
+        name: "pet.adopted",
+        error: `the grant lapsed at ${new Date(NOW + HOUR_MS).toISOString()}, before a renewal ran`,
+      },
+    },
+  ]);
+  expect(context.schedules.at(-1)).toEqual({ cancel: context.schedules[0]?.set?.key });
+  await mcp.close();
+});
+
 test("a renewal on a context whose rules give its code no schedules tells the context at once", async () => {
   const context = contextOfFake({});
   const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
@@ -272,6 +348,7 @@
   expect(context.appended).toEqual([
     {
       type: "events.iterate.com/mcp/subscription-ended",
+      idempotencyKey: expect.stringMatching(/^mcp\/subscription-ended:[0-9a-f]{32}:\d+$/),
       payload: {
         server: SHOP,
         name: "pet.adopted",
@@ -501,7 +578,19 @@
   const sent: { method: string; name: string | null; params: unknown; capabilities: unknown }[] =
     [];
   const schedules: Scheduled[] = [];
-  const appended: unknown[] = [];
+  const appended: { idempotencyKey?: string }[] = [];
+  // as the log: a key that comes back with the same body writes nothing, and with another body
+  // it is refused
+  const append = async (event: { idempotencyKey?: string }) => {
+    const kept = appended.find(
+      (row) => event.idempotencyKey && row.idempotencyKey === event.idempotencyKey,
+    );
+    if (!kept) return void appended.push(event);
+    if (JSON.stringify(kept) !== JSON.stringify(event))
+      throw Object.assign(new Error(`${String(event.idempotencyKey)}: another body`), {
+        code: "IDEMPOTENCY_CONFLICT",
+      });
+  };
   // THE CONTEXT'S SCHEDULES, as the kernel keeps them: `schedules` is every `set` and `cancel` in
   // order, and a row's place is its offset. The schedule of a key stands while its newest row is
   // a `set` that has not fired. A receipt cancels the one definition that it names.
@@ -576,7 +665,7 @@
       return await script({
         connectToMcp: (server: string, options: { headers?: Record<string, string> }) =>
           connectToMcp(itx, server, options, webhook),
-        append: async (event: unknown) => void appended.push(event),
+        append,
         schedules: scheduleTable,
         // what the context's rules take from its own code, for a context that is held
         ...masked,
M core/mind-worker/src/library/mcp-tasks.test.ts
@@ -81,8 +81,12 @@
             call: ["followTask", follow],
             failed: {
               type: "events.iterate.com/mcp/task-settled",
+              // the key of the asking's one end, as `followTask` writes it
+              idempotencyKey: `mcp/task-settled:${key[1]}:${String(NOW)}`,
               payload: { server: SHOP, tool: "make_report", taskId: "task-1", status: "lost" },
             },
+            // a task has no end of its own that the mind knows
+            lapsesAt: null,
           }),
         },
       },
@@ -361,30 +365,68 @@
   // the second try, as the schedule fires it: its claim is the fact that it did not end
   await expect(context.runScheduled(context.schedules[1])).rejects.toThrow("the shop is closed");
   expect(context.sent.filter(({ method }) => method === "tasks/get")).toHaveLength(2);
-  const lost = {
-    type: "events.iterate.com/mcp/task-settled",
-    payload: { server: SHOP, tool: "make_report", taskId: "task-1", status: "lost" },
-  };
-  expect(context.appended).toEqual([
-    { ...lost, payload: { ...lost.payload, error: expect.stringContaining("the shop is closed") } },
-  ]);
-  // the last claim would have said so by itself after eleven minutes; the script took it away,
-  // and nothing asks again
-  expect(context.schedules.slice(2)).toEqual([
+  const lost = [
     {
+      type: "events.iterate.com/mcp/task-settled",
+      // the key that a `followTask` of this asking writes its end under
+      idempotencyKey: expect.stringMatching(/^mcp\/task-settled:[0-9a-f]{32}:\d+$/),
+      payload: {
+        server: SHOP,
+        tool: "make_report",
+        taskId: "task-1",
+        status: "lost",
+        error: expect.stringContaining("the shop is closed"),
+      },
+    },
+  ];
+  expect(context.appended).toEqual(lost);
+  // the last claim is a script that would have said so by itself after eleven minutes; the try
+  // took it away, and nothing asks again
+  expect(context.schedules.slice(2)).toMatchObject([
+    {
       set: {
         key,
         when: { afterMs: 11 * 60_000 },
-        events: [
-          { ...lost, payload: { ...lost.payload, error: "the last try of the follow-up did not end" } },
-        ],
+        events: [{ type: "events.iterate.com/itx/run-requested" }],
       },
     },
     { cancel: key },
   ]);
+  // ONE END FOR ONE ASKING: had the claim stayed and fired, its script writes under the same key,
+  // and the log keeps the end that the try wrote
+  await context.runScheduled(context.schedules[2]);
+  expect(context.appended).toEqual(lost);
   await mcp.close();
 });
 
+test("the end that a last claim writes by itself does not stand beside a task's end", async () => {
+  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
+  onTestFinished(() => void vi.useRealTimers());
+  const context = contextOfFake();
+  const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
+  await mcp.callTool("make_report");
+  context.state("unreachable");
+  await expect(context.runScheduled(context.schedules[0])).rejects.toThrow("the shop is closed");
+  // the second try finds the end, and writes it under the asking's key
+  context.state({ ...WORKING, status: "completed", result: REPORT });
+  expect(await context.runScheduled(context.schedules[1])).toEqual({
+    taskId: "task-1",
+    status: "completed",
+  });
+  const completed = [
+    {
+      idempotencyKey: expect.stringMatching(new RegExp(`^mcp/task-settled:[0-9a-f]{32}:${String(NOW)}$`)),
+      payload: { status: "completed", result: REPORT },
+    },
+  ];
+  expect(context.appended).toMatchObject(completed);
+  // its claim, had it stayed: the script's "lost" has the same key, so the log refuses it
+  await context.runScheduled(context.schedules[2]);
+  expect(context.appended).toHaveLength(1);
+  expect(context.appended).toMatchObject(completed);
+  await mcp.close();
+});
+
 const noWebhook = () => Promise.reject(new Error("no webhook in this test"));
 
 type Scheduled = { set?: { key: unknown; when: unknown; events: unknown[] }; cancel?: unknown };
@@ -425,7 +467,19 @@
     [];
   const schedules: Scheduled[] = [];
   const fired = new Set<Scheduled | undefined>();
-  const appended: unknown[] = [];
+  const appended: { idempotencyKey?: string }[] = [];
+  // as the log: a key that comes back with the same body writes nothing, and with another body
+  // it is refused
+  const append = async (event: { idempotencyKey?: string }) => {
+    const kept = appended.find(
+      (row) => event.idempotencyKey && row.idempotencyKey === event.idempotencyKey,
+    );
+    if (!kept) return void appended.push(event);
+    if (JSON.stringify(kept) !== JSON.stringify(event))
+      throw Object.assign(new Error(`${String(event.idempotencyKey)}: another body`), {
+        code: "IDEMPOTENCY_CONFLICT",
+      });
+  };
   // THE CONTEXT'S SCHEDULES, as the kernel keeps them: `schedules` is every `set` and `cancel` in
   // order, and a row's place is its offset. The schedule of a key stands while its newest row is
   // a `set` that has not fired. A receipt cancels the one definition that it names.
@@ -496,7 +550,7 @@
     },
     builtins: {
       schedules: scheduleTable,
-      append: async (event: unknown) => void appended.push(event),
+      append,
     },
     // the cast: the connection uses `fetch`, its schedules and `append` alone of a context's itx
   } as unknown as LibraryItx;
@@ -518,7 +572,7 @@
       return await script({
         connectToMcp: (server: string, options: { headers?: Record<string, string> }) =>
           connectToMcp(itx, server, options, noWebhook),
-        append: async (event: unknown) => void appended.push(event),
+        append,
         schedules: scheduleTable,
       });
     },
M core/mind-worker/src/library/mcp.ts
@@ -5,7 +5,7 @@
 import type { McpConnectionApi, McpConnectOptions, McpServerInfo } from "iterate/api";
 import { keySortedForPrint } from "iterate/expression";
 import { bytesToBase64, STEP_FORGIVEN_EVERY_MS } from "iterate/lib";
-import { headerNamesASecret, secretPathsIn } from "iterate/secret-placeholder";
+import { basicCredentialOf, SECRET_PLACEHOLDER } from "iterate/secret-placeholder";
 import { RUN_DEADLINE_MS } from "iterate/stream/run";
 import { sha256Hex, type LibraryItx } from "core-itx";
 import { subclassWithMethods } from "./connection.ts";
@@ -310,8 +310,11 @@
               call: ["followTask", follow],
               failed: {
                 type: "events.iterate.com/mcp/task-settled",
+                // the key of the asking's one end, as `followTask` writes it
+                idempotencyKey: `mcp/task-settled:${key[1]}:${String(follow.since)}`,
                 payload: { server: this.#server, tool, taskId, status: "lost" },
               },
+              lapsesAt: null,
             }),
           },
         },
@@ -503,8 +506,11 @@
               ],
               failed: {
                 type: "events.iterate.com/mcp/subscription-ended",
+                // one end for this renewal, whoever writes it: the moment names the renewal
+                idempotencyKey: `mcp/subscription-ended:${key[1]}:${String(Date.now())}`,
                 payload: { server: this.#server, ...subscribed },
               },
+              lapsesAt: Date.parse(subscription.refreshBefore),
             }),
           },
         },
@@ -599,15 +605,15 @@
 export function whyNoFollowUp(url: string, options: McpConnectOptions): string | null {
   const address = new URL(url);
   const header = Object.entries(options.headers || {}).find(
-    ([name, value]) => CREDENTIAL_NAME.test(name) && !headerNamesASecret(value),
+    ([name, value]) => CREDENTIAL_NAME.test(name) && !headerIsASecretAlone(name, value),
   )?.[0];
   const parameter = [...address.searchParams].find(
-    ([name, value]) => CREDENTIAL_NAME.test(name) && !secretPathsIn(value).length,
+    ([name, value]) => CREDENTIAL_NAME.test(name) && !ONE_SECRET.test(value),
   )?.[0];
   const what =
     header !== undefined
       ? `header ${JSON.stringify(header)}`
-      : address.password && !secretPathsIn(decodeURIComponent(address.password)).length
+      : address.password && !ONE_SECRET.test(decodeURIComponent(address.password))
         ? "address's password"
         : parameter !== undefined
           ? `address's parameter ${JSON.stringify(parameter)}`
@@ -619,6 +625,22 @@
 }
 /** The name of a header or of an address's parameter that carries a credential. */
 const CREDENTIAL_NAME = /auth|cookie|key|token|secret|passw|credential|session|signature/i;
+/** One placeholder of a secret, and nothing beside it. */
+const ONE_SECRET = new RegExp(`^(?:${SECRET_PLACEHOLDER.source})$`);
+/** WHETHER A CREDENTIAL'S HEADER HOLDS SECRETS BY NAME ALONE. A header that names one secret and
+ *  writes another out would leave the second in the script. So: each pair of a `cookie` is one
+ *  placeholder; the password of a `Basic` credential is one; and any other value is one, after
+ *  the word of its scheme at most (`Bearer`). */
+function headerIsASecretAlone(name: string, value: string) {
+  if (name.toLowerCase() === "cookie")
+    return value
+      .split(";")
+      .filter((pair) => pair.trim())
+      .every((pair) => ONE_SECRET.test(pair.slice(pair.indexOf("=") + 1).trim()));
+  const basic = basicCredentialOf(value);
+  if (basic !== null) return ONE_SECRET.test(basic.slice(basic.indexOf(":") + 1));
+  return ONE_SECRET.test(value.trim().replace(/^[A-Za-z][A-Za-z-]{0,15}\s+/, ""));
+}
 
 /** THE SCRIPT OF A FOLLOW-UP, which a schedule of the context runs as that context's own code. It
  *  connects as the connection did and calls one method of it (`call`): `subscribe`, to renew a
@@ -627,42 +649,60 @@
  *
  *  IT TRIES TWICE, AND EACH TRY BEGINS WITH A CLAIM: the script sets the follow-up's schedule
  *  (`key`) again, to what happens when this try does not end. For the first try that is the
- *  second try, two minutes on. For the second try it is the event `failed`. So the follow-up's
- *  schedule stands while a try runs: `unsubscribe`, or the end of a task, takes it away, and the
- *  try then sets no schedule and writes no end (`#holds`). A script that dies is no silence
- *  either. The claim's offset goes to the method as `claim`, in its last argument. So the script
- *  needs `itx.schedules` of its context, beside `itx.connectToMcp` and `itx.append`: a context
- *  whose rules give its code no schedules is told with the event `failed` at the first try.
+ *  second try, two minutes on. For the last try it is a script that writes the event `failed`.
+ *  So the follow-up's schedule stands while a try runs: `unsubscribe`, or the end of a task,
+ *  takes it away, and the try then sets no schedule and writes no end (`#holds`). A script that
+ *  dies is no silence either. The claim's offset goes to the method as `claim`, in its last
+ *  argument. So the script needs `itx.schedules` of its context, beside `itx.connectToMcp` and
+ *  `itx.append`: a context whose rules give its code no schedules is told with the event
+ *  `failed` at the first try.
  *
- *  When both tries fail nothing follows up any more, and the script tells the context with the
- *  event `failed`, to whose payload it adds the error's text. It tells the context the same way
- *  when a renewal's grant is one that the context does not renew (`notRenewed`). The values go in
- *  as JSON text, so no value is read as code. */
+ *  A TRY IS THE LAST WHEN A SECOND ONE WOULD COME TOO LATE. `lapsesAt` is when what is followed
+ *  ends by itself: a subscription's grant. A second try at or after it would subscribe anew and
+ *  call that a renewal, with a gap that nobody sees. So a first try with less than two minutes
+ *  left is the last, and a try that begins after the lapse asks the server nothing and tells the
+ *  context that the grant lapsed.
+ *
+ *  ONE END FOR ONE FOLLOW-UP. When the last try fails nothing follows up any more, and the
+ *  script tells the context with the event `failed`, to whose payload it adds the error's text.
+ *  It tells the context the same way when a renewal's grant is one that the context does not
+ *  renew (`notRenewed`). Every writer of that end uses `failed.idempotencyKey`: the script, the
+ *  claim of the last try, and `followTask` for a task's end. So the log keeps one end, also
+ *  when a try wrote it and could not take its claim away. The values go in as JSON text, so no
+ *  value is read as code. */
 export function followUpScript(followUp: {
   server: string;
   options: McpConnectOptions;
   key: [string, string];
   call: [method: "subscribe" | "followTask", ...args: unknown[]];
-  failed: { type: string; payload: Record<string, unknown> };
+  failed: { type: string; idempotencyKey: string; payload: Record<string, unknown> };
+  lapsesAt: number | null;
 }) {
+  const { failed } = followUp;
+  // a second end under the key is refused by the log: that is the purpose, and no failure
+  const once = '.catch((failure) => { if (!failure || failure.code !== "IDEMPOTENCY_CONFLICT") throw failure; })';
+  // what the last try's claim runs when the try did not end
+  const unended = [
+    "async (itx) => {",
+    `  await itx.append(JSON.parse(${JSON.stringify(JSON.stringify({ ...failed, payload: { ...failed.payload, error: "the last try of the follow-up did not end" } }))}))${once};`,
+    "}",
+  ].join("\n");
   const aTry = (retry: string | null) =>
     [
       "async (itx) => {",
-      `  const { server, options, key, call: [method, ...args], failed, retry } = JSON.parse(${JSON.stringify(JSON.stringify({ ...followUp, retry }))});`,
+      `  const { server, options, key, call: [method, ...args], failed, lapsesAt, retry, unended } = JSON.parse(${JSON.stringify(JSON.stringify({ ...followUp, retry, unended }))});`,
       "  const words = (failure) => String((failure && failure.message) || failure).slice(0, 1000);",
+      `  const tell = (error) => itx.append({ ...failed, payload: { ...failed.payload, error } })${once};`,
+      "  const lapsed = lapsesAt !== null && Date.now() >= lapsesAt;",
+      `  const last = !retry || (lapsesAt !== null && Date.now() + ${String(MCP_FOLLOW_UP_SECOND_TRY_MS)} >= lapsesAt);`,
       "  const claim = await itx.schedules",
       "    .set({",
       "      key,",
-      `      when: { afterMs: retry ? ${String(MCP_FOLLOW_UP_SECOND_TRY_MS)} : ${String(MCP_FOLLOW_UP_UNENDED_MS)} },`,
-      "      events: [",
-      "        retry",
-      '          ? { type: "events.iterate.com/itx/run-requested", payload: { code: retry } }',
-      '          : { type: failed.type, payload: { ...failed.payload, error: "the last try of the follow-up did not end" } },',
-      "      ],",
+      `      when: { afterMs: last ? ${String(MCP_FOLLOW_UP_UNENDED_MS)} : ${String(MCP_FOLLOW_UP_SECOND_TRY_MS)} },`,
+      '      events: [{ type: "events.iterate.com/itx/run-requested", payload: { code: last ? unended : retry } }],',
       "    })",
       "    .catch(async (failure) => {",
-      '      const error = "the follow-up could not hold its schedule: " + words(failure);',
-      "      await itx.append({ type: failed.type, payload: { ...failed.payload, error } });",
+      '      await tell("the follow-up could not hold its schedule: " + words(failure));',
       "      throw failure;",
       "    });",
       "  const held = async () => {",
@@ -671,17 +711,21 @@
       "  };",
       "  const end = async (error) => {",
       "    if (!(await held())) return;",
-      "    await itx.append({ type: failed.type, payload: { ...failed.payload, error } });",
+      "    await tell(error);",
       "    await itx.schedules.cancel(claim);",
       "  };",
+      "  if (lapsed) {",
+      '    await end("the grant lapsed at " + new Date(lapsesAt).toISOString() + ", before a renewal ran");',
+      "    return null;",
+      "  }",
       "  try {",
-      "    const last = args.pop();",
-      "    const answer = await (await itx.connectToMcp(server, options))[method](...args, { ...last, claim: claim.scheduledAtOffset });",
+      "    const given = args.pop();",
+      "    const answer = await (await itx.connectToMcp(server, options))[method](...args, { ...given, claim: claim.scheduledAtOffset });",
       "    if (answer && answer.notRenewed) await end(words(answer.notRenewed));",
       "    else if (await held()) await itx.schedules.cancel(claim);",
       "    return answer;",
       "  } catch (failure) {",
-      "    if (!retry) await end(words(failure));",
+      "    if (last) await end(words(failure));",
       "    throw failure;",
       "  }",
       "}",