granttap-mcp 0.8.134 → 0.8.136

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 (38) hide show
  1. package/README.md +7 -0
  2. package/SECURITY.md +5 -0
  3. package/apps/bridge/src/bin/runtime/monitor.ts +4 -1
  4. package/apps/bridge/src/device-management/maintenance.ts +19 -1
  5. package/apps/bridge/src/mesh/store/base.ts +7 -0
  6. package/apps/bridge/src/mesh/tasks/create-task.ts +7 -3
  7. package/apps/bridge/src/monitor/handlers/receipts.ts +10 -0
  8. package/apps/bridge/src/monitor/handlers/user-message.ts +1 -1
  9. package/apps/bridge/src/monitor/index.ts +2 -2
  10. package/apps/bridge/src/monitor/support/leadership.ts +21 -1
  11. package/apps/bridge/src/monitor/support/runtime.ts +2 -2
  12. package/apps/bridge/src/monitor/support/session-activity.ts +2 -2
  13. package/apps/bridge/src/reply/process/index.ts +3 -1
  14. package/apps/bridge/src/runtime-watchdog/README.md +25 -0
  15. package/apps/bridge/src/runtime-watchdog/index.ts +34 -0
  16. package/apps/bridge/src/runtime-watchdog/policy.d.mts +12 -0
  17. package/apps/bridge/src/runtime-watchdog/policy.mjs +76 -0
  18. package/apps/bridge/src/runtime-watchdog/worker.mjs +48 -0
  19. package/apps/bridge/src/sessions/README.md +13 -3
  20. package/apps/bridge/src/sessions/index.ts +10 -1
  21. package/apps/bridge/src/sessions/scan/claude/activity.ts +102 -66
  22. package/apps/bridge/src/sessions/scan/claude/parse.ts +134 -38
  23. package/apps/bridge/src/sessions/scan/claude/recorded-usage/index.ts +3 -2
  24. package/apps/bridge/src/sessions/scan/claude/repository-observation/index.ts +49 -6
  25. package/apps/bridge/src/sessions/scan/claude/scan.ts +2 -2
  26. package/apps/bridge/src/sessions/scan/claude/shared.ts +4 -1
  27. package/apps/bridge/src/sessions/support/activity-helpers.ts +14 -0
  28. package/apps/bridge/src/sessions/support/repository-checkout/index.ts +23 -2
  29. package/apps/bridge/src/task-dispatch/README.md +4 -0
  30. package/apps/bridge/src/task-dispatch/worker/monitor.ts +27 -5
  31. package/apps/bridge/src/task-dispatch/worker/readiness.ts +6 -0
  32. package/cursor-plugin/README.md +1 -1
  33. package/cursor-plugin/mcp.json +1 -1
  34. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  35. package/package.json +1 -1
  36. package/packages/core/task-dispatch/index.ts +6 -1
  37. package/packages/protocol/messages/interaction/index.ts +12 -0
  38. package/packages/protocol/schema.ts +2 -0
package/README.md CHANGED
@@ -856,6 +856,13 @@ The relay can retain recipient-encrypted catalogs, Mesh snapshots, capability us
856
856
 
857
857
  Tools & Skills matches recorded usage to the exact computer, provider and execution. Codex's native history projection supplies actual MCP invocation IDs, results and durations, including calls made through Code Mode. Claude Code uses observed tool-use, result and Skill records, aggregating MCP and skill calls before its recent-detail cache is trimmed. Execution summaries remain available when older call details fall outside the recent-event budget. Counts describe recorded evidence; installation and permission do not prove usage. Missing resource measurements remain unknown. See [native capability history](apps/bridge/src/sessions/native-capability-history/README.md).
858
858
 
859
+ ## Hang recovery
860
+
861
+ If the background monitor stops responding for two minutes, it records the fault and
862
+ restarts as a clean process, at most three times an hour. Past that it stays up and
863
+ only reports, so a recurring hang cannot become a restart loop. Sleep does not count.
864
+ See the [runtime watchdog](apps/bridge/src/runtime-watchdog/README.md).
865
+
859
866
  ## Automatic runtime updates
860
867
 
861
868
  Installed GrantTap background services check for stable MCP updates automatically.
