zelio-cli 0.0.0-stage → 0.1.0-beta.1

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 (175) hide show
  1. package/README.md +178 -2
  2. package/dist/attachments.js +121 -0
  3. package/dist/attachments.js.map +1 -0
  4. package/dist/cli.js +469 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/cloud/board.js +311 -0
  7. package/dist/cloud/board.js.map +1 -0
  8. package/dist/cloud/command.js +260 -0
  9. package/dist/cloud/command.js.map +1 -0
  10. package/dist/cloud/config.js +132 -0
  11. package/dist/cloud/config.js.map +1 -0
  12. package/dist/cloud/credentials.js +134 -0
  13. package/dist/cloud/credentials.js.map +1 -0
  14. package/dist/cloud/login.js +165 -0
  15. package/dist/cloud/login.js.map +1 -0
  16. package/dist/cloud/pair.js +110 -0
  17. package/dist/cloud/pair.js.map +1 -0
  18. package/dist/cloud/pkce.js +16 -0
  19. package/dist/cloud/pkce.js.map +1 -0
  20. package/dist/cloud/push-nudge.js +63 -0
  21. package/dist/cloud/push-nudge.js.map +1 -0
  22. package/dist/cloud/relay.js +129 -0
  23. package/dist/cloud/relay.js.map +1 -0
  24. package/dist/cloud/token.js +66 -0
  25. package/dist/cloud/token.js.map +1 -0
  26. package/dist/cloud/tunnel.js +410 -0
  27. package/dist/cloud/tunnel.js.map +1 -0
  28. package/dist/db/db.js +1614 -0
  29. package/dist/db/db.js.map +1 -0
  30. package/dist/db/lifecycle.js +133 -0
  31. package/dist/db/lifecycle.js.map +1 -0
  32. package/dist/limits.js +35 -0
  33. package/dist/limits.js.map +1 -0
  34. package/dist/metrics.js +30 -0
  35. package/dist/metrics.js.map +1 -0
  36. package/dist/orchestrator/claude-session.js +208 -0
  37. package/dist/orchestrator/claude-session.js.map +1 -0
  38. package/dist/orchestrator/codex-session.js +326 -0
  39. package/dist/orchestrator/codex-session.js.map +1 -0
  40. package/dist/orchestrator/contract.js +181 -0
  41. package/dist/orchestrator/contract.js.map +1 -0
  42. package/dist/orchestrator/explore.js +176 -0
  43. package/dist/orchestrator/explore.js.map +1 -0
  44. package/dist/orchestrator/new-task-prompt.js +51 -0
  45. package/dist/orchestrator/new-task-prompt.js.map +1 -0
  46. package/dist/orchestrator/pi-session.js +228 -0
  47. package/dist/orchestrator/pi-session.js.map +1 -0
  48. package/dist/orchestrator/prompt.js +110 -0
  49. package/dist/orchestrator/prompt.js.map +1 -0
  50. package/dist/orchestrator/research.js +178 -0
  51. package/dist/orchestrator/research.js.map +1 -0
  52. package/dist/orchestrator/runtime.js +1054 -0
  53. package/dist/orchestrator/runtime.js.map +1 -0
  54. package/dist/orchestrator/session.js +2 -0
  55. package/dist/orchestrator/session.js.map +1 -0
  56. package/dist/orchestrator/types.js +2 -0
  57. package/dist/orchestrator/types.js.map +1 -0
  58. package/dist/orchestrator/web.js +276 -0
  59. package/dist/orchestrator/web.js.map +1 -0
  60. package/dist/repo/index.js +188 -0
  61. package/dist/repo/index.js.map +1 -0
  62. package/dist/repo/instructions.js +52 -0
  63. package/dist/repo/instructions.js.map +1 -0
  64. package/dist/repo/linked-boards.js +252 -0
  65. package/dist/repo/linked-boards.js.map +1 -0
  66. package/dist/run/actions.js +233 -0
  67. package/dist/run/actions.js.map +1 -0
  68. package/dist/run/bash-guard.js +183 -0
  69. package/dist/run/bash-guard.js.map +1 -0
  70. package/dist/run/claude-runtime.js +242 -0
  71. package/dist/run/claude-runtime.js.map +1 -0
  72. package/dist/run/claude-stream.js +306 -0
  73. package/dist/run/claude-stream.js.map +1 -0
  74. package/dist/run/codex-client.js +200 -0
  75. package/dist/run/codex-client.js.map +1 -0
  76. package/dist/run/codex-runtime.js +366 -0
  77. package/dist/run/codex-runtime.js.map +1 -0
  78. package/dist/run/context.js +87 -0
  79. package/dist/run/context.js.map +1 -0
  80. package/dist/run/diff.js +196 -0
  81. package/dist/run/diff.js.map +1 -0
  82. package/dist/run/evidence.js +48 -0
  83. package/dist/run/evidence.js.map +1 -0
  84. package/dist/run/finish.js +393 -0
  85. package/dist/run/finish.js.map +1 -0
  86. package/dist/run/harness-runtime.js +28 -0
  87. package/dist/run/harness-runtime.js.map +1 -0
  88. package/dist/run/harnesses.js +273 -0
  89. package/dist/run/harnesses.js.map +1 -0
  90. package/dist/run/issue.js +79 -0
  91. package/dist/run/issue.js.map +1 -0
  92. package/dist/run/keep-awake.js +58 -0
  93. package/dist/run/keep-awake.js.map +1 -0
  94. package/dist/run/lead.js +200 -0
  95. package/dist/run/lead.js.map +1 -0
  96. package/dist/run/manager.js +1709 -0
  97. package/dist/run/manager.js.map +1 -0
  98. package/dist/run/mentions.js +35 -0
  99. package/dist/run/mentions.js.map +1 -0
  100. package/dist/run/merge-watch.js +394 -0
  101. package/dist/run/merge-watch.js.map +1 -0
  102. package/dist/run/models.js +88 -0
  103. package/dist/run/models.js.map +1 -0
  104. package/dist/run/phases.js +23 -0
  105. package/dist/run/phases.js.map +1 -0
  106. package/dist/run/pi-rpc.js +412 -0
  107. package/dist/run/pi-rpc.js.map +1 -0
  108. package/dist/run/pr-merge.js +121 -0
  109. package/dist/run/pr-merge.js.map +1 -0
  110. package/dist/run/profiles.js +43 -0
  111. package/dist/run/profiles.js.map +1 -0
  112. package/dist/run/prompt.js +345 -0
  113. package/dist/run/prompt.js.map +1 -0
  114. package/dist/run/pull-request.js +23 -0
  115. package/dist/run/pull-request.js.map +1 -0
  116. package/dist/run/result-tool.js +93 -0
  117. package/dist/run/result-tool.js.map +1 -0
  118. package/dist/run/result.js +113 -0
  119. package/dist/run/result.js.map +1 -0
  120. package/dist/run/retro.js +346 -0
  121. package/dist/run/retro.js.map +1 -0
  122. package/dist/run/settings.js +25 -0
  123. package/dist/run/settings.js.map +1 -0
  124. package/dist/run/thinking.js +41 -0
  125. package/dist/run/thinking.js.map +1 -0
  126. package/dist/run/types.js +2 -0
  127. package/dist/run/types.js.map +1 -0
  128. package/dist/run/workflow.js +266 -0
  129. package/dist/run/workflow.js.map +1 -0
  130. package/dist/run/worktree.js +354 -0
  131. package/dist/run/worktree.js.map +1 -0
  132. package/dist/server/app.js +2503 -0
  133. package/dist/server/app.js.map +1 -0
  134. package/dist/server/auth.js +93 -0
  135. package/dist/server/auth.js.map +1 -0
  136. package/dist/server/demo.js +96 -0
  137. package/dist/server/demo.js.map +1 -0
  138. package/dist/server/idempotency.js +104 -0
  139. package/dist/server/idempotency.js.map +1 -0
  140. package/dist/server/port.js +36 -0
  141. package/dist/server/port.js.map +1 -0
  142. package/dist/server/principal.js +90 -0
  143. package/dist/server/principal.js.map +1 -0
  144. package/dist/server/terminal.js +285 -0
  145. package/dist/server/terminal.js.map +1 -0
  146. package/dist/setup/components.js +98 -0
  147. package/dist/setup/components.js.map +1 -0
  148. package/dist/setup/config.js +102 -0
  149. package/dist/setup/config.js.map +1 -0
  150. package/dist/setup/ink-ui.js +188 -0
  151. package/dist/setup/ink-ui.js.map +1 -0
  152. package/dist/setup/onboarding.js +183 -0
  153. package/dist/setup/onboarding.js.map +1 -0
  154. package/dist/setup/run.js +70 -0
  155. package/dist/setup/run.js.map +1 -0
  156. package/dist/ticket-cli.js +116 -0
  157. package/dist/ticket-cli.js.map +1 -0
  158. package/dist/voice/index.js +69 -0
  159. package/dist/voice/index.js.map +1 -0
  160. package/dist/voice/moonshine.js +247 -0
  161. package/dist/voice/moonshine.js.map +1 -0
  162. package/dist/voice/wav.js +54 -0
  163. package/dist/voice/wav.js.map +1 -0
  164. package/dist/voice/whisper.js +491 -0
  165. package/dist/voice/whisper.js.map +1 -0
  166. package/dist/web/assets/index-ChuS3qKc.js +254 -0
  167. package/dist/web/assets/index-DR6WkmzI.css +1 -0
  168. package/dist/web/icons/apple-touch-icon.png +0 -0
  169. package/dist/web/icons/icon-192.png +0 -0
  170. package/dist/web/icons/icon-512.png +0 -0
  171. package/dist/web/icons/maskable-512.png +0 -0
  172. package/dist/web/index.html +21 -0
  173. package/dist/web/manifest.webmanifest +30 -0
  174. package/dist/web/sw.js +183 -0
  175. package/package.json +96 -4
