@phren/cli 0.3.19 → 0.3.21

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 (76) hide show
  1. package/dist/bridge/agent-hooks.d.ts +38 -20
  2. package/dist/bridge/agent-hooks.js +100 -37
  3. package/dist/bridge/approval-summary.d.ts +4 -0
  4. package/dist/bridge/approval-summary.js +12 -1
  5. package/dist/bridge/changes.d.ts +4 -0
  6. package/dist/bridge/changes.js +25 -2
  7. package/dist/bridge/code-note.d.ts +1 -0
  8. package/dist/bridge/code-note.js +2 -2
  9. package/dist/bridge/codex-binary.d.ts +5 -0
  10. package/dist/bridge/codex-binary.js +7 -0
  11. package/dist/bridge/command.js +24 -6
  12. package/dist/bridge/dispatch-command.js +1 -1
  13. package/dist/bridge/dispatch-returns.d.ts +14 -2
  14. package/dist/bridge/dispatch-returns.js +72 -16
  15. package/dist/bridge/dispatch.d.ts +23 -0
  16. package/dist/bridge/dispatch.js +169 -8
  17. package/dist/bridge/folder-trust.d.ts +13 -3
  18. package/dist/bridge/folder-trust.js +42 -4
  19. package/dist/bridge/hand-off.js +2 -1
  20. package/dist/bridge/herdr.js +6 -5
  21. package/dist/bridge/hook-fast.d.ts +13 -1
  22. package/dist/bridge/hook-fast.js +17 -2
  23. package/dist/bridge/launch-brief.d.ts +3 -1
  24. package/dist/bridge/launch-brief.js +3 -1
  25. package/dist/bridge/memory-store.d.ts +7 -0
  26. package/dist/bridge/memory-store.js +37 -1
  27. package/dist/bridge/models.d.ts +11 -1
  28. package/dist/bridge/models.js +47 -2
  29. package/dist/bridge/schedule-format.d.ts +1 -1
  30. package/dist/bridge/schedule-format.js +1 -1
  31. package/dist/bridge/schedule-launch.js +5 -0
  32. package/dist/bridge/schedule-watch.d.ts +5 -2
  33. package/dist/bridge/schedule-watch.js +59 -20
  34. package/dist/bridge/server-launch.d.ts +26 -0
  35. package/dist/bridge/server-launch.js +122 -12
  36. package/dist/bridge/server-pane-routes.js +20 -13
  37. package/dist/bridge/server-routes.d.ts +5 -0
  38. package/dist/bridge/server-routes.js +2 -2
  39. package/dist/bridge/server-stream.js +12 -0
  40. package/dist/bridge/server.js +8 -3
  41. package/dist/bridge/session-activity.d.ts +6 -0
  42. package/dist/bridge/session-activity.js +16 -0
  43. package/dist/bridge/settings-switch.d.ts +7 -0
  44. package/dist/bridge/settings-switch.js +15 -0
  45. package/dist/bridge/speech-live.d.ts +45 -0
  46. package/dist/bridge/speech-live.js +413 -0
  47. package/dist/bridge/speech-transcribe.d.ts +13 -3
  48. package/dist/bridge/speech-transcribe.js +26 -8
  49. package/dist/bridge/speech-voice.d.ts +22 -1
  50. package/dist/bridge/speech-voice.js +20 -2
  51. package/dist/bridge/speech.d.ts +24 -4
  52. package/dist/bridge/speech.js +115 -14
  53. package/dist/bridge/stalls.d.ts +9 -2
  54. package/dist/bridge/stalls.js +20 -4
  55. package/dist/bridge/transcript-claude.js +39 -10
  56. package/dist/bridge/transcript-preview.d.ts +11 -1
  57. package/dist/bridge/transcript-preview.js +37 -11
  58. package/dist/bridge/transcripts.d.ts +2 -1
  59. package/dist/bridge/transcripts.js +7 -3
  60. package/dist/bridge/turn-records.d.ts +6 -3
  61. package/dist/bridge/turn-records.js +9 -4
  62. package/dist/bridge/usage.d.ts +1 -1
  63. package/dist/bridge/usage.js +4 -3
  64. package/dist/bridge/worker-close.js +3 -1
  65. package/dist/bridge/worker-unfinished.d.ts +43 -0
  66. package/dist/bridge/worker-unfinished.js +178 -0
  67. package/dist/bridge-hook.mjs +2458 -1351
  68. package/dist/cli-registry.js +3 -2
  69. package/dist/home-paths.d.ts +2 -0
  70. package/dist/home-paths.js +4 -0
  71. package/dist/modules/registry.js +2 -2
  72. package/dist/test-global-setup.js +2 -1
  73. package/dist/test-sandbox.d.ts +15 -0
  74. package/dist/test-sandbox.js +36 -0
  75. package/package.json +1 -1
  76. package/starter/global/skills/conductor/SKILL.md +2 -1
