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 (#13)

Three more faults that `/agents/reviewer` found, in its read of pull #12 (kernel `68f727b`). The fourth of that read is not fixed here: it needs a change to the kernel's schedules, which is the owner's decision (below).

## What was wrong, and what this does

| The reviewer's finding | Before | Now |
| --- | --- | --- |
| "A Cookie header with one vault-backed value and one literal session value passes the check: it only asks whether the header names any secret." | A credential's header was fine when it named any secret. | It must be a secret alone (`headerIsASecretAlone`): 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`). A password or a credential's parameter in the address is one placeholder. Anything else is a credential that is written out, and the connection gets no follow-up. |
| "With a three-minute grant, the first renewal runs at two minutes; if it fails, the next attempt runs at four minutes and can silently replace the expired subscription." | The second try came two minutes on, whatever was left of the grant. | The follow-up's script knows when the grant lapses (`lapsesAt`). A try with less than two minutes left is the last: when it fails, the context gets `mcp/subscription-ended` with the server's reason, before the lapse. A try that begins after the lapse asks the server nothing and tells the context that the grant lapsed. |
| "The watchdog and direct terminal writes do not share a key. If a direct write lands but cancellation does not, the queued watchdog can land a second notice and start a second turn." | The last try's claim was the end fact itself, which a schedule appends with no key. | Every writer of a follow-up's end uses one idempotency key: the script, the claim of the last try (now a script that appends under that key), and `followTask` for a task's end. The log keeps one end for one follow-up. A second writer's append is refused, and it takes that as done. |

## Not fixed here: `unsubscribe` is not yet final

The reviewer: "A fired job can claim its key after unsubscribe's last check, or a checked renewal can write its next schedule after cancellation. [โ€ฆ] Keep a cancellation generation across dispatch and make the next write conditional on it."

That is right, and a library cannot do it with the schedules as they are:

- A one-shot schedule is gone from the moment it fires until its script sets it again. An `unsubscribe` in that moment finds nothing to cancel, and nothing durable says that it ran.
- `schedules.set` has no condition. A renewal that checks its claim and then sets the next renewal makes two calls.

What it needs is one of these, and each is a change of its own:

1. **A conditional `set` in the kernel's schedules** (my recommendation): `set(input, { replaces: receipt })`, refused when the key's schedule is no more the one that the receipt names, and a firing that keeps its key until its run's first `set`. Then a renewal's every write is atomic against `unsubscribe`. It is a small change to `core/itx`, and it is a change to the kernel proper, so a person decides it.
2. **A second schedule that only says "this context holds the subscription"**, which `unsubscribe` cancels first and every renewal checks after each write. It is correct, and it is a schedule that never fires, kept as a flag.

How large the gap is: an `unsubscribe` must fall into the moment between a renewal's firing and its first statement, or between its check and its write. A renewal runs once in two thirds of a grant (forty minutes for a grant of an hour). What it costs: the subscription is renewed again, and its events keep landing on the context's log. They start no turn (`/repos/stdlib` tells an agent no `mcp/webhook-received`). `itx.schedules.list()` shows the renewal, and a second `unsubscribe` ends it.

## Risk map

- **The stricter rule can refuse a header that was fine.** A `cookie` with a pair that is no secret (a locale) now costs the follow-up, since the rule cannot tell that pair from a session. The reason names the header. A header with a scheme word of more than sixteen letters, or with two words before the placeholder, is refused too.
- **A renewal that begins after the lapse subscribes no more.** Before, it subscribed again and went on. Now the context gets `mcp/subscription-ended`, and an agent that wants the events subscribes again (the fact starts its turn in a new mind). A context that slept through a lapse loses its subscription rather than getting a new one with a gap.
- **The last claim is a script run now**, not a plain event: one more thing that needs `itx.append` of its context. It appends one event or nothing.
- The key of a renewal's end has the moment of the renewal's setting in it. Two renewals of one subscription that are set in the same millisecond would share it.

On merge: nothing changes until the stack is deployed.

## Tests

- `mcp-events.test.ts`, 37 (was 28): `whyNoFollowUp` in sixteen rows, among them a cookie with one secret and one session, a second word beside a placeholder, a `Basic` credential with a written password and one with a secret, and a literal glued to a placeholder; a renewal with no time for a second try tries once; a renewal that begins after the lapse asks nothing and tells the context; the last claim's own script writes no second end.
- `mcp-tasks.test.ts`, 25 (was 24): the last claim's script writes no second end after `lost`, and none beside `completed`.
- `mcp-in-workerd.test.ts`, 2, unchanged: both pass with the new script on the real kernel.

## Checks

On Beelink, 26 Nov 2026, 17:28 UTC, on main 6e19dc2 (this branch at 094983d): `tsc` passes for each of the nine packages. `core/mind-worker` passes 365 tests in 43 files. `core/lib` passes 1,091 tests in 58 files. Each run was one package's own. The tests of `core/itx`, `core/auth-worker`, `core/secrets-worker` and `core/boundary-worker` did not run: this changes no file of theirs.

Not proven on a deployed mind. The paths where a try fails ran against a model of the schedules and of the log's idempotency keys in Node, not on the real kernel.

## Review

`/agents/reviewer` has not read this pull. Jonas, 26 Nov 2026, 16:13:58 UTC, in the pane of the Beelink coordinator (session claude 34855f3c-e4fc-4f2f-ad6d-949ee9fb2704): "I'm okay to just like fast forward through the MCP stuff for example and just see where it lands and then fix it in, when it's in the core, in the kernel, in the template, in the iterate mind."

Session: claude 4ff1ee02-4607-4fba-9d52-d36073b41a7b on beelink

๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code)

Iterate-Run: /@618072

jonas, 2026-11-26 17:29 UTC ยท a653591e7c5ea05f4898805c8d01af62a1e768c5 ยท 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;",
       "  }",
       "}",