@mnaimfaizy/agent-kit 1.0.0-beta.14 → 1.0.0-beta.16

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 (180) hide show
  1. package/README.md +22 -4
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +244 -6
  4. package/package.json +3 -2
  5. package/src/checks/ci-workflow.mjs +105 -0
  6. package/src/checks/claude-app.mjs +11 -2
  7. package/src/checks/custom-harness.mjs +157 -0
  8. package/src/checks/github-app.mjs +214 -0
  9. package/src/checks/rulesets.mjs +9 -8
  10. package/src/checks/secrets-and-variables.mjs +27 -8
  11. package/src/checks/stages.mjs +705 -0
  12. package/src/cli.mjs +583 -36
  13. package/src/deep-scan/agent.mjs +88 -21
  14. package/src/deep-scan/credential.mjs +81 -32
  15. package/src/deep-scan/docker-driver.mjs +105 -42
  16. package/src/deep-scan/harness-text.mjs +99 -0
  17. package/src/deep-scan/lifecycle.mjs +68 -178
  18. package/src/deep-scan/limits.mjs +13 -7
  19. package/src/deep-scan/model-proxy.mjs +21 -10
  20. package/src/deep-scan/preflight.mjs +19 -6
  21. package/src/deep-scan/recipe.mjs +4 -0
  22. package/src/deep-scan/runtime.mjs +54 -6
  23. package/src/deep-scan/sandbox-run.mjs +232 -0
  24. package/src/deep-scan/sbx-driver.mjs +224 -39
  25. package/src/deep-scan/tar.mjs +69 -22
  26. package/src/deep-scan/verify.mjs +6 -1
  27. package/src/deep-scan.mjs +73 -13
  28. package/src/doctor.mjs +166 -5
  29. package/src/exec.mjs +14 -5
  30. package/src/factory/budget/budget.mjs +259 -0
  31. package/src/factory/build/command.mjs +321 -0
  32. package/src/factory/build/factory.mjs +473 -0
  33. package/src/factory/build/findings.mjs +55 -0
  34. package/src/factory/build/host.mjs +230 -0
  35. package/src/factory/build/notes.mjs +191 -0
  36. package/src/factory/build/pull-request.mjs +74 -0
  37. package/src/factory/bundle.mjs +146 -0
  38. package/src/factory/checks/allowed-paths.mjs +50 -0
  39. package/src/factory/checks/plan-header.mjs +296 -0
  40. package/src/factory/checks/qa.mjs +85 -0
  41. package/src/factory/checks/review.mjs +73 -0
  42. package/src/factory/checks/security.mjs +50 -0
  43. package/src/factory/checks/stage-check.mjs +89 -0
  44. package/src/factory/claims/command.mjs +187 -0
  45. package/src/factory/claims/release.mjs +111 -0
  46. package/src/factory/decision/answers.mjs +103 -0
  47. package/src/factory/decision/command.mjs +64 -0
  48. package/src/factory/decision/plan.mjs +99 -0
  49. package/src/factory/decision/request.mjs +116 -0
  50. package/src/factory/doctor/files.mjs +329 -0
  51. package/src/factory/doctor/index.mjs +56 -0
  52. package/src/factory/doctor/local.mjs +497 -0
  53. package/src/factory/doctor/orchestrate.mjs +146 -0
  54. package/src/factory/engine/lease.mjs +146 -0
  55. package/src/factory/engine/local-engine.mjs +177 -0
  56. package/src/factory/engine/lockfile.mjs +64 -0
  57. package/src/factory/engine/workflow-engine.mjs +124 -0
  58. package/src/factory/gate/comment.mjs +88 -0
  59. package/src/factory/gate/config.mjs +57 -0
  60. package/src/factory/gate/gate-core.mjs +250 -0
  61. package/src/factory/gate/guarded.mjs +17 -0
  62. package/src/factory/gate/reads.mjs +105 -0
  63. package/src/factory/gate/task.mjs +193 -0
  64. package/src/factory/gate/trip-reads.mjs +82 -0
  65. package/src/factory/gate/trip.mjs +87 -0
  66. package/src/factory/init/blueprint.mjs +174 -0
  67. package/src/factory/init/index.mjs +337 -0
  68. package/src/factory/labels/evidence.mjs +162 -0
  69. package/src/factory/labels/moves.mjs +32 -0
  70. package/src/factory/labels/reconcile.mjs +267 -0
  71. package/src/factory/labels/revert.mjs +87 -0
  72. package/src/factory/labels/timeline.mjs +72 -0
  73. package/src/factory/labels/voided.mjs +59 -0
  74. package/src/factory/limits/harness.mjs +39 -0
  75. package/src/factory/limits/limits.mjs +123 -0
  76. package/src/factory/merge/command.mjs +172 -0
  77. package/src/factory/outbox/check.mjs +240 -0
  78. package/src/factory/outbox/rulings.mjs +195 -0
  79. package/src/factory/plan/command.mjs +66 -0
  80. package/src/factory/plan/comment.mjs +156 -0
  81. package/src/factory/plan/publish.mjs +149 -0
  82. package/src/factory/plan/risk.mjs +153 -0
  83. package/src/factory/qa/command.mjs +163 -0
  84. package/src/factory/records/engine-record.mjs +133 -0
  85. package/src/factory/records/main.mjs +96 -0
  86. package/src/factory/records/record.mjs +226 -0
  87. package/src/factory/records/sink.mjs +57 -0
  88. package/src/factory/report/build.mjs +92 -0
  89. package/src/factory/report/command.mjs +80 -0
  90. package/src/factory/report/facts.mjs +226 -0
  91. package/src/factory/report/gate-section.mjs +122 -0
  92. package/src/factory/report/metrics.mjs +111 -0
  93. package/src/factory/report/reads.mjs +246 -0
  94. package/src/factory/report/render.mjs +121 -0
  95. package/src/factory/report/rollout.mjs +154 -0
  96. package/src/factory/review/command.mjs +182 -0
  97. package/src/factory/run/awake.mjs +70 -0
  98. package/src/factory/run/collect.mjs +77 -0
  99. package/src/factory/run/command.mjs +490 -0
  100. package/src/factory/run/gh.mjs +46 -0
  101. package/src/factory/run/launch.mjs +47 -0
  102. package/src/factory/run/pipelines.mjs +261 -0
  103. package/src/factory/run/raw.mjs +96 -0
  104. package/src/factory/run/restart.mjs +83 -0
  105. package/src/factory/run/s3.mjs +193 -0
  106. package/src/factory/run/secrets.mjs +142 -0
  107. package/src/factory/run/teardown.mjs +242 -0
  108. package/src/factory/run/token.mjs +68 -0
  109. package/src/factory/security/command.mjs +157 -0
  110. package/src/factory/setup/app.mjs +122 -0
  111. package/src/factory/setup/command.mjs +409 -0
  112. package/src/factory/setup/labels.mjs +25 -0
  113. package/src/factory/setup/reads.mjs +129 -0
  114. package/src/factory/setup/writes.mjs +126 -0
  115. package/src/factory/snapshot/write.mjs +176 -0
  116. package/src/factory/stop/command.mjs +136 -0
  117. package/src/factory/sweep/actions-main.mjs +117 -0
  118. package/src/factory/sweep/command.mjs +65 -0
  119. package/src/factory/sweep/knobs.mjs +78 -0
  120. package/src/factory/sweep/marker-version.mjs +15 -0
  121. package/src/factory/sweep/markers.mjs +112 -0
  122. package/src/factory/sweep/overlap.mjs +24 -0
  123. package/src/factory/sweep/run.mjs +198 -0
  124. package/src/factory/sweep/shell.mjs +394 -0
  125. package/src/factory/sweep/split.mjs +104 -0
  126. package/src/factory/sweep/states.mjs +87 -0
  127. package/src/factory/sweep/sweep-core.mjs +1781 -0
  128. package/src/factory/tracker/github.mjs +674 -0
  129. package/src/factory/tracker/operations.mjs +153 -0
  130. package/src/factory/upgrade/index.mjs +83 -0
  131. package/src/harness/adapters.mjs +30 -0
  132. package/src/harness/antigravity.mjs +187 -0
  133. package/src/harness/claude-code.mjs +8 -1
  134. package/src/harness/codex.mjs +219 -0
  135. package/src/harness/cursor.mjs +199 -0
  136. package/src/harness/custom/registry.mjs +21 -0
  137. package/src/harness/custom/schema.mjs +90 -0
  138. package/src/harness/custom.mjs +299 -0
  139. package/src/harness/facts.mjs +44 -7
  140. package/src/harness/gemini.mjs +164 -0
  141. package/src/harness/install-layer.mjs +86 -3
  142. package/src/harness/opencode.mjs +289 -0
  143. package/src/harness/resolve.mjs +156 -0
  144. package/src/harness/support-levels.mjs +151 -3
  145. package/src/harness-live/assess.mjs +29 -6
  146. package/src/harness-live/cursor-real.mjs +146 -0
  147. package/src/harness-live/cursor-version.mjs +70 -0
  148. package/src/harness-live/cursor.mjs +80 -0
  149. package/src/harness-live/custom.mjs +91 -0
  150. package/src/harness-live/fixture-harness.mjs +45 -0
  151. package/src/harness-live/harnesses.mjs +263 -0
  152. package/src/harness-live/host.mjs +113 -4
  153. package/src/harness-live/opencode.mjs +289 -0
  154. package/src/harness-live/probes.mjs +87 -7
  155. package/src/harness-live/run.mjs +101 -20
  156. package/src/harness-live/setup.mjs +126 -0
  157. package/src/harness-live/stage.mjs +25 -15
  158. package/src/harness-live/suite.mjs +276 -95
  159. package/src/harness-test.mjs +116 -0
  160. package/src/init.mjs +374 -36
  161. package/src/kit-owned-paths.mjs +1 -1
  162. package/src/model-proxy/core.mjs +128 -20
  163. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  164. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  165. package/src/model-proxy/profiles/openai.mjs +327 -0
  166. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  167. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  168. package/src/model-proxy/stub.mjs +9 -1
  169. package/src/stage/audit.mjs +79 -0
  170. package/src/stage/egress-route.mjs +207 -0
  171. package/src/stage/implement/carry.mjs +308 -0
  172. package/src/stage/implement/sandbox.mjs +271 -0
  173. package/src/stage/implement/verify.mjs +70 -0
  174. package/src/stage/implement.mjs +218 -0
  175. package/src/stage/plan.mjs +115 -0
  176. package/src/stage/review-response.mjs +172 -0
  177. package/src/stage/review.mjs +185 -0
  178. package/src/stage/workspace.mjs +274 -0
  179. package/src/stage.mjs +1087 -0
  180. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,185 @@
