@phnx-labs/agents-cli 1.23.31 → 1.23.33

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.33
4
+
5
+ - **A Codex session that opened several PRs before the upgrade lists them all.** The resumable Codex parse state moves to v5, so a v4 checkpoint (written before the index recorded every PR) re-parses its transcript once instead of resuming with only its first PR, as Claude's v7 already does. Source: cli/src/lib/session/discover.ts
6
+
7
+ - **A live Claude row lists the PRs and tickets the session acted on.** `touchedPrs` (`[{ url, number, repo, action }]`, action `merged`, `reviewed`, `commented`, `checked out`, `edited` or `closed`) comes from `gh pr merge|review|comment|checkout|edit|close` and `agents projects prs merge|review|comment`; `touchedTickets` (`[{ id, action }]`) from `linear update`. Only calls that ran and succeeded count, newest first with the last action per item, leaving out what the session created itself (`prs`, `createdTickets`). Upgrading re-parses a Claude transcript from the start the next time it changes. Source: cli/src/lib/session/touched.ts, cli/src/lib/session/discover.ts, cli/src/lib/session/active.ts
8
+
9
+ ## 1.23.32
10
+
11
+ - **A session row lists every PR the session opened (#3989).** The session index records each PR a Claude or Codex session created (`pr_urls`, schema v53), not only the first, and live and ended rows read it as `prs`, so a long session whose PR creations scrolled out of its transcript tail still lists them all. Upgrading re-parses only the transcripts of sessions that already have a PR. Source: cli/src/lib/session/discover.ts, cli/src/lib/session/db.ts, cli/src/lib/session/active.ts
12
+
3
13
  ## 1.23.31
4
14
 
5
15
  - **A session row's `title` is the one name to show, and a fork says it is one.** `title` on `agents ps --json`, `agents ps watch --json` and `agents feed watch --json` (live and history rows) is never Claude's `<folder>-<n>` placeholder such as "agents-92" or "agents-1f", never the `[host/<device>]` fallback, and never an injected note, sub-agent hand-back or bare slash command; it falls through to the next usable name instead of going empty. A session started by `agents fork` carries `forkOf` (the source session id) and, until it has a name of its own, the source's name as its `title` instead of "fork of …". `agents fork` no longer launches an unnamed fork with `--name "fork of …"`, so the harness's own title takes over once it writes one; `--name` still names it. Source: `cli/src/lib/session/title.ts`, `cli/src/lib/session/fork.ts`, `cli/src/lib/session/active.ts`, `cli/src/lib/session/remote/watch.ts`, `cli/src/commands/fork.ts`.
@@ -2,6 +2,7 @@ import type { CloudTaskStatus } from '../cloud/types.js';
2
2
  import { type PidSessionEntry } from './pid-registry.js';
3
3
  import { type HookSessionIndex } from './hook-sessions.js';
4
4
  import { type SessionRecap } from './title.js';
5
+ import type { TouchedPr, TouchedTicket } from './touched.js';
5
6
  import { type UserPromptKind } from '@phnx-labs/sessions-cli/reader';
6
7
  import { type SessionState, type SessionActivity, type AwaitingReason, type StructuredQuestion, type TodoProgress, type DetectedPr, type DetectedWorktree, type DetectedTicket } from '@phnx-labs/sessions-cli/reader';
7
8
  import { type SessionAgentId, type SessionAttachment, type SessionFiles, type SessionMeta, type SessionRequest, type SessionTimeline } from '@phnx-labs/sessions-cli/reader';
@@ -21,7 +22,8 @@ export declare function unattributedFullRescanCountForTest(): number;
21
22
  export declare function attributedSetLostPids(prev: Set<number>, next: Set<number>): boolean;
22
23
  export declare function filterCachedUnattributed(sessions: ActiveSession[], attributed: Set<number>, alive: (pid: number, processStartedAtMs?: number) => boolean, ppidMap?: Map<number, number>): ActiveSession[];
23
24
  export type ActiveContext = 'terminal' | 'teams' | 'cloud' | 'headless';
24
- type BackfillMeta = Pick<SessionMeta, 'version' | 'account' | 'accountId' | 'accountKey' | 'timestamp' | 'label' | 'firstUserMessage' | 'lastUserMessage' | 'generatedTitle' | 'ticketId' | 'prUrl' | 'prNumber' | 'harness' | 'tokenCount' | 'durationMs' | 'subAgentCount' | 'lastActivity'>;
25
+ type BackfillMeta = Pick<SessionMeta, 'version' | 'account' | 'accountId' | 'accountKey' | 'timestamp' | 'label' | 'firstUserMessage' | 'lastUserMessage' | 'generatedTitle' | 'ticketId' | 'prUrl' | 'prNumber' | 'prUrls' | 'harness' | 'tokenCount' | 'durationMs' | 'subAgentCount' | 'lastActivity'>;
26
+ export declare function prsFromUrls(urls: string[]): DetectedPr[];
25
27
  export declare function backfillActiveRowsFromMeta(sessions: ActiveSession[], metaById: Map<string, BackfillMeta>): void;
26
28
  export declare function applySessionNames(sessions: ActiveSession[]): void;
27
29
  export declare function sessionAccountLabel(kind: string, session: Pick<SessionMeta, 'accountId' | 'accountKey' | 'account'>, accounts?: import("../account-registry.js").NativeAccount[]): string | undefined;
@@ -107,6 +109,8 @@ export interface ActiveSession {
107
109
  ticket?: DetectedTicket;
108
110
  rateLimited?: boolean;
109
111
  createdTickets?: string[];
112
+ touchedPrs?: TouchedPr[];
113
+ touchedTickets?: TouchedTicket[];
110
114
  spawnedTeam?: string;
111
115
  attachments?: SessionAttachment[];
112
116
  request?: SessionRequest;
@@ -21,7 +21,7 @@ import { forkSourceOf } from './fork.js';
21
21
  import { getIndexedSessionNames, latestSessionFileForCwd, indexedSessionIdForFile, findSessionsByShortIds, findSessionMachinesByIds, getSessionById } from './db.js';
22
22
  import { extractSessionTopic, classifyUserPrompt, tidyRequest } from '@phnx-labs/sessions-cli/reader';
23
23
  import { readSessionTailWithRaw } from '@phnx-labs/sessions-cli/reader';
24
- import { parseSession } from '@phnx-labs/sessions-cli/reader';
24
+ import { parseSession, extractPrUrl } from '@phnx-labs/sessions-cli/reader';
25
25
  import { computeTokPerSec } from './throughput.js';
26
26
  import { inferSessionState, readHarnessStatus } from '@phnx-labs/sessions-cli/reader';
27
27
  import { isSessionTrackedAgent, SESSION_AGENTS, AG_TMUX_NAME_RE } from '@phnx-labs/sessions-cli/reader';
@@ -85,6 +85,9 @@ export function filterCachedUnattributed(sessions, attributed, alive, ppidMap) {
85
85
  return alive(s.pid, s.processStartedAtMs);
86
86
  });
87
87
  }