@@ -0,0 +1,196 @@
1
+ import { execFile, execFileSync } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { commitTicketWork } from "./finish.js";
4
+ const exec = promisify(execFile);
5
+ const GIT_TIMEOUT_MS = 15_000;
6
+ async function git(cwd, args) {
7
+ const { stdout } = await exec("git", ["-C", cwd, ...args], {
8
+ timeout: GIT_TIMEOUT_MS,
9
+ maxBuffer: 10 * 1024 * 1024,
10
+ });
11
+ return stdout;
12
+ }
13
+ /** The commit the worktree started from, before the agent touches it. */
14
+ export function worktreeHead(path) {
15
+ try {
16
+ return execFileSync("git", ["-C", path, "rev-parse", "HEAD"], {
17
+ encoding: "utf8",
18
+ timeout: GIT_TIMEOUT_MS,
19
+ // A worktree that has since been removed is a `null`, not a console full
20
+ // of git's complaint: the caller decides what a missing checkout means.
21
+ stdio: ["ignore", "pipe", "pipe"],
22
+ }).trim();
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /**
29
+ * The commits and pull request a run produced. `gh` is best-effort: a missing
30
+ * CLI or an unauthenticated machine is not a run failure, and the commits are
31
+ * still worth recording.
32
+ */
33
+ export async function captureRunFacts(path, since, ghCommand = "gh") {
34
+ const range = since ? `${since}..HEAD` : "-20";
35
+ const log = await git(path, ["log", "--format=%H%x09%s", range]).catch(() => "");
36
+ const commits = log
37
+ .split("\n")
38
+ .map((line) => line.trim())
39
+ .filter(Boolean)
40
+ .map((line) => {
41
+ const [sha = "", ...subject] = line.split("\t");
42
+ return { sha, subject: subject.join("\t") };
43
+ });
44
+ const branch = await git(path, ["branch", "--show-current"])
45
+ .then((value) => value.trim() || null)
46
+ .catch(() => null);
47
+ // A branch with no upstream has not been pushed, so there cannot be a PR
48
+ // yet; skip the network lookup entirely in that case.
49
+ const hasUpstream = await git(path, [
50
+ "rev-parse",
51
+ "--abbrev-ref",
52
+ "--symbolic-full-name",
53
+ "@{upstream}",
54
+ ]).then(() => true, () => false);
55
+ let prUrl = null;
56
+ if (hasUpstream) {
57
+ try {
58
+ const { stdout } = await exec(ghCommand, ["pr", "view", "--json", "url", "--jq", ".url"], {
59
+ cwd: path,
60
+ timeout: 10_000,
61
+ });
62
+ prUrl = String(stdout).trim() || null;
63
+ }
64
+ catch {
65
+ // No PR, no gh, or no network: commits are still the record.
66
+ }
67
+ }
68
+ return { branch, commits, prUrl };
69
+ }
70
+ /**
71
+ * Before a retry, whatever the failed attempt left uncommitted is committed on
72
+ * the ticket branch. A retry must never lose work, and the next attempt needs a
73
+ * known starting point rather than half-written files. Secret-looking files
74
+ * (env files, keys, the .zelio directory) are never staged.
75
+ */
76
+ export async function commitAttempt(path, message) {
77
+ return (await commitTicketWork(path, message)).committed;
78
+ }
79
+ /**
80
+ * The pushed merge commit the resolution had to leave behind. Each question is
81
+ * a separate git call that fails quietly: a checkout git cannot read is a run
82
+ * that resolved nothing, not an error the person needs to see.
83
+ */
84
+ export async function readMergeCommit(path, since) {
85
+ const head = await git(path, ["rev-parse", "HEAD"])
86
+ .then((value) => value.trim() || null)
87
+ .catch(() => null);
88
+ if (!head)
89
+ return { head: null, moved: false, merge: false, pushed: false, conflicts: [] };
90
+ const [parents, upstream, conflicts] = await Promise.all([
91
+ git(path, ["rev-list", "--parents", "-n", "1", "HEAD"]).catch(() => ""),
92
+ git(path, ["rev-parse", "@{upstream}"]).catch(() => ""),
93
+ git(path, ["diff", "--name-only", "--diff-filter=U"]).catch(() => ""),
94
+ ]);
95
+ return {
96
+ head,
97
+ moved: since === null ? true : head !== since,
98
+ merge: parents.trim().split(/\s+/).length > 2,
99
+ pushed: upstream.trim() === head,
100
+ conflicts: conflicts
101
+ .split("\n")
102
+ .map((line) => line.trim())
103
+ .filter(Boolean),
104
+ };
105
+ }
106
+ /**
107
+ * Where the ticket's branch left the default branch. A review reads the whole
108
+ * branch, not the last run's slice of it, so the diff starts here. Local and
109
+ * remote copies of the default branch can each be stale, and the one nearest
110
+ * to HEAD is the real fork point.
111
+ */
112
+ async function branchBase(path) {
113
+ let best = null;
114
+ for (const ref of ["origin/HEAD", "origin/main", "origin/master", "main", "master"]) {
115
+ try {
116
+ const sha = (await git(path, ["merge-base", "HEAD", ref])).trim();
117
+ if (!sha)
118
+ continue;
119
+ const ahead = Number((await git(path, ["rev-list", "--count", `${sha}..HEAD`])).trim());
120
+ if (Number.isFinite(ahead) && (best === null || ahead < best.ahead))
121
+ best = { sha, ahead };
122
+ }
123
+ catch {
124
+ // The ref does not exist here, or shares no history with HEAD.
125
+ }
126
+ }
127
+ return best?.sha ?? null;
128
+ }
129
+ /**
130
+ * What the agent left behind, captured after the process is gone. `since` is
131
+ * the commit this run started from; it is only the base when the branch's fork
132
+ * point cannot be found, because a follow-up run's own start commit would hide
133
+ * the earlier runs' work from the ticket's changes.
134
+ */
135
+ export async function captureWorktree(path, since = null) {
136
+ const base = (await branchBase(path)) ?? since ?? "HEAD";
137
+ const [status, diff] = await Promise.all([
138
+ git(path, ["status", "--porcelain"]),
139
+ // From the branch's fork point to the working tree: every run's commits and
140
+ // any uncommitted edits belong in the same review. Untracked files still
141
+ // show in `status`; rendering them belongs to the review surface, not here.
142
+ git(path, ["diff", "--no-color", base, "--"]),
143
+ ]);
144
+ return { status, diff };
145
+ }
146
+ function unquotePath(value) {
147
+ let path = value.split("\t")[0]?.trim() ?? "";
148
+ if (path.startsWith('"') && path.endsWith('"')) {
149
+ path = path.slice(1, -1).replace(/\\(.)/g, "$1");
150
+ }
151
+ if (path.startsWith("a/") || path.startsWith("b/"))
152
+ path = path.slice(2);
153
+ return path;
154
+ }
155
+ function pathOf(chunk) {
156
+ const plus = chunk.match(/^\+\+\+ (.+)$/m)?.[1];
157
+ const minus = chunk.match(/^--- (.+)$/m)?.[1];
158
+ for (const candidate of [plus, minus]) {
159
+ if (!candidate)
160
+ continue;
161
+ const path = unquotePath(candidate);
162
+ if (path && path !== "/dev/null")
163
+ return path;
164
+ }
165
+ const header = chunk.match(/^diff --git (.+) (.+)$/m);
166
+ return header ? unquotePath(header[2] ?? "") : "unknown";
167
+ }
168
+ /**
169
+ * The run record stores git's unified diff. The UI needs files and counts, not
170
+ * another git call, so the split happens here: one patch per file, with the
171
+ * `+`/`-` counts a human scans before opening it.
172
+ */
173
+ export function parseUnifiedDiff(text) {
174
+ const source = (text ?? "").replace(/\r\n/g, "\n");
175
+ const chunks = source
176
+ .split(/^diff --git /m)
177
+ .slice(1)
178
+ .map((chunk) => `diff --git ${chunk}`);
179
+ const files = chunks.map((patch) => {
180
+ let additions = 0;
181
+ let deletions = 0;
182
+ for (const line of patch.split("\n")) {
183
+ if (line.startsWith("+") && !line.startsWith("+++"))
184
+ additions += 1;
185
+ else if (line.startsWith("-") && !line.startsWith("---"))
186
+ deletions += 1;
187
+ }
188
+ return { path: pathOf(patch), additions, deletions, patch: patch.trimEnd() };
189
+ });
190
+ return {
191
+ files,
192
+ additions: files.reduce((total, file) => total + file.additions, 0),
193
+ deletions: files.reduce((total, file) => total + file.deletions, 0),
194
+ };
195
+ }
196
+ //# sourceMappingURL=diff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff.js","sourceRoot":"","sources":["../../src/run/diff.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,MAAM,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AACjC,MAAM,cAAc,GAAG,MAAM,CAAC;AAkB9B,KAAK,UAAU,GAAG,CAAC,GAAW,EAAE,IAAc;IAC5C,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE;QACzD,OAAO,EAAE,cAAc;QACvB,SAAS,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;KAC5B,CAAC,CAAC;IACH,OAAO,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AAO,EAAE,EAAE,CAAC;IAC/E,CAAC,CAAC,CAAC;IAEH,OAAO;QACL,KAAK;QACL,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;QACnE,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;KACpE,CAAC;AACJ,CAAC"}
@@ -0,0 +1,48 @@
1
+ import { createHash } from "node:crypto";
2
+ import { execFile } from "node:child_process";
3
+ import { lstat, readlink } from "node:fs/promises";
4
+ import { createReadStream } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { promisify } from "node:util";
7
+ const exec = promisify(execFile);
8
+ /** Content identity survives a commit; changed tracked/untracked inputs invalidate old checks. */
9
+ export async function evidenceRevision(worktree) {
10
+ try {
11
+ const { stdout } = await exec("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], {
12
+ cwd: worktree,
13
+ encoding: "utf8",
14
+ timeout: 2_000,
15
+ maxBuffer: 4 * 1024 * 1024,
16
+ });
17
+ const hash = createHash("sha256");
18
+ for (const path of [...new Set(stdout.split("\0").filter(Boolean))].sort()) {
19
+ hash.update(path).update("\0");
20
+ const full = join(worktree, path);
21
+ const stat = await lstat(full).catch((error) => {
22
+ if (error.code === "ENOENT")
23
+ return null;
24
+ throw error;
25
+ });
26
+ if (!stat) {
27
+ hash.update("deleted\0");
28
+ continue;
29
+ }
30
+ hash.update(String(stat.mode)).update("\0");
31
+ if (stat.isSymbolicLink())
32
+ hash.update(await readlink(full));
33
+ else if (stat.isFile()) {
34
+ for await (const chunk of createReadStream(full))
35
+ hash.update(chunk);
36
+ const after = await lstat(full);
37
+ if (stat.mtimeMs !== after.mtimeMs || stat.size !== after.size)
38
+ return null;
39
+ }
40
+ hash.update("\0");
41
+ }
42
+ return hash.digest("hex");
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ //# sourceMappingURL=evidence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evidence.js","sourceRoot":"","sources":["../../src/run/evidence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,MAAM,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAEjC,kGAAkG;AAClG,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,QAAgB;IACrD,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAC3B,KAAK,EACL,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,oBAAoB,EAAE,IAAI,CAAC,EAChE;YACE,GAAG,EAAE,QAAQ;YACb,QAAQ,EAAE,MAAM;YAChB,OAAO,EAAE,KAAK;YACd,SAAS,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI;SAC3B,CACF,CAAC;QACF,MAAM,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;QAClC,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YAC3E,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,IAAI,GA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emp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { promisify } from "node:util";
7
+ const execFileAsync = promisify(execFile);
8
+ const GIT_TIMEOUT_MS = 15_000;
9
+ const GH_TIMEOUT_MS = 30_000;
10
+ const PUSH_TIMEOUT_MS = 60_000;
11
+ const ERROR_TAIL_CHARS = 1_000;
12
+ const KILL_GRACE_MS = 1_000;
13
+ const SECRET_EXAMPLES = new Set([".env.example", ".env.sample", ".env.template"]);
14
+ /**
15
+ * Runs the checks one after another in `cwd` and stops at the first one that
16
+ * fails, so later checks never run against a tree already known to be broken.
17
+ * A check that cannot start is a failed result, never a thrown error.
18
+ */
19
+ export async function runChecks(cwd, checks, options = {}) {
20
+ const results = [];
21
+ for (const check of checks) {
22
+ let result = await runCheck(cwd, check, options);
23
+ if (!result.passed && options.rerunFailed) {
24
+ const rerun = await runCheck(cwd, check, options);
25
+ result = { ...rerun, flaky: rerun.passed };
26
+ }
27
+ results.push(result);
28
+ if (!result.passed)
29
+ break;
30
+ }
31
+ return results;
32
+ }
33
+ /**
34
+ * A fingerprint of the ticket's uncommitted work: tracked changes, the status
35
+ * listing, and the bytes of every untracked file. Two equal fingerprints mean
36
+ * the developer left the work exactly as it was. Null when it cannot be read,
37
+ * which callers must treat as changed, never as unchanged.
38
+ */
39
+ export async function worktreeFingerprint(cwd) {
40
+ try {
41
+ const status = await git(cwd, ["status", "--porcelain", "-z", "--untracked-files=all"]);
42
+ const hash = createHash("sha256");
43
+ hash.update(await git(cwd, ["diff", "HEAD", "--binary"]));
44
+ hash.update(status);
45
+ for (const entry of status.split("\0")) {
46
+ if (!entry.startsWith("?? "))
47
+ continue;
48
+ hash.update(await readFile(join(cwd, entry.slice(3))).catch(() => "missing"));
49
+ }
50
+ return hash.digest("hex");
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ }
56
+ function runCheck(cwd, check, options) {
57
+ const timeoutMs = options.timeoutMs ?? 120_000;
58
+ const maxOutput = options.maxOutput ?? 4_000;
59
+ const env = options.env ?? process.env;
60
+ const started = Date.now();
61
+ return new Promise((resolve) => {
62
+ let output = "";
63
+ let exitCode = null;
64
+ let timedOut = false;
65
+ let aborted = false;
66
+ let failedToStart = false;
67
+ let settled = false;
68
+ let child;
69
+ let timer;
70
+ let fallback;
71
+ function finish() {
72
+ if (settled)
73
+ return;
74
+ settled = true;
75
+ clearTimeout(timer);
76
+ clearTimeout(fallback);
77
+ options.signal?.removeEventListener("abort", onAbort);
78
+ if (aborted)
79
+ output += "\naborted";
80
+ resolve({
81
+ label: check.label,
82
+ command: check.command,
83
+ passed: !failedToStart && !timedOut && !aborted && exitCode === 0,
84
+ exitCode,
85
+ timedOut,
86
+ output: output.slice(-maxOutput),
87
+ durationMs: Date.now() - started,
88
+ });
89
+ }
90
+ // Kill the whole group so a `sh -c` wrapper cannot leave its children
91
+ // running. If 'close' never arrives (a stuck pipe), finish anyway.
92
+ function kill() {
93
+ if (child.pid) {
94
+ try {
95
+ process.kill(-child.pid, "SIGKILL");
96
+ }
97
+ catch {
98
+ try {
99
+ child.kill("SIGKILL");
100
+ }
101
+ catch {
102
+ /* already gone */
103
+ }
104
+ }
105
+ }
106
+ fallback = setTimeout(finish, KILL_GRACE_MS);
107
+ }
108
+ function onAbort() {
109
+ aborted = true;
110
+ kill();
111
+ }
112
+ if (options.signal?.aborted) {
113
+ aborted = true;
114
+ finish();
115
+ return;
116
+ }
117
+ try {
118
+ child = spawn("/bin/sh", ["-c", check.command], {
119
+ cwd,
120
+ env,
121
+ detached: true,
122
+ stdio: ["ignore", "pipe", "pipe"],
123
+ });
124
+ }
125
+ catch (error) {
126
+ output += `${errorMessage(error)}\n`;
127
+ failedToStart = true;
128
+ finish();
129
+ return;
130
+ }
131
+ const onData = (chunk) => {
132
+ output += chunk.toString("utf8");
133
+ if (output.length > maxOutput * 2)
134
+ output = output.slice(-maxOutput);
135
+ };
136
+ child.stdout?.on("data", onData);
137
+ child.stderr?.on("data", onData);
138
+ child.on("error", (error) => {
139
+ output += `${error.message}\n`;
140
+ failedToStart = true;
141
+ finish();
142
+ });
143
+ child.on("close", (code) => {
144
+ exitCode = code;
145
+ finish();
146
+ });
147
+ timer = setTimeout(() => {
148
+ timedOut = true;
149
+ kill();
150
+ }, timeoutMs);
151
+ options.signal?.addEventListener("abort", onAbort, { once: true });
152
+ });
153
+ }
154
+ /**
155
+ * The text the developer agent reads when checks fail: one block per failed
156
+ * check, with its exit code or timeout and its output. Empty when all passed.
157
+ */
158
+ export function failureReport(results) {
159
+ return results
160
+ .filter((result) => !result.passed)
161
+ .map((result) => {
162
+ const how = result.timedOut
163
+ ? `timed out after ${(result.durationMs / 1000).toFixed(1)}s`
164
+ : result.exitCode === null
165
+ ? "did not finish"
166
+ : `exit code ${result.exitCode}`;
167
+ const fence = result.output.includes("```") ? "````" : "```";
168
+ return `Check "${result.label}" failed (${how}): ${result.command}\n\n${fence}text\n${result.output}\n${fence}`;
169
+ })
170
+ .join("\n\n");
171
+ }
172
+ /**
173
+ * Paths a ticket commit must never carry: env files with secrets, key
174
+ * material, and the board's own state directory. Example env files are fine.
175
+ */
176
+ export function isSecretPath(path) {
177
+ const segments = path.split(/[\\/]/).filter(Boolean);
178
+ const name = segments[segments.length - 1] ?? "";
179
+ if (segments.includes(".zelio"))
180
+ return true;
181
+ if (name === ".env" || (name.startsWith(".env.") && !SECRET_EXAMPLES.has(name)))
182
+ return true;
183
+ if (/\.(pem|key|p12|pfx)$/.test(name))
184
+ return true;
185
+ return /^id_(rsa|ed25519|ecdsa)/.test(name);
186
+ }
187
+ /**
188
+ * Stages everything except secret-looking files and commits what is left. The
189
+ * refused files stay untracked in the working tree, so the person can decide
190
+ * about them; nothing here ever pushes them.
191
+ */
192
+ export async function commitTicketWork(cwd, message) {
193
+ const refused = [];
194
+ try {
195
+ await git(cwd, ["add", "-A"]);
196
+ const staged = (await git(cwd, ["diff", "--cached", "--name-only", "-z"]))
197
+ .split("\0")
198
+ .filter(Boolean);
199
+ for (const path of staged) {
200
+ if (!isSecretPath(path))
201
+ continue;
202
+ await git(cwd, ["reset", "-q", "--", path]);
203
+ refused.push(path);
204
+ }
205
+ if (staged.every((path) => refused.includes(path))) {
206
+ return { committed: false, head: await headOf(cwd), refused, error: null };
207
+ }
208
+ // Keep the repo's own identity when it has one; the fallback only fills in
209
+ // what a fresh machine lacks.
210
+ const hasIdentity = await git(cwd, ["config", "user.email"]).then((value) => value.trim() !== "", () => false);
211
+ const identity = hasIdentity
212
+ ? []
213
+ : ["-c", "user.name=zelio", "-c", "user.email=zelio@localhost"];
214
+ await git(cwd, [...identity, "commit", "-m", message]);
215
+ return { committed: true, head: await headOf(cwd), refused, error: null };
216
+ }
217
+ catch (error) {
218
+ return {
219
+ committed: false,
220
+ head: await headOf(cwd),
221
+ refused,
222
+ error: tail(errorText(error), ERROR_TAIL_CHARS),
223
+ };
224
+ }
225
+ }
226
+ /**
227
+ * Whether the ticket has work to commit or commits past its base. The base is
228
+ * the remote's default branch when it resolves, else the local main. With no
229
+ * base to compare against, a checkout that has a HEAD counts as changed, so an
230
+ * unknown base never blocks the board. Never throws.
231
+ */
232
+ export async function hasTicketChanges(cwd, base) {
233
+ try {
234
+ // A refused secret is never committed, so it is not a change the ticket can ship.
235
+ const changed = (await git(cwd, ["status", "--porcelain", "-z", "--untracked-files=all"]))
236
+ .split("\0")
237
+ .filter((entry) => entry.length > 3)
238
+ .map((entry) => entry.slice(3))
239
+ .some((path) => !isSecretPath(path));
240
+ if (changed)
241
+ return true;
242
+ const ref = base ?? (await baseRef(cwd));
243
+ if (!ref)
244
+ return (await headOf(cwd)) !== null;
245
+ const count = await git(cwd, ["rev-list", "--count", `${ref}..HEAD`]);
246
+ return Number(count.trim()) > 0;
247
+ }
248
+ catch {
249
+ return (await headOf(cwd)) !== null;
250
+ }
251
+ }
252
+ /**
253
+ * The ticket's diff against its base, for the lead: committed and uncommitted
254
+ * tracked changes both show. Untracked files are named, never read, and
255
+ * secret-looking paths are left out of both. Truncated to `maxChars`, with the
256
+ * untracked list kept at the end. Never throws; an error reads as no diff.
257
+ */
258
+ export async function ticketDiff(cwd, maxChars = 12_000) {
259
+ try {
260
+ const ref = (await baseRef(cwd)) ?? "HEAD";
261
+ const status = await git(cwd, ["status", "--porcelain", "-z", "--untracked-files=all"]);
262
+ const untracked = status
263
+ .split("\0")
264
+ .filter((entry) => entry.startsWith("?? "))
265
+ .map((entry) => entry.slice(3))
266
+ .filter((path) => !isSecretPath(path));
267
+ const tracked = (await git(cwd, ["diff", "--name-only", "-z", ref]))
268
+ .split("\0")
269
+ .filter(Boolean)
270
+ .filter((path) => !isSecretPath(path));
271
+ const diff = tracked.length === 0 ? "" : await git(cwd, ["diff", ref, "--", ...tracked]);
272
+ const marker = "\n… (diff truncated)";
273
+ const listing = untracked.length ? `Untracked: ${untracked.slice(0, 50).join(", ")}` : "";
274
+ const room = Math.max(0, maxChars - listing.length - marker.length - 1);
275
+ const body = diff.length > room ? `${diff.slice(0, room)}${marker}` : diff;
276
+ return [body.trimEnd(), listing].filter(Boolean).join("\n");
277
+ }
278
+ catch {
279
+ return "";
280
+ }
281
+ }
282
+ async function baseRef(cwd) {
283
+ const name = await defaultBase(cwd, "origin");
284
+ const candidates = [`origin/${name}`, "main"];
285
+ const found = await Promise.all(candidates.map((candidate) => git(cwd, ["rev-parse", "--verify", "--quiet", `${candidate}^{commit}`]).then(() => true, () => false)));
286
+ return candidates.find((_, index) => found[index]) ?? null;
287
+ }
288
+ /**
289
+ * Pushes the ticket branch and makes sure a pull request exists for it. A push
290
+ * failure means nothing was published; a `gh` failure after a good push means
291
+ * the branch is on the remote and only the PR is missing.
292
+ */
293
+ export async function publishBranch(cwd, branch, pr, options = {}) {
294
+ const remote = options.remote ?? "origin";
295
+ try {
296
+ await git(cwd, ["push", "-u", remote, branch], options.timeoutMs ?? PUSH_TIMEOUT_MS);
297
+ }
298
+ catch (error) {
299
+ return {
300
+ pushed: false,
301
+ prUrl: null,
302
+ error: tail(redactCredentials(errorText(error)), ERROR_TAIL_CHARS),
303
+ };
304
+ }
305
+ try {
306
+ const prUrl = await pullRequestUrl(cwd, branch, pr, { ...options, remote });
307
+ return { pushed: true, prUrl, error: null };
308
+ }
309
+ catch (error) {
310
+ return {
311
+ pushed: true,
312
+ prUrl: null,
313
+ error: `pull request: ${tail(redactCredentials(errorText(error)), ERROR_TAIL_CHARS)}`,
314
+ };
315
+ }
316
+ }
317
+ async function pullRequestUrl(cwd, branch, pr, options) {
318
+ const gh = options.gh ?? "gh";
319
+ const env = { ...process.env, GH_PROMPT_DISABLED: "1" };
320
+ const existing = await execFileAsync(gh, ["pr", "view", branch, "--json", "url", "--jq", ".url"], { cwd, env, timeout: GH_TIMEOUT_MS }).then(({ stdout }) => urlIn(String(stdout)), () => null);
321
+ if (existing)
322
+ return existing;
323
+ const dir = await mkdtemp(join(tmpdir(), "zelio-pr-"));
324
+ try {
325
+ const bodyFile = join(dir, "body.md");
326
+ await writeFile(bodyFile, pr.body, "utf8");
327
+ const base = options.base ?? (await defaultBase(cwd, options.remote ?? "origin"));
328
+ const { stdout } = await execFileAsync(gh, [
329
+ "pr",
330
+ "create",
331
+ "--head",
332
+ branch,
333
+ "--base",
334
+ base,
335
+ "--title",
336
+ pr.title,
337
+ "--body-file",
338
+ bodyFile,
339
+ ], { cwd, env, timeout: GH_TIMEOUT_MS });
340
+ const url = urlIn(String(stdout));
341
+ if (!url)
342
+ throw new Error("gh did not print a pull request URL");
343
+ return url;
344
+ }
345
+ finally {
346
+ await rm(dir, { recursive: true, force: true });
347
+ }
348
+ }
349
+ /** The remote's default branch, read from its HEAD ref; "main" when unknown. */
350
+ async function defaultBase(cwd, remote) {
351
+ const ref = await git(cwd, ["symbolic-ref", "--short", `refs/remotes/${remote}/HEAD`]).then((value) => value.trim(), () => "");
352
+ const prefix = `${remote}/`;
353
+ const name = ref.startsWith(prefix) ? ref.slice(prefix.length) : ref;
354
+ return name || "main";
355
+ }
356
+ /** Hides credentials that git, gh or a remote URL may have echoed back. */
357
+ export function redactCredentials(text) {
358
+ return text
359
+ .replace(/https:\/\/[^\s/]+@/g, "https://***@")
360
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, "***")
361
+ .replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, "***");
362
+ }
363
+ async function git(cwd, args, timeout = GIT_TIMEOUT_MS) {
364
+ const { stdout } = await execFileAsync("git", ["-C", cwd, ...args], {
365
+ timeout,
366
+ maxBuffer: 10 * 1024 * 1024,
367
+ });
368
+ return String(stdout);
369
+ }
370
+ async function headOf(cwd) {
371
+ return git(cwd, ["rev-parse", "HEAD"]).then((value) => value.trim() || null, () => null);
372
+ }
373
+ function urlIn(text) {
374
+ return text.match(/https:\/\/\S+/)?.[0] ?? null;
375
+ }
376
+ function errorMessage(error) {
377
+ return error instanceof Error ? error.message : String(error);
378
+ }
379
+ /**
380
+ * git and gh put their reason in stderr, but a failing commit or push hook
381
+ * often prints to stdout; both are kept, and the message is the fallback.
382
+ */
383
+ export function errorText(error) {
384
+ const failed = error;
385
+ const parts = [failed?.stdout, failed?.stderr]
386
+ .map((value) => (typeof value === "string" ? value.trim() : ""))
387
+ .filter(Boolean);
388
+ return parts.length > 0 ? parts.join("\n") : errorMessage(error);
389
+ }
390
+ export function tail(text, length) {
391
+ return text.length > length ? text.slice(-length) : text;
392
+ }
393
+ //# sourceMappingURL=finish.js.map