1
+ // What the review is as a CI Stage (ADR 0024): its limits, the paths its brief
2
+ // names in the sandbox, what the Launcher adds to the trusted step's brief, and
3
+ // the shape of its Stage result (ADR 0026). The brief, with the skill, the spec
4
+ // and the reviewer's open threads, is built by the trusted step that calls the
5
+ // Launcher, and so are the diff and the log it copies in.
6
+ //
7
+ // The result's shape alone is checked here, to judge completion. The trusted
8
+ // step that posts it (.github/agent-runtime/review-threads.mjs `publish`)
9
+ // checks the shape again, then the caps and the threads an entry names, and
10
+ // scripts/review-publish.test.mjs holds the two to the same shapes.
11
+
12
+ import { routeSentence } from "./egress-route.mjs";
13
+
14
+ /** The Stage as `cli/harnesses.json` and the settings name it. */
15
+ export const STAGE = "review";
16
+
17
+ /** Where the sandbox holds the checkout. */
18
+ export const WORKSPACE = "/workspace";
19
+
20
+ /** The folder the brief, the prompt and the trusted step's files go in. */
21
+ export const IN_DIR = "/agent-kit/in";
22
+ export const BRIEF_PATH = `${IN_DIR}/brief.md`;
23
+ /** The one kit-written line the harness gets on its stdin (ADR 0027). */
24
+ export const PROMPT_PATH = `${IN_DIR}/prompt.md`;
25
+ /** The one result path every review brief names. */
26
+ export const RESULT_PATH = "/agent-kit/out/review.json";
27
+
28
+ /** The most the result holds: past it, nothing is published. */
29
+ export const MAX_RESULT_BYTES = 256 * 1024;
30
+
31
+ /** The most read out of the sandbox, so an oversized result is named as one. */
32
+ export const MAX_COPY_BYTES = 10 * 1024 * 1024;
33
+
34
+ /** The limits a review runs within unless a flag says otherwise. */
35
+ export const LIMITS = Object.freeze({
36
+ setupMinutes: 10,
37
+ scanMinutes: 30,
38
+ turns: 120,
39
+ tokens: 10_000_000,
40
+ });
41
+
42
+ /** It takes the files the trusted step prepared (`--input`). */
43
+ export const TAKES_INPUTS = true;
44
+
45
+ /** What the command calls the result in its lines. */
46
+ export const RESULT_NAME = "review.json";
47
+
48
+ /** The page that describes this Stage on the Launcher. */
49
+ export const DOCS_PAGE = "plan-implement-review.md#the-review-through-the-launcher";
50
+
51
+ /** A stopped run's result is left as it is: the trusted step publishes none. */
52
+ export const markStopped = (data) => data;
53
+ /** What the result's line adds on a run a limit stopped. */
54
+ export const stoppedNote = () => "partial, so nothing of it is to be published";
55
+
56
+ export const PROMPT = `Read the review brief at ${BRIEF_PATH} and follow it exactly. Write your whole review as JSON to the result path it names, and put no finding, file content or review text in your answer.\n`;
57
+
58
+ const AXES = Object.freeze(["standards", "spec", "correctness"]);
59
+
60
+ /**
61
+ * The Launcher's own opening of the brief, before the trusted step's.
62
+ * @param {{ checkoutConfig: readonly string[], instructionFiles: readonly string[] }} shape
63
+ * @param {readonly string[]} [inputs] the names of the files copied beside it
64
+ */
65
+ export function briefPreamble(shape, inputs = []) {
66
+ const { checkoutConfig, instructionFiles } = shape;
67
+ const listed = (paths) => paths.map((p) => `\`${p}\``).join(", ");
68
+ return [
69
+ "# Stage brief, from the agent-kit Launcher",
70
+ "",
71
+ "You are reviewing a pull request inside a closed, disposable sandbox. " +
72
+ routeSentence(shape) +
73
+ ", and the harness's own web and server-side tools are off. You hold no GitHub credential and post nothing: a trusted step posts your review from your result file after you finish. Nothing you change here is kept.",
74
+ "",
75
+ `- The repository: \`${WORKSPACE}\`, a copy of the head under review, with no \`.git\` folder.`,
76
+ ...(inputs.length
77
+ ? [`- Files prepared for you: ${listed(inputs.map((name) => `${IN_DIR}/${name}`))}.`]
78
+ : []),
79
+ `- Your result: write it to \`${RESULT_PATH}\`. It is the one result that leaves the sandbox. Write it early and keep it whole and valid as you add to it.`,
80
+ `- The harness's own config is not in the copy (${listed(checkoutConfig)}), so none of it could configure you.`,
81
+ `- The files the harness loads by itself (${listed(instructionFiles)}) are the trusted commit's, whatever the pull request holds.`,
82
+ "- Without a subagent tool, run the three axes one after another yourself.",
83
+ "",
84
+ "## The result file",
85
+ "",
86
+ "One JSON object with exactly these four keys, and no Markdown around it:",
87
+ "",
88
+ "```json",
89
+ JSON.stringify(
90
+ {
91
+ entries: [
92
+ {
93
+ axis: "standards | spec | correctness",
94
+ path: "path/from/the/repository/root",
95
+ line: 12,
96
+ summary: "one line",
97
+ body: "the finding, in Markdown",
98
+ },
99
+ {
100
+ axis: "standards | spec | correctness",
101
+ summary: "one line",
102
+ thread: "the url of one of your open threads, listed below",
103
+ },
104
+ ],
105
+ fixed: { standards: [], spec: [], correctness: ["an earlier finding the head fixed"] },
106
+ checked: { standards: [], spec: ["what you confirmed"], correctness: [] },
107
+ replies: [{ thread: "the url of an open thread", reply: "why you disagree" }],
108
+ },
109
+ null,
110
+ 2,
111
+ ),
112
+ "```",
113
+ "",
114
+ "- `entries`: one for each finding that stands. A new finding has `axis`, `path`, `line`, `summary` and `body`, with `line` a line of the head's version of `path`. A finding one of your open threads already holds has `axis`, `summary` and `thread`, and nothing else. An empty array means no findings.",
115
+ "- `fixed` and `checked`: short notes per axis; an axis with none may be left out.",
116
+ "- `replies`: your disagreements with a Verdict; an empty array when there are none.",
117
+ "- Caps: 100 entries, 100 replies, 50 notes in each list, 500 characters in a summary or a note, 1000 in a path, 10000 in a body, 4000 in a reply, 256 KiB in the file, and 60000 characters for the report your summaries and notes make up. Over a cap, or with a `thread` that is not one of your open threads, nothing is published and the review fails.",
118
+ "",
119
+ "-----",
120
+ "",
121
+ "",
122
+ ].join("\n");
123
+ }
124
+
125
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
126
+ const hasKeys = (v, keys) =>
127
+ isObject(v) && Object.keys(v).sort().join(",") === [...keys].sort().join(",");
128
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
129
+
130
+ /** Whether `entry` is a new finding or one an open thread already holds. */
131
+ function isEntry(entry) {
132
+ if (!isObject(entry) || !AXES.includes(entry.axis) || !isText(entry.summary)) return false;
133
+ if (hasKeys(entry, ["axis", "summary", "thread"])) return isText(entry.thread);
134
+ return (
135
+ hasKeys(entry, ["axis", "path", "line", "summary", "body"]) &&
136
+ isText(entry.path) &&
137
+ !/[\0-\x1f]/.test(entry.path) &&
138
+ Number.isSafeInteger(entry.line) &&
139
+ entry.line > 0 &&
140
+ isText(entry.body)
141
+ );
142
+ }
143
+
144
+ const isNotes = (notes) =>
145
+ isObject(notes) &&
146
+ Object.entries(notes).every(
147
+ ([axis, list]) => AXES.includes(axis) && Array.isArray(list) && list.every(isText),
148
+ );
149
+
150
+ /**
151
+ * Why `data` is no Stage result, or null when it is one. The reason is the
152
+ * kit's own words alone: nothing of the agent's goes into it.
153
+ * @param {Buffer} data
154
+ * @returns {string | null}
155
+ */
156
+ export function invalid(data) {
157
+ if (data.length > MAX_RESULT_BYTES) {
158
+ return `the file there is over the size cap of ${MAX_RESULT_BYTES / 1024} KiB`;
159
+ }
160
+ let value;
161
+ try {
162
+ value = JSON.parse(data.toString("utf8"));
163
+ } catch {
164
+ return "the file there is not JSON";
165
+ }
166
+ const bad = (what) => `the file there does not match the review result's schema: ${what}`;
167
+ if (!hasKeys(value, ["entries", "fixed", "checked", "replies"])) {
168
+ return bad("it is one object with the keys entries, fixed, checked and replies");
169
+ }
170
+ if (!Array.isArray(value.entries)) return bad("entries is an array");
171
+ const at = value.entries.findIndex((entry) => !isEntry(entry));
172
+ if (at !== -1) return bad(`entry ${at} is neither a new finding nor an existing one`);
173
+ for (const key of ["fixed", "checked"]) {
174
+ if (!isNotes(value[key])) return bad(`${key} holds lists of notes by axis`);
175
+ }
176
+ if (
177
+ !Array.isArray(value.replies) ||
178
+ !value.replies.every(
179
+ (r) => hasKeys(r, ["thread", "reply"]) && isText(r.thread) && isText(r.reply),
180
+ )
181
+ ) {
182
+ return bad("replies is an array of { thread, reply }");
183
+ }
184
+ return null;
185
+ }
@@ -0,0 +1,274 @@
1
+ // The copy of the checkout a CI Stage's sandbox gets (ADR 0025), as a tar the
2
+ // Launcher builds itself, under `workspace/`: every file of the checked-out
3
+ // commit, read blob by blob from git's objects, so no `.gitattributes` in the
4
+ // tree can leave a file out or rewrite it; none of the executable harness
5
+ // config the adapter's launch plan lists, at any depth; and the instruction
6
+ // files the harness loads by itself from the trusted commit alone. Untracked
7
+ // files (a scanner's output) come too only when asked for, under the same
8
+ // rules. A submodule is not copied.
9
+
10
+ import { lstatSync, readFileSync } from "node:fs";
11
+ import { join, posix } from "node:path";
12
+ import { firstLine } from "../exec.mjs";
13
+ import { tarOf } from "../deep-scan/tar.mjs";
14
+
15
+ /** The most the copy holds: the Launcher keeps it in memory. */
16
+ export const MAX_WORKSPACE_BYTES = 1024 * 1024 * 1024;
17
+ /** The most untracked files may add to it. */
18
+ export const MAX_UNTRACKED_BYTES = 256 * 1024 * 1024;
19
+
20
+ const PREFIX = "workspace";
21
+ const LINK = "120000";
22
+ const EXECUTABLE = "100755";
23
+ /** How many links an instruction file's link is followed through. */
24
+ const LINK_HOPS = 5;
25
+
26
+ /** Why the copy could not be made. */
27
+ export class WorkspaceError extends Error {}
28
+
29
+ /**
30
+ * Whether `path` is one of `listed`, or sits in one, at any depth.
31
+ * @param {string} path a repository path
32
+ * @param {readonly string[]} listed paths as a launch plan names them
33
+ */
34
+ export function underListed(path, listed) {
35
+ const walled = `/${path}/`;
36
+ return listed.some((entry) => walled.includes(`/${entry}/`));
37
+ }
38
+
39
+ /** Whether a link at `path` could stand in for a folder that holds a listed path. */
40
+ function standsFor(path, listed) {
41
+ const segments = path.split("/");
42
+ return listed.some((entry) => {
43
+ const parts = entry.split("/");
44
+ for (let n = 1; n < parts.length; n++) {
45
+ if (segments.slice(-n).join("/") === parts.slice(0, n).join("/")) return true;
46
+ }
47
+ return false;
48
+ });
49
+ }
50
+
51
+ /**
52
+ * The tar to unpack at the sandbox's root.
53
+ * @param {{
54
+ * runner: import("../exec.mjs").Runner,
55
+ * root: string,
56
+ * commit: string,
57
+ * trusted: string,
58
+ * checkoutConfig: readonly string[],
59
+ * instructionFiles: readonly string[],
60
+ * untracked?: boolean,
61
+ * }} opts `commit` is the checked-out commit and `trusted` the trusted one.
62
+ * @returns {Promise<{ tar: Buffer, files: number, left: number, skipped: number }>}
63
+ * `left` counts the entries left out as harness config or untrusted
64
+ * instructions, and `skipped` the untracked entries not copied (not a
65
+ * regular file, or past the size cap).
66
+ */
67
+ export async function workspaceTar({
68
+ runner,
69
+ root,
70
+ commit,
71
+ trusted,
72
+ checkoutConfig,
73
+ instructionFiles,
74
+ untracked = false,
75
+ }) {
76
+ const {
77
+ entries: all,
78
+ head,
79
+ wanted,
80
+ keeps,
81
+ } = await copied({ runner, root, commit, trusted, checkoutConfig, instructionFiles });
82
+ const size = all.reduce((n, e) => n + e.size, 0);
83
+ if (size > MAX_WORKSPACE_BYTES) {
84
+ throw new WorkspaceError(
85
+ `the checkout is larger than ${MAX_WORKSPACE_BYTES / 1024 / 1024} MiB, the most the Launcher holds in memory to copy in`,
86
+ );
87
+ }
88
+ const read = await blobs(runner, root, all);
89
+ const entries = new Map();
90
+ const add = (path, entry) => entries.set(path, { path: `${PREFIX}/${path}`, ...entry });
91
+ for (const e of all) {
92
+ const data = read.get(e.oid);
93
+ if (e.mode === LINK) add(e.path, { link: data.toString("utf8") });
94
+ else add(e.path, { data, executable: e.mode === EXECUTABLE });
95
+ }
96
+
97
+ let skipped = 0;
98
+ if (untracked) {
99
+ let room = MAX_UNTRACKED_BYTES;
100
+ for (const path of untrackedPaths(runner, root)) {
101
+ if (entries.has(path) || !keeps(path, false)) continue;
102
+ const file = join(root, path);
103
+ let stat;
104
+ try {
105
+ stat = lstatSync(file);
106
+ } catch {
107
+ skipped += 1;
108
+ continue;
109
+ }
110
+ // No link of the runner's is followed.
111
+ if (!stat.isFile() || stat.size > room || throughLink(root, path)) {
112
+ skipped += 1;
113
+ continue;
114
+ }
115
+ room -= stat.size;
116
+ add(path, { data: readFileSync(file), executable: (stat.mode & 0o111) !== 0 });
117
+ }
118
+ }
119
+
120
+ const tar = tarOf([{ path: PREFIX, dir: true }, ...entries.values()]);
121
+ return { tar, files: entries.size, left: head.length - wanted.length, skipped };
122
+ }
123
+
124
+ /**
125
+ * What a writing Stage needs to make the sandbox's copy a git repository: a
126
+ * pack of `commit`, its trees and its files (no history), the tracked paths the
127
+ * copy leaves out or holds with other text (`skip`), and the files the copy
128
+ * adds that `commit` does not track (`added`).
129
+ * @param {Parameters<typeof workspaceTar>[0]} opts as the copy's own
130
+ */
131
+ export async function seedPack({
132
+ runner,
133
+ root,
134
+ commit,
135
+ trusted,
136
+ checkoutConfig,
137
+ instructionFiles,
138
+ }) {
139
+ const r = runner("git", ["-C", root, "ls-tree", "-r", "-t", "-z", "--full-tree", commit], {
140
+ maxBuffer: MAX_WORKSPACE_BYTES,
141
+ });
142
+ if (r.status !== 0) throw new WorkspaceError(firstLine(r.stderr) || "git ls-tree failed");
143
+ const tracked = r.stdout
144
+ .split("\0")
145
+ .filter(Boolean)
146
+ .map((line) => {
147
+ const tab = line.indexOf("\t");
148
+ const [mode, type, oid] = line.slice(0, tab).split(" ");
149
+ return { mode, type, oid, path: line.slice(tab + 1) };
150
+ });
151
+ const copy = await copied({ runner, root, commit, trusted, checkoutConfig, instructionFiles });
152
+ const placed = new Map(copy.entries.map((e) => [e.path, e.oid]));
153
+ const skip = tracked
154
+ .filter((e) => e.type !== "tree" && placed.get(e.path) !== e.oid)
155
+ .map((e) => e.path);
156
+ const known = new Set(tracked.map((e) => e.path));
157
+ const added = [...placed.keys()].filter((path) => !known.has(path));
158
+ const tree = runner("git", ["-C", root, "rev-parse", `${commit}^{tree}`]);
159
+ if (tree.status !== 0) throw new WorkspaceError(firstLine(tree.stderr) || "git rev-parse failed");
160
+ // A submodule's commit is not one of this repository's objects.
161
+ const objects = [
162
+ commit,
163
+ tree.stdout.trim(),
164
+ ...tracked.filter((e) => e.type !== "commit").map((e) => e.oid),
165
+ ];
166
+ const packed = await runner.start("git", ["-C", root, "pack-objects", "-q", "--stdout"], {
167
+ stdin: `${[...new Set(objects)].join("\n")}\n`,
168
+ maxOutput: MAX_WORKSPACE_BYTES,
169
+ });
170
+ if (packed.truncated || packed.status !== 0) {
171
+ throw new WorkspaceError(firstLine(packed.stderr) || "git pack-objects failed");
172
+ }
173
+ return { pack: packed.stdout, skip, added };
174
+ }
175
+
176
+ /** The tracked entries the copy holds, from `commit` and the trusted commit. */
177
+ async function copied({ runner, root, commit, trusted, checkoutConfig, instructionFiles }) {
178
+ const withheld = [...checkoutConfig, ...instructionFiles];
179
+ const keeps = (path, link) =>
180
+ !underListed(path, withheld) && !(link && standsFor(path, withheld));
181
+
182
+ const head = treeOf(runner, root, commit);
183
+ const wanted = head.filter((e) => keeps(e.path, e.mode === LINK));
184
+ const base = trusted === commit ? head : treeOf(runner, root, trusted);
185
+ const instructions = base.filter(
186
+ (e) => underListed(e.path, instructionFiles) && !underListed(e.path, checkoutConfig),
187
+ );
188
+
189
+ // A trusted instruction file that is a link is placed as the trusted file it
190
+ // names, so the checkout under audit does not decide its text.
191
+ const byPath = new Map(base.map((e) => [e.path, e]));
192
+ const links = await blobs(
193
+ runner,
194
+ root,
195
+ base.filter((e) => e.mode === LINK),
196
+ );
197
+ const resolve = (entry) => {
198
+ let current = entry;
199
+ for (let hop = 0; current && current.mode === LINK && hop < LINK_HOPS; hop++) {
200
+ const target = links.get(current.oid).toString("utf8");
201
+ if (posix.isAbsolute(target)) return null;
202
+ current = byPath.get(posix.normalize(posix.join(posix.dirname(current.path), target)));
203
+ }
204
+ return current && current.mode !== LINK ? { ...current, path: entry.path } : null;
205
+ };
206
+ const placed = instructions.map(resolve).filter(Boolean);
207
+ // A file or link of the checkout's where a trusted instruction file needs a
208
+ // folder would send it elsewhere, or stop the unpacking: it is left out.
209
+ const shadows = (e) => placed.some((p) => p.path.startsWith(`${e.path}/`));
210
+
211
+ const all = [...wanted.filter((e) => !shadows(e)), ...placed];
212
+ return { entries: all, head, wanted, keeps };
213
+ }
214
+
215
+ /** Whether any folder on the way to `path` is a symbolic link. */
216
+ function throughLink(root, path) {
217
+ const segments = path.split("/").slice(0, -1);
218
+ return segments.some((_, i) =>
219
+ lstatSync(join(root, ...segments.slice(0, i + 1))).isSymbolicLink(),
220
+ );
221
+ }
222
+
223
+ /** Every file and link of `commit`, as { mode, oid, size, path }. */
224
+ function treeOf(runner, root, commit) {
225
+ const r = runner("git", ["-C", root, "ls-tree", "-r", "-l", "-z", "--full-tree", commit], {
226
+ maxBuffer: MAX_WORKSPACE_BYTES,
227
+ });
228
+ if (r.status !== 0) throw new WorkspaceError(firstLine(r.stderr) || "git ls-tree failed");
229
+ return r.stdout
230
+ .split("\0")
231
+ .filter(Boolean)
232
+ .map((line) => {
233
+ const tab = line.indexOf("\t");
234
+ const [mode, type, oid, size] = line.slice(0, tab).split(/ +/);
235
+ return { mode, type, oid, size: Number(size), path: line.slice(tab + 1) };
236
+ })
237
+ .filter((e) => e.type === "blob");
238
+ }
239
+
240
+ /** The bytes of each entry's blob, by object id. */
241
+ async function blobs(runner, root, entries) {
242
+ const oids = [...new Set(entries.map((e) => e.oid))];
243
+ const found = new Map();
244
+ if (!oids.length) return found;
245
+ const r = await runner.start("git", ["-C", root, "cat-file", "--batch"], {
246
+ stdin: `${oids.join("\n")}\n`,
247
+ maxOutput: MAX_WORKSPACE_BYTES + oids.length * 128,
248
+ });
249
+ if (r.truncated || r.status !== 0) {
250
+ throw new WorkspaceError(firstLine(r.stderr) || "git cat-file failed");
251
+ }
252
+ let at = 0;
253
+ for (const oid of oids) {
254
+ const end = r.stdout.indexOf(0x0a, at);
255
+ const [name, type, size] = r.stdout.subarray(at, end).toString("utf8").split(" ");
256
+ if (end < 0 || name !== oid || type !== "blob") {
257
+ throw new WorkspaceError(`git cat-file did not give the object ${oid}`);
258
+ }
259
+ found.set(oid, r.stdout.subarray(end + 1, end + 1 + Number(size)));
260
+ at = end + 1 + Number(size) + 1;
261
+ }
262
+ return found;
263
+ }
264
+
265
+ /** Every untracked file, ignored ones included. A nested repository is not entered. */
266
+ function untrackedPaths(runner, root) {
267
+ const r = runner("git", ["-C", root, "ls-files", "-z", "--others", "--full-name"], {
268
+ maxBuffer: MAX_WORKSPACE_BYTES,
269
+ });
270
+ if (r.status !== 0) throw new WorkspaceError(firstLine(r.stderr) || "git ls-files failed");
271
+ return r.stdout
272
+ .split("\0")
273
+ .filter((p) => p && !p.endsWith("/") && !p.split("/").includes(".git"));
274
+ }