@@ -60,7 +60,8 @@ export declare function childAgent(tree: ChildAgentRelation[], id: string): Loca
60
60
  * teammates, workflow agents and fan-out jobs a finished turn still waits on. */
61
61
  export declare function runningChildAgents(tree: ChildAgentRelation[]): ChildAgentRelation[];
62
62
  /**
63
- * The phren store whose `.runtime/sessions` holds phren-agent event logs.
63
+ * The phren store whose `.sessions` holds phren-agent event logs (and
64
+ * `.runtime/sessions` OpenCode's plugin logs).
64
65
  * `PHREN_PATH` or the shared `~/.phren` root — the two resolutions the CLI's
65
66
  * `findPhrenPath` makes without a working directory, which a service has none
66
67
  * of. Kept inline rather than importing phren-paths: that module drags in
@@ -99,7 +99,8 @@ function toolOutputReferences(output) {
99
99
  return Array.isArray(result.content) ? { ...result, content: imageReferences(result.content) } : output;
100
100
  }
101
101
  /**
102
- * The phren store whose `.runtime/sessions` holds phren-agent event logs.
102
+ * The phren store whose `.sessions` holds phren-agent event logs (and
103
+ * `.runtime/sessions` OpenCode's plugin logs).
103
104
  * `PHREN_PATH` or the shared `~/.phren` root — the two resolutions the CLI's
104
105
  * `findPhrenPath` makes without a working directory, which a service has none
105
106
  * of. Kept inline rather than importing phren-paths: that module drags in
@@ -211,8 +212,11 @@ export async function transcriptPath(source, session, account) {
211
212
  throw new BridgeError(400, "Invalid conversation identity.");
212
213
  const bases = source === "codex" ? [{ base: path.join(codexHome(), "sessions") }]
213
214
  : source === "claude" ? claudeHomes().map(home => ({ id: home.id, base: path.join(home.dir, "projects") }))
214
- : source === "phren" || source === "opencode" ? [{ base: path.join(phrenStoreRoot(), ".runtime", "sessions") }]
215
- : [{ base: path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state") }];
215
+ // phren-agent keeps its event logs in the store's `.sessions` (the CLI's
216
+ // sessionsDir); OpenCode's plugin writes under `.runtime/sessions`.
217
+ : source === "phren" ? [{ base: path.join(phrenStoreRoot(), ".sessions") }, { base: path.join(phrenStoreRoot(), ".runtime", "sessions") }]
218
+ : source === "opencode" ? [{ base: path.join(phrenStoreRoot(), ".runtime", "sessions") }]
219
+ : [{ base: path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state") }];
216
220
  const pattern = source === "codex" ? `*/*/*/rollout-*-${session}.jsonl` : source === "claude" ? `*/${session}.jsonl`
217
221
  : source === "phren" ? `session-${session}.events.jsonl` : source === "opencode" ? `opencode-${session}.events.jsonl` : `${session}/events.jsonl`;
218
222
  const found = [];
@@ -18,16 +18,17 @@ declare const turnRecordSchema: z.ZodObject<{
18
18
  prompt: z.ZodOptional<z.ZodObject<{
19
19
  seq: z.ZodNumber;
20
20
  at: z.ZodString;
21
- }, z.core.$strict>>;
21
+ }, z.core.$strip>>;
22
22
  stop: z.ZodOptional<z.ZodObject<{
23
23
  seq: z.ZodNumber;
24
24
  at: z.ZodString;
25
25
  background: z.ZodOptional<z.ZodNumber>;
26
26
  reply: z.ZodOptional<z.ZodString>;
27
27
  truncated: z.ZodOptional<z.ZodBoolean>;
28
- }, z.core.$strict>>;
28
+ cwd: z.ZodOptional<z.ZodString>;
29
+ }, z.core.$strip>>;
29
30
  at: z.ZodString;
30
- }, z.core.$strict>;
31
+ }, z.core.$strip>;
31
32
  export type TurnRecord = z.infer<typeof turnRecordSchema>;
32
33
  export interface TurnEvent {
33
34
  event: string;
@@ -40,6 +41,8 @@ export interface TurnEvent {
40
41
  background?: number;
41
42
  /** Stop only: the harness's last assistant message, when it reports one. */
42
43
  reply?: string;
44
+ /** Stop only: the agent's working directory, as its hook payload names it. */
45
+ cwd?: string;
43
46
  at?: number;
44
47
  }
45
48
  export declare const turnPath: (server: string, pane: string) => string;
@@ -24,7 +24,9 @@ import { atomicInPrivateDir, bridgeRoot, provider, serverName, sessionId } from
24
24
  /** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
25
25
  export const TURN_REPLY_LIMIT = 4000;
26
26
  const MAX_RECORD_BYTES = 16_384;
27
- const stamp = z.object({ seq: z.number().int().min(0), at: z.string().datetime() }).strict();
27
+ // Not strict: a field a newer Hook adds (as `stop.cwd` was) is dropped on
28
+ // read here, never a reason to throw the pane's record away.
29
+ const stamp = z.object({ seq: z.number().int().min(0), at: z.string().datetime() });
28
30
  const turnRecordSchema = z.object({
29
31
  terminal: z.string().min(1).max(200), source: provider, session: sessionId,
30
32
  /** Climbs with every recorded event, so prompt and stop are ordered without trusting the clock. */
@@ -37,9 +39,11 @@ const turnRecordSchema = z.object({
37
39
  /** Background tasks (shells, subagents, monitors) the harness still ran when the turn stopped. */
38
40
  background: z.number().int().min(0).max(999).optional(),
39
41
  reply: z.string().max(TURN_REPLY_LIMIT).optional(), truncated: z.boolean().optional(),
40
- }).strict().optional(),
42
+ /** The agent's working directory when the turn stopped: where its uncommitted work would be. */
43
+ cwd: z.string().max(4096).optional(),
44
+ }).optional(),
41
45
  at: z.string().datetime(),
42
- }).strict();
46
+ });
43
47
  export const turnPath = (server, pane) => path.join(bridgeRoot(), "turns", encodeURIComponent(serverName.parse(server)), encodeURIComponent(pane) + ".json");
44
48
  /** `value` cut to at most `limit` UTF-8 bytes on a character boundary. */
45
49
  export function truncateUtf8(value, limit = TURN_REPLY_LIMIT) {
@@ -70,7 +74,8 @@ export function nextTurn(previous, event) {
70
74
  else {
71
75
  const reply = event.reply?.trim() ? truncateUtf8(event.reply.trim()) : undefined;
72
76
  record.stop = { seq: record.seq, at, ...(event.background !== undefined ? { background: Math.min(999, Math.max(0, Math.floor(event.background))) } : {}),
73
- ...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}) };
77
+ ...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}),
78
+ ...(event.cwd && path.isAbsolute(event.cwd) && event.cwd.length <= 4096 ? { cwd: event.cwd } : {}) };
74
79
  }
75
80
  return record;
76
81
  }
@@ -87,7 +87,7 @@ export declare function fetchOpenRouterUsage(key: string, fetchImpl?: typeof fet
87
87
  /** ElevenLabs' subscription: characters used this billing period against the plan's limit. */
88
88
  export declare function elevenLabsUsage(value: unknown, now?: Date): AccountUsage;
89
89
  /** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
90
- export declare function fetchElevenLabsUsage(key: string, fetchImpl?: typeof fetch, now?: Date): Promise<AccountUsage>;
90
+ export declare function fetchElevenLabsUsage(key: string, fetchImpl?: typeof fetch, now?: Date, origin?: string): Promise<AccountUsage>;
91
91
  /** Claude Code's documented status-line payload: rate_limits carries the
92
92
  * five_hour and seven_day windows (the 5h/7d unified limits) and, when the
93
93
  * build emits them, per-model keys such as seven_day_fable. Every window
@@ -10,6 +10,7 @@ import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
10
10
  import { stripTerminal } from "../terminal-text.js";
11
11
  import { codexExecutable } from "./codex-binary.js";
12
12
  import { readSpeechKey } from "./speech-key.js";
13
+ import { resolveSpeechRegion, SPEECH_REGIONS } from "./speech-voice.js";
13
14
  import { CODEX_ACCOUNT, claudeAccountSubscription, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
14
15
  import { planName, subscriptionDate } from "./subscription.js";
15
16
  const exec = promisify(execFile);
@@ -352,11 +353,11 @@ export function elevenLabsUsage(value, now = new Date()) {
352
353
  return { source: "elevenlabs", ...metadata, windows: entry ? [{ ...entry, usedCharacters: used, limitCharacters: limit }] : [], updatedAt: now.toISOString() };
353
354
  }
354
355
  /** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
355
- export async function fetchElevenLabsUsage(key, fetchImpl = fetch, now = new Date()) {
356
+ export async function fetchElevenLabsUsage(key, fetchImpl = fetch, now = new Date(), origin = SPEECH_REGIONS.global) {
356
357
  const controller = new AbortController();
357
358
  const timer = setTimeout(() => controller.abort(), 8_000);
358
359
  try {
359
- const response = await fetchImpl("https://api.elevenlabs.io/v1/user/subscription", {
360
+ const response = await fetchImpl(`${origin}/v1/user/subscription`, {
360
361
  headers: { "xi-api-key": key, accept: "application/json" },
361
362
  redirect: "error",
362
363
  signal: controller.signal,
@@ -377,7 +378,7 @@ async function liveElevenLabsUsage(now) {
377
378
  if (!key)
378
379
  return undefined;
379
380
  try {
380
- return await fetchElevenLabsUsage(key, fetch, now);
381
+ return await fetchElevenLabsUsage(key, fetch, now, (await resolveSpeechRegion()).origin);
381
382
  }
382
383
  catch {
383
384
  return { source: "elevenlabs", windows: [], updatedAt: now.toISOString(), message: "Could not read ElevenLabs usage. Check this computer's ElevenLabs key." };
@@ -51,7 +51,9 @@ export async function closeFinishedWorker(input, queue) {
51
51
  return { ok: true, closed: false };
52
52
  const seen = (await workerStates({ targets: [{ ...data.target, dispatch: data.dispatch }] })).workers[0];
53
53
  const turn = workerTurnKey(seen);
54
- if (!seen.completed || seen.background || seen.error || turn !== data.turn)
54
+ // A turn still working, one that stopped mid-task or with background work
55
+ // running, or whose checkout could not be read, keeps its pane.
56
+ if ((seen.state !== "done" && seen.state !== "idle") || !seen.completed || seen.background || seen.error || seen.unfinished || seen.unchecked || turn !== data.turn)
55
57
  return { ok: true, closed: false };
56
58
  // One final fresh binding before the terminal mutation.
57
59
  const current = await validateTarget(data.target, false, true);
@@ -0,0 +1,43 @@
1
+ /** The first sentence of the reply's closing paragraph that announces a next
2
+ * step ("Let me…", "I'll…", "Now running…"), else undefined. The closing line
3
+ * counts even as a list item; earlier lines only as prose, so a summary list
4
+ * that quotes an old step is not one. */
5
+ export declare function announcedNextStep(reply: string | undefined): string | undefined;
6
+ /** The first sentence of the reply's closing paragraph that waits on work
7
+ * still to finish ("Now waiting on the rerun.", "I'll push once it passes."),
8
+ * else undefined. */
9
+ export declare function awaitedInReply(reply: string | undefined): string | undefined;
10
+ /** A checkout git could not read in time (or at all): its work is unknown,
11
+ * so a turn there is never closed on the strength of it. */
12
+ export declare const UNKNOWN = "unknown";
13
+ export type Uncommitted = number | typeof UNKNOWN | undefined;
14
+ /** Tracked files with uncommitted changes (staged or not) in the checkout at
15
+ * `directory`. Untracked files are left out: a main checkout often holds the
16
+ * owner's own (worktree folders, scratch files) and they are not the worker's.
17
+ * Undefined when it is not a repository; UNKNOWN when git does not answer in
18
+ * time or fails otherwise. */
19
+ export declare function uncommittedFiles(directory: string, timeoutMs?: number): Promise<Uncommitted>;
20
+ /** `uncommittedFiles` for the returns loop, which asks about a finished
21
+ * worker on every poll (15 s) for as long as its receipt is watched: a read
22
+ * under a minute old answers. An UNKNOWN read is not kept, so the next poll
23
+ * (and the close recheck) asks git again. */
24
+ export declare function recentUncommitted(directory: string, now?: number, read?: (directory: string) => Promise<Uncommitted>): Promise<Uncommitted>;
25
+ /** The checkout `directory` is in: the nearest folder holding `.git` (a
26
+ * linked worktree's is a file), or undefined outside any. */
27
+ export declare function checkoutRoot(directory: string): Promise<string | undefined>;
28
+ /** Whether any of `folders` (other panes' working folders) is in the same
29
+ * checkout as `directory`. Uncommitted files there may be the owner's or a
30
+ * sibling worker's, so they say nothing about this worker. */
31
+ export declare function sharedCheckout(directory: string, folders: readonly unknown[]): Promise<boolean>;
32
+ /** Why a turn that ended is not done: it announced a next step, or it left
33
+ * uncommitted work with no PR reported or named in the reply (`unfinished`). `unchecked` when its
34
+ * checkout could not be read: the turn may be done, but it is not safe to
35
+ * close. Empty when it reads as done. */
36
+ export declare function unfinishedTurn(input: {
37
+ reply?: string;
38
+ prs?: readonly unknown[];
39
+ directory?: string;
40
+ }, uncommitted?: (directory: string) => Promise<Uncommitted>): Promise<{
41
+ unfinished?: string;
42
+ unchecked?: true;
43
+ }>;
@@ -0,0 +1,178 @@
1
+ import { execFile } from "node:child_process";
2
+ import { lstat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { nonInteractiveGitEnv } from "../utils-helpers.js";
6
+ import { countGit } from "./metrics.js";
7
+ /**
8
+ * A worker whose turn ended is not always done. OpenCode in particular ends a
9
+ * turn on a line like "The worktree lacks node_modules. Let me install
10
+ * dependencies." with nothing run after it (hook-permission-mode, 2026-09-30:
11
+ * returned done, its pane closed, 9 files of uncommitted work left behind).
12
+ * Dispatch returns report such a turn as needs-you, never done, so its pane
13
+ * is not closed and the dispatcher nudges it on.
14
+ */
15
+ const exec = promisify(execFile);
16
+ /** A sentence that announces work the turn never did: "Let me…", "I'll…",
17
+ * "I need to…", or "Now" with a working verb. Whatever follows the subject in
18
+ * HANDOVER, or a sentence waiting on something (CONDITIONAL, read by
19
+ * `awaitedInReply` instead), is not one: a done worker that says "I'll wait
20
+ * for your review" must not read as needs-you. "Let me know…" is a sign-off. */
21
+ const NEXT_STEP = /^(?:(?:ok(?:ay)?|alright|now|next|then|first|great|good)\b[,.!:]?\s+)*(?:let me(?! know)|let's|let us|i'll|i will|i'm going to|i am going to|i need to|i'm now|i am now|now i)\s+(.*)$/i;
22
+ const NOW_DOING = /^now,?\s+(?:adding|applying|building|checking|cleaning|committing|compiling|creating|debugging|editing|fixing|generating|implementing|installing|investigating|launching|looking|moving|opening|patching|pushing|reading|rebuilding|refactoring|removing|rerunning|re-running|running|searching|setting|starting|testing|trying|updating|verifying|wiring|working|writing)\b/i;
23
+ /** What a finished worker says it does next: wait, leave it to the owner, stop, be around. */
24
+ const HANDOVER = /^(?:just\s+)?(?:wait|await|leave|stop|hold|pause|be|hand|defer|stand|end|wrap|let you|keep an eye|check back|merge|ship|land|release|discuss|review|done|finished|ready)\b/i;
25
+ const CONDITIONAL = /\b(?:once|when|whenever|after|as soon as|if|until|unless)\b/i;
26
+ /** A sentence that waits on something other than the owner: "Now waiting on
27
+ * the MacBook rerun.", "I'll push once it passes.", "Let's merge once CI is
28
+ * green." (ios-fast-voice2, 2026-10-01: returned done and closed with its test
29
+ * run going). Waiting for the owner's review or answer is a handover. */
30
+ const WAITS = /(?<!\bwhile\s)\b(?:wait(?:ing|s)?|await(?:ing|s)?)\s+(?:on|for|until)\b/i;
31
+ /** "Once it passes", "when the build finishes": waiting on a job, not an "if". */
32
+ const ONCE_DONE = /\b(?:once|when|after|as soon as|until)\s+(?:it|its|the|that|this|they|both|all|my|ci)\b/i;
33
+ const FUTURE = /\b(?:i'll|i will|we'll|we will|let's|let us|then i|will)\b/i;
34
+ const OWNER = /\b(?:you|your|yours|owner|reviewers?|approv\w*|let me know)\b/i;
35
+ const NEGATED = /\b(?:nothing|no longer|not|no need|without)\b|n't\b/i;
36
+ /** The closing paragraph's prose lines: blank lines end a paragraph and fenced
37
+ * code is skipped, so "Let me run:" before a closing code block is still in it. */
38
+ function closingLines(reply) {
39
+ let fenced = false, lines = [];
40
+ for (const raw of reply.replace(/\r/g, "").split("\n")) {
41
+ const line = raw.trim();
42
+ if (/^(?:```|~~~)/.test(line)) {
43
+ fenced = !fenced;
44
+ continue;
45
+ }
46
+ if (fenced)
47
+ continue;
48
+ if (!line) {
49
+ if (lines.length)
50
+ lines = [...lines, ""];
51
+ continue;
52
+ }
53
+ if (lines.at(-1) === "")
54
+ lines = [];
55
+ lines.push(line);
56
+ }
57
+ return lines.filter(Boolean);
58
+ }
59
+ const LIST_ITEM = /^(?:[-*+>]|\d+[.)])\s+/;
60
+ const sentences = (line) => line.replace(LIST_ITEM, "").replace(/[*_`#]+/g, "").replace(/[\u2018\u2019]/g, "'").trim()
61
+ .split(/(?<=[.!?\u2026])\s+/).map(sentence => sentence.trim()).filter(Boolean);
62
+ function nextStep(sentence) {
63
+ if (CONDITIONAL.test(sentence))
64
+ return false;
65
+ const step = NEXT_STEP.exec(sentence);
66
+ return step ? !HANDOVER.test(step[1]) : NOW_DOING.test(sentence);
67
+ }
68
+ /** The first sentence of the reply's closing paragraph that announces a next
69
+ * step ("Let me…", "I'll…", "Now running…"), else undefined. The closing line
70
+ * counts even as a list item; earlier lines only as prose, so a summary list
71
+ * that quotes an old step is not one. */
72
+ export function announcedNextStep(reply) {
73
+ const lines = reply ? closingLines(reply) : [];
74
+ const found = lines.flatMap((line, index) => index === lines.length - 1 || !LIST_ITEM.test(line) ? sentences(line) : []).find(nextStep);
75
+ return found?.slice(0, 160);
76
+ }
77
+ /** The first sentence of the reply's closing paragraph that waits on work
78
+ * still to finish ("Now waiting on the rerun.", "I'll push once it passes."),
79
+ * else undefined. */
80
+ export function awaitedInReply(reply) {
81
+ const found = (reply ? closingLines(reply) : []).flatMap(sentences).find(sentence => !OWNER.test(sentence) && !NEGATED.test(sentence)
82
+ && (WAITS.test(sentence) || (ONCE_DONE.test(sentence) && FUTURE.test(sentence))));
83
+ return found?.slice(0, 160);
84
+ }
85
+ /** A checkout git could not read in time (or at all): its work is unknown,
86
+ * so a turn there is never closed on the strength of it. */
87
+ export const UNKNOWN = "unknown";
88
+ /** Tracked files with uncommitted changes (staged or not) in the checkout at
89
+ * `directory`. Untracked files are left out: a main checkout often holds the
90
+ * owner's own (worktree folders, scratch files) and they are not the worker's.
91
+ * Undefined when it is not a repository; UNKNOWN when git does not answer in
92
+ * time or fails otherwise. */
93
+ export async function uncommittedFiles(directory, timeoutMs = 3000) {
94
+ if (!path.isAbsolute(directory))
95
+ return undefined;
96
+ countGit("worker-unfinished");
97
+ try {
98
+ const { stdout } = await exec("git", ["-C", directory, "--no-pager", "-c", "core.fsmonitor=false", "status", "--porcelain=v1", "--untracked-files=no", "-z"], {
99
+ timeout: timeoutMs, maxBuffer: 1_048_576, env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" }),
100
+ });
101
+ // -z: renames carry their source as a second entry with no status.
102
+ return stdout.split("\0").filter(entry => /^[ MADRCTU?!]{2} /.test(entry)).length;
103
+ }
104
+ catch (error) {
105
+ const failed = error;
106
+ // Exit 128 naming no repository (or no such folder) is a plain answer, not a slow one.
107
+ if (failed.code === 128 && !failed.killed && /not a git repository|cannot change to/i.test(String(failed.stderr ?? "")))
108
+ return undefined;
109
+ return UNKNOWN;
110
+ }
111
+ }
112
+ const recent = new Map();
113
+ /** `uncommittedFiles` for the returns loop, which asks about a finished
114
+ * worker on every poll (15 s) for as long as its receipt is watched: a read
115
+ * under a minute old answers. An UNKNOWN read is not kept, so the next poll
116
+ * (and the close recheck) asks git again. */
117
+ export function recentUncommitted(directory, now = Date.now(), read = uncommittedFiles) {
118
+ const hit = recent.get(directory);
119
+ if (hit && now - hit.at < 60_000)
120
+ return hit.files;
121
+ const files = read(directory).catch(() => UNKNOWN);
122
+ recent.delete(directory);
123
+ recent.set(directory, { at: now, files });
124
+ while (recent.size > 256)
125
+ recent.delete(recent.keys().next().value);
126
+ void files.then(value => { if (value === UNKNOWN && recent.get(directory)?.files === files)
127
+ recent.delete(directory); });
128
+ return files;
129
+ }
130
+ /** The checkout `directory` is in: the nearest folder holding `.git` (a
131
+ * linked worktree's is a file), or undefined outside any. */
132
+ export async function checkoutRoot(directory) {
133
+ if (!path.isAbsolute(directory))
134
+ return undefined;
135
+ let folder = path.resolve(directory);
136
+ for (let depth = 0; depth < 64; depth++) {
137
+ if (await lstat(path.join(folder, ".git")).then(() => true, () => false))
138
+ return folder;
139
+ const parent = path.dirname(folder);
140
+ if (parent === folder)
141
+ return undefined;
142
+ folder = parent;
143
+ }
144
+ return undefined;
145
+ }
146
+ /** Whether any of `folders` (other panes' working folders) is in the same
147
+ * checkout as `directory`. Uncommitted files there may be the owner's or a
148
+ * sibling worker's, so they say nothing about this worker. */
149
+ export async function sharedCheckout(directory, folders) {
150
+ const root = await checkoutRoot(directory);
151
+ if (!root)
152
+ return false;
153
+ const others = [...new Set(folders.filter((folder) => typeof folder === "string" && path.isAbsolute(folder)))].slice(0, 64);
154
+ for (const folder of others)
155
+ if (folder.startsWith(root) && await checkoutRoot(folder) === root)
156
+ return true;
157
+ return false;
158
+ }
159
+ /** A pull request the reply itself names: a GitHub PR link or "PR #12". */
160
+ const PR_NAMED = /\/pull\/\d+|\bPR\s*#\d+/i;
161
+ /** Why a turn that ended is not done: it announced a next step, or it left
162
+ * uncommitted work with no PR reported or named in the reply (`unfinished`). `unchecked` when its
163
+ * checkout could not be read: the turn may be done, but it is not safe to
164
+ * close. Empty when it reads as done. */
165
+ export async function unfinishedTurn(input, uncommitted) {
166
+ const step = announcedNextStep(input.reply);
167
+ if (step)
168
+ return { unfinished: `Stopped mid-task: ${step}` };
169
+ const waiting = awaitedInReply(input.reply);
170
+ if (waiting)
171
+ return { unfinished: `Stopped waiting: ${waiting}` };
172
+ if (input.prs?.length || PR_NAMED.test(input.reply ?? "") || !input.directory || !uncommitted)
173
+ return {};
174
+ const files = await uncommitted(input.directory).catch(() => UNKNOWN);
175
+ if (files === UNKNOWN)
176
+ return { unchecked: true };
177
+ return files ? { unfinished: `Stopped with ${files} uncommitted file${files === 1 ? "" : "s"} and no PR.` } : {};
178
+ }