granttap-mcp 0.8.199 → 0.8.200

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.
package/README.md CHANGED
@@ -73,7 +73,7 @@ service need a durable path, not npm's temporary `npx` cache.
73
73
 
74
74
  ## What's new
75
75
 
76
- Available now, with GrantTap MCP 0.8.199 on npm and GrantTap 1.0.2 on the App Store:
76
+ Available now, with GrantTap MCP 0.8.200 on npm and GrantTap 1.0.2 on the App Store:
77
77
 
78
78
  - **Phones on the connection card.** In Claude (including the Claude desktop app),
79
79
  Codex, Cursor and Grok Build, the GrantTap card lists every phone paired with
@@ -8,6 +8,7 @@ import { childEntryFields } from "../../support/child-threads";
8
8
  import { diffPreviewFromInput, patchStatsByToolUse, sensitivePath, statsFromInput } from "../../support/edit-stats";
9
9
  import { redactSecrets } from "../../telemetry/command-preview";
10
10
  import { recordObservedWrite, writtenPaths } from "../../../mesh/observed/writes";
11
+ import type { ListedChanges } from "../../../transcript-history/recorded-edits";
11
12
  import {
12
13
  activityTelemetry,
13
14
  observeCapability,
@@ -190,11 +191,13 @@ function appendClaudeToolUse(input: {
190
191
  createdAt: number;
191
192
  index: number;
192
193
  blockIndex: number;
194
+ recorded?: ReadonlyMap<string, ListedChanges>;
193
195
  }): void {
194
196
  const {
195
197
  out, seen, session, observations, patches, childFields, sourceThreadId,
196
198
  block, createdAt, index, blockIndex,
197
199
  } = input;
200
+ const recorded = typeof block.id === "string" ? input.recorded?.get(block.id) : undefined;
198
201
  const classified = classifyTool(block.name, block.input);
199
202
  const sourceId =
200
203
  typeof block.id === "string"
@@ -221,6 +224,9 @@ function appendClaudeToolUse(input: {
221
224
  ...classified,
222
225
  ...(stats ?? {}),
223
226
  ...(diffPreview ? { diffPreview } : {}),
227
+ // What the call changed, for the chat's Files list; an agent launch carries its agent's edits.
228
+ ...(recorded?.files.length ? { fileChanges: recorded.files } : {}),
229
+ ...(recorded?.files.length && !recorded.complete ? { fileChangesComplete: false } : {}),
224
230
  ...(toolDescription(block.input) ? { summary: toolDescription(block.input) } : {}),
225
231
  ...(observation
226
232
  ? activityTelemetry(observation)
@@ -236,6 +242,8 @@ export function appendClaudeActivity(input: {
236
242
  observations: Map<string, CapabilityObservation>;
237
243
  child?: ChildThreadInfo;
238
244
  fullText?: boolean;
245
+ /** Recorded edits by tool call, read over the whole page; see `transcript-history/recorded-edits`. */
246
+ recorded?: ReadonlyMap<string, ListedChanges>;
239
247
  }): void {
240
248
  const pushEntry = (entry: PushEntryInput) => appendEntry({ ...entry, fullText: input.fullText });
241
249
  const { out, seen, session, lines, observations, child } = input;
@@ -284,7 +292,7 @@ export function appendClaudeActivity(input: {
284
292
  } else if (block?.type === "tool_use") {
285
293
  appendClaudeToolUse({
286
294
  out, seen, session, observations, patches, childFields, sourceThreadId,
287
- block, createdAt, index, blockIndex,
295
+ block, createdAt, index, blockIndex, recorded: input.recorded,
288
296
  });
289
297
  }
290
298
  });
@@ -264,6 +264,7 @@ type EntryExtras = Partial<
264
264
  | "linesRemoved"
265
265
  | "diffPreview"
266
266
  | "fileChanges"
267
+ | "fileChangesComplete"
267
268
  | "summary"
268
269
  >
269
270
  >;
@@ -17,6 +17,9 @@ back to the native turn boundary so the completed reply includes edits outside
17
17
  the visible page. Reads, file lists and diff previews are bounded; partial
18
18
  summaries and truncated diffs carry explicit flags. `tool-details.ts` keeps
19
19
  readable bounded call/result text independently of the compact timeline label.
20
+ [`recorded-edits/`](recorded-edits/README.md) adds Claude's own edits and every
21
+ nested agent's edits (Claude and Codex) to the same lists, each marked with its
22
+ agent and grouped by the checkout it is in.
20
23
 
21
24
  Behavior tests live in `tests/`. Licensed under the [GrantTap Commercial Source License](../../../../LICENSE).
22
25
 
@@ -3,7 +3,11 @@ import { sensitivePath } from "../sessions/support/edit-stats";
3
3
  import { statsFromPatchText } from "../sessions/support/edit-stats";
4
4
  import { redactSecrets } from "../sessions/telemetry/command-preview";
5
5
 
6
- export type RecordedFileChange = { path: string; linesAdded: number; linesRemoved: number; diff: string; diffTruncated?: boolean };
6
+ export type RecordedFileChange = { path: string; linesAdded: number; linesRemoved: number; diff: string; diffTruncated?: boolean;
7
+ /** Set when a nested agent made the change: its thread and the description it was launched with. */
8
+ agentThreadId?: string; agentTitle?: string;
9
+ /** The Git checkout, or else the folder, the file belongs to. */
10
+ folder?: string };
7
11
 
8
12
  export function nativeChanges(item: any): RecordedFileChange[] {
9
13
  if (item?.type !== "FileChange" || item.status !== "completed" || !item.changes) return [];
@@ -8,6 +8,7 @@ import { previousNativeLines } from "./native-lines";
8
8
  import { recordedFileChanges } from "./changes";
9
9
  import { recordedToolDetails } from "./tool-details";
10
10
  import { completedTurnChanges } from "./turn-changes";
11
+ import { claudeRecordedChanges, withCodexAgentChanges } from "./recorded-edits";
11
12
  import { cursorActivity, cursorConversationHistory } from "../sessions/cursor";
12
13
  export { nativeImageLines } from "./images";
13
14
  export { nativeTranscriptImage } from './images/native';
@@ -58,12 +59,13 @@ export function readTranscriptHistory(input: SessionInfo, cursor?: string): Sess
58
59
  const out: ActivityEntry[] = [];
59
60
  const seen = new Set<string>();
60
61
  const changes = recordedFileChanges(lines);
62
+ const recorded = session.agent === "claude" ? claudeRecordedChanges(session, lines) : undefined;
61
63
  const details = recordedToolDetails(lines);
62
64
  const offsets = new Map<string, number>();
63
65
  for (const line of window.lines) {
64
66
  const before = out.length;
65
67
  if (session.agent === "claude") {
66
- appendClaudeActivity({ out, seen, session, lines: [line.text], observations, fullText: true });
68
+ appendClaudeActivity({ out, seen, session, lines: [line.text], observations, fullText: true, recorded });
67
69
  } else {
68
70
  appendCodexActivity({ out, seen, session, lines: [line.text], observations, changes, details, fullText: true });
69
71
  }
@@ -75,7 +77,8 @@ export function readTranscriptHistory(input: SessionInfo, cursor?: string): Sess
75
77
  let entries = out.slice(from);
76
78
  for (const entry of entries) {
77
79
  if (entry.kind !== "final") continue;
78
- const summary = completedTurnChanges(path, session.sessionId, entry.id, offsets.get(entry.id)!, window.lines);
80
+ const summary = withCodexAgentChanges(session,
81
+ completedTurnChanges(path, session.sessionId, entry.id, offsets.get(entry.id)!, window.lines), entry.createdAt);
79
82
  entry.fileChanges = summary.files;
80
83
  entry.fileChangesComplete = summary.complete;
81
84
  }
@@ -0,0 +1,45 @@
1
+ # Recorded edits beyond the chat's own native items
2
+
3
+ Public entry: [`index.ts`](index.ts). Part of [transcript history](../README.md).
4
+
5
+ A chat's **Files** list is built from `fileChanges` on its root rows. Codex
6
+ writes completed `FileChange` items for its own turn; this module records what
7
+ was otherwise missing from that list:
8
+
9
+ - **Claude's own edits.** `claudeRecordedChanges` pairs each `Edit`, `Write`
10
+ and `MultiEdit` call on a history page with its result. Only a result without
11
+ `is_error` counts. The host's `structuredPatch` is the diff when its row
12
+ answers exactly one call; otherwise the call's old and new text is, the same
13
+ estimate the row's "+n −m" uses. The call's row carries the change.
14
+ - **What Claude's agents changed.** An `Agent` (or older `Task`) call's row
15
+ carries every file the agent it started changed, and the files of agents
16
+ that agent started, to 16 levels. A launch is linked to its transcript in
17
+ `<session>/subagents/` by the `agentId` its result names, or else by the
18
+ `toolUseId` in the `agent-*.meta.json` Claude Code writes beside it. Only the
19
+ chat's own listed subagent transcripts are read, and only those a launch on
20
+ the page leads to. A transcript is read once and then only what was appended
21
+ to it.
22
+ - **What Codex's agents changed.** A Codex agent is its own rollout with no link
23
+ to the call that started it, so a completed reply's `fileChanges` also holds
24
+ the edits its child rollouts completed between the turn's start and the reply.
25
+ An agent's edits during a turn that has not completed show once it has.
26
+
27
+ Each agent file names the agent: `agentThreadId` and `agentTitle` (the
28
+ description it was launched with, else the agent's first request). Every file
29
+ carries `folder`: the Git checkout it is in (a repository, or a worktree whose
30
+ `.git` is a file), the top folder that no longer exists for a removed worktree,
31
+ or else the file's own folder. Lists group by it.
32
+
33
+ Bounds are the history page's: at most 64 files per row (beyond that the row
34
+ says `fileChangesComplete: false`), diffs of at most 2 KiB per file, 128 KiB of
35
+ files per row and 384 KiB per page. Files whose names mark them as secrets are
36
+ left out, as for Codex; diffs are redacted. These are recorded edits, not a
37
+ claim about the final working tree. Older apps show the extra rows without the
38
+ new fields.
39
+
40
+ Tests in [`tests/`](tests/) use synthetic transcripts: Claude agents editing a
41
+ second worktree, a plain folder and a removed worktree, nested agents, a failed
42
+ and a secret edit, an agent still writing, the file and byte bounds, unreadable
43
+ or missing agents, and a Codex agent's edits inside and after a turn.
44
+
45
+ Licensed under the [GrantTap Commercial Source License](../../../../../LICENSE).
@@ -0,0 +1,128 @@
1
+ import { closeSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
2
+ import { basename } from 'node:path';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import type { SessionInfo } from '../../../../../packages/protocol/schema';
5
+ import { safeParse } from '../../sessions/support/common';
6
+ import { claudeChildLogPaths, claudeChildLogPathsBySession, claudeLogPath } from '../../sessions/scan/claude/shared';
7
+ import type { RecordedFileChange } from '../changes';
8
+ import { createClaudeCallReader } from './claude-calls';
9
+
10
+ export const MAX_LISTED_FILES = 64;
11
+ export const MAX_LISTED_DIFF = 2048;
12
+ export type ListedChanges = { files: RecordedFileChange[]; complete: boolean };
13
+
14
+ /** What one agent's transcript recorded so far; only appended bytes are read again. */
15
+ type AgentLog = {
16
+ ino: number; offset: number; carry: string; decoder: StringDecoder; read: (row: any) => void;
17
+ files: Map<string, RecordedFileChange>; overflow: boolean;
18
+ launches: Map<string, string | undefined>; agents: Map<string, string>;
19
+ };
20
+ const logs = new Map<string, AgentLog>();
21
+ const metas = new Map<string, { mtimeMs: number; call?: string }>();
22
+
23
+ /** Successive edits of one file read as one row, its diff bounded like a reply's summary. */
24
+ export function mergeChange(previous: RecordedFileChange | undefined, edit: RecordedFileChange): RecordedFileChange {
25
+ const diff = previous ? `${previous.diff}\n${edit.diff}` : edit.diff;
26
+ return { ...previous, ...edit, linesAdded: (previous?.linesAdded ?? 0) + edit.linesAdded,
27
+ linesRemoved: (previous?.linesRemoved ?? 0) + edit.linesRemoved, diff: diff.slice(0, MAX_LISTED_DIFF),
28
+ ...(previous?.diffTruncated || edit.diffTruncated || diff.length > MAX_LISTED_DIFF ? { diffTruncated: true } : {}) };
29
+ }
30
+
31
+ function freshLog(ino: number): AgentLog {
32
+ const log: AgentLog = { ino, offset: 0, carry: '', decoder: new StringDecoder('utf8'), read: () => {},
33
+ files: new Map(), overflow: false, launches: new Map(), agents: new Map() };
34
+ log.read = createClaudeCallReader({
35
+ edit: (_, change) => {
36
+ const previous = log.files.get(change.path);
37
+ if (!previous && log.files.size >= MAX_LISTED_FILES) { log.overflow = true; return; }
38
+ log.files.set(change.path, mergeChange(previous, change));
39
+ },
40
+ launch: (call, description) => log.launches.set(call, description),
41
+ agent: (call, agentId) => log.agents.set(call, agentId),
42
+ });
43
+ return log;
44
+ }
45
+
46
+ function agentLog(path: string): AgentLog | undefined {
47
+ let stat;
48
+ try { stat = statSync(path); } catch { logs.delete(path); return undefined; }
49
+ let log = logs.get(path);
50
+ if (!log || log.ino !== stat.ino || stat.size < log.offset) log = freshLog(stat.ino);
51
+ if (stat.size > log.offset) {
52
+ const fd = openSync(path, 'r');
53
+ try {
54
+ const buffer = Buffer.allocUnsafe(1 << 20);
55
+ while (log.offset < stat.size) {
56
+ const count = readSync(fd, buffer, 0, Math.min(buffer.length, stat.size - log.offset), log.offset);
57
+ if (!count) break;
58
+ log.offset += count;
59
+ const lines = (log.carry + log.decoder.write(buffer.subarray(0, count))).split('\n');
60
+ log.carry = lines.pop() ?? '';
61
+ for (const line of lines) if (line.includes('"tool_')) log.read(safeParse(line));
62
+ }
63
+ } finally { closeSync(fd); }
64
+ }
65
+ logs.delete(path);
66
+ logs.set(path, log);
67
+ while (logs.size > 128) logs.delete(logs.keys().next().value!);
68
+ return log;
69
+ }
70
+
71
+ /** The call an older agent was started by, from the small file Claude Code writes beside it. */
72
+ function metaCall(path: string): string | undefined {
73
+ const file = path.replace(/\.jsonl$/, '.meta.json');
74
+ let stat;
75
+ try { stat = statSync(file); } catch { return undefined; }
76
+ const known = metas.get(file);
77
+ if (known?.mtimeMs === stat.mtimeMs) return known.call;
78
+ let call: string | undefined;
79
+ try {
80
+ const meta = stat.size <= 64 * 1024 ? JSON.parse(readFileSync(file, 'utf8')) : undefined;
81
+ call = typeof meta?.toolUseId === 'string' ? meta.toolUseId : undefined;
82
+ } catch { /* An unreadable note links nothing. */ }
83
+ metas.set(file, { mtimeMs: stat.mtimeMs, call });
84
+ if (metas.size > 1024) metas.delete(metas.keys().next().value!);
85
+ return call;
86
+ }
87
+
88
+ /**
89
+ * Each root launch's agent edits, including agents those agents started.
90
+ * Only the chat's own listed subagent transcripts are read, and only those a
91
+ * launch in the visible page leads to.
92
+ */
93
+ export function claudeAgentChanges(session: SessionInfo, launches: Map<string, string | undefined>,
94
+ links: Map<string, string>): Map<string, ListedChanges> {
95
+ const out = new Map<string, ListedChanges>();
96
+ const parent = launches.size ? claudeLogPath(session.sessionId) : undefined;
97
+ if (!parent) return out;
98
+ const paths = claudeChildLogPathsBySession.get(session.sessionId) ?? claudeChildLogPaths(parent, session.sessionId);
99
+ const byAgent = new Map(paths.map(path => [basename(path, '.jsonl').replace(/^agent-/, ''), path]));
100
+ let byCall: Map<string, string> | undefined;
101
+ const pathFor = (call: string, named: Map<string, string>) => byAgent.get(named.get(call) ?? '')
102
+ ?? (byCall ??= new Map(paths.flatMap(path => { const id = metaCall(path); return id ? [[id, path]] : []; }))).get(call);
103
+ for (const [root, description] of launches) {
104
+ const files: RecordedFileChange[] = [];
105
+ let complete = true;
106
+ const queue = [{ call: root, description, named: links, depth: 0 }];
107
+ const visited = new Set<string>();
108
+ for (let item = queue.shift(); item; item = queue.shift()) {
109
+ const path = pathFor(item.call, item.named);
110
+ const log = path && !visited.has(path) && item.depth < 16 ? agentLog(path) : undefined;
111
+ if (!path || !log) continue;
112
+ visited.add(path);
113
+ const agentThreadId = basename(path, '.jsonl').replace(/^agent-/, '').slice(0, 256);
114
+ const agentTitle = item.description ?? session.childThreads?.find(child => child.threadId === agentThreadId)?.title;
115
+ for (const file of log.files.values()) files.push({ ...file, agentThreadId, ...(agentTitle ? { agentTitle } : {}) });
116
+ complete &&= !log.overflow;
117
+ for (const [call, launched] of log.launches) queue.push({ call, description: launched, named: log.agents, depth: item.depth + 1 });
118
+ }
119
+ if (files.length) out.set(root, listedChanges(files, complete));
120
+ }
121
+ return out;
122
+ }
123
+
124
+ /** At most 64 files per answer row, in path order; a list cut short says so. */
125
+ export function listedChanges(files: RecordedFileChange[], complete = true): ListedChanges {
126
+ const sorted = [...files].sort((a, b) => a.path.localeCompare(b.path));
127
+ return { files: sorted.slice(0, MAX_LISTED_FILES), complete: complete && sorted.length <= MAX_LISTED_FILES };
128
+ }
@@ -0,0 +1,89 @@
1
+ import { claudeTranscriptRecord } from '../../sessions/support/activity-helpers';
2
+ import { childTitle } from '../../sessions/support/child-threads';
3
+ import { sensitivePath, statsFromInput, statsFromPatch } from '../../sessions/support/edit-stats';
4
+ import { redactSecrets } from '../../sessions/telemetry/command-preview';
5
+ import type { RecordedFileChange } from '../changes';
6
+ import { changeFolder } from './folders';
7
+
8
+ const EDIT_TOOLS = new Set(['edit', 'write', 'multiedit']);
9
+ const AGENT_TOOLS = new Set(['agent', 'task']);
10
+ const MAX_DIFF = 16_384;
11
+ const AGENT_ID = /^[A-Za-z0-9_-]{1,128}$/;
12
+
13
+ export type ClaudeCallSink = {
14
+ /** A file edit whose result came back without an error. */
15
+ edit(callId: string, change: RecordedFileChange): void;
16
+ /** A call that started a nested agent, with the description it was given. */
17
+ launch(callId: string, description: string | undefined): void;
18
+ /** That call's result named the agent it started. */
19
+ agent(callId: string, agentId: string): void;
20
+ };
21
+
22
+ const leaf = (name: unknown) => String(name ?? '').trim().toLowerCase().split(/[.:/]/).at(-1) ?? '';
23
+
24
+ function marked(value: unknown, mark: string): string[] {
25
+ return typeof value === 'string' && value ? value.replace(/\n$/, '').split('\n').map(line => mark + line) : [];
26
+ }
27
+
28
+ function inputLines(tool: string, input: Record<string, unknown>): string[] {
29
+ if (tool === 'write') return marked(input.content, '+');
30
+ const edits = tool === 'multiedit' && Array.isArray(input.edits) ? input.edits : [input];
31
+ return edits.flatMap((edit: any) => [...marked(edit?.old_string, '-'), ...marked(edit?.new_string, '+')]);
32
+ }
33
+
34
+ function patchLines(patch: unknown): string[] {
35
+ if (!Array.isArray(patch)) return [];
36
+ return patch.flatMap((hunk: any) => Array.isArray(hunk?.lines)
37
+ ? hunk.lines.filter((line: unknown): line is string => typeof line === 'string') : []);
38
+ }
39
+
40
+ /**
41
+ * One successful Claude file edit. The host's own patch is exact when its
42
+ * result row carries one; otherwise the call's old and new text is the
43
+ * honest estimate, the same one the transcript row's "+n −m" uses.
44
+ * A file that must not travel is left out, like Codex's recorded edits.
45
+ */
46
+ export function claudeEditChange(tool: string, input: Record<string, unknown>, result: any): RecordedFileChange | undefined {
47
+ const path = typeof input.file_path === 'string' ? input.file_path.trim() : '';
48
+ if (!path || sensitivePath(path)) return undefined;
49
+ const patch = result && typeof result === 'object' && result.filePath === input.file_path ? result.structuredPatch : undefined;
50
+ const hunks = patchLines(patch);
51
+ const stats = (hunks.length ? statsFromPatch(patch) : undefined) ?? statsFromInput(tool, input)
52
+ ?? { linesAdded: 0, linesRemoved: 0 };
53
+ const clean = redactSecrets((hunks.length ? hunks : inputLines(tool, input)).join('\n'));
54
+ const folder = changeFolder(path);
55
+ return { path: path.slice(0, 2048), ...stats, diff: clean.slice(0, MAX_DIFF),
56
+ ...(clean.length > MAX_DIFF ? { diffTruncated: true } : {}), ...(folder ? { folder } : {}) };
57
+ }
58
+
59
+ /**
60
+ * Pairs Claude tool calls with their results one row at a time, so a growing
61
+ * transcript is read once. A row that answers several calls at once carries
62
+ * no per-call result detail; its edits fall back to their inputs.
63
+ */
64
+ export function createClaudeCallReader(sink: ClaudeCallSink): (row: any) => void {
65
+ const pending = new Map<string, { tool: string; input: Record<string, unknown> }>();
66
+ return row => {
67
+ const blocks = row?.message?.content;
68
+ if (!Array.isArray(blocks) || !claudeTranscriptRecord(row)) return;
69
+ const results = blocks.filter((block: any) => block?.type === 'tool_result').length;
70
+ const detail = results === 1 ? row.toolUseResult : undefined;
71
+ for (const block of blocks) {
72
+ if (block?.type === 'tool_use' && typeof block.id === 'string' && block.input && typeof block.input === 'object') {
73
+ const tool = leaf(block.name);
74
+ if (AGENT_TOOLS.has(tool)) sink.launch(block.id, childTitle(block.input.description));
75
+ else if (EDIT_TOOLS.has(tool)) {
76
+ if (pending.size >= 256) pending.delete(pending.keys().next().value!);
77
+ pending.set(block.id, { tool, input: block.input });
78
+ }
79
+ } else if (block?.type === 'tool_result' && typeof block.tool_use_id === 'string') {
80
+ if (typeof detail?.agentId === 'string' && AGENT_ID.test(detail.agentId)) sink.agent(block.tool_use_id, detail.agentId);
81
+ const call = pending.get(block.tool_use_id);
82
+ if (!call) continue;
83
+ pending.delete(block.tool_use_id);
84
+ const change = block.is_error === true ? undefined : claudeEditChange(call.tool, call.input, detail);
85
+ if (change) sink.edit(block.tool_use_id, change);
86
+ }
87
+ }
88
+ };
89
+ }
@@ -0,0 +1,49 @@
1
+ import { statSync } from 'node:fs';
2
+ import type { ActivityEntry, ChildThreadInfo, SessionInfo } from '../../../../../packages/protocol/schema';
3
+ import { appendCodexActivity } from '../../sessions/scan/codex/activity/rows';
4
+ import { CODEX_ACTIVITY_HEAD_BYTES, CODEX_ACTIVITY_TAIL_BYTES, codexActivitySourcesBySession,
5
+ readCodexLogWindow } from '../../sessions/scan/codex/shared';
6
+ import { recordedFileChanges, type RecordedFileChange } from '../changes';
7
+ import { mergeChange } from './claude-agents';
8
+ import { withFolder } from './folders';
9
+
10
+ type ChildEdits = { mtimeMs: number; size: number; edits: { at: number; files: RecordedFileChange[] }[] };
11
+ const children = new Map<string, ChildEdits>();
12
+
13
+ /** A child rollout's completed edits with their times; read again only when the file changes. */
14
+ function childEdits(path: string, session: SessionInfo, child: ChildThreadInfo): ChildEdits['edits'] {
15
+ let stat;
16
+ try { stat = statSync(path); } catch { children.delete(path); return []; }
17
+ const known = children.get(path);
18
+ if (known?.mtimeMs === stat.mtimeMs && known.size === stat.size) return known.edits;
19
+ const lines = readCodexLogWindow(path, CODEX_ACTIVITY_HEAD_BYTES, CODEX_ACTIVITY_TAIL_BYTES);
20
+ const out: ActivityEntry[] = [];
21
+ appendCodexActivity({ out, seen: new Set(), session, lines, observations: new Map(), child,
22
+ changes: recordedFileChanges(lines) });
23
+ const edits = out.flatMap(entry => entry.fileChanges?.length ? [{ at: entry.createdAt, files: entry.fileChanges }] : []);
24
+ children.delete(path);
25
+ children.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, edits });
26
+ while (children.size > 128) children.delete(children.keys().next().value!);
27
+ return edits;
28
+ }
29
+
30
+ /**
31
+ * Codex records a nested agent as its own rollout with no link to the call
32
+ * that started it, so a reply owns the agent edits completed during its turn.
33
+ */
34
+ export function codexAgentChanges(session: SessionInfo, from: number, to: number): RecordedFileChange[] {
35
+ const files = new Map<string, RecordedFileChange>();
36
+ for (const { path, child } of codexActivitySourcesBySession.get(session.sessionId) ?? []) {
37
+ if (!child) continue;
38
+ const agentTitle = child.title ?? child.agentName;
39
+ for (const edit of childEdits(path, session, child)) {
40
+ if (edit.at < from || edit.at > to) continue;
41
+ for (const file of edit.files) {
42
+ const key = `${child.threadId}\0${file.path}`;
43
+ files.set(key, mergeChange(files.get(key), withFolder({ ...file, agentThreadId: child.threadId,
44
+ ...(agentTitle ? { agentTitle } : {}) })));
45
+ }
46
+ }
47
+ }
48
+ return [...files.values()];
49
+ }
@@ -0,0 +1,40 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, isAbsolute, join } from 'node:path';
3
+
4
+ /** Folder → the checkout above it, or null when none is; shared by every file under it. */
5
+ const checkouts = new Map<string, string | null>();
6
+
7
+ /**
8
+ * The Git checkout (a repository or a worktree, whose `.git` is a file) a
9
+ * changed file belongs to, or else the folder it is in. Agents edit other
10
+ * worktrees than the chat's own, and a list grouped by checkout stays readable.
11
+ */
12
+ export function changeFolder(path: string): string | undefined {
13
+ if (!isAbsolute(path)) return undefined;
14
+ const visited: string[] = [];
15
+ let found: string | null = null;
16
+ for (let folder = dirname(path); visited.length < 64; folder = dirname(folder)) {
17
+ const known = checkouts.get(folder);
18
+ if (known !== undefined) { found = known; break; }
19
+ visited.push(folder);
20
+ if (existsSync(join(folder, '.git'))) { found = folder; break; }
21
+ if (dirname(folder) === folder) break;
22
+ }
23
+ if (checkouts.size > 4096) checkouts.clear();
24
+ for (const folder of visited) checkouts.set(folder, found);
25
+ return (found ?? removedFolder(path) ?? dirname(path)).slice(0, 2048);
26
+ }
27
+
28
+ /** A worktree removed since its agent finished: the top folder that is gone groups its files. */
29
+ function removedFolder(path: string): string | undefined {
30
+ let top: string | undefined;
31
+ for (let folder = dirname(path); dirname(folder) !== folder && !existsSync(folder); folder = dirname(folder)) top = folder;
32
+ return top;
33
+ }
34
+
35
+ /** A recorded file with the folder it is listed under. */
36
+ export function withFolder<T extends { path: string; folder?: string }>(file: T): T {
37
+ if (file.folder) return file;
38
+ const folder = changeFolder(file.path);
39
+ return folder ? { ...file, folder } : file;
40
+ }
@@ -0,0 +1,39 @@
1
+ import type { SessionInfo } from '../../../../../packages/protocol/schema';
2
+ import { safeParse } from '../../sessions/support/common';
3
+ import type { RecordedFileChange } from '../changes';
4
+ import { claudeAgentChanges, listedChanges, mergeChange, type ListedChanges } from './claude-agents';
5
+ import { createClaudeCallReader } from './claude-calls';
6
+ import { codexAgentChanges } from './codex-agents';
7
+ import { withFolder } from './folders';
8
+ export { changeFolder } from './folders';
9
+ export type { ListedChanges } from './claude-agents';
10
+
11
+ /**
12
+ * The recorded edits of a Claude page, keyed by the tool call they belong to:
13
+ * each successful Edit, Write or MultiEdit, and for each agent launch every
14
+ * file that agent (or an agent it started) changed.
15
+ */
16
+ export function claudeRecordedChanges(session: SessionInfo, lines: readonly string[]): Map<string, ListedChanges> {
17
+ const out = new Map<string, ListedChanges>();
18
+ const launches = new Map<string, string | undefined>(), links = new Map<string, string>();
19
+ const read = createClaudeCallReader({
20
+ edit: (call, change) => out.set(call, { files: [change], complete: true }),
21
+ launch: (call, description) => launches.set(call, description),
22
+ agent: (call, agentId) => links.set(call, agentId),
23
+ });
24
+ for (const line of lines) if (line.includes('"tool_')) read(safeParse(line));
25
+ for (const [call, changes] of claudeAgentChanges(session, launches, links)) out.set(call, changes);
26
+ return out;
27
+ }
28
+
29
+ /** A completed Codex reply's own edits and its agents' edits during the turn, one row per file. */
30
+ export function withCodexAgentChanges(session: SessionInfo, reply: { files: RecordedFileChange[]; complete: boolean;
31
+ startedAt?: number }, endedAt: number): ListedChanges {
32
+ const byPath = new Map<string, RecordedFileChange>();
33
+ for (const file of [...reply.files, ...codexAgentChanges(session, reply.startedAt ?? 0, endedAt)]) {
34
+ const previous = byPath.get(file.path);
35
+ byPath.set(file.path, previous ? mergeChange(previous, withFolder(file)) : withFolder(file));
36
+ }
37
+ const listed = listedChanges([...byPath.values()]);
38
+ return { files: listed.files, complete: reply.complete && listed.complete };
39
+ }
@@ -1,8 +1,9 @@
1
- import { safeParse } from "../sessions/support/common";
1
+ import { safeParse, ts } from "../sessions/support/common";
2
2
  import { nativeChanges, recordedFileChanges, type RecordedFileChange } from "./changes";
3
3
  import { nativeHistoryCursor, previousNativeLines, type NativeLine } from "./native-lines";
4
4
 
5
- type Summary = { files: RecordedFileChange[]; complete: boolean };
5
+ /** `startedAt` is when the reply's turn began, when its boundary row was read. */
6
+ type Summary = { files: RecordedFileChange[]; complete: boolean; startedAt?: number };
6
7
  const summaries = new Map<string, Summary>();
7
8
 
8
9
  function collectFiles(edits: RecordedFileChange[]): Summary {
@@ -35,6 +36,7 @@ export function completedTurnChanges(path: string, sessionId: string, finalId: s
35
36
  const native = new Map<string, RecordedFileChange[]>();
36
37
  const legacy: string[] = [];
37
38
  let legacyBytes = 0, complete = false, bounded = false;
39
+ let startedAt: number | undefined;
38
40
  let cursor = nativeHistoryCursor(path, sessionId, finalOffset);
39
41
  for (let page = 0; page < 32 && cursor; page++) {
40
42
  const window = previousNativeLines(path, sessionId, cursor);
@@ -46,6 +48,7 @@ export function completedTurnChanges(path: string, sessionId: string, finalId: s
46
48
  || row.type === "turn_context" && p.turn_id && p.turn_id !== turnId)
47
49
  || !turnId && (p.type === "user_message" || p.type === "message" && p.role === "user")) {
48
50
  complete = true;
51
+ startedAt = ts(row.timestamp) || undefined;
49
52
  break;
50
53
  }
51
54
  if (p.type === "item_completed" && (!turnId || p.turn_id === turnId)) {
@@ -63,7 +66,7 @@ export function completedTurnChanges(path: string, sessionId: string, finalId: s
63
66
  }
64
67
  const edits = native.size ? [...native.values()].reverse().flat()
65
68
  : [...recordedFileChanges(legacy).values()].flat();
66
- const summary = collectFiles(edits);
69
+ const summary: Summary = { ...collectFiles(edits), ...(startedAt ? { startedAt } : {}) };
67
70
  summary.complete &&= complete && (!bounded || native.size > 0);
68
71
  summaries.set(key, summary);
69
72
  if (summaries.size > 64) summaries.delete(summaries.keys().next().value!);
@@ -18,7 +18,7 @@ keeps each phone response tied to the exact originating chat and prompt.
18
18
  Install the supported CLI on this computer, then run:
19
19
 
20
20
  ```bash
21
- npm install -g granttap-mcp@0.8.199
21
+ npm install -g granttap-mcp@0.8.200
22
22
  granttap setup
23
23
  granttap status
24
24
  ```
@@ -4,7 +4,7 @@
4
4
  "command": "node",
5
5
  "args": [
6
6
  "-e",
7
- "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.199\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
7
+ "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.200\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
8
8
  ]
9
9
  }
10
10
  }
@@ -7,7 +7,7 @@ const { spawn } = require("node:child_process");
7
7
  const { existsSync } = require("node:fs");
8
8
  const { delimiter, dirname, join } = require("node:path");
9
9
 
10
- const PACKAGE = "granttap-mcp@0.8.199";
10
+ const PACKAGE = "granttap-mcp@0.8.200";
11
11
  const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
12
12
  const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
13
13
  ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granttap-mcp",
3
- "version": "0.8.199",
3
+ "version": "0.8.200",
4
4
  "description": "Approve, answer and steer Claude Code, Codex, Cursor and Grok Build from iPhone, iPad and Apple Watch: the local runtime, CLI and MCP server for GrantTap, a free App Store download.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -96,6 +96,11 @@ export const ActivityEntry = z.object({
96
96
  path: z.string().max(2048), linesAdded: z.number().int().nonnegative(),
97
97
  linesRemoved: z.number().int().nonnegative(), diff: z.string().max(16_384),
98
98
  diffTruncated: z.boolean().optional(),
99
+ /** The nested agent that made the change; absent for the chat's own edits. */
100
+ agentThreadId: z.string().max(256).optional(),
101
+ agentTitle: z.string().max(160).optional(),
102
+ /** The Git checkout, or else the folder, the file belongs to: what a list groups it under. */
103
+ folder: z.string().max(2048).optional(),
99
104
  })).max(64).optional(),
100
105
  });
101
106
  export type ActivityEntry = z.infer<typeof ActivityEntry>;