granttap-mcp 0.8.190 → 0.8.191

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.
Files changed (43) hide show
  1. package/README.md +4 -2
  2. package/apps/bridge/src/helper-runs/kinds.ts +1 -1
  3. package/apps/bridge/src/machine-load/README.md +3 -0
  4. package/apps/bridge/src/machine-load/host/process-sampler.ts +11 -0
  5. package/apps/bridge/src/monitor/support/runtime.ts +11 -4
  6. package/apps/bridge/src/paired-phones/README.md +4 -0
  7. package/apps/bridge/src/paired-phones/index.ts +2 -2
  8. package/apps/bridge/src/paired-phones/roster.ts +22 -0
  9. package/apps/bridge/src/reply/README.md +13 -0
  10. package/apps/bridge/src/reply/in-flight.ts +10 -4
  11. package/apps/bridge/src/reply/process/index.ts +9 -2
  12. package/apps/bridge/src/reply/run-watch.ts +176 -0
  13. package/apps/bridge/src/reply/survival/README.md +2 -1
  14. package/apps/bridge/src/runtime-updates/README.md +2 -0
  15. package/apps/bridge/src/sessions/scan/claude/parse.ts +4 -3
  16. package/apps/bridge/src/sessions/scan/codex/parse.ts +2 -1
  17. package/apps/bridge/src/started-by/README.md +62 -15
  18. package/apps/bridge/src/started-by/attach.ts +8 -3
  19. package/apps/bridge/src/started-by/facts.ts +19 -5
  20. package/apps/bridge/src/started-by/folders/index.ts +79 -0
  21. package/apps/bridge/src/started-by/folders/launches.ts +98 -0
  22. package/apps/bridge/src/started-by/headless.ts +24 -4
  23. package/apps/bridge/src/started-by/index.ts +2 -0
  24. package/apps/bridge/src/started-by/live/index.ts +133 -0
  25. package/apps/mcp/src/connection-center/README.md +38 -5
  26. package/apps/mcp/src/connection-center/{bridge.js → card/bridge.js} +26 -23
  27. package/apps/mcp/src/connection-center/card/card.css +187 -0
  28. package/apps/mcp/src/connection-center/card/phones-view.js +195 -0
  29. package/apps/mcp/src/connection-center/card/phones.js +145 -0
  30. package/apps/mcp/src/connection-center/card/view.js +210 -0
  31. package/apps/mcp/src/connection-center/card/widget.html +94 -0
  32. package/apps/mcp/src/connection-center/state.ts +5 -1
  33. package/apps/mcp/src/mcp-tools/README.md +2 -1
  34. package/apps/mcp/src/mcp-tools/connect/widget.ts +19 -6
  35. package/apps/mcp/src/mcp-tools/phones/index.ts +5 -2
  36. package/apps/mcp/src/mcp-tools/phones/removal.ts +6 -3
  37. package/apps/mcp/src/status/pairing-status.ts +24 -11
  38. package/cursor-plugin/README.md +1 -1
  39. package/cursor-plugin/mcp.json +1 -1
  40. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  41. package/package.json +1 -1
  42. package/apps/mcp/src/connection-center/view.js +0 -155
  43. package/apps/mcp/src/connection-center/widget.html +0 -51
package/README.md CHANGED
@@ -150,7 +150,9 @@ Every phone or iPad that scanned a QR for a computer keeps a key there until som
150
150
  debug installs pile up. In the app, **Devices → a computer → Phones** lists each phone with its name or label,
151
151
  **This iPhone**, and when it last reached the computer, and removes one (swipe or context menu), several, or
152
152
  every phone not seen for 30 days. Removing the phone in use is its own confirmed action, **Unpair this
153
- phone**, and the last phone always stays. A removed phone stops receiving from the computer at once, in every
153
+ phone**, and the last phone always stays. On the computer, the GrantTap connection card in Claude, Codex, Grok
154
+ Build or Cursor (`connection_status`) lists the same phones with **Remove** on each and **Remove N** for those
155
+ not seen for 30 days; a removal there is confirmed on the card and then with a yes on a phone (`remove_phones`). A removed phone stops receiving from the computer at once, in every
154
156
  running GrantTap process, without a restart; it needs a new QR to pair again. Removing the first pairing hands
155
157
  its place to the phone heard from most recently.
156
158
 
@@ -649,7 +651,7 @@ trust.
649
651
  | `connect_with_passkey` | Link this computer to the user's GrantTap account so a signed-in phone can connect without a QR; returns a 15-minute granttap.com link, the passkey is entered only there, and existing QR pairings stay unchanged |
650
652
  | `connect` | Show the existing pairing on the connection card, or on an unpaired computer create a one-time QR shown only on the card |
651
653
  | `reconnect` | After explicit confirmation, show a one-time QR to reconnect or add an independent controller device while retaining the current room |
652
- | `remove_phones` | Ask the person to remove paired phones that are no longer used, by `notSeenForDays` and/or `phoneIds` from `connection_status`; nothing is removed without a yes on a phone, and the phone that answers, any phone heard from while the question is open, and the last phone stay |
654
+ | `remove_phones` | Ask the person to remove paired phones that are no longer used, by `notSeenForDays` (never the phone heard from most recently; `connection_status` marks the 30-day ones `stale`) and/or `phoneIds` from `connection_status`; nothing is removed without a yes on a phone, and the phone that answers, any phone heard from while the question is open, and the last phone stay |
653
655
  | `notify` | Send a non-blocking status of at most 2,000 characters that nobody answers, and/or one task-scoped Mesh event |