88
+ export function prsFromUrls(urls) {
89
+ return urls.map((url) => extractPrUrl(url) ?? { url });
90
+ }
88
91
  export function backfillActiveRowsFromMeta(sessions, metaById) {
89
92
  const accounts = listNativeAccounts(readMeta());
90
93
  for (const s of sessions) {
@@ -110,6 +113,8 @@ export function backfillActiveRowsFromMeta(sessions, metaById) {
110
113
  s.ticket = { id: m.ticketId, url: linearIssueUrl(m.ticketId) };
111
114
  if (!s.pr && m.prUrl)
112
115
  s.pr = { url: m.prUrl, number: m.prNumber };
116
+ if (m.prUrls && m.prUrls.length > (s.prs?.length ?? 0))
117
+ s.prs = prsFromUrls(m.prUrls);
113
118
  if (!s.startedAtMs && m.timestamp) {
114
119
  const ts = new Date(m.timestamp).getTime();
115
120
  if (!Number.isNaN(ts))
@@ -153,6 +158,10 @@ export function applySessionNames(sessions) {
153
158
  }) ?? s.label;
154
159
  if (stored?.recap)
155
160
  s.recap = stored.recap;
161
+ if (stored?.touchedPrs)
162
+ s.touchedPrs = stored.touchedPrs;
163
+ if (stored?.touchedTickets)
164
+ s.touchedTickets = stored.touchedTickets;
156
165
  }
157
166
  }
158
167
  export function sessionAccountLabel(kind, session, accounts = listNativeAccounts(readMeta())) {
@@ -1,10 +1,11 @@
1
1
  import Database from '../sqlite.js';
2
2
  import type { SessionAgentId, SessionCheckpoint, SessionChecklistItem, SessionEvent, SessionFiles, SessionGlance, SessionMeta, SessionRequest, SessionSubagent, SessionTimeline, SummaryState } from '@phnx-labs/sessions-cli/reader';
3
3
  import type { SessionRecap } from './title.js';
4
+ import type { TouchedPr, TouchedTicket } from './touched.js';
4
5
  import { type IndexedToolCall } from '@phnx-labs/sessions-cli/reader';
5
6
  import { type ToolScanResumePoint } from './tool-store.js';
6
7
  import { type TimelineState } from '@phnx-labs/sessions-cli/reader';
7
- export declare const SCHEMA_VERSION = 52;
8
+ export declare const SCHEMA_VERSION = 53;
8
9
  export declare const CONTENT_INDEX_VERSION = 8;
9
10
  export declare const INSIGHTS_EXTRACTOR_VERSION = 7;
10
11
  export declare const SESSION_SUMMARY_EXTRACTOR_VERSION = 1;
@@ -94,6 +95,8 @@ export interface IndexedSessionNames {
94
95
  label?: string;
95
96
  customTitle?: string;
96
97
  recap?: SessionRecap;
98
+ touchedPrs?: TouchedPr[];
99
+ touchedTickets?: TouchedTicket[];
97
100
  }
98
101
  export declare function getIndexedSessionNames(rows: Array<{
99
102
  id: string;
@@ -18,7 +18,7 @@ import { firstUserMessageFromEvents, lastUserMessageFromEvents } from '@phnx-lab
18
18
  import { emptyTimelineState, TIMELINE_EXTRACTOR_VERSION } from '@phnx-labs/sessions-cli/reader';
19
19
  const SESSIONS_DIR = getSessionsDir();
20
20
  const DB_PATH = getSessionsDbPath();
21
- export const SCHEMA_VERSION = 52;
21
+ export const SCHEMA_VERSION = 53;
22
22
  export const CONTENT_INDEX_VERSION = 8;
23
23
  const RESOURCE_INDEX_VERSION = 2;
24
24
  function canonicalLedgerKey(filePath) {
@@ -74,6 +74,7 @@ CREATE TABLE IF NOT EXISTS sessions (
74
74
  is_team_origin INTEGER DEFAULT 0,
75
75
  pr_url TEXT,
76
76
  pr_number INTEGER,
77
+ pr_urls TEXT,
77
78
  worktree_slug TEXT,
78
79
  ticket_id TEXT,
79
80
  spawned_team TEXT,
@@ -1031,6 +1032,15 @@ function migrateSchema(db, fromVersion) {
1031
1032
  `);
1032
1033
  db.exec(`DELETE FROM session_resource_usage WHERE plugin IS NOT NULL AND plugin <> '' AND instr(name, ':') = 0`);
1033
1034
  }
1035
+ if (fromVersion < 53) {
1036
+ const cols = db.prepare(`PRAGMA table_info(sessions)`).all();
1037
+ if (!cols.some(c => c.name === 'pr_urls'))
1038
+ db.exec(`ALTER TABLE sessions ADD COLUMN pr_urls TEXT`);
1039
+ const withPr = db.prepare(`SELECT file_path FROM sessions WHERE pr_url IS NOT NULL AND file_path IS NOT NULL`).all();
1040
+ const dropLedger = db.prepare(`DELETE FROM scan_ledger WHERE file_path = ?`);
1041
+ for (const { file_path } of withPr)
1042
+ dropLedger.run(canonicalLedgerKey(file_path));
1043
+ }
1034
1044
  }
1035
1045
  function backfillClaudeAccounts(db, scope = 'all') {
1036
1046
  const where = scope === 'all'
@@ -1440,7 +1450,7 @@ const upsertSessionStmt = (db) => db.prepare(`
1440
1450
  output_tokens, input_tokens, cache_read_tokens, cache_write_tokens,
1441
1451
  cost_usd, cost_usd_nocache, duration_ms, model, tool_call_count,
1442
1452
  file_path, file_mtime_ms, file_size, scanned_at, is_team_origin,
1443
- pr_url, pr_number, worktree_slug, ticket_id, spawned_team,
1453
+ pr_url, pr_number, pr_urls, worktree_slug, ticket_id, spawned_team,
1444
1454
  sub_agent_count, background_shell_count, plan, todos,
1445
1455
  recent_directories_touched, linear_project, linear_project_url, machine,
1446
1456
  actor, initiated_by, phoenix_id, used_browser, used_computer
@@ -1451,7 +1461,7 @@ const upsertSessionStmt = (db) => db.prepare(`
1451
1461
  @output_tokens, @input_tokens, @cache_read_tokens, @cache_write_tokens,
1452
1462
  @cost_usd, @cost_usd_nocache, @duration_ms, @model, @tool_call_count,
1453
1463
  @file_path, @file_mtime_ms, @file_size, @scanned_at, @is_team_origin,
1454
- @pr_url, @pr_number, @worktree_slug, @ticket_id, @spawned_team,
1464
+ @pr_url, @pr_number, @pr_urls, @worktree_slug, @ticket_id, @spawned_team,
1455
1465
  @sub_agent_count, @background_shell_count, @plan, @todos,
1456
1466
  @recent_directories_touched, @linear_project, @linear_project_url, @machine,
1457
1467
  @actor, @initiated_by, @phoenix_id, @used_browser, @used_computer
@@ -1517,6 +1527,7 @@ const upsertSessionStmt = (db) => db.prepare(`
1517
1527
  is_team_origin = excluded.is_team_origin,
1518
1528
  pr_url = excluded.pr_url,
1519
1529
  pr_number = excluded.pr_number,
1530
+ pr_urls = excluded.pr_urls,
1520
1531
  worktree_slug = excluded.worktree_slug,
1521
1532
  ticket_id = excluded.ticket_id,
1522
1533
  spawned_team = excluded.spawned_team,
@@ -1749,6 +1760,7 @@ export function upsertSession(meta, content, scan, assistantContent = '') {
1749
1760
  is_team_origin: meta.isTeamOrigin ? 1 : 0,
1750
1761
  pr_url: meta.prUrl ?? null,
1751
1762
  pr_number: meta.prNumber ?? null,
1763
+ pr_urls: meta.prUrls ? JSON.stringify(meta.prUrls) : null,
1752
1764
  worktree_slug: meta.worktreeSlug ?? null,
1753
1765
  ticket_id: meta.ticketId ?? null,
1754
1766
  spawned_team: meta.spawnedTeam ?? null,
@@ -1922,6 +1934,7 @@ export function upsertSessionsBatch(entries) {
1922
1934
  is_team_origin: meta.isTeamOrigin ? 1 : 0,
1923
1935
  pr_url: meta.prUrl ?? null,
1924
1936
  pr_number: meta.prNumber ?? null,
1937
+ pr_urls: meta.prUrls ? JSON.stringify(meta.prUrls) : null,
1925
1938
  worktree_slug: meta.worktreeSlug ?? null,
1926
1939
  ticket_id: meta.ticketId ?? null,
1927
1940
  spawned_team: meta.spawnedTeam ?? null,
@@ -1971,6 +1984,10 @@ export function upsertSessionsBatch(entries) {
1971
1984
  }
1972
1985
  maintainSessionSearchIndex(db);
1973
1986
  }
1987
+ function nonEmptyJsonArray(raw) {
1988
+ const list = raw ? JSON.parse(raw) : undefined;
1989
+ return list && list.length > 0 ? list : undefined;
1990
+ }
1974
1991
  export function getIndexedSessionNames(rows) {
1975
1992
  const out = new Map();
1976
1993
  if (rows.length === 0)
@@ -1997,14 +2014,16 @@ export function getIndexedSessionNames(rows) {
1997
2014
  for (let i = 0; i < keys.length; i += CHUNK) {
1998
2015
  const chunk = keys.slice(i, i + CHUNK);
1999
2016
  const fromState = db
2000
- .prepare(`SELECT file_path, json_extract(parser_state, '$.customTitle') AS custom_title, json_extract(parser_state, '$.recap') AS recap FROM scan_ledger WHERE file_path IN (${chunk.map(() => '?').join(',')}) AND json_valid(parser_state)`)
2017
+ .prepare(`SELECT file_path, json_extract(parser_state, '$.customTitle') AS custom_title, json_extract(parser_state, '$.recap') AS recap, json_extract(parser_state, '$.touchedPrs') AS touched_prs, json_extract(parser_state, '$.touchedTickets') AS touched_tickets FROM scan_ledger WHERE file_path IN (${chunk.map(() => '?').join(',')}) AND json_valid(parser_state)`)
2001
2018
  .all(...chunk);
2002
2019
  for (const row of fromState) {
2003
2020
  const id = idByLedgerKey.get(row.file_path);
2004
2021
  const customTitle = typeof row.custom_title === 'string' && row.custom_title ? row.custom_title : undefined;
2005
2022
  const recap = row.recap ? JSON.parse(row.recap) : undefined;
2006
- if (customTitle || recap)
2007
- out.set(id, { ...out.get(id), customTitle, recap });
2023
+ const touchedPrs = nonEmptyJsonArray(row.touched_prs);
2024
+ const touchedTickets = nonEmptyJsonArray(row.touched_tickets);
2025
+ if (customTitle || recap || touchedPrs || touchedTickets)
2026
+ out.set(id, { ...out.get(id), customTitle, recap, touchedPrs, touchedTickets });
2008
2027
  }
2009
2028
  }
2010
2029
  return out;
@@ -2115,6 +2134,7 @@ function rowToMeta(row) {
2115
2134
  isTeamOrigin: row.is_team_origin === 1,
2116
2135
  prUrl: row.pr_url ?? undefined,
2117
2136
  prNumber: row.pr_number ?? undefined,
2137
+ prUrls: parseJsonColumn(row.pr_urls),
2118
2138
  worktreeSlug: row.worktree_slug ?? undefined,
2119
2139
  ticketId: row.ticket_id ?? undefined,
2120
2140
  spawnedTeam: row.spawned_team ?? undefined,
@@ -1,6 +1,7 @@
1
1
  import type { SessionAgentId, SessionEvent, SessionMeta, TodoProgress } from '@phnx-labs/sessions-cli/reader';
2
2
  export { machineForSessionFile } from './origin-machine.js';
3
3
  import { type ScanStamp } from './db.js';
4
+ import { type CommandTouches, type TouchedPr, type TouchedTicket } from './touched.js';
4
5
  import { type LiveSessionName, type SessionRecap } from './title.js';
5
6
  import { ToolCallCollector, type IndexedToolCall, type ToolCallCollectorSnapshot } from '@phnx-labs/sessions-cli/reader';
6
7
  interface DiscoverOptions {
@@ -58,6 +59,7 @@ interface ClaudeSessionScan {
58
59
  assistantText?: string;
59
60
  prUrl?: string;
60
61
  prNumber?: number;
62
+ prUrls?: string[];
61
63
  worktreeSlug?: string;
62
64
  ticketId?: string;
63
65
  createdTickets?: string[];
@@ -99,6 +101,7 @@ interface CodexSessionScan {
99
101
  assistantText?: string;
100
102
  prUrl?: string;
101
103
  prNumber?: number;
104
+ prUrls?: string[];
102
105
  worktreeSlug?: string;
103
106
  ticketId?: string;
104
107
  createdTickets?: string[];
@@ -201,11 +204,15 @@ interface ClaudeParseState {
201
204
  seenAssistantIds: Set<string>;
202
205
  userTexts: string[];
203
206
  assistantTexts: string[];
204
- sawPrCreate: boolean;
207
+ pendingPrCreates: Set<string>;
205
208
  prUrl?: string;
206
209
  prNumber?: number;
210
+ prUrls: string[];
207
211
  createdTickets: Set<string>;
208
212
  pendingTicketTools: Set<string>;
213
+ touchedPrs: TouchedPr[];
214
+ touchedTickets: TouchedTicket[];
215
+ pendingTouches: Map<string, CommandTouches>;
209
216
  spawnedTeam?: string;
210
217
  plan?: string;
211
218
  checklistEvents: SessionEvent[];
@@ -221,7 +228,7 @@ export declare function applyClaudeLine(state: ClaudeParseState, parsed: any): v
221
228
  export declare function finalizeClaudeScan(state: ClaudeParseState, sessionFile?: string): ClaudeSessionScan;
222
229
  export declare function scanClaudeSession(filePath: string): Promise<ClaudeSessionScan>;
223
230
  export interface ClaudeParserState {
224
- v: 6;
231
+ v: 7;
225
232
  subAgents: number;
226
233
  backgroundShells: number | undefined;
227
234
  offset: number;
@@ -253,11 +260,15 @@ export interface ClaudeParserState {
253
260
  costUsdNoCache: number;
254
261
  seenIdsSize: number;
255
262
  seenIdsRecent: string[];
256
- sawPrCreate: boolean;
263
+ pendingPrCreates?: string[];
257
264
  prUrl?: string;
258
265
  prNumber?: number;
266
+ prUrls: string[];
259
267
  pendingTicketTools: string[];
260
268
  createdTickets: string[];
269
+ touchedPrs: TouchedPr[];
270
+ touchedTickets: TouchedTicket[];
271
+ pendingTouches: Array<[string, CommandTouches]>;
261
272
  spawnedTeam?: string;
262
273
  ticketId?: string;
263
274
  contentText?: string;
@@ -304,9 +315,10 @@ interface CodexParseState {
304
315
  lastTsMs?: number;
305
316
  userTexts: string[];
306
317
  assistantTexts: string[];
307
- sawPrCreate: boolean;
318
+ pendingPrCreates: Set<string>;
308
319
  prUrl?: string;
309
320
  prNumber?: number;
321
+ prUrls: string[];
310
322
  createdTickets: Set<string>;
311
323
  pendingTicketTools: Set<string>;
312
324
  spawnedTeam?: string;
@@ -317,8 +329,10 @@ interface CodexParseState {
317
329
  slashCommandEvents: SessionEvent[];
318
330
  }
319
331
  export declare function initCodexParseState(): CodexParseState;
332
+ export declare function applyCodexLine(state: CodexParseState, parsed: any): void;
333
+ export declare function finalizeCodexScan(state: CodexParseState): CodexSessionScan;
320
334
  export interface CodexParserState {
321
- v: 4;
335
+ v: 5;
322
336
  offset: number;
323
337
  jsonlDroppingOversizedLine?: boolean;
324
338
  sessionId?: string;
@@ -334,9 +348,10 @@ export interface CodexParserState {
334
348
  lastTotalTokenUsage?: any;
335
349
  firstTsMs?: number;
336
350
  lastTsMs?: number;
337
- sawPrCreate: boolean;
351
+ pendingPrCreates?: string[];
338
352
  prUrl?: string;
339
353
  prNumber?: number;
354
+ prUrls: string[];
340
355
  pendingTicketTools: string[];
341
356
  createdTickets: string[];
342
357
  spawnedTeam?: string;
@@ -348,6 +363,7 @@ export interface CodexParserState {
348
363
  toolCalls: ToolCallCollectorSnapshot;
349
364
  }
350
365
  export declare function serializeCodexParserState(state: CodexParseState, offset: number, jsonlDroppingOversizedLine?: boolean): CodexParserState;
366
+ export declare function hydrateCodexParseState(prior: CodexParserState): CodexParseState;
351
367
  export declare function scanCodexSessionIncremental(filePath: string, fromOffset: number, prior: CodexParserState): Promise<{
352
368
  scan: CodexSessionScan;
353
369
  newState: CodexParserState;
@@ -30,6 +30,7 @@ export { machineForSessionFile } from './origin-machine.js';
30
30
  import { mapBounded } from '../concurrency.js';
31
31
  import { getDB, getScanStampByPath, getScanStampsForPaths, getParserStatesForPaths, getDirLedgerForPaths, recordDirScans, recordScans, seedLabelsFromNames, syncTopics, upsertSessionsBatch, querySessions, countSessions, ftsSearch, getSessionById, tryClaimScan, releaseScan, scanInProgressByLivePid, cacheLinearProject, CONTENT_INDEX_VERSION, } from './db.js';
32
32
  import { buildRunNameMap } from './run-names.js';
33
+ import { recordTouches, touchesFromCommand, trackPendingTouches } from './touched.js';
33
34
  import { claudeRecapFromLine, resolveSessionName } from './title.js';
34
35
  import { resolveLinearApiKey } from '../linear-cache.js';
35
36
  import { ToolCallCollector, collectClaudeToolCalls, collectCodexToolCalls, } from '@phnx-labs/sessions-cli/reader';
@@ -799,6 +800,7 @@ async function readClaudeMeta(filePath, sessionId, scanStamp, priorRow, names =
799
800
  isTeamOrigin,
800
801
  prUrl: scan.prUrl,
801
802
  prNumber: scan.prNumber,
803
+ prUrls: scan.prUrls,
802
804
  worktreeSlug: scan.worktreeSlug,
803
805
  ticketId: scan.ticketId,
804
806
  createdTickets: scan.createdTickets,
@@ -841,6 +843,7 @@ async function readClaudeMeta(filePath, sessionId, scanStamp, priorRow, names =
841
843
  isTeamOrigin,
842
844
  prUrl: scan.prUrl,
843
845
  prNumber: scan.prNumber,
846
+ prUrls: scan.prUrls,
844
847
  worktreeSlug: scan.worktreeSlug,
845
848
  ticketId: scan.ticketId,
846
849
  createdTickets: scan.createdTickets,
@@ -1082,6 +1085,7 @@ export async function readCodexMeta(filePath, resolveAccount, currentVersion, sc
1082
1085
  account: resolveAccount?.(),
1083
1086
  prUrl: scan.prUrl,
1084
1087
  prNumber: scan.prNumber,
1088
+ prUrls: scan.prUrls,
1085
1089
  worktreeSlug: scan.worktreeSlug,
1086
1090
  ticketId: scan.ticketId,
1087
1091
  createdTickets: scan.createdTickets,
@@ -2146,11 +2150,15 @@ export function initClaudeParseState() {
2146
2150
  seenAssistantIds: new Set(),
2147
2151
  userTexts: [],
2148
2152
  assistantTexts: [],
2149
- sawPrCreate: false,
2153
+ pendingPrCreates: new Set(),
2150
2154
  prUrl: undefined,
2151
2155
  prNumber: undefined,
2156
+ prUrls: [],
2152
2157
  createdTickets: new Set(),
2153
2158
  pendingTicketTools: new Set(),
2159
+ touchedPrs: [],
2160
+ touchedTickets: [],
2161
+ pendingTouches: new Map(),
2154
2162
  spawnedTeam: undefined,
2155
2163
  plan: undefined,
2156
2164
  checklistEvents: [],
@@ -2208,6 +2216,9 @@ export function applyClaudeLine(state, parsed) {
2208
2216
  if (typeof b?.id === 'string' && isTicketCreateTool(b?.name, b?.input?.command)) {
2209
2217
  state.pendingTicketTools.add(b.id);
2210
2218
  }
2219
+ if (typeof b?.id === 'string' && b?.name === 'Bash' && typeof b?.input?.command === 'string' && b.input.run_in_background !== true) {
2220
+ trackPendingTouches(state.pendingTouches, b.id, touchesFromCommand(b.input.command, typeof parsed.cwd === 'string' ? parsed.cwd : state.cwd));
2221
+ }
2211
2222
  if (b?.name === 'ExitPlanMode' && typeof b?.input?.plan === 'string') {
2212
2223
  const p = b.input.plan.trim();
2213
2224
  if (p)
@@ -2234,27 +2245,37 @@ export function applyClaudeLine(state, parsed) {
2234
2245
  state.createdTickets.add(t);
2235
2246
  }
2236
2247
  }
2237
- if (!state.prUrl) {
2238
- if (!state.sawPrCreate && parsed.type === 'assistant' && Array.isArray(parsed.message?.content)) {
2239
- for (const b of parsed.message.content) {
2240
- if (b?.type === 'tool_use' && typeof b?.input?.command === 'string' && isPrCreateCommand(b.input.command)) {
2241
- state.sawPrCreate = true;
2242
- }
2248
+ if (parsed.type === 'assistant' && Array.isArray(parsed.message?.content)) {
2249
+ for (const b of parsed.message.content) {
2250
+ if (b?.type === 'tool_use' && typeof b?.id === 'string' && typeof b?.input?.command === 'string' && isPrCreateCommand(b.input.command)) {
2251
+ state.pendingPrCreates.add(b.id);
2243
2252
  }
2244
2253
  }
2245
- if (state.sawPrCreate && parsed.type === 'user' && Array.isArray(parsed.message?.content)) {
2246
- for (const b of parsed.message.content) {
2247
- if (b?.type !== 'tool_result')
2248
- continue;
2249
- const text = typeof b.content === 'string'
2250
- ? b.content
2251
- : Array.isArray(b.content) ? b.content.map((c) => c?.text || '').join('\n') : '';
2252
- const pr = extractPrUrl(text);
2253
- if (pr) {
2254
- state.prUrl = pr.url;
2255
- state.prNumber = pr.number;
2256
- }
2257
- }
2254
+ }
2255
+ if (state.pendingPrCreates.size > 0 && parsed.type === 'user' && Array.isArray(parsed.message?.content)) {
2256
+ for (const b of parsed.message.content) {
2257
+ if (b?.type !== 'tool_result' || !state.pendingPrCreates.delete(b.tool_use_id))
2258
+ continue;
2259
+ const text = typeof b.content === 'string'
2260
+ ? b.content
2261
+ : Array.isArray(b.content) ? b.content.map((c) => c?.text || '').join('\n') : '';
2262
+ recordCreatedPr(state, extractPrUrl(text));
2263
+ }
2264
+ }
2265
+ if (state.pendingTouches.size > 0 && parsed.type === 'user' && Array.isArray(parsed.message?.content)) {
2266
+ for (const b of parsed.message.content) {
2267
+ if (b?.type !== 'tool_result' || typeof b?.tool_use_id !== 'string')
2268
+ continue;
2269
+ const touches = state.pendingTouches.get(b.tool_use_id);
2270
+ if (!touches)
2271
+ continue;
2272
+ state.pendingTouches.delete(b.tool_use_id);
2273
+ if (b.is_error === true)
2274
+ continue;
2275
+ const output = typeof b.content === 'string'
2276
+ ? b.content
2277
+ : Array.isArray(b.content) ? b.content.map((c) => c?.text || '').join('\n') : '';
2278
+ recordTouches(state, touches, output, { prUrls: state.prUrls, tickets: state.createdTickets });
2258
2279
  }
2259
2280
  }
2260
2281
  if (typeof parsed.timestamp === 'string') {
@@ -2389,6 +2410,7 @@ export function finalizeClaudeScan(state, sessionFile) {
2389
2410
  assistantText: state.assistantTexts.length > 0 ? state.assistantTexts.join('\n') : undefined,
2390
2411
  prUrl: state.prUrl,
2391
2412
  prNumber: state.prNumber,
2413
+ prUrls: state.prUrls.length > 1 ? [...state.prUrls] : undefined,
2392
2414
  worktreeSlug: worktree?.slug,
2393
2415
  ticketId: ticket?.id,
2394
2416
  createdTickets: state.createdTickets.size > 0 ? [...state.createdTickets] : undefined,
@@ -2434,7 +2456,7 @@ export function serializeClaudeParserState(state, offset, jsonlDroppingOversized
2434
2456
  : allIds;
2435
2457
  const ticket = detectTicket(state.userTexts.join('\n') || undefined, state.gitBranch);
2436
2458
  return {
2437
- v: 6,
2459
+ v: 7,
2438
2460
  subAgents: state.subAgents,
2439
2461
  backgroundShells: state.backgroundShells,
2440
2462
  offset,
@@ -2466,11 +2488,15 @@ export function serializeClaudeParserState(state, offset, jsonlDroppingOversized
2466
2488
  costUsdNoCache: state.costUsdNoCache,
2467
2489
  seenIdsSize: state.seenAssistantIds.size,
2468
2490
  seenIdsRecent,
2469
- sawPrCreate: state.sawPrCreate,
2491
+ pendingPrCreates: [...state.pendingPrCreates],
2470
2492
  prUrl: state.prUrl,
2471
2493
  prNumber: state.prNumber,
2494
+ prUrls: state.prUrls,
2472
2495
  pendingTicketTools: [...state.pendingTicketTools],
2473
2496
  createdTickets: [...state.createdTickets],
2497
+ touchedPrs: state.touchedPrs,
2498
+ touchedTickets: state.touchedTickets,
2499
+ pendingTouches: [...state.pendingTouches],
2474
2500
  spawnedTeam: state.spawnedTeam,
2475
2501
  ticketId: ticket?.id,
2476
2502
  contentText: state.userTexts.length > 0 ? state.userTexts.join('\n') : undefined,
@@ -2520,10 +2546,14 @@ export function hydrateClaudeParseState(prior) {
2520
2546
  assistantTexts: prior.assistantContentText !== undefined && prior.assistantContentText.length > 0
2521
2547
  ? [prior.assistantContentText]
2522
2548
  : [],
2523
- sawPrCreate: prior.sawPrCreate,
2549
+ pendingPrCreates: new Set(prior.pendingPrCreates),
2524
2550
  prUrl: prior.prUrl,
2525
2551
  prNumber: prior.prNumber,
2552
+ prUrls: prior.prUrls,
2526
2553
  createdTickets: new Set(prior.createdTickets),
2554
+ touchedPrs: prior.touchedPrs,
2555
+ touchedTickets: prior.touchedTickets,
2556
+ pendingTouches: new Map(prior.pendingTouches),
2527
2557
  pendingTicketTools: new Set(prior.pendingTicketTools),
2528
2558
  spawnedTeam: prior.spawnedTeam,
2529
2559
  plan: prior.plan,
@@ -2593,12 +2623,22 @@ async function claudeSessionIdentityAt(filePath, maxBytes = 1_048_576) {
2593
2623
  }
2594
2624
  return state.timestamp;
2595
2625
  }
2626
+ function recordCreatedPr(state, pr) {
2627
+ if (!pr)
2628
+ return;
2629
+ if (!state.prUrl) {
2630
+ state.prUrl = pr.url;
2631
+ state.prNumber = pr.number;
2632
+ }
2633
+ if (!state.prUrls.includes(pr.url))
2634
+ state.prUrls.push(pr.url);
2635
+ }
2596
2636
  function parsePriorClaudeState(row) {
2597
2637
  if (!row?.parserState)
2598
2638
  return null;
2599
2639
  try {
2600
2640
  const parsed = JSON.parse(row.parserState);
2601
- if (parsed?.v !== 6 || typeof parsed.offset !== 'number' || parsed.toolCalls?.v !== 1)
2641
+ if (parsed?.v !== 7 || typeof parsed.offset !== 'number' || parsed.toolCalls?.v !== 1)
2602
2642
  return null;
2603
2643
  return parsed;
2604
2644
  }
@@ -2632,9 +2672,10 @@ export function initCodexParseState() {
2632
2672
  lastTsMs: undefined,
2633
2673
  userTexts: [],
2634
2674
  assistantTexts: [],
2635
- sawPrCreate: false,
2675
+ pendingPrCreates: new Set(),
2636
2676
  prUrl: undefined,
2637
2677
  prNumber: undefined,
2678
+ prUrls: [],
2638
2679
  createdTickets: new Set(),
2639
2680
  pendingTicketTools: new Set(),
2640
2681
  spawnedTeam: undefined,
@@ -2645,7 +2686,7 @@ export function initCodexParseState() {
2645
2686
  slashCommandEvents: [],
2646
2687
  };
2647
2688
  }
2648
- function applyCodexLine(state, parsed) {
2689
+ export function applyCodexLine(state, parsed) {
2649
2690
  collectCodexToolCalls(state.toolCollector, parsed);
2650
2691
  if (parsed.type === 'response_item') {
2651
2692
  const p = parsed.payload || {};
@@ -2661,8 +2702,8 @@ function applyCodexLine(state, parsed) {
2661
2702
  type: 'tool_use', agent: 'codex', timestamp: parsed.timestamp || '', tool: p.name, args,
2662
2703
  path: args.file_path || args.path, command: cmd || undefined,
2663
2704
  });
2664
- if (!state.prUrl && !state.sawPrCreate && isPrCreateCommand(cmd))
2665
- state.sawPrCreate = true;
2705
+ if (typeof p.call_id === 'string' && isPrCreateCommand(cmd))
2706
+ state.pendingPrCreates.add(p.call_id);
2666
2707
  if (!state.spawnedTeam) {
2667
2708
  const team = detectSpawnedTeam(cmd);
2668
2709
  if (team)
@@ -2673,13 +2714,8 @@ function applyCodexLine(state, parsed) {
2673
2714
  }
2674
2715
  }
2675
2716
  if (p.type === 'function_call_output') {
2676
- if (!state.prUrl && state.sawPrCreate) {
2677
- const pr = extractPrUrl(String(p.output || ''));
2678
- if (pr) {
2679
- state.prUrl = pr.url;
2680
- state.prNumber = pr.number;
2681
- }
2682
- }
2717
+ if (typeof p.call_id === 'string' && state.pendingPrCreates.delete(p.call_id))
2718
+ recordCreatedPr(state, extractPrUrl(String(p.output || '')));
2683
2719
  if (typeof p.call_id === 'string' && state.pendingTicketTools.has(p.call_id)) {
2684
2720
  state.pendingTicketTools.delete(p.call_id);
2685
2721
  const t = extractCreatedTicket(String(p.output || ''));
@@ -2752,7 +2788,7 @@ function applyCodexLine(state, parsed) {
2752
2788
  state.model = parsed.payload.info.model;
2753
2789
  }
2754
2790
  }
2755
- function finalizeCodexScan(state) {
2791
+ export function finalizeCodexScan(state) {
2756
2792
  const snap = state.lastTotalTokenUsage;
2757
2793
  const outputTokens = snap
2758
2794
  ? (snap.output_tokens ?? 0) + (snap.reasoning_output_tokens ?? 0)
@@ -2806,6 +2842,7 @@ function finalizeCodexScan(state) {
2806
2842
  assistantText: state.assistantTexts.length > 0 ? state.assistantTexts.join('\n') : undefined,
2807
2843
  prUrl: state.prUrl,
2808
2844
  prNumber: state.prNumber,
2845
+ prUrls: state.prUrls.length > 1 ? [...state.prUrls] : undefined,
2809
2846
  worktreeSlug: worktree?.slug,
2810
2847
  ticketId: ticket?.id,
2811
2848
  createdTickets: state.createdTickets.size > 0 ? [...state.createdTickets] : undefined,
@@ -2841,7 +2878,7 @@ async function scanCodexSession(filePath) {
2841
2878
  export function serializeCodexParserState(state, offset, jsonlDroppingOversizedLine = false) {
2842
2879
  const ticket = detectTicket(state.userTexts.join('\n') || undefined, state.gitBranch);
2843
2880
  return {
2844
- v: 4,
2881
+ v: 5,
2845
2882
  offset,
2846
2883
  jsonlDroppingOversizedLine: jsonlDroppingOversizedLine || undefined,
2847
2884
  sessionId: state.sessionId,
@@ -2857,9 +2894,10 @@ export function serializeCodexParserState(state, offset, jsonlDroppingOversizedL
2857
2894
  lastTotalTokenUsage: state.lastTotalTokenUsage,
2858
2895
  firstTsMs: state.firstTsMs,
2859
2896
  lastTsMs: state.lastTsMs,
2860
- sawPrCreate: state.sawPrCreate,
2897
+ pendingPrCreates: [...state.pendingPrCreates],
2861
2898
  prUrl: state.prUrl,
2862
2899
  prNumber: state.prNumber,
2900
+ prUrls: state.prUrls,
2863
2901
  pendingTicketTools: [...state.pendingTicketTools],
2864
2902
  createdTickets: [...state.createdTickets],
2865
2903
  spawnedTeam: state.spawnedTeam,
@@ -2871,7 +2909,7 @@ export function serializeCodexParserState(state, offset, jsonlDroppingOversizedL
2871
2909
  toolCalls: state.toolCollector.snapshot(),
2872
2910
  };
2873
2911
  }
2874
- function hydrateCodexParseState(prior) {
2912
+ export function hydrateCodexParseState(prior) {
2875
2913
  return {
2876
2914
  sessionId: prior.sessionId,
2877
2915
  timestamp: prior.timestamp,
@@ -2890,9 +2928,10 @@ function hydrateCodexParseState(prior) {
2890
2928
  assistantTexts: prior.assistantContentText !== undefined && prior.assistantContentText.length > 0
2891
2929
  ? [prior.assistantContentText]
2892
2930
  : [],
2893
- sawPrCreate: prior.sawPrCreate,
2931
+ pendingPrCreates: new Set(prior.pendingPrCreates),
2894
2932
  prUrl: prior.prUrl,
2895
2933
  prNumber: prior.prNumber,
2934
+ prUrls: prior.prUrls,
2896
2935
  createdTickets: new Set(prior.createdTickets),
2897
2936
  pendingTicketTools: new Set(prior.pendingTicketTools),
2898
2937
  spawnedTeam: prior.spawnedTeam,
@@ -2967,7 +3006,7 @@ function parsePriorCodexState(row) {
2967
3006
  return null;
2968
3007
  try {
2969
3008
  const parsed = JSON.parse(row.parserState);
2970
- if (parsed?.v !== 4 || typeof parsed.offset !== 'number' || parsed.toolCalls?.v !== 1)
3009
+ if (parsed?.v !== 5 || typeof parsed.offset !== 'number' || parsed.toolCalls?.v !== 1)
2971
3010
  return null;
2972
3011
  return parsed;
2973
3012
  }
@@ -10,7 +10,7 @@ import { machineId, normalizeHost } from '../../machine-id.js';
10
10
  import { shellQuote } from '../../ssh-exec.js';
11
11
  import { streamFromPeer } from './peer-stream.js';
12
12
  import { buildWindowsAgentsCommand, remoteShellFor } from '../../hosts/remote-cmd.js';
13
- import { artifactKind, deriveImportantMessage, deriveSessionRecap, isReapableOrphan, sessionAccountLabel } from '../active.js';
13
+ import { artifactKind, deriveImportantMessage, deriveSessionRecap, isReapableOrphan, prsFromUrls, sessionAccountLabel } from '../active.js';
14
14
  import { loadSessionPreviewDigest, readCachedPreviewDigest } from '../preview-digest.js';
15
15
  import { indexArtifactSidecars, mergeArtifacts } from '@phnx-labs/sessions-cli/reader';
16
16
  import { listNativeAccounts } from '../../account-registry.js';
@@ -133,6 +133,7 @@ export function toPreviousSessionWatchRow(scope, session, accounts = listNativeA
133
133
  ...(session.account ? { account: session.account } : {}),
134
134
  accountLabel: sessionAccountLabel(session.agent, session, accounts),
135
135
  ...(session.prUrl ? { pr: { url: session.prUrl, number: session.prNumber } } : {}),
136
+ ...(session.prUrls ? { prs: prsFromUrls(session.prUrls) } : {}),
136
137
  ...(worktree ? { worktree } : {}),
137
138
  ...(session.gitBranch ? { branch: session.gitBranch } : {}),
138
139
  ...(session.ticketId ? { ticket: { id: session.ticketId, url: linearIssueUrl(session.ticketId) } } : {}),
@@ -0,0 +1,30 @@
1
+ export type TouchedPrAction = 'merged' | 'reviewed' | 'commented' | 'checked out' | 'edited' | 'closed';
2
+ export interface TouchedPr {
3
+ url: string;
4
+ number: number;
5
+ repo: string;
6
+ action: TouchedPrAction;
7
+ }
8
+ export interface TouchedTicket {
9
+ id: string;
10
+ action: string;
11
+ }
12
+ export interface CommandTouches {
13
+ prs: Array<TouchedPr & {
14
+ masked?: true;
15
+ }>;
16
+ tickets: Array<TouchedTicket & {
17
+ masked?: true;
18
+ }>;
19
+ }
20
+ export declare function touchesFromCommand(command: string, cwd: string | undefined, repoForDir?: (dir: string) => string | undefined): CommandTouches;
21
+ interface TouchedLedger {
22
+ touchedPrs: TouchedPr[];
23
+ touchedTickets: TouchedTicket[];
24
+ }
25
+ export declare function trackPendingTouches(pending: Map<string, CommandTouches>, id: string, touches: CommandTouches): void;
26
+ export declare function recordTouches(ledger: TouchedLedger, touches: CommandTouches, output: string, created: {
27
+ prUrls: string[];
28
+ tickets: Iterable<string>;
29
+ }): void;
30
+ export {};
@@ -0,0 +1,297 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { linearIssueKeys, tokenizeBash } from '@phnx-labs/sessions-cli/reader';
6
+ import { repoFromRemote } from '../github/gh-overload.js';
7
+ const TOUCHED_MAX = 50;
8
+ const PENDING_MAX = 64;
9
+ const GH_BODY_FLAGS = ['-b', '--body', '-F', '--body-file'];
10
+ const GH_PR_VERBS = {
11
+ merge: { action: 'merged', valueFlags: new Set([...GH_BODY_FLAGS, '-t', '--subject', '--match-head-commit', '-A', '--author-email']) },
12
+ review: { action: 'reviewed', valueFlags: new Set(GH_BODY_FLAGS) },
13
+ comment: { action: 'commented', valueFlags: new Set(GH_BODY_FLAGS) },
14
+ checkout: { action: 'checked out', valueFlags: new Set(['-b', '--branch']) },
15
+ edit: {
16
+ action: 'edited',
17
+ valueFlags: new Set([...GH_BODY_FLAGS, '-t', '--title', '-B', '--base', '-m', '--milestone',
18
+ '--add-assignee', '--remove-assignee', '--add-label', '--remove-label', '--add-reviewer',
19
+ '--remove-reviewer', '--add-project', '--remove-project']),
20
+ },
21
+ close: { action: 'closed', valueFlags: new Set(['-c', '--comment']) },
22
+ };
23
+ const AGENTS_PRS_ACTIONS = {
24
+ merge: 'merged',
25
+ review: 'reviewed',
26
+ comment: 'commented',
27
+ };
28
+ const LINEAR_UPDATE_VALUE_FLAGS = new Set([
29
+ '--status', '--comment', '--proof', '--label', '--unlabel', '--priority', '--assign', '--delegate',
30
+ '--parent', '--project', '--milestone', '--title', '--description', '--description-file',
31
+ '--due-date', '--remind-at', '--cycle', '--blocks', '--blocked-by', '--relates', '--team',
32
+ ]);
33
+ const MERGED_EVIDENCE_RE = /"merged":\s*true|\bmerged pull request\b/i;
34
+ const PR_URL_RE = /^https?:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)(?:[/?#]\S*)?$/;
35
+ function heredocDelimiter(cmd, at) {
36
+ const m = cmd.slice(at).match(/^<<(-?)\s*(['"]?)([A-Za-z_][\w-]*)\2/);
37
+ return m ? { word: m[3], strip: m[1] === '-' } : undefined;
38
+ }
39
+ function splitTopLevel(cmd) {
40
+ const out = [];
41
+ const heredocs = [];
42
+ let start = 0;
43
+ let depth = 0;
44
+ let quote;
45
+ const cut = (end, op, next) => {
46
+ const text = cmd.slice(start, end).trim();
47
+ if (text)
48
+ out.push({ text, op });
49
+ else if (out.length > 0 && op)
50
+ out[out.length - 1].op = op;
51
+ start = next;
52
+ return next - 1;
53
+ };
54
+ for (let i = 0; i < cmd.length; i++) {
55
+ const c = cmd[i];
56
+ if (quote) {
57
+ if (c === '\\' && quote !== "'")
58
+ i++;
59
+ else if (c === quote)
60
+ quote = undefined;
61
+ continue;
62
+ }
63
+ if (c === '\\') {
64
+ i++;
65
+ continue;
66
+ }
67
+ if (c === "'" || c === '"' || c === '`') {
68
+ quote = c;
69
+ continue;
70
+ }
71
+ if (c === '(') {
72
+ depth++;
73
+ continue;
74
+ }
75
+ if (c === ')') {
76
+ depth = Math.max(0, depth - 1);
77
+ continue;
78
+ }
79
+ if (depth > 0)
80
+ continue;
81
+ if (c === '<' && cmd[i + 1] === '<' && cmd[i + 2] !== '<') {
82
+ const h = heredocDelimiter(cmd, i);
83
+ if (h)
84
+ heredocs.push(h);
85
+ i++;
86
+ continue;
87
+ }
88
+ if (c === '\n') {
89
+ let next = i + 1;
90
+ for (const h of heredocs.splice(0)) {
91
+ while (next < cmd.length) {
92
+ const eol = cmd.indexOf('\n', next);
93
+ const line = cmd.slice(next, eol < 0 ? cmd.length : eol);
94
+ next = eol < 0 ? cmd.length : eol + 1;
95
+ if ((h.strip ? line.replace(/^\t+/, '') : line) === h.word)
96
+ break;
97
+ }
98
+ }
99
+ i = cut(i, ';', next);
100
+ continue;
101
+ }
102
+ if (c === ';') {
103
+ i = cut(i, ';', i + 1);
104
+ continue;
105
+ }
106
+ if (c === '&' && cmd[i + 1] === '&') {
107
+ i = cut(i, '&&', i + 2);
108
+ continue;
109
+ }
110
+ if (c === '|' && cmd[i + 1] === '|') {
111
+ i = cut(i, '||', i + 2);
112
+ continue;
113
+ }
114
+ if (c === '|') {
115
+ i = cut(i, '|', cmd[i + 1] === '&' ? i + 2 : i + 1);
116
+ continue;
117
+ }
118
+ if (c === '&' && cmd[i - 1] !== '>' && cmd[i + 1] !== '>') {
119
+ i = cut(i, '&', i + 1);
120
+ continue;
121
+ }
122
+ }
123
+ cut(cmd.length, '', cmd.length);
124
+ return out;
125
+ }
126
+ function flagValue(tokens, names) {
127
+ for (let i = 0; i < tokens.length; i++) {
128
+ const t = tokens[i];
129
+ for (const name of names) {
130
+ if (t === name)
131
+ return tokens[i + 1];
132
+ if (name.startsWith('--') && t.startsWith(`${name}=`))
133
+ return t.slice(name.length + 1);
134
+ }
135
+ }
136
+ return undefined;
137
+ }
138
+ function positionals(tokens, valueFlags) {
139
+ const out = [];
140
+ for (let i = 0; i < tokens.length; i++) {
141
+ const t = tokens[i];
142
+ if (t === '--') {
143
+ out.push(...tokens.slice(i + 1));
144
+ break;
145
+ }
146
+ if (t.startsWith('-')) {
147
+ if (valueFlags.has(t))
148
+ i++;
149
+ continue;
150
+ }
151
+ out.push(t);
152
+ }
153
+ return out;
154
+ }
155
+ function normalizeRepo(value) {
156
+ if (!value)
157
+ return undefined;
158
+ const m = value.replace(/^https?:\/\//, '').replace(/^github\.com\//, '').replace(/\.git$/, '').match(/^([\w.-]+)\/([\w.-]+)$/);
159
+ return m ? `${m[1]}/${m[2]}` : undefined;
160
+ }
161
+ function prTouch(repo, number, action) {
162
+ return { url: `https://github.com/${repo}/pull/${number}`, number, repo, action };
163
+ }
164
+ function withoutEnvPrefix(tokens) {
165
+ let i = 0;
166
+ while (i < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i]))
167
+ i++;
168
+ return tokens.slice(i);
169
+ }
170
+ function ghPrTouch(tokens, inferRepo) {
171
+ const verb = GH_PR_VERBS[tokens[2] ?? ''];
172
+ if (!verb)
173
+ return undefined;
174
+ const args = tokens.slice(3);
175
+ if (verb.action === 'merged' && (args.includes('--auto') || args.includes('--disable-auto')))
176
+ return undefined;
177
+ const target = positionals(args, new Set(['-R', '--repo', ...verb.valueFlags]))[0];
178
+ if (!target)
179
+ return undefined;
180
+ const url = target.match(PR_URL_RE);
181
+ if (url)
182
+ return prTouch(`${url[1]}/${url[2]}`, Number(url[3]), verb.action);
183
+ if (!/^\d+$/.test(target))
184
+ return undefined;
185
+ const repo = normalizeRepo(flagValue(args, ['-R', '--repo'])) ?? inferRepo();
186
+ return repo ? prTouch(repo, Number(target), verb.action) : undefined;
187
+ }
188
+ function agentsPrsTouch(tokens) {
189
+ const action = AGENTS_PRS_ACTIONS[tokens[3] ?? ''];
190
+ if (!action)
191
+ return undefined;
192
+ const args = tokens.slice(4);
193
+ const repo = normalizeRepo(flagValue(args, ['--repo']));
194
+ const number = flagValue(args, ['--number']);
195
+ return repo && number && /^\d+$/.test(number) ? prTouch(repo, Number(number), action) : undefined;
196
+ }
197
+ function linearUpdateTouches(tokens) {
198
+ const args = tokens.slice(2);
199
+ const status = args.includes('--done') ? 'done'
200
+ : args.includes('--pickup') ? 'started'
201
+ : args.includes('--todo') ? 'moved to Todo'
202
+ : flagValue(args, ['--status']) ? `moved to ${flagValue(args, ['--status'])}`
203
+ : undefined;
204
+ const action = status
205
+ ?? (flagValue(args, ['--comment', '--proof']) !== undefined ? 'commented' : 'updated');
206
+ const ids = positionals(args, LINEAR_UPDATE_VALUE_FLAGS).flatMap(t => linearIssueKeys(t).filter(k => k === t.toUpperCase()));
207
+ return [...new Set(ids)].map(id => ({ id, action }));
208
+ }
209
+ function exitStatusCounts(segments, index) {
210
+ return segments.slice(index, -1).every(s => s.op === '&&');
211
+ }
212
+ export function touchesFromCommand(command, cwd, repoForDir = githubRepoForDir) {
213
+ const prs = [];
214
+ const tickets = [];
215
+ const segments = splitTopLevel(command);
216
+ let dir = cwd;
217
+ segments.forEach((segment, index) => {
218
+ const tokens = withoutEnvPrefix(tokenizeBash(segment.text)[0] ?? []);
219
+ const bin = path.basename(tokens[0] ?? '');
220
+ if (bin === 'cd') {
221
+ dir = resolveCommandDir(dir, tokens[1]);
222
+ return;
223
+ }
224
+ const mark = exitStatusCounts(segments, index) ? {} : { masked: true };
225
+ if (bin === 'gh' && tokens[1] === 'pr') {
226
+ const pr = ghPrTouch(tokens, () => (dir ? repoForDir(dir) : undefined));
227
+ if (pr)
228
+ prs.push({ ...pr, ...mark });
229
+ }
230
+ else if ((bin === 'agents' || bin === 'ag') && tokens[1] === 'projects' && tokens[2] === 'prs') {
231
+ const pr = agentsPrsTouch(tokens);
232
+ if (pr)
233
+ prs.push({ ...pr, ...mark });
234
+ }
235
+ else if (bin === 'linear' && tokens[1] === 'update') {
236
+ tickets.push(...linearUpdateTouches(tokens).map(t => ({ ...t, ...mark })));
237
+ }
238
+ });
239
+ return { prs, tickets };
240
+ }
241
+ const REPO_CACHE_MAX = 1024;
242
+ const repoByDir = new Map();
243
+ function githubRepoForDir(dir) {
244
+ const cached = repoByDir.get(dir);
245
+ if (cached !== undefined)
246
+ return cached ?? undefined;
247
+ let repo = null;
248
+ try {
249
+ if (fs.statSync(dir).isDirectory()) {
250
+ const url = execFileSync('git', ['-C', dir, 'config', '--get', 'remote.origin.url'], {
251
+ encoding: 'utf-8',
252
+ stdio: ['ignore', 'pipe', 'ignore'],
253
+ timeout: 2_000,
254
+ });
255
+ repo = repoFromRemote(url);
256
+ }
257
+ }
258
+ catch { }
259
+ if (repoByDir.size >= REPO_CACHE_MAX)
260
+ repoByDir.delete(repoByDir.keys().next().value);
261
+ repoByDir.set(dir, repo);
262
+ return repo ?? undefined;
263
+ }
264
+ function resolveCommandDir(cwd, cdTarget) {
265
+ if (!cdTarget || cdTarget === '~')
266
+ return os.homedir();
267
+ const expanded = cdTarget.startsWith('~/') ? path.join(os.homedir(), cdTarget.slice(2)) : cdTarget;
268
+ if (path.isAbsolute(expanded))
269
+ return expanded;
270
+ return cwd ? path.resolve(cwd, expanded) : undefined;
271
+ }
272
+ export function trackPendingTouches(pending, id, touches) {
273
+ if (touches.prs.length === 0 && touches.tickets.length === 0)
274
+ return;
275
+ if (pending.size >= PENDING_MAX)
276
+ pending.delete(pending.keys().next().value);
277
+ pending.set(id, touches);
278
+ }
279
+ export function recordTouches(ledger, touches, output, created) {
280
+ const createdPrs = new Set(created.prUrls.map(u => u.toLowerCase()));
281
+ const createdTickets = new Set([...created.tickets].map(t => t.toUpperCase()));
282
+ for (const { masked, ...pr } of touches.prs) {
283
+ if (masked && !(pr.action === 'merged' && MERGED_EVIDENCE_RE.test(output)))
284
+ continue;
285
+ const key = pr.url.toLowerCase();
286
+ if (createdPrs.has(key))
287
+ continue;
288
+ ledger.touchedPrs = [pr, ...ledger.touchedPrs.filter(p => p.url.toLowerCase() !== key)].slice(0, TOUCHED_MAX);
289
+ }
290
+ for (const { masked, ...ticket } of touches.tickets) {
291
+ if (masked)
292
+ continue;
293
+ if (createdTickets.has(ticket.id))
294
+ continue;
295
+ ledger.touchedTickets = [ticket, ...ledger.touchedTickets.filter(t => t.id !== ticket.id)].slice(0, TOUCHED_MAX);
296
+ }
297
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.31",
3
+ "version": "1.23.33",
4
4
  "description": "One CLI for all your AI coding agents - versions, config, cloud dispatch, sessions, and teams (now with first-class Grok Build CLI support)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -89,7 +89,7 @@
89
89
  "@fontsource/jetbrains-mono": "^5.3.0",
90
90
  "@inquirer/prompts": "8.5.2",
91
91
  "@phnx-labs/secrets-cli": "0.4.0",
92
- "@phnx-labs/sessions-cli": "0.8.7",
92
+ "@phnx-labs/sessions-cli": "0.8.9",
93
93
  "@resvg/resvg-wasm": "^2.6.2",
94
94
  "@types/proper-lockfile": "4.1.4",
95
95
  "@zed-industries/agent-client-protocol": "0.4.5",