@operad-io/dev 0.2.0 → 0.3.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.
package/src/gate.ts CHANGED
@@ -47,7 +47,7 @@ import { appendChange } from "./model.ts";
47
47
  import { reviewTestHooks } from "./clock.ts";
48
48
  export { reviewTestHooks };
49
49
  import { modelErrorIn, modelWaitsForPerson, type ModelErrorInfo } from "./model-error.ts";
50
- import { commitOf, git } from "./git.ts";
50
+ import { baseName, commitOf, fetchRemote, git } from "./git.ts";
51
51
  import {
52
52
  briefText,
53
53
  cancelledStep,
@@ -101,6 +101,7 @@ export function branchHead(
101
101
  const branch = workBranch(workName);
102
102
  const local = commitOf(repositoryPath, branch);
103
103
  if (local !== undefined) return local;
104
+ if (settings.remote === undefined) return undefined;
104
105
  return commitOf(repositoryPath, `refs/remotes/${settings.remote}/${branch}`);
105
106
  }
106
107
 
@@ -110,8 +111,7 @@ function mergeBase(
110
111
  settings: DevSettings,
111
112
  sha: string,
112
113
  ): string | undefined {
113
- const main = `${settings.remote}/${settings.mainBranch}`;
114
- const result = git(repositoryPath, ["merge-base", main, sha]);
114
+ const result = git(repositoryPath, ["merge-base", baseName(settings), sha]);
115
115
  return result.ok && result.out.length > 0 ? result.out : undefined;
116
116
  }
117
117
 
@@ -180,11 +180,7 @@ export async function runVerify(
180
180
  const task = context.task;
181
181
  const attempt = attemptOf(ctx, task);
182
182
  const previous = attempt.verify;
183
- git(context.repository.path, [
184
- "fetch",
185
- "--prune",
186
- context.settings.remote,
187
- ]);
183
+ fetchRemote(context.repository.path, context.settings);
188
184
  const sha = branchHead(
189
185
  context.repository.path,
190
186
  context.settings,
@@ -254,7 +250,9 @@ export async function runVerify(
254
250
 
255
251
  if (sha === undefined) {
256
252
  return failed(
257
- `no branch "${workBranch(context.workName)}" or "${context.settings.remote}/${workBranch(context.workName)}" to verify`,
253
+ context.settings.remote === undefined
254
+ ? `no branch "${workBranch(context.workName)}" to verify`
255
+ : `no branch "${workBranch(context.workName)}" or "${context.settings.remote}/${workBranch(context.workName)}" to verify`,
258
256
  );
259
257
  }
260
258
  const prepared = recreateGateWorktree(
@@ -716,11 +714,16 @@ function atOrAbove(severity: string, level: FixLevel): boolean {
716
714
  /** The line `dev/work` writes into the worker's answer for a main-checkout change. */
717
715
  const MAIN_CHECKOUT_CHANGE = "changed the main checkout:";
718
716
 
717
+ /** An entry of that line that names the main checkout's HEAD moving, not a file. */
718
+ const MOVED_HEAD = / \((?:moved|switched) [^)]*\)$/;
719
+
719
720
  /**
720
721
  * The paths an attempt's work changed outside its worktree, read from the line
721
722
  * the work step wrote into the worker's answer (T-0646).
722
723
  */
723
724
  function mainCheckoutChanges(attempt: TaskAttempt): readonly string[] {
725
+ // An attempt that works in the main clone changes it by design.
726
+ if (attempt.inPlace === true) return [];
724
727
  const message = attempt.finalMessage;
725
728
  if (typeof message !== "string") return [];
726
729
  const paths: string[] = [];
@@ -758,13 +761,23 @@ function mainCheckoutFindings(
758
761
  );
759
762
  return paths
760
763
  .filter((path) => !blocked.has(normalizePath(path)))
761
- .map((path) => ({
762
- file: path,
763
- line: 0,
764
- severity: "major",
765
- summary: "the work changed this file in the main checkout",
766
- trigger: "the work must make this change in its own worktree instead",
767
- }));
764
+ .map((path) =>
765
+ MOVED_HEAD.test(path)
766
+ ? {
767
+ file: path,
768
+ line: 0,
769
+ severity: "major",
770
+ summary: "the work committed in the main checkout",
771
+ trigger: "the work must commit on its own branch in its own worktree instead",
772
+ }
773
+ : {
774
+ file: path,
775
+ line: 0,
776
+ severity: "major",
777
+ summary: "the work changed this file in the main checkout",
778
+ trigger: "the work must make this change in its own worktree instead",
779
+ },
780
+ );
768
781
  }
769
782
 
770
783
  /** The counted findings of a failed review, as the task's history and brief show them. */
@@ -2002,8 +2015,14 @@ export async function runReview(
2002
2015
  typeof sha === "string" && recorded.sha === undefined
2003
2016
  ? { ...recorded, sha }
2004
2017
  : recorded;
2005
- const record: ReviewRecord =
2018
+ const withSettings: ReviewRecord =
2006
2019
  used === undefined ? stamped : { ...stamped, reviewSettings: used };
2020
+ // The fix level in force for this round, so a later view shows it and not
2021
+ // whatever dev.json says by then.
2022
+ const record: ReviewRecord = {
2023
+ ...withSettings,
2024
+ fixLevel: context.settings.reviewer.fixLevel,
2025
+ };
2007
2026
  const waiting =
2008
2027
  record.decision !== "findings" && record.result !== "fail";
2009
2028
  const written = await saveTaskGuarded(
@@ -2084,11 +2103,7 @@ export async function runReview(
2084
2103
  });
2085
2104
  }
2086
2105
 
2087
- git(context.repository.path, [
2088
- "fetch",
2089
- "--prune",
2090
- context.settings.remote,
2091
- ]);
2106
+ fetchRemote(context.repository.path, context.settings);
2092
2107
  const base = mergeBase(context.repository.path, context.settings, sha);
2093
2108
  if (base === undefined) {
2094
2109
  const record: ReviewRecord = {
@@ -2097,7 +2112,7 @@ export async function runReview(
2097
2112
  sha,
2098
2113
  round,
2099
2114
  reason: "no_merge_base",
2100
- message: `cannot find the merge base of ${context.settings.remote}/${context.settings.mainBranch} and ${sha}`,
2115
+ message: `cannot find the merge base of ${baseName(context.settings)} and ${sha}`,
2101
2116
  };
2102
2117
  return finish(record, "failed", {
2103
2118
  reason: "no_merge_base",
@@ -2306,6 +2321,38 @@ export async function runReview(
2306
2321
  // review to ask a model for. A change made only of left-out files still runs
2307
2322
  // the reviewer: the list is what tells it those files exist.
2308
2323
  if (prepared.files.length === 0) {
2324
+ // The work never reported done and the branch has no change: the empty
2325
+ // diff is the failed work, not a finished task with nothing to add.
2326
+ if (attempt.workDone !== true) {
2327
+ const findings: ReviewFinding[] = [
2328
+ {
2329
+ file: "(branch)",
2330
+ line: 0,
2331
+ severity: "major",
2332
+ summary: "the branch has no change against main and the work did not finish",
2333
+ trigger: "the work stopped before it committed anything; do the work again",
2334
+ },
2335
+ ];
2336
+ const message = describeFindings(findings);
2337
+ const record: ReviewRecord = {
2338
+ result: "findings",
2339
+ decision: "findings",
2340
+ run: ctx.runId,
2341
+ sha,
2342
+ round,
2343
+ runs: [],
2344
+ findings,
2345
+ verified: [],
2346
+ reason: "findings",
2347
+ message,
2348
+ };
2349
+ return finish(record, "fail", {
2350
+ reason: "findings",
2351
+ counted: 1,
2352
+ message,
2353
+ leftOut: prepared.leftOut.map(leftOutLine),
2354
+ });
2355
+ }
2309
2356
  // A main-checkout change fails even without a diff: no reviewer is asked,
2310
2357
  // and dev adds the major finding itself.
2311
2358
  const findings = mainCheckoutFindings(mainPaths, []);
@@ -0,0 +1,155 @@
1
+ /**
2
+ * What git a folder has, computed each time and never stored: the user can run
3
+ * `git init`, install git or make a commit at any moment, so a stored answer
4
+ * would be stale on the next tick. Chat needs none of it; creating a task needs
5
+ * `ready`. The states and their use are in docs/research/2026-11-22-dev-without-git.md
6
+ * section 5.
7
+ *
8
+ * A folder git cannot judge (it refuses with dubious ownership, `.git` is
9
+ * unreadable, it prints nothing) is an error, `GitStateError`, never `no repository`.
10
+ *
11
+ * Not told apart: a bare repository and a folder inside a `.git` directory both
12
+ * have no work tree, so they read as `no repository`.
13
+ */
14
+
15
+ import { realpathSync, statSync } from "node:fs";
16
+ import { findGit, realGitFinderHost, type GitFinderHost } from "@operad-io/engine/platform";
17
+ import { git, type GitOptions } from "./git.ts";
18
+ import { DevRefusal } from "./model.ts";
19
+
20
+ /** The user name and email git would write into a commit, as the configuration holds them. */
21
+ export interface GitIdentity {
22
+ /** `user.name`, or `undefined` when it is not set or empty. */
23
+ readonly name: string | undefined;
24
+ /** `user.email`, or `undefined` when it is not set or empty. */
25
+ readonly email: string | undefined;
26
+ /** True when both are set: a commit can be made. */
27
+ readonly set: boolean;
28
+ }
29
+
30
+ export type GitState =
31
+ /** The git program is not installed (or, on macOS, only its stub is). */
32
+ | { readonly state: "no program" }
33
+ /** Git is there; the folder is in no work tree. */
34
+ | { readonly state: "no repository"; readonly identity: GitIdentity }
35
+ /** The folder is inside the work tree whose top is `root`. */
36
+ | { readonly state: "subfolder"; readonly root: string; readonly identity: GitIdentity }
37
+ /** The folder is a work tree root with no commit; `branch` is the unborn branch's name. */
38
+ | {
39
+ readonly state: "no commit";
40
+ readonly branch: string | undefined;
41
+ readonly identity: GitIdentity;
42
+ }
43
+ /** The folder is a work tree root with a commit; `branch` is undefined on a detached HEAD. */
44
+ | {
45
+ readonly state: "ready";
46
+ readonly branch: string | undefined;
47
+ readonly identity: GitIdentity;
48
+ };
49
+
50
+ export interface GitStateOptions {
51
+ /** The environment of every git run; the default is this process's. */
52
+ readonly env?: NodeJS.ProcessEnv;
53
+ /** The machine the git program is looked up on; a test injects one without git. */
54
+ readonly finder?: GitFinderHost;
55
+ }
56
+
57
+ /** What git says when the folder is in no work tree (a bare repository has none either). */
58
+ const NO_REPOSITORY = /not a git repository|this operation must be run in a work tree/i;
59
+
60
+ /** Git could not say whether the folder is in a repository; `reason` is git's own message. */
61
+ export class GitStateError extends Error {
62
+ constructor(
63
+ readonly folder: string,
64
+ readonly reason: string,
65
+ ) {
66
+ super(`git cannot tell what "${folder}" is: ${reason.length > 0 ? reason : "no detail"}`);
67
+ this.name = "GitStateError";
68
+ }
69
+ }
70
+
71
+ function canonical(path: string): string {
72
+ try {
73
+ return realpathSync(path);
74
+ } catch {
75
+ return path;
76
+ }
77
+ }
78
+
79
+ function identityOf(folder: string, options: GitOptions): GitIdentity {
80
+ const read = (key: string): string | undefined => {
81
+ const result = git(folder, ["config", "--get", key], options);
82
+ return result.ok && result.out !== "" ? result.out : undefined;
83
+ };
84
+ const name = read("user.name");
85
+ const email = read("user.email");
86
+ return { name, email, set: name !== undefined && email !== undefined };
87
+ }
88
+
89
+ /** Test-only: the machine every state check looks for git on, when the caller gives none. */
90
+ export const gitStateTestHooks: { finder?: GitFinderHost | undefined } = {};
91
+
92
+ /** The state of `folder`, which must be an existing directory. */
93
+ export function gitStateOf(folder: string, stateOptions: GitStateOptions = {}): GitState {
94
+ if (statSync(folder, { throwIfNoEntry: false })?.isDirectory() !== true) {
95
+ throw new Error(`"${folder}" is not a folder`);
96
+ }
97
+ const env = stateOptions.env ?? { ...process.env };
98
+ const options: GitOptions = { env };
99
+ // The finder runs nothing that could open the macOS install dialog.
100
+ if (findGit(stateOptions.finder ?? gitStateTestHooks.finder ?? { ...realGitFinderHost(), env }) === undefined) return { state: "no program" };
101
+ const identity = identityOf(folder, options);
102
+ // Git's messages are forced to English for this one question, so the words
103
+ // that say "no repository" can be told from every other refusal.
104
+ const top = git(folder, ["rev-parse", "--show-toplevel"], {
105
+ env: { ...env, LC_ALL: "C", LANGUAGE: "" },
106
+ });
107
+ if (!top.ok) {
108
+ if (NO_REPOSITORY.test(top.err)) return { state: "no repository", identity };
109
+ // Dubious ownership, an unreadable .git, a git that prints nothing: the
110
+ // folder may well be a repository, so it is not taken for a plain folder.
111
+ throw new GitStateError(folder, top.err);
112
+ }
113
+ if (canonical(top.out) !== canonical(folder)) {
114
+ return { state: "subfolder", root: top.out, identity };
115
+ }
116
+ const branchResult = git(folder, ["symbolic-ref", "--short", "-q", "HEAD"], options);
117
+ const branch = branchResult.ok && branchResult.out !== "" ? branchResult.out : undefined;
118
+ const head = git(folder, ["rev-parse", "--verify", "-q", "HEAD^{commit}"], options);
119
+ return { state: head.ok ? "ready" : "no commit", branch, identity };
120
+ }
121
+
122
+ // Why a task cannot be created in `folder` now, in the line a person reads, or
123
+ // `undefined` when git is ready there. The bot turns the line into the person's
124
+ // language and starts the git setup; the line itself starts nothing.
125
+ export function taskRefusalOf(folder: string, stateOptions: GitStateOptions = {}): string | undefined {
126
+ const state = gitStateOf(folder, stateOptions);
127
+ switch (state.state) {
128
+ case "ready":
129
+ return undefined;
130
+ case "no program":
131
+ return "Creating a task needs git, and git is not installed on this machine. Ask the bot to help you install it.";
132
+ case "no repository":
133
+ return "This folder is not under git yet, and a task needs it. Ask the bot to set up git here: it will show you a list of the files first.";
134
+ case "no commit":
135
+ return "Git is set up here but has no commit yet, and a task needs one. Ask the bot to make the first commit: it will show you a list of the files first.";
136
+ case "subfolder":
137
+ return `This folder is inside the git repository at ${state.root}. Add ${state.root} as the project instead (operad dev repo add ${state.root}), or keep chatting here.`;
138
+ }
139
+ }
140
+
141
+ // The same line as `taskRefusalOf`, for a folder git cannot judge too.
142
+ export function taskGitRefusal(folder: string, stateOptions: GitStateOptions = {}): string | undefined {
143
+ try {
144
+ return taskRefusalOf(folder, stateOptions);
145
+ } catch (error) {
146
+ if (!(error instanceof GitStateError)) throw error;
147
+ return `Git cannot tell what this folder is, so a task cannot be created: ${error.reason}`;
148
+ }
149
+ }
150
+
151
+ // Throws a refusal when a task cannot be created in `folder`.
152
+ export function assertCanCreateTask(folder: string, stateOptions: GitStateOptions = {}): void {
153
+ const line = taskGitRefusal(folder, stateOptions);
154
+ if (line !== undefined) throw new DevRefusal(line);
155
+ }
package/src/git.ts CHANGED
@@ -5,6 +5,8 @@
5
5
  * before an empty answer is believed.
6
6
  */
7
7
 
8
+ import { findGit, GIT_NOT_INSTALLED, realGitFinderHost } from "@operad-io/engine/platform";
9
+
8
10
  export interface GitResult {
9
11
  readonly ok: boolean;
10
12
  readonly out: string;
@@ -55,8 +57,10 @@ export function printsOnSuccess(args: readonly string[]): boolean {
55
57
  const [command, sub] = args;
56
58
  switch (command) {
57
59
  case "rev-parse":
58
- case "symbolic-ref":
59
60
  return true;
61
+ case "symbolic-ref":
62
+ // The setting form (`symbolic-ref HEAD refs/heads/x`) prints nothing.
63
+ return !args.some((argument) => argument.startsWith("refs/"));
60
64
  case "worktree":
61
65
  return sub === "list";
62
66
  case "merge-base":
@@ -75,8 +79,13 @@ export function printsOnSuccess(args: readonly string[]): boolean {
75
79
 
76
80
  function runOnce(cwd: string, args: readonly string[], options: GitOptions): GitResult {
77
81
  const started = Date.now();
82
+ const env = options.env ?? { ...process.env };
83
+ // The absolute path found now, not the word `git`: a PATH that changed after
84
+ // this process started is not seen by a spawn. Nothing is spawned without it.
85
+ const program = findGit({ ...realGitFinderHost(), env });
86
+ if (program === undefined) return { ok: false, out: "", err: GIT_NOT_INSTALLED };
78
87
  const result = Bun.spawnSync({
79
- cmd: ["git", "-C", cwd, ...args],
88
+ cmd: [program, "-C", cwd, ...args],
80
89
  stdin:
81
90
  options.input === undefined
82
91
  ? "ignore"
@@ -85,8 +94,7 @@ function runOnce(cwd: string, args: readonly string[], options: GitOptions): Git
85
94
  : options.input,
86
95
  stdout: "pipe",
87
96
  stderr: "pipe",
88
- // Passed on so the child is found through the current PATH.
89
- env: options.env ?? { ...process.env },
97
+ env,
90
98
  timeout: options.timeoutMs ?? GIT_TIMEOUT_MS,
91
99
  killSignal: "SIGKILL",
92
100
  });
@@ -183,3 +191,36 @@ export function branchExists(
183
191
  : `refs/remotes/${remote}/${branch}`;
184
192
  return git(cwd, ["show-ref", "--verify", "--quiet", ref]).ok;
185
193
  }
194
+
195
+ // The two settings that name a repository's base branch.
196
+ export interface BaseSettings {
197
+ // Undefined when the repository has no remote.
198
+ readonly remote?: string | undefined;
199
+ readonly mainBranch: string;
200
+ }
201
+
202
+ // The name a task branch starts from and merges into: `<remote>/<main>`, or
203
+ // the local main branch when the repository has no remote.
204
+ export function baseName(settings: BaseSettings): string {
205
+ return settings.remote === undefined
206
+ ? settings.mainBranch
207
+ : `${settings.remote}/${settings.mainBranch}`;
208
+ }
209
+
210
+ // The full ref of `baseName`.
211
+ export function baseRef(settings: BaseSettings): string {
212
+ return settings.remote === undefined
213
+ ? `refs/heads/${settings.mainBranch}`
214
+ : `refs/remotes/${settings.remote}/${settings.mainBranch}`;
215
+ }
216
+
217
+ // Fetches the remote; a repository with no remote has nothing to fetch, which
218
+ // counts as a fetch that worked.
219
+ export function fetchRemote(
220
+ cwd: string,
221
+ settings: BaseSettings,
222
+ args: readonly string[] = ["--prune"],
223
+ ): GitResult {
224
+ if (settings.remote === undefined) return { ok: true, out: "", err: "" };
225
+ return git(cwd, ["fetch", ...args, settings.remote]);
226
+ }
package/src/index.ts CHANGED
@@ -32,6 +32,7 @@ export function createDevPlugin() {
32
32
  name: "dev",
33
33
  kind: "domain",
34
34
  version: pkg.version,
35
+ listTitle: "Projects",
35
36
  objects: [
36
37
  {
37
38
  name: "repo",
@@ -239,6 +240,9 @@ export function createDevPlugin() {
239
240
  /** The `SKILL.md` Setup Dev gives a bot (ADR 0010 D7). */
240
241
  export const DEV_SETUP_GUIDE = fileURLToPath(new URL("../skills/setup/SKILL.md", import.meta.url));
241
242
 
243
+ /** The `SKILL.md` a bot follows for the first task in a folder without git (ADR 0039 D8), through `bot setup-git`. */
244
+ export const DEV_GIT_GUIDE = fileURLToPath(new URL("../skills/git/SKILL.md", import.meta.url));
245
+
242
246
  export default createDevPlugin();
243
247
 
244
248
  export * from "./actions.ts";
@@ -256,6 +260,8 @@ export * from "./project-flows.ts";
256
260
  export * from "./schedule.ts";
257
261
  export * from "./service.ts";
258
262
  export * from "./register-requests.ts";
263
+ export * from "./git-state.ts";
264
+ export * from "./setup-git.ts";
259
265
  export * from "./places.ts";
260
266
  export * from "./project-settings.ts";
261
267
  export * from "./retry.ts";