654
656
  | `ask_yes_no` | Ask a yes/no question and wait about three minutes for the explicit answer; a timeout is neither yes nor no |
655
657
  | `ask` | Ask an open question and wait about three minutes for typed or spoken text |
@@ -125,7 +125,7 @@ function parentOf(folder: string): string | undefined {
125
125
  }
126
126
 
127
127
  /** Whether a folder lies inside a Git checkout: one of the folders above it holds `.git`. */
128
- function insideCheckout(folder: string): boolean {
128
+ export function insideCheckout(folder: string): boolean {
129
129
  let above = parentOf(folder);
130
130
  for (let depth = 0; above !== undefined && depth < 48; depth += 1) {
131
131
  if (existsSync(`${above === "/" ? "" : above}/.git`)) return true;
@@ -5,6 +5,9 @@ catalogs. `index.ts` assembles and publishes the bounded wire payload,
5
5
  `host/process-sampler.ts` owns agent ancestry, `host/ps-reader.ts` reads operating-system
6
6
  CPU time and RSS, `mcp/scan-cost.ts` retains provider discovery cost, and `host/loop.ts`
7
7
  runs a two-second active / thirty-second idle cadence from cached session status.
8
+ `captureStartedRunsNow` lists processes once for headless runs alone and reports
9
+ nothing; a new provider transcript asks for it, since a run a usage limit stops can
10
+ end between two samples ([chats started by another chat](../started-by/README.md)).
8
11
 
9
12
  `command-process/history.ts` hashes process command fingerprints and uses
10
13
  the provider's existing call/result timestamps to match one newly started
@@ -221,6 +221,17 @@ export function resetSessionResolver(read?: EnvironmentReader, now?: () => numbe
221
221
  resolveSessions = createSessionResolver(read, now);
222
222
  }
223
223
 
224
+ /**
225
+ * One listing for headless runs alone, nothing reported: a run a usage limit stops lives three or
226
+ * four seconds, so a new transcript asks for this at once (`started-by/live`).
227
+ */
228
+ export async function captureStartedRunsNow(): Promise<number> {
229
+ const rows = await sampleProcessRows();
230
+ const sampledAt = Date.now();
231
+ const sessions = await resolveSessions(rows);
232
+ return captureStartedRuns(startedRunProcesses(rows, attributeByAncestry(rows), sessions, sampledAt));
233
+ }
234
+
224
235
  export async function sampleAgentProcesses(): Promise<Record<string, AgentProcessLoad>> {
225
236
  const rows = await sampleProcessRows();
226
237
  const sampledAt = Date.now();
@@ -32,6 +32,8 @@ import { publishedCatalog, rememberPublishedCatalog, resumePublishedChats,
32
32
  publishCatalogHeads, stopCatalogHeads } from "../../session-catalog";
33
33
  import { createMachineLoadPublisher } from "../../machine-load";
34
34
  import { startMachineLoadLoop } from "../../machine-load/host/loop";
35
+ import { captureStartedRunsNow } from "../../machine-load/host/process-sampler";
36
+ import { watchHeadlessRuns } from "../../started-by";
35
37
  import { scanSessionHistoryCooperatively, scanSessionsCooperatively, TOKEN_WINDOW_HOURS } from "../../sessions";
36
38
  import { boundedCatalogHistory, INTERVAL_MS, publishSessionEvents } from "../handlers/catalog";
37
39
  import { sweepAttachments } from "../handlers/receipts";
@@ -353,18 +355,23 @@ function monitorLoadLoop(client: RelayClient, leadership: ReturnType<typeof moni
353
355
  const publishMachineLoad = createMachineLoadPublisher({
354
356
  log: (line) => process.stderr.write(`[monitor] ${line}\n`),
355
357
  });
356
- return startMachineLoadLoop({
358
+ // A headless run that lives seconds is looked at when its transcript appears, by the leader alone.
359
+ const runWatch = watchHeadlessRuns(captureStartedRunsNow);
360
+ const loop = startMachineLoadLoop({
357
361
  connected: () => client.isConnected,
358
362
  // Only the leader reports load. Every MCP server used to run this loop
359
363
  // too, each with the code of the day it started, and the phone flickered
360
364
  // between their answers.
361
- publish: (status, intervalMs) => (leadership.acquire()
362
- ? publishMachineLoad(client, status, intervalMs)
363
- : Promise.resolve(undefined)),
365
+ publish: (status, intervalMs) => {
366
+ if (!leadership.acquire()) { runWatch.stop(); return Promise.resolve(undefined); }
367
+ runWatch.start();
368
+ return publishMachineLoad(client, status, intervalMs);
369
+ },
364
370
  onError: (error) => {
365
371
  process.stderr.write(
366
372
  `[monitor] load report failed: ${error instanceof Error ? error.message : String(error)}\n`,
367
373
  );
368
374
  },
369
375
  });
376
+ return { ...loop, stop: () => { runWatch.stop(); loop.stop(); } };
370
377
  }
@@ -8,6 +8,10 @@ removing them, and the place a new phone takes when the computer is full.
8
8
  public key in hex, and `label`, the first six characters of the id; its key never leaves the computer. Names,
9
9
  last-seen and added-at times come from `presence.json`. Added-at is recorded only for keys added since phone
10
10
  management shipped, so older keys have none. An unscanned key whose QR expired is not accepted and is not listed.
11
+ `mostRecentPhone` is the phone heard from most recently (by last-seen, then latest activity, then roster order),
12
+ and `stalePhones(days)` the phones idle that long except that one: what `remove_phones` with `notSeenForDays`
13
+ and the connection card's "Remove phones not seen for 30 days" take, so the phone in use stays even when every
14
+ phone has been away.
11
15
  - `removal.ts` removes keys in one write under the `machine.json` lock, through the existing config writer.
12
16
  `controllerPeerGate` rereads `machine.json` before every send and every received message, so a removed phone
13
17
  stops receiving sealed broadcasts at once in every running process, the first pairing included. Removing the
@@ -1,6 +1,6 @@
1
1
  /** Public entry of the phones paired with this computer: listing, removal, and the place a new phone takes. */
2
- export { DAY_MS, EXTRA_PHONE_LIMIT, idleFor, lastActivity, longestIdle, phoneEntries, phoneId, phoneRoster,
3
- type PhoneRecord } from "./roster";
2
+ export { DAY_MS, EXTRA_PHONE_LIMIT, idleFor, lastActivity, longestIdle, mostRecentPhone, phoneEntries, phoneId,
3
+ phoneRoster, stalePhones, type PhoneRecord } from "./roster";
4
4
  export { LAST_PHONE, PhoneChangeRefused, removePhoneKeys, type PhoneRemoval } from "./removal";
5
5
  export { admitPhoneKey, EVICTION_IDLE_DAYS, evictionFor, PHONE_LIMIT_REACHED } from "./admission";
6
6
  export { isPhoneAction, phonesFor, planPhoneChange, type PhoneChangeOutcome, type PlannedPhoneChange }
@@ -66,6 +66,28 @@ export function idleFor(phone: PhoneRecord, days: number, now = Date.now()): boo
66
66
  return at == null || now - at >= days * DAY_MS;
67
67
  }
68
68
 
69
+ /**
70
+ * The phone heard from most recently: the one in use, or the likeliest to be. Without any last-seen time the
71
+ * latest activity decides, and among equals the earlier one in the roster (the first pairing first).
72
+ */
73
+ export function mostRecentPhone(phones: readonly PhoneRecord[]): PhoneRecord | undefined {
74
+ const rank = (phone: PhoneRecord): [number, number] => [phone.lastSeenAt ?? -1, lastActivity(phone) ?? -1];
75
+ return phones.reduce<PhoneRecord | undefined>((best, phone) => {
76
+ if (best === undefined) return phone;
77
+ const [seen, active] = rank(phone), [bestSeen, bestActive] = rank(best);
78
+ return seen > bestSeen || (seen === bestSeen && active > bestActive) ? phone : best;
79
+ }, undefined);
80
+ }
81
+
82
+ /**
83
+ * The phones a "not seen for `days`" removal takes: idle that long, and never the phone heard from most
84
+ * recently, so the phone in use stays even when every phone has been away.
85
+ */
86
+ export function stalePhones(phones: readonly PhoneRecord[], days: number, now = Date.now()): PhoneRecord[] {
87
+ const latest = mostRecentPhone(phones);
88
+ return phones.filter((phone) => phone !== latest && idleFor(phone, days, now));
89
+ }
90
+
69
91
  /** The longest idle first; unknown counts as oldest, and among equals the earlier-added phone goes first. */
70
92
  export function longestIdle(phones: readonly PhoneRecord[]): PhoneRecord | undefined {
71
93
  return phones.reduce<PhoneRecord | undefined>((oldest, phone) =>
@@ -15,6 +15,19 @@ A phone delivery's Claude, Codex or Grok run writes to files in a folder of its
15
15
  survives a monitor restart; the next monitor takes it over and sends its answer
16
16
  ([`survival/`](survival/README.md)).
17
17
 
18
+ `in-flight.ts` holds a chat's key until its run settles, which is when this monitor sees the provider
19
+ process end or at the run's deadline (six hours for a phone run). `run-watch.ts` watches the provider
20
+ processes started under each key (the key and any key around it, such as a moved Task's `transfer-…`
21
+ around its provider's new-task key) and looks at the process table once a minute while any run. A
22
+ runtime update stops counting a run (`blockingDeliveries`) whose process is gone, a zombie or its pid
23
+ reused for two minutes, whose process exited without the run ending for two minutes, whose work is still
24
+ pending ten minutes after its process ended, or whose process group wrote nothing and used under a second
25
+ of processor time a minute for thirty minutes. The monitor log says so once per run: `A runtime update no
26
+ longer waits for the run in chat … that started … min ago: <why>.` The run itself is left alone, and work
27
+ that never started a provider process, such as a Codex desktop delivery, is never judged. Before this a
28
+ moved Task's turn whose process went without its end being seen kept every update waiting until its
29
+ deadline. Tests: [`tests/run-watch/stalled-run.test.ts`](tests/run-watch/stalled-run.test.ts).
30
+
18
31
  On POSIX, a managed provider command owns a process group. Phone pause and
19
32
  timeouts signal that group, so local descendants that remain in it are also
20
33
  requested to stop. The stop count records accepted signals, not confirmed exit
@@ -1,4 +1,5 @@
1
1
  import type { ReplyResult } from "./payload/types";
2
+ import { forgetDelivery, stalledDelivery, withinDelivery } from "./run-watch";
2
3
  import { currentSurvivor, survivableKey } from "./survival";
3
4
 
4
5
  /**
@@ -20,11 +21,15 @@ export function hasPendingDeliveries(): boolean { return inFlight.size > 0; }
20
21
 
21
22
  /**
22
23
  * The keys whose work a newer monitor could not take over: anything but one run another monitor can
23
- * adopt, with nothing queued in memory behind it (`../survival`). Each with when its wait began.
24
+ * adopt, with nothing queued in memory behind it (`../survival`). Each with when its wait began. Work
25
+ * whose provider process is gone, or that showed no sign of work for long (`run-watch.ts`), is left out:
26
+ * it would hold the update until its deadline, hours away, and never ends in this monitor otherwise.
24
27
  */
25
- export function blockingDeliveries(survivable: (key: string) => boolean = survivableKey): Array<{ key: string; since: number }> {
28
+ export function blockingDeliveries(survivable: (key: string) => boolean = survivableKey,
29
+ stalled: (key: string, since: number) => string | undefined = stalledDelivery): Array<{ key: string; since: number }> {
26
30
  return [...inFlight.keys()].filter(key => !(depth.get(key) === 1 && survivable(key)))
27
- .map(key => ({ key, since: startedAt.get(key) ?? Date.now() }));
31
+ .map(key => ({ key, since: startedAt.get(key) ?? Date.now() }))
32
+ .filter(({ key, since }) => stalled(key, since) === undefined);
28
33
  }
29
34
 
30
35
  export function hasBlockingDeliveries(): boolean { return blockingDeliveries().length > 0; }
@@ -50,12 +55,13 @@ function enqueue(key: string, start: () => Promise<ReplyResult | null>, since =
50
55
  const previous = inFlight.get(key) ?? Promise.resolve(null);
51
56
  if (!inFlight.has(key)) startedAt.set(key, since);
52
57
  depth.set(key, (depth.get(key) ?? 0) + 1);
53
- const settled = previous.then(start).finally(() => {
58
+ const settled = previous.then(() => withinDelivery(key, start)).finally(() => {
54
59
  const left = (depth.get(key) ?? 1) - 1;
55
60
  if (left > 0) depth.set(key, left); else depth.delete(key);
56
61
  if (inFlight.get(key) !== tracked) return;
57
62
  inFlight.delete(key);
58
63
  startedAt.delete(key);
64
+ forgetDelivery(key);
59
65
  });
60
66
  const tracked = settled.catch(() => null);
61
67
  inFlight.set(key, tracked);
@@ -9,6 +9,7 @@ import { environmentProcessEnv, loadEnvironment } from "../../mesh/context/env";
9
9
  import type { ReplyResult } from "../payload/types";
10
10
  import { survivalEnabled, type RunParser } from "../survival";
11
11
  import { prepareSurvivableRun, type SurvivableRun } from "../survival/run";
12
+ import { watchRunProcess, type RunWatch } from "../run-watch";
12
13
 
13
14
  function projectEnvForCwd(cwd?: string): NodeJS.ProcessEnv {
14
15
  if (!cwd) return {};
@@ -145,6 +146,8 @@ export function runProcess(
145
146
  function watchProvider(watched: Watched, resolve: (result: ReplyResult) => void): void {
146
147
  const { command, child, run, timeoutMs, admission } = watched;
147
148
  const untrack = watched.key ? trackProviderProcess(watched.key, child) : () => {};
149
+ // Lets a runtime update stop waiting for this run if its process goes without its end being seen here.
150
+ const watch = watchRunProcess(child.pid);
148
151
  const state = { stdout: "", stderr: "", done: false, admissionReported: false };
149
152
  const finish = (result: ReplyResult): void => {
150
153
  if (state.done) return;
@@ -153,6 +156,7 @@ function watchProvider(watched: Watched, resolve: (result: ReplyResult) => void)
153
156
  clearTimeout(startupTimer);
154
157
  clearInterval(poll);
155
158
  untrack();
159
+ watch.release();
156
160
  const answer = !result.ok && admission?.confirmed(state.stdout) ? { ...result, delivery: 'native' as const } : result;
157
161
  if (!run) { resolve(answer); return; }
158
162
  // A run another monitor delivers is handed over: this one sends nothing for it.
@@ -169,13 +173,14 @@ function watchProvider(watched: Watched, resolve: (result: ReplyResult) => void)
169
173
  signalOwnedProcess(child, "SIGKILL");
170
174
  finish({ ok: false, error: admission.timeoutMessage });
171
175
  }, admission.withinMs) : undefined;
172
- const output = providerOutput(watched, state, finish, () => clearTimeout(startupTimer));
176
+ const output = providerOutput(watched, state, finish, () => clearTimeout(startupTimer), watch);
173
177
  const poll = run ? setInterval(output.readFiles, OUTPUT_POLL_MS) : undefined;
174
178
  child.stdout?.setEncoding('utf8');
175
179
  child.stderr?.setEncoding('utf8');
176
180
  child.stdout?.on("data", output.stdout);
177
181
  child.stderr?.on("data", output.stderr);
178
182
  child.on("error", (error) => finish({ ok: false, error: `${command}: ${error.message}` }));
183
+ child.on("exit", () => watch.exited());
179
184
  child.on("close", (code) => {
180
185
  output.readFiles();
181
186
  if (!state.done) finish(closedResult(watched, state, code));
@@ -192,10 +197,11 @@ function watchProvider(watched: Watched, resolve: (result: ReplyResult) => void)
192
197
 
193
198
  /** What the provider writes, read from its pipes or, for a survivable run, from its files. */
194
199
  function providerOutput(watched: Watched, state: { stdout: string; stderr: string; done: boolean; admissionReported: boolean },
195
- finish: (result: ReplyResult) => void, admitted: () => void) {
200
+ finish: (result: ReplyResult) => void, admitted: () => void, watch: RunWatch) {
196
201
  const { command, child, run, admission } = watched;
197
202
  const stdout = (chunk: string) => {
198
203
  state.stdout += chunk;
204
+ watch.output();
199
205
  if (state.done || state.admissionReported || !admission?.confirmed(state.stdout)) return;
200
206
  state.admissionReported = true;
201
207
  admitted();
@@ -208,6 +214,7 @@ function providerOutput(watched: Watched, state: { stdout: string; stderr: strin
208
214
  };
209
215
  const stderr = (chunk: string) => {
210
216
  state.stderr += chunk;
217
+ watch.output();
211
218
  if (state.done || (admission && admission.confirmed(state.stdout))) return;
212
219
  const error = providerSignInFailure(command, state.stderr);
213
220
  if (error) { providerSignIns.refused(providerAgent(command)); signalOwnedProcess(child, 'SIGKILL'); finish({ ok: false, error }); }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Whether a run in flight still runs. A run's place in `in-flight.ts` is freed when this monitor sees its
3
+ * provider process end, or at its deadline, hours away for a phone run. When the end is never seen, or the
4
+ * process hangs, the run held a runtime update back until that deadline: a moved Task's turn cannot be
5
+ * handed over, and each hold that gave up waited for it to end. This watches the provider processes started
6
+ * under each in-flight key, so the update stops waiting for a run whose process is gone, or that showed no
7
+ * sign of work for a long time. The run itself is left alone; only the update stops counting it.
8
+ */
9
+ import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { execFile } from "node:child_process";
11
+ import { parsePsClock } from "../machine-load/host/ps-reader";
12
+
13
+ /** A provider process that exited, or vanished, this long ago no longer holds an update back. */
14
+ export const GONE_GRACE_MS = 2 * 60_000;
15
+ /** Work still pending this long after its last provider process ended normally no longer holds an update back. */
16
+ export const ENDED_GRACE_MS = 10 * 60_000;
17
+ /** A provider process with no output and no processor time in its process group for this long no longer does either. */
18
+ export const NO_PROGRESS_MS = 30 * 60_000;
19
+ /** How often watched processes are looked at, and the processor time between two looks that counts as work. */
20
+ export const SAMPLE_MS = 60_000;
21
+ const ACTIVE_CPU_MS = 1_000;
22
+
23
+ export type ProcessRow = { pid: number; pgid: number; stat: string; cpuMs: number; elapsedMs: number };
24
+ type Watched = {
25
+ pid: number; keys: readonly string[]; startedAt: number; signAt: number;
26
+ endedAt?: number; how?: "exited" | "gone"; cpuMs?: number; sampledAt?: number;
27
+ };
28
+
29
+ const scope = new AsyncLocalStorage<readonly string[]>();
30
+ const watched = new Set<Watched>();
31
+ /** Keys whose last provider process ended while their work went on, and when. */
32
+ const endedAt = new Map<string, number>();
33
+ const reported = new Map<string, string>();
34
+ let clock = Date.now;
35
+ let readRows: () => Promise<ProcessRow[]> = readProcessTable;
36
+ let log = (line: string): void => { process.stderr.write(`[monitor] ${line}\n`); };
37
+ let sampler: ReturnType<typeof setInterval> | undefined;
38
+
39
+ /** Runs `work` as the in-flight work of `key`: provider processes it starts are watched for it and the keys around it. */
40
+ export function withinDelivery<T>(key: string, work: () => T): T {
41
+ endedAt.delete(key);
42
+ return scope.run([...(scope.getStore() ?? []), key], work);
43
+ }
44
+
45
+ /** The key settled: nothing about it is kept. */
46
+ export function forgetDelivery(key: string): void {
47
+ endedAt.delete(key);
48
+ reported.delete(key);
49
+ }
50
+
51
+ export type RunWatch = { output: () => void; exited: () => void; release: () => void };
52
+ const unwatched: RunWatch = { output() {}, exited() {}, release() {} };
53
+
54
+ /**
55
+ * Watch a provider process started for the work in flight here. `output`: it wrote something; `exited`:
56
+ * this monitor saw it exit; `release`: its run has finished, whatever the outcome.
57
+ */
58
+ export function watchRunProcess(pid: number | undefined): RunWatch {
59
+ const keys = scope.getStore();
60
+ if (!keys?.length || !pid) return unwatched;
61
+ const now = clock();
62
+ const run: Watched = { pid, keys, startedAt: now, signAt: now };
63
+ watched.add(run);
64
+ for (const key of keys) endedAt.delete(key);
65
+ startSampling();
66
+ return {
67
+ output: () => { run.signAt = clock(); },
68
+ exited: () => { if (run.endedAt === undefined) { run.endedAt = clock(); run.how = "exited"; } },
69
+ release: () => {
70
+ if (!watched.delete(run)) return;
71
+ const at = clock();
72
+ for (const key of keys) if (![...watched].some(other => other.keys.includes(key))) endedAt.set(key, at);
73
+ if (watched.size === 0) stopSampling();
74
+ },
75
+ };
76
+ }
77
+
78
+ const gone = (run: Watched, now: number) => run.endedAt !== undefined && now - run.endedAt >= GONE_GRACE_MS;
79
+ // Without a recent look at the process table, quiet output alone proves nothing: Claude's JSON comes at the end.
80
+ const quiet = (run: Watched, now: number) => run.sampledAt !== undefined && now - run.sampledAt <= 3 * SAMPLE_MS
81
+ && now - run.signAt >= NO_PROGRESS_MS;
82
+
83
+ function reason(key: string, now: number): string | undefined {
84
+ const runs = [...watched].filter(run => run.keys.includes(key));
85
+ if (runs.length === 0) {
86
+ const ended = endedAt.get(key);
87
+ return ended !== undefined && now - ended >= ENDED_GRACE_MS
88
+ ? `its provider process ended ${minutes(now - ended)} min ago, but the run never finished` : undefined;
89
+ }
90
+ if (runs.every(run => gone(run, now))) {
91
+ return runs.some(run => run.how === "gone") ? "its provider process is gone" : "its provider process exited, but the run never finished";
92
+ }
93
+ return runs.every(run => gone(run, now) || quiet(run, now))
94
+ ? `its provider process wrote nothing and used no processor time for ${minutes(NO_PROGRESS_MS)} min` : undefined;
95
+ }
96
+
97
+ /**
98
+ * Why the work in flight under `key`, waiting since `since`, no longer holds a runtime update back; undefined
99
+ * while it may still be running. Work that never started a provider process (a Codex desktop delivery) is
100
+ * never judged here. The first time a reason holds, the monitor log says so.
101
+ */
102
+ export function stalledDelivery(key: string, since: number): string | undefined {
103
+ const now = clock(), why = reason(key, now);
104
+ if (why && reported.get(key) !== why) {
105
+ reported.set(key, why);
106
+ log(`A runtime update no longer waits for the run ${label(key)} that started ${minutes(now - since)} min ago: ${why}.`);
107
+ }
108
+ return why;
109
+ }
110
+
111
+ function label(key: string): string {
112
+ const task = /^__new_([a-z]+)_task__/.exec(key)?.[1];
113
+ return task ? `of a new ${task} task` : `in chat ${key.slice(0, 16)}`;
114
+ }
115
+
116
+ /** Look at every watched process once: gone, a zombie, a reused pid, or how much processor time its group used. */
117
+ export async function sampleRuns(): Promise<void> {
118
+ if (watched.size === 0) return;
119
+ let rows: ProcessRow[];
120
+ try { rows = await readRows(); } catch { return; }
121
+ const now = clock();
122
+ for (const run of watched) {
123
+ if (run.endedAt !== undefined) continue;
124
+ const leader = rows.find(row => row.pid === run.pid);
125
+ // A pid reused by a later process is younger than the run.
126
+ if (!leader || leader.stat.startsWith("Z") || leader.elapsedMs < now - run.startedAt - SAMPLE_MS) {
127
+ run.endedAt = now; run.how = "gone"; continue;
128
+ }
129
+ const group = leader.pgid === leader.pid ? rows.filter(row => row.pgid === leader.pid && !row.stat.startsWith("Z")) : [leader];
130
+ const cpu = group.reduce((sum, row) => sum + row.cpuMs, 0);
131
+ if (run.cpuMs !== undefined && cpu - run.cpuMs >= ACTIVE_CPU_MS) run.signAt = now;
132
+ run.cpuMs = cpu;
133
+ run.sampledAt = now;
134
+ }
135
+ }
136
+
137
+ function startSampling(): void {
138
+ if (sampler) return;
139
+ sampler = setInterval(() => { void sampleRuns(); }, SAMPLE_MS);
140
+ sampler.unref?.();
141
+ }
142
+
143
+ function stopSampling(): void {
144
+ if (sampler) clearInterval(sampler);
145
+ sampler = undefined;
146
+ }
147
+
148
+ /** `pid pgid stat time etime` rows, as `ps -A -o pid=,pgid=,stat=,time=,etime=` prints them on macOS and Linux. */
149
+ export function parseProcessTable(stdout: string): ProcessRow[] {
150
+ return stdout.split("\n").flatMap((line): ProcessRow[] => {
151
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)$/);
152
+ if (!match) return [];
153
+ const cpuMs = parsePsClock(match[4]!), elapsedMs = parsePsClock(match[5]!);
154
+ return cpuMs == null || elapsedMs == null ? []
155
+ : [{ pid: Number(match[1]), pgid: Number(match[2]), stat: match[3]!, cpuMs, elapsedMs }];
156
+ });
157
+ }
158
+
159
+ export function readProcessTable(): Promise<ProcessRow[]> {
160
+ return new Promise((resolve, reject) => {
161
+ execFile("ps", ["-A", "-o", "pid=,pgid=,stat=,time=,etime="], { timeout: 5_000, maxBuffer: 8 * 1024 * 1024 },
162
+ (error, stdout) => { if (error) reject(error); else resolve(parseProcessTable(stdout)); });
163
+ });
164
+ }
165
+
166
+ function minutes(ms: number): number { return Math.max(0, Math.round(ms / 60_000)); }
167
+
168
+ /** For tests in one process: a clock, a process table and a log instead of the system's; nothing watched is kept. */
169
+ export function setRunWatchForTests(options: { now?: () => number; rows?: () => Promise<ProcessRow[]>;
170
+ log?: (line: string) => void } = {}): void {
171
+ stopSampling();
172
+ watched.clear(); endedAt.clear(); reported.clear();
173
+ clock = options.now ?? Date.now;
174
+ readRows = options.rows ?? readProcessTable;
175
+ log = options.log ?? ((line: string) => { process.stderr.write(`[monitor] ${line}\n`); });
176
+ }
@@ -63,7 +63,8 @@ Task's turn (its transfer record is updated by the monitor that started it), a C
63
63
  live connection to the agent), a Codex desktop delivery in progress, a phone message waiting in memory
64
64
  behind a running turn of its chat, a pending approval or provider sign-in, a maintenance action, and an
65
65
  answer being sent. Windows keeps pipes and does not hand runs over. `GRANTTAP_RUN_SURVIVAL=0` on the
66
- service turns handing over off.
66
+ service turns handing over off. A run that cannot be handed over stops holding the update once its process is gone or it
67
+ showed no sign of work for thirty minutes (`../run-watch.ts`).
67
68
 
68
69
  Tests: `tests/adoption.test.ts` (a run left by a monitor that exited is taken over, delivered once,
69
70
  paused, cut off at its deadline; a run that ended while no monitor ran; a live monitor's run is left
@@ -45,6 +45,8 @@ provider run that cannot be handed over (a moved Task's turn, a Cursor conversat
45
45
  delivery, a turn not yet past acceptance or not yet confirmed by Grok), a phone message waiting in memory
46
46
  behind a running turn of its chat, an answer being sent, a pending approval, a provider sign-in, or a
47
47
  maintenance action.
48
+ A run whose provider process is gone, or that showed no sign of work for thirty minutes, stops holding
49
+ an update back, and the monitor log says so ([`../reply/run-watch.ts`](../reply/README.md)).
48
50
 
49
51
  | Bound | Value |
50
52
  | --- | --- |
@@ -303,7 +303,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
303
303
  const observations = progress.capabilities.snapshot();
304
304
  const childThreads = yield* readChildren(actualChildPaths, ownSession, progress, observations);
305
305
  const session = aggregateChildThreads(ownSession, childThreads);
306
- const lineage = claudeLineage(state, ownSession, progress.lineage.snapshot());
306
+ const lineage = claudeLineage(state, ownSession, progress.lineage.snapshot(), progress.lineage.launches());
307
307
  claudeSummaryCache.set(file, {
308
308
  mtimeMs: fileStat.mtimeMs,
309
309
  size: fileStat.size,
@@ -322,9 +322,10 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
322
322
  }
323
323
 
324
324
  /** Where the chat came from, for `startedBy`: never published itself. */
325
- function claudeLineage(state: ClaudeParseState, session: SessionInfo, calls: LineageFact["calls"]): LineageFact {
325
+ function claudeLineage(state: ClaudeParseState, session: SessionInfo, calls: LineageFact["calls"],
326
+ launches: LineageFact["launches"]): LineageFact {
326
327
  const headless = /^sdk-/.test(state.entrypoint ?? "");
327
328
  return { agent: "claude", sessionId: session.sessionId, cwd: state.launchCwd ?? session.cwd, startedAt: session.startedAt,
328
329
  ...(headless ? { headless } : {}), ...(headless && state.prompt ? { prompt: state.prompt } : {}),
329
- ...(calls?.length ? { calls } : {}) };
330
+ ...(calls?.length ? { calls } : {}), ...(launches?.length ? { launches } : {}) };
330
331
  }
@@ -279,7 +279,8 @@ export function parseCodexFile(file: string): CodexCandidate | undefined {
279
279
  /** Where the chat came from, for `startedBy`: never published itself. A forked agent is no chat. */
280
280
  function codexLineage(state: CodexParseState, session: SessionInfo): LineageFact {
281
281
  const calls = state.calls.snapshot();
282
+ const launches = state.calls.launches();
282
283
  return { agent: "codex", sessionId: session.sessionId, cwd: session.cwd, startedAt: session.startedAt,
283
284
  ...(state.headless ? { headless: true } : {}), ...(state.headless && state.prompt ? { prompt: state.prompt } : {}),
284
- ...(calls.length ? { calls } : {}) };
285
+ ...(calls.length ? { calls } : {}), ...(launches.length ? { launches } : {}) };
285
286
  }
@@ -37,6 +37,19 @@ inherited from a chat further up started that provider, not this run. A run
37
37
  with no provider above it counts when exactly one chat is named. Nothing else
38
38
  read from a process is logged or kept.
39
39
 
40
+ **Short runs** (`live/`). A run a usage limit stops lives three or four
41
+ seconds, less than samples take to come round (every 2 s while chats work,
42
+ every 30 s while none does). On macOS the leading monitor also watches the
43
+ providers' session folders, in one stream per folder tree: a new transcript (a
44
+ Codex `rollout-*.jsonl`, a Claude chat's `<id>.jsonl` but no subagent's, a Grok
45
+ session's `chat_history.jsonl`) made in the last minute asks at once for one
46
+ listing of the provider processes, which captures runs as above and reports
47
+ nothing. A provider writes it about a second after its run starts. Listings are
48
+ single-flight: transcripts that appear during one ask for one more after it,
49
+ however many they are, so a batch of hundreds of runs costs at most one listing
50
+ per run and nothing while no transcript appears. Only file names and creation
51
+ times are read. A monitor that stops leading stops watching.
52
+
40
53
  **Joined** (`attach.ts`, `links.ts`). The run's process does not say which
41
54
  session it writes, so the run waits in `started-by.json` in the config
42
55
  directory (`runs`, at most 256, a day at most) until the catalog shows a
@@ -47,17 +60,21 @@ by the child session (`links`, at most 4,000, six months) and outlives the run,
47
60
  its process and the parent's transcript. The first link of a chat stands; a link
48
61
  its own process named replaces one read from a transcript.
49
62
 
50
- **After the fact** (`facts.ts`, `attach.ts`). A run whose process was never
51
- seen (it ran before this runtime, or while the monitor was down) is matched
52
- from the parent's transcript, conservatively. The scanners already read each
53
- chat's transcript row by row; while they do, they keep the commands that start
54
- another provider headless (Claude `Bash` calls, Codex `exec_command`, `shell`
55
- and code-mode `exec` calls), in one spelling with shell quoting and escapes
56
- dropped, with the time each ran: from the call to its result, or for a Claude
57
- command sent to the background, until Claude's notification that it finished.
58
- At most 32 such commands of 8 KB per chat are held, in memory only. A child is
59
- linked to a chat when all of these hold, and to none when more than one chat
60
- qualifies:
63
+ **After the fact** (`facts.ts`, `attach.ts`, `folders/`). A run whose process
64
+ was never seen (it ran before this runtime, while the monitor was down, or for
65
+ less time than one sample takes to come round) is matched from the parent's
66
+ transcript, conservatively: by its request, and failing that by its folder.
67
+ The scanners already read each chat's transcript row by row; while they do,
68
+ they keep the commands that start another provider headless (Claude `Bash`
69
+ calls, Codex `exec_command`, `shell` and code-mode `exec` calls), in one
70
+ spelling with shell quoting and escapes dropped, with the time each ran: from
71
+ the call to its result, or for a Claude command sent to the background, until
72
+ Claude's notification that it finished. At most 32 such commands of 8 KB per
73
+ chat are held, in memory only. A script's argument list starts the provider it
74
+ names (`subprocess.run(["codex", "exec", "-C", "/tmp/art", prompt])`); a
75
+ command line a chat only looks for (`pgrep`, `pkill`, `grep` or `ps` of
76
+ `"codex exec …"`) starts none. By its request, a child is linked to a chat when
77
+ all of these hold, and to none when more than one chat qualifies:
61
78
 
62
79
  - the child is headless and started in the last 48 hours;
63
80
  - its first request has at least 40 characters, and its first 64 (the whole
@@ -69,9 +86,34 @@ qualifies:
69
86
  - the parent started before the child, is not the child, and was read on the
70
87
  same computer.
71
88
 
72
- A command that runs a script naming no provider (`bash make-pictures.sh`) or
73
- that builds each request from a file is not matched: the transcript does not
74
- show the request. Such runs are linked only while their process is alive.
89
+ **By its folder** (`folders/`). A script that builds each request from a file
90
+ (`one.sh <index>` reading `prompts.json`, a Python loop over a queue, run
91
+ detached through `xargs`) leaves no request in the chat's commands, but they
92
+ still name the folder the runs work in. Each command that starts a provider
93
+ headless notes every folder it names: an absolute path (from `/`, `~` or
94
+ `$HOME`) as it is, or the folder of a file it names (`/tmp/art/one.sh`), never
95
+ the system's folders, a temp directory itself, the home folder or one above
96
+ it. Per chat, folder and provider, the time of the first such command is kept,
97
+ and the time of the chat's last command of any kind that named the folder or a
98
+ path inside it: at most 32 per chat, the folder named longest ago let go first,
99
+ in memory only, so a launch long out of the last 32 commands still counts. A
100
+ child its request did not link is linked when all of these hold:
101
+
102
+ - the child is headless, started in the last 48 hours, on this computer;
103
+ - its folder is one made for runs: gone, or holding no checkout and lying in
104
+ none (asked once a minute per folder);
105
+ - exactly one chat read on this computer started the child's provider headless
106
+ in a command naming that folder; when a second chat did, at any time, the
107
+ folder links nothing;
108
+ - the child started between 3 s before that chat's first such command and
109
+ 12 hours after the chat last named the folder, so a batch left running
110
+ detached, or waiting out a usage limit, stays its chat's;
111
+ - the parent started before the child and is not the child.
112
+
113
+ Such a link is written like any other read from a transcript (`source:
114
+ "transcript"`). A run in a checkout or in a folder two chats used, whose
115
+ request a script built from a file, or whose script names no provider and was
116
+ not written by the chat, is linked only while its process is alive.
75
117
 
76
118
  **Mesh** (`mesh/`). A child whose folder is no checkout of its own (a temp
77
119
  folder, a plain folder without Git, one that is gone) is its parent's work: the
@@ -89,6 +131,11 @@ Projects, like a helper run's.
89
131
  Tests live in `tests/`: command and session recognition, capture, transcript
90
132
  matching (inside and outside a command's window, short requests, another
91
133
  computer, two candidate parents), publishing and the stored links, and the
92
- Mesh rules.
134
+ Mesh rules. `folders/tests/` covers matching by folder on a course's real shapes
135
+ (`lessonart.ts`: a script written then run detached, a Python batch, a Grok
136
+ worker): two chats naming one folder, a checkout or a folder inside one, runs
137
+ outside the window, and the catalog that results. `live/tests/` covers the
138
+ watch, and on macOS a real run that lives 1.6 s, caught while it lives and
139
+ joined to its session.
93
140
 
94
141
  Licensed under the GrantTap Commercial Source License. See the repository root `LICENSE`.