package/SECURITY.md CHANGED
@@ -20,6 +20,11 @@ credential used for authenticated WebSocket and APNs registration.
20
20
  Provider credentials remain in each provider's own local authentication flow.
21
21
  GrantTap does not send them to the relay.
22
22
 
23
+ If the background monitor hangs, the [runtime watchdog](apps/bridge/src/runtime-watchdog/README.md)
24
+ sends the site a fault report holding only the fault kind, duration, restart count,
25
+ GrantTap and Node versions, platform and architecture. It never holds a prompt, path,
26
+ room, key or computer name. `GRANTTAP_DISABLE_FAULT_REPORTS=1` turns sending off.
27
+
23
28
  Installed Claude Code, Codex, and Cursor hooks deny direct agent tool calls
24
29
  that name GrantTap's local pairing, key, or policy files, including calls that
25
30
  would otherwise be auto-accepted or run in provider bypass mode. The denial
@@ -16,6 +16,7 @@ import { applyNetworkRoute } from "../../device-network/settings";
16
16
  import { startEndpointPublisher } from "../../device-network/directory";
17
17
  import { managedAdmissionOptions } from "../../managed-admission";
18
18
  import { publishStableNode } from "../../install/stable-node/index";
19
+ import { startRuntimeWatchdog } from "../../runtime-watchdog";
19
20
 
20
21
  import { startTaskDispatchMonitor } from "../../task-dispatch/worker/monitor";
21
22
  import { startTaskNetworkMonitor } from '../../task-network/runtime';
@@ -30,6 +31,7 @@ let stopTaskNetwork = () => {};
30
31
  let stopEngineRecovery = () => {};
31
32
  let stopRuntimeUpdates = () => {};
32
33
  let stopUpdateReadiness = () => {};
34
+ const stopWatchdog = startRuntimeWatchdog();
33
35
 
34
36
  publishStableNode();
35
37
 
@@ -41,7 +43,7 @@ try {
41
43
  replayPath: join(configDir(), `replay-${cfg.room}.json`),
42
44
  peerAllowed: controllerPeerGate(cfg),
43
45
  });
44
- monitor = startSessionMonitor(client);
46
+ monitor = startSessionMonitor(client, { primary: process.env.GRANTTAP_MONITOR_PRIMARY === "1" });
45
47
  stopTaskDispatch = startTaskDispatchMonitor({ config: cfg, client,
46
48
  isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish });
47
49
  stopTaskNetwork = startTaskNetworkMonitor({ config: cfg, client,
@@ -59,6 +61,7 @@ try {
59
61
  const stop = (): void => {
60
62
  if (stopping) return;
61
63
  stopping = true;
64
+ stopWatchdog();
62
65
  stopRuntimeUpdates();
63
66
  stopUpdateReadiness();
64
67
  stopEngineRecovery();
@@ -9,7 +9,8 @@ import type { CodingAgent, DeviceManagementSnapshot } from '../../../../packages
9
9
  import { configDir } from '../config/runtime/paths';
10
10
  import { observedComputerId } from '../mesh/identity/computer';
11
11
  import { automaticUpdatesAllowed } from '../runtime-updates/preferences/storage.mjs';
12
- import { readState, runtimeVersion } from '../runtime-updates/selection.mjs';
12
+ import { newerVersion, readState, runtimeVersion } from '../runtime-updates/selection.mjs';
13
+ import { latestRelease, trustedRelease } from '../runtime-updates/registry';
13
14
  import { checkForRuntimeUpdate } from '../runtime-updates';
14
15
  import { binaryVersion } from '../tools/version';
15
16
  import { providerCommand, providerAuthentication, installedProvider, providerEnvironment } from './provider-command';
@@ -39,6 +40,22 @@ export function maintenanceIdle(): boolean {
39
40
  && agents.every(agent => ownedProviderProcesses(providerCommand(agent)).length === 0);
40
41
  }
41
42
 
43
+ const RELEASE_CHECK_MS = 60 * 60_000;
44
+ let knownRelease: { at: number; version?: string } = { at: 0 };
45
+
46
+ /** The phone offers an update from this answer; a registry problem only hides the offer. */
47
+ async function availableRuntimeVersion(): Promise<string | undefined> {
48
+ if (Date.now() - knownRelease.at >= RELEASE_CHECK_MS) {
49
+ knownRelease = { at: Date.now(), version: knownRelease.version };
50
+ try {
51
+ const release = await latestRelease();
52
+ if (trustedRelease(release)) knownRelease.version = release.version;
53
+ } catch { /* Keep what was last known. */ }
54
+ }
55
+ const version = knownRelease.version;
56
+ return version && newerVersion(version, runtimeVersion(runtimeRoot)) ? version : undefined;
57
+ }
58
+
42
59
  export async function managementSnapshot(): Promise<DeviceManagementSnapshot> {
43
60
  const observedAt = Date.now();
44
61
  const directory = join(configDir(), 'runtime-updates');
@@ -52,6 +69,7 @@ export async function managementSnapshot(): Promise<DeviceManagementSnapshot> {
52
69
  }));
53
70
  return { computerId: observedComputerId(), computerName: hostname(), observedAt,
54
71
  runtimeVersion: runtimeVersion(runtimeRoot), runtimeEpoch, selectedRuntimeVersion: selected.version,
72
+ availableRuntimeVersion: await availableRuntimeVersion(),
55
73
  automaticUpdatesEnabled: automaticUpdatesAllowed(directory),
56
74
  runtimeUpdateSupported: runtimeRoot.includes('/node_modules/'), runtimeRestartSupported: runtimeRestartSupported(),
57
75
  cache: (await computerCache(runtimeRoot)).map(({ paths: _paths, ...category }) => category), providers };
@@ -227,6 +227,13 @@ export class MeshStoreBase {
227
227
  return bindingForEndpoint(this.state.bindings, repositoryId, endpointId);
228
228
  }
229
229
 
230
+ /** A folder this computer registered for a Project, whichever agent worked there. */
231
+ hasLocalBinding(projectId: string, localPath: string, endpointId: string): boolean {
232
+ this.sync();
233
+ return this.state.bindings.some((item) => item.projectId === projectId
234
+ && item.endpointId === endpointId && item.available && item.localPathHint === localPath);
235
+ }
236
+
230
237
  upsertTask(input: TaskValue): void {
231
238
  this.sync();
232
239
  const task = MeshTask.parse(input);
@@ -55,11 +55,15 @@ export function evaluateCreateTask(input: {
55
55
  now?: number;
56
56
  }): CreateTaskEvaluation {
57
57
  const endpoint = input.localEndpointId ?? computerId();
58
- const known = [...scanSessions().sessions, ...scanSessionHistory()].some((session) =>
59
- session.agent === input.agent && session.cwd === input.cwd);
58
+ const store = localMeshStore();
59
+ const requestedProjectId = input.projectId?.trim();
60
+ // The Mesh composer offers folders this computer registered for the Project.
61
+ // Its agent choice is free, so one that never ran there is not a stranger.
62
+ const known = (requestedProjectId && store.hasLocalBinding(requestedProjectId, input.cwd, endpoint))
63
+ || [...scanSessions().sessions, ...scanSessionHistory()].some((session) =>
64
+ session.agent === input.agent && session.cwd === input.cwd);
60
65
  if (!known) return { ok: false, reason: "unknown_workspace", detail: DETAILS.unknown_workspace };
61
66
  const repository = inspectRepository(input.cwd);
62
- const store = localMeshStore();
63
67
  const resolved = resolveCreateTaskProject({
64
68
  requestedProjectId: input.projectId,
65
69
  endpointBinding: store.bindingForEndpoint(repository.canonicalRepositoryId, endpoint),
@@ -31,6 +31,16 @@ export async function sendDeliveryReceipt(
31
31
  : client.send(payload, "phone", options)).catch(() => {});
32
32
  }
33
33
 
34
+ /** The message reached this computer. The relay repeats offers, so the caller sends this once. */
35
+ export async function sendDeliveryArrival(client: RelayClient, messageId: string, sessionId: string | undefined,
36
+ peerPublicKey: string | undefined): Promise<void> {
37
+ const payload = { type: "delivery.arrival" as const, messageId, sessionId: sessionId?.trim() || undefined, receivedAt: Date.now() };
38
+ const options = { ttlMs: 24 * 60 * 60_000, peerPublicKey };
39
+ await (sessionId && !peerPublicKey
40
+ ? sendSessionPayload(client, payload, sessionId, "phone", options)
41
+ : client.send(payload, "phone", options)).catch(() => {});
42
+ }
43
+
34
44
  export function agentEventForUserMessage(
35
45
  message: UserMessage,
36
46
  text: string,
@@ -91,7 +91,7 @@ async function startNewAgentTask(input: {
91
91
  let run: Promise<ReplyResult>;
92
92
  try {
93
93
  run = create(projectGuidancePrompt(admittedProjectId, message.text), requestedCwd, PHONE_RUN_LIMIT_MS, resolved.attachments,
94
- message.model, undefined, message.effort).catch(() => {
94
+ message.model, message.messageId, message.effort).catch(() => {
95
95
  input.origin?.registry.complete(input.origin.scope, { ok: true });
96
96
  return { ok: false, error: 'The provider task stopped unexpectedly.' } as ReplyResult;
97
97
  });
@@ -16,6 +16,6 @@ export { sweepAttachments, resolveMessageAttachments } from "./handlers/receipts
16
16
  export { handleUserMessage } from "./handlers/user-message";
17
17
  export type { SessionMonitor } from "./support/runtime";
18
18
 
19
- export function startSessionMonitor(client: RelayClient) {
20
- return start(client);
19
+ export function startSessionMonitor(client: RelayClient, options: { primary?: boolean } = {}) {
20
+ return start(client, options);
21
21
  }
@@ -87,13 +87,20 @@ function tryAcquireLock(input: {
87
87
  return false;
88
88
  }
89
89
 
90
+ /**
91
+ * Only the installed monitor process may claim to be primary. The flag lives in
92
+ * its environment, and every chat it starts inherits that environment; an MCP
93
+ * server inside such a chat that trusted the variable would take the lease
94
+ * from the real monitor, publish only from its own corner, and leave the phone
95
+ * without the other chats' progress.
96
+ */
90
97
  export function monitorLeadership(
91
98
  now: () => number = Date.now,
92
99
  report: (message: string) => void = (message) => process.stderr.write(message),
93
100
  connected: () => boolean = () => true,
101
+ primary = false,
94
102
  ): MonitorLeadership {
95
103
  const path = join(configDir(), "monitor.lock");
96
- const primary = process.env.GRANTTAP_MONITOR_PRIMARY === "1";
97
104
  const token = `${process.pid}:${randomUUID()}:${primary ? "primary" : "peer"}`;
98
105
  let leader = false;
99
106
  let reportedAt = 0;
@@ -110,8 +117,21 @@ export function monitorLeadership(
110
117
  writeFileSync(path, token, { mode: 0o600 });
111
118
  };
112
119
 
120
+ /** A monitor that is gone cannot renew; its successor need not wait out the lease. */
121
+ const holderGone = (): boolean => {
122
+ const holder = Number(read()?.split(":", 1)[0]);
123
+ if (!Number.isSafeInteger(holder) || holder < 1) return false;
124
+ try {
125
+ process.kill(holder, 0);
126
+ return false;
127
+ } catch (error) {
128
+ return (error as NodeJS.ErrnoException).code === "ESRCH";
129
+ }
130
+ };
131
+
113
132
  /** A lease nobody renewed is free, whatever process now owns that id. */
114
133
  const expired = (): boolean => {
134
+ if (holderGone()) return true;
115
135
  try {
116
136
  return now() - statSync(path).mtimeMs > LEADERSHIP_TTL_MS;
117
137
  } catch {
@@ -173,9 +173,9 @@ async function publishMonitorTick(input: {
173
173
  * used by MCP tools. This keeps STDIO stdout clean and removes the old need for
174
174
  * a separate `granttap-mcp monitor` terminal process.
175
175
  */
176
- export function startSessionMonitor(client: RelayClient): SessionMonitor {
176
+ export function startSessionMonitor(client: RelayClient, options: { primary?: boolean } = {}): SessionMonitor {
177
177
  const subscriptions = new Set<string>();
178
- const leadership = monitorLeadership(Date.now, undefined, () => client.isConnected);
178
+ const leadership = monitorLeadership(Date.now, undefined, () => client.isConnected, options.primary === true);
179
179
  restoreMonitorState(client);
180
180
  let historyCache: { generatedAt: number; sessions: SessionsStatus["sessions"] } | undefined;
181
181
  let historyRead: Promise<SessionsStatus["sessions"]> | undefined;
@@ -1,5 +1,5 @@
1
1
  import type { SessionActivity, SessionInfo } from "../../../../../packages/protocol/schema";
2
- import { scanSessionActivity } from "../../sessions";
2
+ import { scanChildActivity, scanSessionActivity } from "../../sessions";
3
3
  import { readTranscriptHistory } from "../../transcript-history";
4
4
 
5
5
  type ActivityReader = (session: SessionInfo) => SessionActivity;
@@ -62,6 +62,6 @@ export const cachedSessionActivity = sessionActivityCache((session) => {
62
62
  const history = readTranscriptHistory(session);
63
63
  if (!history) return scanSessionActivity(session);
64
64
  if (!session.childThreads?.length) return history;
65
- const children = scanSessionActivity(session).entries.filter((entry) => entry.childThreadId);
65
+ const children = scanChildActivity(session);
66
66
  return { ...history, entries: [...history.entries, ...children].sort((a, b) => a.createdAt - b.createdAt) };
67
67
  });
@@ -21,8 +21,10 @@ function projectEnvForCwd(cwd?: string): NodeJS.ProcessEnv {
21
21
  }
22
22
  }
23
23
 
24
+ /** A chat started from the phone is not the monitor, whatever the monitor's environment says. */
24
25
  export function providerProcessEnvironment(cwd?: string): NodeJS.ProcessEnv {
25
- const env: NodeJS.ProcessEnv = { ...process.env, GRANTTAP_DELIVERY: "1", ...projectEnvForCwd(cwd) };
26
+ const { GRANTTAP_MONITOR_PRIMARY: _monitorOnly, ...inherited } = process.env;
27
+ const env: NodeJS.ProcessEnv = { ...inherited, GRANTTAP_DELIVERY: "1", ...projectEnvForCwd(cwd) };
26
28
  const nodeDirectory = dirname(process.execPath);
27
29
  env.PATH = [nodeDirectory, ...(env.PATH ?? '').split(delimiter)
28
30
  .filter(part => part && part !== nodeDirectory)].join(delimiter);
@@ -0,0 +1,25 @@
1
+ # Runtime watchdog
2
+
3
+ [Monitor](../monitor/README.md) · [Runtime updates](../runtime-updates/README.md)
4
+
5
+ The monitor is one event loop. If it hangs, nothing inside it can notice. A worker
6
+ thread watches a heartbeat the loop writes every second. After 120 seconds without
7
+ one, it records a fault, tries to send it to the site, and kills the process so the
8
+ service manager starts a clean one.
9
+
10
+ Restarts are bounded: at most three per hour, counted in a file that survives them.
11
+ Past that the process stays up and only reports. Sleep is not a hang: a gap in the
12
+ watchdog's own timer starts a fresh grace period. A monitor started by hand reports
13
+ and is never killed, because nothing would bring it back.
14
+
15
+ A report holds only the fault kind, duration, action, restart count, GrantTap version,
16
+ Node version, platform and architecture. It never holds a prompt, path, room, key or
17
+ computer name. Unsent reports stay in `runtime-watchdog/pending-reports.json` in the
18
+ private configuration folder until the site confirms them.
19
+ `GRANTTAP_DISABLE_FAULT_REPORTS=1` turns sending off and keeps the local record.
20
+
21
+ Public entry: `startRuntimeWatchdog`. Tests hang a real process and check the kill,
22
+ the spent budget, the sent report and the sleep case.
23
+
24
+ License: this module is distributed under the GrantTap Commercial Source License
25
+ in the repository-root `LICENSE` file.
@@ -0,0 +1,34 @@
1
+ import { join } from 'node:path';
2
+ import { Worker } from 'node:worker_threads';
3
+ import { configDir } from '../config';
4
+
5
+ export const FAULT_REPORT_URL = 'https://granttap.com/api/runtime-faults';
6
+ const BEAT_MS = 1_000;
7
+
8
+ /** Starts the monitor's hang watchdog. Its failure to start never stops the monitor. */
9
+ export function startRuntimeWatchdog(options: { version?: string; restartAllowed?: boolean; reportUrl?: string;
10
+ directory?: string; stallMs?: number; checkMs?: number } = {}): () => void {
11
+ try {
12
+ const buffer = new SharedArrayBuffer(8);
13
+ const beat = new BigInt64Array(buffer);
14
+ const touch = () => { Atomics.store(beat, 0, BigInt(Date.now())); };
15
+ touch();
16
+ const timer = setInterval(touch, BEAT_MS);
17
+ timer.unref();
18
+ const reportsAllowed = process.env.GRANTTAP_DISABLE_FAULT_REPORTS !== '1';
19
+ const worker = new Worker(new URL('./worker.mjs', import.meta.url), {
20
+ execArgv: [],
21
+ workerData: { buffer, directory: options.directory ?? join(configDir(), 'runtime-watchdog'),
22
+ version: options.version ?? process.env.GRANTTAP_PACKAGE_VERSION ?? 'unknown',
23
+ reportUrl: reportsAllowed ? options.reportUrl ?? FAULT_REPORT_URL : undefined,
24
+ // Only a managed service comes back after the kill; a monitor started by hand just reports.
25
+ restartAllowed: options.restartAllowed ?? process.env.GRANTTAP_MONITOR_PRIMARY === '1',
26
+ ...(options.stallMs ? { stallMs: options.stallMs } : {}), ...(options.checkMs ? { checkMs: options.checkMs } : {}) },
27
+ });
28
+ worker.unref();
29
+ worker.on('error', () => { clearInterval(timer); });
30
+ return () => { clearInterval(timer); void worker.terminate(); };
31
+ } catch {
32
+ return () => {};
33
+ }
34
+ }
@@ -0,0 +1,12 @@
1
+ export const STALL_MS: number;
2
+ export const CHECK_MS: number;
3
+ export const RESTART_LIMIT: number;
4
+ export const RESTART_WINDOW_MS: number;
5
+ export function nextStep(input: { now: number; lastCheck: number; beat: number; graceUntil: number; reported: boolean;
6
+ stallMs?: number; checkMs?: number }): { graceUntil: number; stalled: boolean; recovered: boolean };
7
+ export function spendRestart(directory: string, now: number, limit?: number, windowMs?: number):
8
+ { restart: boolean; restartsInWindow: number };
9
+ export function faultReport(input: { id: string; kind: string; at: number; stalledMs: number; action: string;
10
+ restartsInWindow: number; version: string }): Record<string, unknown>;
11
+ export function rememberFault(directory: string, report: Record<string, unknown>): void;
12
+ export function sendPendingFaults(directory: string, url: string, request?: typeof fetch): Promise<number>;
@@ -0,0 +1,76 @@
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ export const STALL_MS = 120_000;
5
+ export const CHECK_MS = 5_000;
6
+ export const RESTART_LIMIT = 3;
7
+ export const RESTART_WINDOW_MS = 60 * 60_000;
8
+ const PENDING_REPORT_LIMIT = 50;
9
+
10
+ function readJson(path, fallback) {
11
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }
12
+ }
13
+
14
+ function writeJson(directory, name, value) {
15
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
16
+ const path = join(directory, name), next = `${path}.${process.pid}.tmp`;
17
+ writeFileSync(next, JSON.stringify(value), { mode: 0o600 });
18
+ renameSync(next, path);
19
+ }
20
+
21
+ /** One step of the watchdog loop. A gap in its own timer means the computer slept, not a hang. */
22
+ export function nextStep(input) {
23
+ const { now, lastCheck, beat, graceUntil, reported, stallMs = STALL_MS, checkMs = CHECK_MS } = input;
24
+ const slept = now - lastCheck > checkMs * 3;
25
+ const grace = slept ? now + stallMs : graceUntil;
26
+ const stalled = now - beat >= stallMs && now >= grace;
27
+ return { graceUntil: grace, stalled, recovered: !stalled && reported && now - beat < stallMs };
28
+ }
29
+
30
+ /**
31
+ * The restart budget survives the restart it pays for. Once it is spent the
32
+ * process stays up and only reports, so a hang that returns after every start
33
+ * cannot become an endless restart.
34
+ */
35
+ export function spendRestart(directory, now, limit = RESTART_LIMIT, windowMs = RESTART_WINDOW_MS) {
36
+ const recent = readJson(join(directory, 'restarts.json'), [])
37
+ .filter(at => Number.isFinite(at) && now - at < windowMs && at <= now);
38
+ if (recent.length >= limit) return { restart: false, restartsInWindow: recent.length };
39
+ recent.push(now);
40
+ writeJson(directory, 'restarts.json', recent);
41
+ return { restart: true, restartsInWindow: recent.length };
42
+ }
43
+
44
+ /** Only these fields leave the computer: no prompt, path, room, key or computer name. */
45
+ export function faultReport(input) {
46
+ return { id: input.id, kind: input.kind, at: input.at, stalledMs: input.stalledMs, action: input.action,
47
+ restartsInWindow: input.restartsInWindow, version: input.version, node: process.versions.node,
48
+ platform: process.platform, arch: process.arch };
49
+ }
50
+
51
+ export function rememberFault(directory, report) {
52
+ const pending = readJson(join(directory, 'pending-reports.json'), []);
53
+ pending.push(report);
54
+ writeJson(directory, 'pending-reports.json', pending.slice(-PENDING_REPORT_LIMIT));
55
+ }
56
+
57
+ /** Reports wait on this computer until the site confirms them, so a hang offline is not lost. */
58
+ export async function sendPendingFaults(directory, url, request = fetch) {
59
+ const pending = readJson(join(directory, 'pending-reports.json'), []);
60
+ const delivered = new Set();
61
+ for (const report of pending) {
62
+ try {
63
+ const response = await request(url, { method: 'POST', redirect: 'error',
64
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify(report),
65
+ signal: AbortSignal.timeout(5_000) });
66
+ // The site refused this report for good; it must not hold back the others.
67
+ if (response.status === 400) { delivered.add(report.id); continue; }
68
+ if (!response.ok) break;
69
+ delivered.add(report.id);
70
+ } catch { break; }
71
+ }
72
+ if (!delivered.size) return 0;
73
+ const current = readJson(join(directory, 'pending-reports.json'), []);
74
+ writeJson(directory, 'pending-reports.json', current.filter(report => !delivered.has(report.id)));
75
+ return delivered.size;
76
+ }
@@ -0,0 +1,48 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { workerData } from 'node:worker_threads';
3
+ import { CHECK_MS, STALL_MS, faultReport, nextStep, rememberFault, sendPendingFaults, spendRestart } from './policy.mjs';
4
+
5
+ /**
6
+ * This thread keeps its own event loop, so it still runs when the monitor's is
7
+ * stuck. A stuck loop cannot run a shutdown handler either, which is why the
8
+ * restart is a kill: the launcher exits with it and the service manager starts
9
+ * a clean process. Durable jobs are not replayed after that; an attempt that
10
+ * was running is reported as needing confirmation.
11
+ */
12
+ const { buffer, directory, version, reportUrl, restartAllowed, stallMs = STALL_MS, checkMs = CHECK_MS } = workerData;
13
+ const beat = new BigInt64Array(buffer);
14
+ const send = () => reportUrl ? sendPendingFaults(directory, reportUrl).catch(() => 0) : Promise.resolve(0);
15
+ const within = (work, ms) => Promise.race([work, new Promise(resolve => setTimeout(resolve, ms))]);
16
+
17
+ let lastCheck = Date.now(), graceUntil = 0, reported = false, busy = false;
18
+ const record = (kind, stalledMs, action, restartsInWindow) => {
19
+ rememberFault(directory, faultReport({ id: randomUUID(), kind, at: Date.now(), stalledMs, action, restartsInWindow, version }));
20
+ };
21
+
22
+ async function check() {
23
+ if (busy) return;
24
+ busy = true;
25
+ try {
26
+ const now = Date.now(), last = Number(Atomics.load(beat, 0));
27
+ const step = nextStep({ now, lastCheck, beat: last, graceUntil, reported, stallMs, checkMs });
28
+ lastCheck = now; graceUntil = step.graceUntil;
29
+ if (step.recovered) {
30
+ reported = false;
31
+ record('event-loop-recovered', 0, 'none', 0);
32
+ await send();
33
+ return;
34
+ }
35
+ if (!step.stalled) return;
36
+ const budget = restartAllowed ? spendRestart(directory, now) : { restart: false, restartsInWindow: 0 };
37
+ if (!budget.restart && reported) return;
38
+ record('event-loop-stall', now - last, budget.restart ? 'restart' : 'held', budget.restartsInWindow);
39
+ reported = true;
40
+ await within(send(), 5_000);
41
+ if (budget.restart) process.kill(process.pid, 'SIGKILL');
42
+ } catch { /* A watchdog fault must never become the monitor's fault. */ }
43
+ finally { busy = false; }
44
+ }
45
+
46
+ setInterval(() => void check(), checkMs);
47
+ void send();
48
+ setInterval(() => void send(), 60 * 60_000).unref();
@@ -11,9 +11,19 @@ replaces them; checkout verification caches belong to one scan across its yields
11
11
 
12
12
  Claude root records update the current working folder and branch as the native
13
13
  conversation moves. Its launch directory is not a permanent repository binding.
14
- Sidechain folders and tool observations cannot replace the root conversation's
15
- checkout. Catalog linking verifies the current Git root while preserving the
16
- existing Task and Project identities.
14
+ Sidechain folders cannot replace the root conversation's checkout. When the
15
+ launch folder is inside a repository, the current folder decides, unless
16
+ sustained recent tool work shows another checkout. When it is a parent folder
17
+ such as `~/dev`, the chat belongs to the repository it most recently changed
18
+ (Write, Edit, MultiEdit, NotebookEdit, or `git -C <path> commit`), found by
19
+ walking up for `.git` without running Git; the current folder decides only
20
+ until such a change is known. Catalog linking verifies the chosen Git root while
21
+ preserving the existing Task and Project identities.
22
+
23
+ A pasted Claude image appears as an attachment. The label Claude Code writes
24
+ beside it (`[Image: source: …]`, `[Image #1]`) is dropped from the chat, title
25
+ and child title when that block holds only labels and the message carries the
26
+ image; any words the person typed with it stay.
17
27
 
18
28
  Claude child reads use only the requested owned log and its bounded recent
19
29
  window. Native `agentId` remains authoritative when it differs from the filename;
@@ -31,6 +31,7 @@ import {
31
31
  } from "./cursor";
32
32
  import { grokCapabilityUsage } from "./scan/grok";
33
33
  import { activityForSession } from './session-activity';
34
+ import { localTaskTransfers } from "../task-transfer";
34
35
  export { MAX_THREAD_ENTRIES, scanThreadActivity } from './session-activity';
35
36
  import {
36
37
  limitCapabilityUsageEvents,
@@ -40,7 +41,7 @@ import {
40
41
  import { createCapabilityTotals } from "./support/capability-totals";
41
42
  import { createExecutionSummaries, budgetExecutionSummaries } from './telemetry/execution-summaries';
42
43
  import { readCodexCapabilityHistory, type NativeCapabilityEvidence } from './native-capability-history';
43
- import { recordedClaudeUsage } from './scan/claude';
44
+ import { claudeChildActivity, recordedClaudeUsage } from './scan/claude';
44
45
 
45
46
  export { MAX_ACTIVITY_ENTRIES, MAX_ACTIVITY_TEXT, TOKEN_WINDOW_HOURS };
46
47
  export { nativeTranscriptRoots, nativeTranscriptSource, restoreNativeTranscriptSource } from "./native-source";
@@ -78,6 +79,14 @@ export function pickActivityEntries(all: ActivityEntry[], limit: number): Activi
78
79
  return [...byId.values()].sort((a, b) => a.createdAt - b.createdAt);
79
80
  }
80
81
 
82
+ /** Subagent rows of a chat whose own transcript already has a bounded reader. */
83
+ export function scanChildActivity(input: SessionInfo): ActivityEntry[] {
84
+ const session = localTaskTransfers().nativeSession(input);
85
+ const entries = session.agent === "claude" ? claudeChildActivity(session)
86
+ : scanSessionActivity(input).entries;
87
+ return pickActivityEntries(entries.filter((entry) => entry.childThreadId), MAX_ACTIVITY_ENTRIES);
88
+ }
89
+
81
90
  export function scanSessionActivity(session: SessionInfo): SessionActivity {
82
91
  // A Project rule that refused something is part of what happened in this
83
92
  // chat, so it is shown there, beside the call it stopped.