@aigile/engine 0.0.0-stage → 0.2.0

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 (118) hide show
  1. package/dist/agents/code-reviewer.d.ts +37 -0
  2. package/dist/agents/code-reviewer.d.ts.map +1 -0
  3. package/dist/agents/code-reviewer.js +192 -0
  4. package/dist/agents/code-reviewer.js.map +1 -0
  5. package/dist/agents/engineer.d.ts +118 -0
  6. package/dist/agents/engineer.d.ts.map +1 -0
  7. package/dist/agents/engineer.js +528 -0
  8. package/dist/agents/engineer.js.map +1 -0
  9. package/dist/agents/monitor.d.ts +66 -0
  10. package/dist/agents/monitor.d.ts.map +1 -0
  11. package/dist/agents/monitor.js +281 -0
  12. package/dist/agents/monitor.js.map +1 -0
  13. package/dist/agents/orchestrator.d.ts +49 -0
  14. package/dist/agents/orchestrator.d.ts.map +1 -0
  15. package/dist/agents/orchestrator.js +204 -0
  16. package/dist/agents/orchestrator.js.map +1 -0
  17. package/dist/agents/release-manager.d.ts +76 -0
  18. package/dist/agents/release-manager.d.ts.map +1 -0
  19. package/dist/agents/release-manager.js +312 -0
  20. package/dist/agents/release-manager.js.map +1 -0
  21. package/dist/agents/spec-analyst.d.ts +102 -0
  22. package/dist/agents/spec-analyst.d.ts.map +1 -0
  23. package/dist/agents/spec-analyst.js +406 -0
  24. package/dist/agents/spec-analyst.js.map +1 -0
  25. package/dist/agents/verifier.d.ts +41 -0
  26. package/dist/agents/verifier.d.ts.map +1 -0
  27. package/dist/agents/verifier.js +173 -0
  28. package/dist/agents/verifier.js.map +1 -0
  29. package/dist/ai-service.d.ts +52 -0
  30. package/dist/ai-service.d.ts.map +1 -0
  31. package/dist/ai-service.js +164 -0
  32. package/dist/ai-service.js.map +1 -0
  33. package/dist/build-service.d.ts +65 -0
  34. package/dist/build-service.d.ts.map +1 -0
  35. package/dist/build-service.js +140 -0
  36. package/dist/build-service.js.map +1 -0
  37. package/dist/checkout.d.ts +57 -0
  38. package/dist/checkout.d.ts.map +1 -0
  39. package/dist/checkout.js +187 -0
  40. package/dist/checkout.js.map +1 -0
  41. package/dist/command-runner.d.ts +67 -0
  42. package/dist/command-runner.d.ts.map +1 -0
  43. package/dist/command-runner.js +149 -0
  44. package/dist/command-runner.js.map +1 -0
  45. package/dist/conversations.d.ts +18 -0
  46. package/dist/conversations.d.ts.map +1 -0
  47. package/dist/conversations.js +34 -0
  48. package/dist/conversations.js.map +1 -0
  49. package/dist/data-access.d.ts +34 -0
  50. package/dist/data-access.d.ts.map +1 -0
  51. package/dist/data-access.js +85 -0
  52. package/dist/data-access.js.map +1 -0
  53. package/dist/git-host.d.ts +43 -0
  54. package/dist/git-host.d.ts.map +1 -0
  55. package/dist/git-host.js +83 -0
  56. package/dist/git-host.js.map +1 -0
  57. package/dist/in-memory-store.d.ts +25 -0
  58. package/dist/in-memory-store.d.ts.map +1 -0
  59. package/dist/in-memory-store.js +52 -0
  60. package/dist/in-memory-store.js.map +1 -0
  61. package/dist/index.d.ts +28 -0
  62. package/dist/index.d.ts.map +1 -0
  63. package/dist/index.js +28 -0
  64. package/dist/index.js.map +1 -0
  65. package/dist/milestones.d.ts +36 -0
  66. package/dist/milestones.d.ts.map +1 -0
  67. package/dist/milestones.js +50 -0
  68. package/dist/milestones.js.map +1 -0
  69. package/dist/pull-request-sync.d.ts +29 -0
  70. package/dist/pull-request-sync.d.ts.map +1 -0
  71. package/dist/pull-request-sync.js +79 -0
  72. package/dist/pull-request-sync.js.map +1 -0
  73. package/dist/questions.d.ts +37 -0
  74. package/dist/questions.d.ts.map +1 -0
  75. package/dist/questions.js +79 -0
  76. package/dist/questions.js.map +1 -0
  77. package/dist/queue.d.ts +51 -0
  78. package/dist/queue.d.ts.map +1 -0
  79. package/dist/queue.js +108 -0
  80. package/dist/queue.js.map +1 -0
  81. package/dist/reviews.d.ts +17 -0
  82. package/dist/reviews.d.ts.map +1 -0
  83. package/dist/reviews.js +42 -0
  84. package/dist/reviews.js.map +1 -0
  85. package/dist/router.d.ts +13 -0
  86. package/dist/router.d.ts.map +1 -0
  87. package/dist/router.js +22 -0
  88. package/dist/router.js.map +1 -0
  89. package/dist/scheduler.d.ts +57 -0
  90. package/dist/scheduler.d.ts.map +1 -0
  91. package/dist/scheduler.js +134 -0
  92. package/dist/scheduler.js.map +1 -0
  93. package/dist/services.d.ts +359 -0
  94. package/dist/services.d.ts.map +1 -0
  95. package/dist/services.js +674 -0
  96. package/dist/services.js.map +1 -0
  97. package/dist/spec-resolver.d.ts +69 -0
  98. package/dist/spec-resolver.d.ts.map +1 -0
  99. package/dist/spec-resolver.js +200 -0
  100. package/dist/spec-resolver.js.map +1 -0
  101. package/dist/text-diff.d.ts +16 -0
  102. package/dist/text-diff.d.ts.map +1 -0
  103. package/dist/text-diff.js +51 -0
  104. package/dist/text-diff.js.map +1 -0
  105. package/dist/tool-sandbox.d.ts +47 -0
  106. package/dist/tool-sandbox.d.ts.map +1 -0
  107. package/dist/tool-sandbox.js +245 -0
  108. package/dist/tool-sandbox.js.map +1 -0
  109. package/dist/tracks.d.ts +58 -0
  110. package/dist/tracks.d.ts.map +1 -0
  111. package/dist/tracks.js +149 -0
  112. package/dist/tracks.js.map +1 -0
  113. package/dist/verifier.d.ts +27 -0
  114. package/dist/verifier.d.ts.map +1 -0
  115. package/dist/verifier.js +99 -0
  116. package/dist/verifier.js.map +1 -0
  117. package/package.json +31 -4
  118. package/README.md +0 -3
@@ -0,0 +1,140 @@
1
+ import { buildSchema, COLLECTIONS, newId, nowIso } from '@aigile/core';
2
+ import { SpecResolver } from './spec-resolver.js';
3
+ import { diffLines, formatUnifiedDiff } from './text-diff.js';
4
+ /**
5
+ * Creates Builds from the resolved spec set and diffs consecutive Builds.
6
+ *
7
+ * Flow (matching the product spec): load the most recent Build for the project,
8
+ * create a new Build from the currently-resolved spec revisions, diff the revision
9
+ * references to find changed specs, and diff their content. The resulting
10
+ * {@link BuildPlan} — content diffs + git ref — is what gets handed to the (still
11
+ * deferred) build/code-modification agent via {@link buildAgentMessages}.
12
+ */
13
+ export class BuildService {
14
+ data;
15
+ store;
16
+ resolver;
17
+ constructor(data, store) {
18
+ this.data = data;
19
+ this.store = store;
20
+ this.resolver = new SpecResolver(data);
21
+ }
22
+ /** Most recent Build for a project (by timestamp), or null. */
23
+ async latestBuild(projectId) {
24
+ const builds = (await this.data.builds()).filter((b) => b.projectId === projectId && b.status !== 'failed' && b.status !== 'discarded' && b.status !== 'rejected');
25
+ // ISO-8601 timestamps sort lexicographically; newest last → take the max.
26
+ builds.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
27
+ return builds.at(-1) ?? null;
28
+ }
29
+ async planBuild(projectId, gitRef, options = {}) {
30
+ const previous = await this.latestBuild(projectId);
31
+ const resolution = await this.resolver.resolveProject(projectId);
32
+ const specRevisions = resolution.resolved.map((r) => ({
33
+ specId: r.specId,
34
+ revision: r.revision,
35
+ }));
36
+ const ts = nowIso();
37
+ const build = buildSchema.parse({
38
+ id: newId(),
39
+ timestamp: ts,
40
+ projectId,
41
+ specRevisions,
42
+ gitRef,
43
+ createdAt: ts,
44
+ updatedAt: ts,
45
+ ...(options.seed ?? {}),
46
+ });
47
+ const changes = await this.diffBuilds(previous, build);
48
+ const unchangedCount = specRevisions.length - changes.filter((c) => c.kind !== 'removed').length;
49
+ if (options.persist !== false) {
50
+ await this.store.put(COLLECTIONS.builds, build.id, build, {
51
+ message: `Build ${projectId} @ ${gitRef}`,
52
+ });
53
+ }
54
+ return { projectId, build, previousBuildId: previous?.id ?? null, changes, unchangedCount };
55
+ }
56
+ async get(id) {
57
+ const raw = await this.store.get(COLLECTIONS.builds, id);
58
+ if (raw === null)
59
+ throw new Error(`build ${id} not found`);
60
+ return buildSchema.parse(raw);
61
+ }
62
+ /** Every build, newest first. */
63
+ async forProjectAll() {
64
+ return (await this.data.builds()).sort((a, b) => b.timestamp.localeCompare(a.timestamp));
65
+ }
66
+ /** Every build of a project, newest first. */
67
+ async forProject(projectId) {
68
+ return (await this.data.builds()).filter((b) => b.projectId === projectId).sort((a, b) => b.timestamp.localeCompare(a.timestamp));
69
+ }
70
+ async update(id, patch, message) {
71
+ const next = { ...(await this.get(id)), ...patch, updatedAt: nowIso() };
72
+ await this.store.put(COLLECTIONS.builds, id, next, { message });
73
+ return next;
74
+ }
75
+ /** The spec changes a build was planned from (against the build before it). */
76
+ async changesOf(build) {
77
+ const earlier = (await this.forProject(build.projectId)).filter((b) => b.timestamp < build.timestamp && b.status !== 'failed' && b.status !== 'discarded' && b.status !== 'rejected');
78
+ return this.diffBuilds(earlier[0] ?? null, build);
79
+ }
80
+ /** Compute per-spec changes between two builds' revision sets and content. */
81
+ async diffBuilds(previous, current) {
82
+ const prevMap = new Map((previous?.specRevisions ?? []).map((r) => [r.specId, r.revision]));
83
+ const currMap = new Map(current.specRevisions.map((r) => [r.specId, r.revision]));
84
+ const changes = [];
85
+ // Added or changed specs (present in the new build).
86
+ for (const [specId, toRevision] of currMap) {
87
+ const fromRevision = prevMap.get(specId) ?? null;
88
+ if (fromRevision === toRevision)
89
+ continue; // unchanged
90
+ const before = fromRevision ? await this.contentAt(specId, fromRevision) : '';
91
+ const after = await this.contentAt(specId, toRevision);
92
+ changes.push({
93
+ specId,
94
+ kind: fromRevision === null ? 'added' : 'changed',
95
+ fromRevision,
96
+ toRevision,
97
+ diff: diffLines(before, after),
98
+ });
99
+ }
100
+ // Removed specs (present before, gone now).
101
+ for (const [specId, fromRevision] of prevMap) {
102
+ if (currMap.has(specId))
103
+ continue;
104
+ const before = await this.contentAt(specId, fromRevision);
105
+ changes.push({
106
+ specId,
107
+ kind: 'removed',
108
+ fromRevision,
109
+ toRevision: null,
110
+ diff: diffLines(before, ''),
111
+ });
112
+ }
113
+ changes.sort((a, b) => (a.specId < b.specId ? -1 : a.specId > b.specId ? 1 : 0));
114
+ return changes;
115
+ }
116
+ async contentAt(specId, revision) {
117
+ const spec = await this.data.specAtRevision(specId, revision);
118
+ return spec?.content ?? '';
119
+ }
120
+ }
121
+ /**
122
+ * Assemble the message payload for the build/code-modification agent from a plan
123
+ * plus caller-supplied application instructions. The AiProvider call itself is
124
+ * deferred (the default provider is a stub); this is the seam that feeds it.
125
+ */
126
+ export function buildAgentMessages(plan, instructions) {
127
+ const sections = plan.changes.map((change) => {
128
+ const header = `### Spec ${change.specId} (${change.kind}) ${change.fromRevision ?? '∅'} → ${change.toRevision ?? '∅'}`;
129
+ return `${header}\n\`\`\`diff\n${formatUnifiedDiff(change.diff)}\n\`\`\``;
130
+ });
131
+ const user = [
132
+ `Project: ${plan.projectId}`,
133
+ `Target git ref: ${plan.build.gitRef}`,
134
+ `Changed specs: ${plan.changes.length} (unchanged: ${plan.unchangedCount})`,
135
+ '',
136
+ sections.join('\n\n'),
137
+ ].join('\n');
138
+ return { system: instructions, messages: [{ role: 'user', content: user }] };
139
+ }
140
+ //# sourceMappingURL=build-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-service.js","sourceRoot":"","sources":["../src/build-service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEvE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAiB,SAAS,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAgC7E;;;;;;;;GAQG;AACH,MAAM,OAAO,YAAY;IAIJ;IACA;IAJF,QAAQ,CAAe;IAExC,YACmB,IAAgB,EAChB,KAAgB;QADhB,SAAI,GAAJ,IAAI,CAAY;QAChB,UAAK,GAAL,KAAK,CAAW;QAEjC,IAAI,CAAC,QAAQ,GAAG,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,+DAA+D;IAC/D,KAAK,CAAC,WAAW,CAAC,SAAiB;QACjC,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAA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CAAC,OAAO,CAAC,MAAM,gBAAgB,IAAI,CAAC,cAAc,GAAG;QAC3E,EAAE;QACF,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC;KACtB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAEb,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAC/E,CAAC"}
@@ -0,0 +1,57 @@
1
+ export interface CheckoutAuthor {
2
+ name: string;
3
+ email: string;
4
+ }
5
+ /**
6
+ * A project's checkout: the one place the Engineer works, under the
7
+ * installation's `.aigile/work/<projectId>`. Cloned once, fetched and reset
8
+ * before every build, and the only thing aigile ever writes to the target is
9
+ * a branch of its own, pushed on approval.
10
+ */
11
+ export declare class Checkout {
12
+ readonly dir: string;
13
+ private readonly remote;
14
+ private readonly base;
15
+ constructor(dir: string, remote: string, base: string);
16
+ /** Options on every git aigile runs in a checkout, so nothing an agent planted in the repository's config or attributes runs on the host. */
17
+ static readonly SAFE: string[];
18
+ private knownConfig;
19
+ git(args: string[], author?: CheckoutAuthor): Promise<string>;
20
+ /** Put `.git/config` back as aigile last saw it, so a planted filter, hook path or credential helper never runs. */
21
+ pinConfig(): Promise<void>;
22
+ private runIn;
23
+ private exists;
24
+ /** Clone or fetch, then start `branch` clean from the base's tip. */
25
+ prepare(branch: string): Promise<void>;
26
+ /** The commit a branch points at. */
27
+ tipOf(branch: string): Promise<string>;
28
+ /** Stage everything and commit as the service identity; null when nothing changed. */
29
+ commitAll(message: string, author: CheckoutAuthor): Promise<string | null>;
30
+ /** The branch's changes against the base's tip. */
31
+ diff(branch: string): Promise<{
32
+ stat: string;
33
+ patch: string;
34
+ }>;
35
+ /** The uncommitted changes in the working tree (a failed build leaves them for a person). */
36
+ workingTreeDiff(): Promise<string>;
37
+ /** Push exactly `commit` as the branch, and refuse when the local branch no longer points at it. */
38
+ push(branch: string, commit: string): Promise<void>;
39
+ /** Drop a branch (and a remote copy, if it was pushed). */
40
+ discard(branch: string): Promise<void>;
41
+ /** A detached worktree of a branch for a reader that must change nothing here; a leftover one is replaced. */
42
+ addWorktree(branch: string, dir: string): Promise<void>;
43
+ /** Files changed in a worktree against its HEAD, as checkout-relative paths (untracked included). */
44
+ changedIn(dir: string): Promise<string[]>;
45
+ private statusIn;
46
+ /** Put a worktree's files back as HEAD has them (tracked), and drop the untracked ones; fails loudly, never partly. */
47
+ revertIn(dir: string, files: string[]): Promise<void>;
48
+ /** HEAD of a worktree. */
49
+ headOf(dir: string): Promise<string>;
50
+ /** Commit everything in a worktree; null when nothing changed. */
51
+ commitIn(dir: string, message: string, author: CheckoutAuthor): Promise<string | null>;
52
+ /** Move a branch from `expected` to a commit made elsewhere (a detached worktree) and bring this checkout along; refused when the branch moved meanwhile. */
53
+ adoptCommit(branch: string, sha: string, expected: string): Promise<void>;
54
+ removeWorktree(dir: string): Promise<void>;
55
+ branchExists(branch: string): Promise<boolean>;
56
+ }
57
+ //# sourceMappingURL=checkout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkout.d.ts","sourceRoot":"","sources":["../src/checkout.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;GAKG;AACH,qBAAa,QAAQ;IAEjB,QAAQ,CAAC,GAAG,EAAE,MAAM;IACpB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAFZ,GAAG,EAAE,MAAM,EACH,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM;IAG/B,6IAA6I;IAC7I,MAAM,CAAC,QAAQ,CAAC,IAAI,WAAiK;IAErL,OAAO,CAAC,WAAW,CAAuB;IAEpC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,MAAM,CAAC,EAAE,cA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AAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAQ5F,6JAA6J;IACvJ,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKzE,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ1C,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;CAQrD"}
@@ -0,0 +1,187 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ const exec = promisify(execFile);
6
+ /**
7
+ * A project's checkout: the one place the Engineer works, under the
8
+ * installation's `.aigile/work/<projectId>`. Cloned once, fetched and reset
9
+ * before every build, and the only thing aigile ever writes to the target is
10
+ * a branch of its own, pushed on approval.
11
+ */
12
+ export class Checkout {
13
+ dir;
14
+ remote;
15
+ base;
16
+ constructor(dir, remote, base) {
17
+ this.dir = dir;
18
+ this.remote = remote;
19
+ this.base = base;
20
+ }
21
+ /** Options on every git aigile runs in a checkout, so nothing an agent planted in the repository's config or attributes runs on the host. */
22
+ static SAFE = ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'core.sshCommand=ssh -o BatchMode=yes', '-c', 'gc.auto=0', '-c', 'maintenance.auto=0'];
23
+ knownConfig = null;
24
+ async git(args, author) {
25
+ return this.runIn(this.dir, args, author);
26
+ }
27
+ /** Put `.git/config` back as aigile last saw it, so a planted filter, hook path or credential helper never runs. */
28
+ async pinConfig() {
29
+ const path = join(this.dir, '.git', 'config');
30
+ try {
31
+ const current = await readFile(path, 'utf8');
32
+ if (this.knownConfig === null)
33
+ this.knownConfig = current;
34
+ else if (current !== this.knownConfig)
35
+ await writeFile(path, this.knownConfig, 'utf8');
36
+ }
37
+ catch {
38
+ // No config yet (no clone yet).
39
+ }
40
+ }
41
+ async runIn(dir, args, author) {
42
+ await this.pinConfig();
43
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' };
44
+ delete env.GIT_CONFIG_COUNT;
45
+ if (author) {
46
+ env.GIT_AUTHOR_NAME = author.name;
47
+ env.GIT_AUTHOR_EMAIL = author.email;
48
+ env.GIT_COMMITTER_NAME = author.name;
49
+ env.GIT_COMMITTER_EMAIL = author.email;
50
+ }
51
+ const { stdout } = await exec('git', [...Checkout.SAFE, ...args], { cwd: dir, env, maxBuffer: 64 * 1024 * 1024 });
52
+ return stdout;
53
+ }
54
+ async exists() {
55
+ try {
56
+ return (await stat(`${this.dir}/.git`)).isDirectory();
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ /** Clone or fetch, then start `branch` clean from the base's tip. */
63
+ async prepare(branch) {
64
+ if (!(await this.exists())) {
65
+ await mkdir(dirname(this.dir), { recursive: true });
66
+ await exec('git', [...Checkout.SAFE, 'clone', '--quiet', '--branch', this.base, this.remote, this.dir], { env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' } });
67
+ this.knownConfig = null;
68
+ await this.pinConfig();
69
+ }
70
+ else {
71
+ await this.git(['fetch', '--quiet', '--prune', 'origin']);
72
+ }
73
+ await this.git(['checkout', '--quiet', '--force', '-B', branch, `origin/${this.base}`]);
74
+ await this.git(['clean', '-fdqx']);
75
+ }
76
+ /** The commit a branch points at. */
77
+ async tipOf(branch) {
78
+ return (await this.git(['rev-parse', `refs/heads/${branch}`])).trim();
79
+ }
80
+ /** Stage everything and commit as the service identity; null when nothing changed. */
81
+ async commitAll(message, author) {
82
+ await this.git(['add', '-A']);
83
+ const staged = await this.git(['diff', '--cached', '--name-only']);
84
+ if (!staged.trim())
85
+ return null;
86
+ await this.git(['commit', '--quiet', '-m', message], author);
87
+ return (await this.git(['rev-parse', 'HEAD'])).trim();
88
+ }
89
+ /** The branch's changes against the base's tip. */
90
+ async diff(branch) {
91
+ const range = `origin/${this.base}...${branch}`;
92
+ const [stat, patch] = await Promise.all([this.git(['diff', '--no-ext-diff', '--no-textconv', '--stat', range]), this.git(['diff', '--no-ext-diff', '--no-textconv', range])]);
93
+ return { stat, patch };
94
+ }
95
+ /** The uncommitted changes in the working tree (a failed build leaves them for a person). */
96
+ async workingTreeDiff() {
97
+ await this.git(['add', '-N', '.']);
98
+ return this.git(['diff', '--no-ext-diff', '--no-textconv']);
99
+ }
100
+ /** Push exactly `commit` as the branch, and refuse when the local branch no longer points at it. */
101
+ async push(branch, commit) {
102
+ const tip = await this.tipOf(branch);
103
+ if (tip !== commit)
104
+ throw new Error(`${branch} points at ${tip.slice(0, 8)}, not the reviewed ${commit.slice(0, 8)}; refusing to push`);
105
+ await this.git(['push', '--quiet', '-u', 'origin', `${commit}:refs/heads/${branch}`]);
106
+ }
107
+ /** Drop a branch (and a remote copy, if it was pushed). */
108
+ async discard(branch) {
109
+ await this.git(['checkout', '--quiet', '--force', '--detach', `origin/${this.base}`]);
110
+ try {
111
+ await this.git(['branch', '-D', branch]);
112
+ }
113
+ catch {
114
+ // Never created.
115
+ }
116
+ }
117
+ /** A detached worktree of a branch for a reader that must change nothing here; a leftover one is replaced. */
118
+ async addWorktree(branch, dir) {
119
+ await this.git(['worktree', 'prune']);
120
+ try {
121
+ await this.git(['worktree', 'remove', '--force', dir]);
122
+ }
123
+ catch {
124
+ // None left behind.
125
+ }
126
+ await this.git(['worktree', 'add', '--detach', '--force', dir, branch]);
127
+ }
128
+ /** Files changed in a worktree against its HEAD, as checkout-relative paths (untracked included). */
129
+ async changedIn(dir) {
130
+ return (await this.statusIn(dir)).map((e) => e.path);
131
+ }
132
+ async statusIn(dir) {
133
+ const out = await this.runIn(dir, ['status', '--porcelain', '--untracked-files=all']);
134
+ return out
135
+ .split('\n')
136
+ .filter(Boolean)
137
+ .map((line) => ({ path: line.slice(3).trim().replace(/^"|"$/g, ''), untracked: line.startsWith('??') }));
138
+ }
139
+ /** Put a worktree's files back as HEAD has them (tracked), and drop the untracked ones; fails loudly, never partly. */
140
+ async revertIn(dir, files) {
141
+ if (files.length === 0)
142
+ return;
143
+ const status = new Map((await this.statusIn(dir)).map((e) => [e.path, e.untracked]));
144
+ const tracked = files.filter((f) => status.get(f) === false);
145
+ const untracked = files.filter((f) => status.get(f) === true);
146
+ if (tracked.length)
147
+ await this.runIn(dir, ['checkout', '--', ...tracked]);
148
+ if (untracked.length)
149
+ await this.runIn(dir, ['clean', '-fq', '--', ...untracked]);
150
+ }
151
+ /** HEAD of a worktree. */
152
+ async headOf(dir) {
153
+ return (await this.runIn(dir, ['rev-parse', 'HEAD'])).trim();
154
+ }
155
+ /** Commit everything in a worktree; null when nothing changed. */
156
+ async commitIn(dir, message, author) {
157
+ await this.runIn(dir, ['add', '-A']);
158
+ const staged = await this.runIn(dir, ['diff', '--cached', '--name-only']);
159
+ if (!staged.trim())
160
+ return null;
161
+ await this.runIn(dir, ['commit', '--quiet', '-m', message], author);
162
+ return (await this.runIn(dir, ['rev-parse', 'HEAD'])).trim();
163
+ }
164
+ /** Move a branch from `expected` to a commit made elsewhere (a detached worktree) and bring this checkout along; refused when the branch moved meanwhile. */
165
+ async adoptCommit(branch, sha, expected) {
166
+ await this.git(['update-ref', `refs/heads/${branch}`, sha, expected]);
167
+ await this.git(['checkout', '--quiet', '--force', branch]);
168
+ }
169
+ async removeWorktree(dir) {
170
+ try {
171
+ await this.git(['worktree', 'remove', '--force', dir]);
172
+ }
173
+ catch {
174
+ // Already gone.
175
+ }
176
+ }
177
+ async branchExists(branch) {
178
+ try {
179
+ await this.git(['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]);
180
+ return true;
181
+ }
182
+ catch {
183
+ return false;
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AAM,CAAC,CAAC;QACpE,OAAO,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/D,CAAC;IAED,6JAA6J;IAC7J,KAAK,CAAC,WAAW,CAAC,MAAc,EAAE,GAAW,EAAE,QAAgB;QAC7D,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC,YAAY,EAAE,cAAc,MAAM,EAAE,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC;QACtE,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,GAAW;QAC9B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC;QACzD,CAAC;QAAC,MAAM,CAAC;YACP,gBAAgB;QAClB,CAAC;IACH,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,MAAc;QAC/B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,MAAM,EAAE,CAAC,CAAC,CAAC;YAC7E,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC"}
@@ -0,0 +1,67 @@
1
+ import type { SandboxConfig } from '@aigile/core';
2
+ export interface RunResult {
3
+ output: string;
4
+ exitCode: number | null;
5
+ killed: boolean;
6
+ }
7
+ export interface RunOptions {
8
+ /** The command's working directory: the checkout. */
9
+ cwd: string;
10
+ timeoutMs: number;
11
+ /** How much output to keep. */
12
+ maxOutput: number;
13
+ }
14
+ /** Runs one shell command for the sandbox: on the host, or in a container. */
15
+ export interface CommandRunner {
16
+ readonly kind: 'host' | 'container';
17
+ readonly description: string;
18
+ run(command: string, options: RunOptions): Promise<RunResult>;
19
+ }
20
+ /** What a model command sees of the host's environment: the few variables it needs, never the secrets or the SSH agent. */
21
+ export declare function commandEnv(source?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
22
+ /** Today's way: bash on the machine that runs aigile, in the checkout. */
23
+ export declare class HostRunner implements CommandRunner {
24
+ readonly kind = "host";
25
+ readonly description = "the host";
26
+ run(command: string, options: RunOptions): Promise<RunResult>;
27
+ }
28
+ export interface ContainerOptions {
29
+ engine: 'podman' | 'docker';
30
+ image: string;
31
+ /** The directories mounted at their own absolute paths: the project's checkout and the one worktree in use, nothing else. */
32
+ mounts: string[];
33
+ memory: string;
34
+ cpus: number;
35
+ pids: number;
36
+ extraArgs: string[];
37
+ }
38
+ /**
39
+ * A fresh container per command: no network, bounded memory, cpus and
40
+ * processes, the work directory mounted at its own path so every absolute
41
+ * path (a worktree's `.git` file, the model's own) means the same thing
42
+ * inside, and the checkout as the working directory. Podman keeps the
43
+ * caller's uid with `--userns=keep-id`; docker runs as the caller's uid:gid.
44
+ * A timeout kills the container by name, not only the client.
45
+ */
46
+ export declare class ContainerRunner implements CommandRunner {
47
+ private readonly options;
48
+ readonly kind = "container";
49
+ readonly description: string;
50
+ private counter;
51
+ constructor(options: ContainerOptions);
52
+ /** The `run` command line, as a list; the shell command is its last argument. */
53
+ argsFor(command: string, cwd: string, name: string): string[];
54
+ run(command: string, options: RunOptions): Promise<RunResult>;
55
+ }
56
+ /** The first of podman and docker on PATH, or null. */
57
+ export declare function detectEngine(lookup?: (name: string) => boolean): 'podman' | 'docker' | null;
58
+ /**
59
+ * The runner `agents.sandbox` asks for: a container when an engine is on
60
+ * PATH; the host only when the installation says `host` outright. In `auto`
61
+ * with no engine there is no quiet fallback: the agents' commands cannot
62
+ * run until podman or docker is there, or the installation opts into the
63
+ * host. `mounts` are the directories the command may see (the checkout and
64
+ * its worktree), at their own paths.
65
+ */
66
+ export declare function runnerFor(config: SandboxConfig, mounts: string[], projectId: string, lookup?: (name: string) => boolean): CommandRunner;
67
+ //# sourceMappingURL=command-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-runner.d.ts","sourceRoot":"","sources":["../src/command-runner.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,qDAAqD;IACrD,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,+BAA+B;IAC/B,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,8EAA8E;AAC9E,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;IACpC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CAC/D;AAID,2HAA2H;AAC3H,wBAAgB,UAAU,CAAC,MAAM,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,CAAC,UAAU,CAKrF;AA4BD,0EAA0E;AAC1E,qBAAa,UAAW,YAAW,aAAa;IAC9C,QAAQ,CAAC,IAAI,UAAU;IACvB,QAAQ,CAAC,WAAW,cAAc;IAClC,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;CAI9D;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,6HAA6H;IAC7H,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,EAAE,CAAC;CACrB;AAED;;;;;;;GAOG;AACH,qBAAa,eAAgB,YAAW,aAAa;IAKvC,OAAO,CAAC,QAAQ,CAAC,OAAO;IAJpC,QAAQ,CAAC,IAAI,eAAe;IAC5B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,OAAO,CAAC,OAAO,CAAK;gBAES,OAAO,EAAE,gBAAgB;IAItD,iFAAiF;IACjF,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE;IAiC7D,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;CAO9D;AAED,uDAAuD;AACvD,wBAAgB,YAAY,CAAC,MAAM,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAgB,GAAG,QAAQ,GAAG,QAAQ,GAAG,IAAI,CAInG;AAeD;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,GAAG,aAAa,CAWvI"}
@@ -0,0 +1,149 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { userInfo } from 'node:os';
3
+ import { delimiter, join } from 'node:path';
4
+ import { accessSync, constants } from 'node:fs';
5
+ const BASE_ENV = { GIT_TERMINAL_PROMPT: '0', CI: '1', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' };
6
+ /** What a model command sees of the host's environment: the few variables it needs, never the secrets or the SSH agent. */
7
+ export function commandEnv(source = process.env) {
8
+ const keep = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'TMPDIR', 'TERM', 'NVM_DIR', 'NODE_OPTIONS'];
9
+ const env = {};
10
+ for (const k of keep)
11
+ if (source[k] !== undefined)
12
+ env[k] = source[k];
13
+ return { ...env, ...BASE_ENV };
14
+ }
15
+ function collect(child, options, onTimeout) {
16
+ return new Promise((done) => {
17
+ let out = '';
18
+ let killed = false;
19
+ const take = (chunk) => {
20
+ if (out.length < options.maxOutput)
21
+ out += chunk.toString();
22
+ };
23
+ child.stdout?.on('data', take);
24
+ child.stderr?.on('data', take);
25
+ const timer = setTimeout(() => {
26
+ killed = true;
27
+ onTimeout();
28
+ child.kill('SIGKILL');
29
+ }, options.timeoutMs);
30
+ child.on('close', (code) => {
31
+ clearTimeout(timer);
32
+ const text = out.length >= options.maxOutput ? `${out.slice(0, options.maxOutput)}\n[output truncated]` : out;
33
+ done({ output: killed ? `${text}\n[killed after ${options.timeoutMs} ms]` : text, exitCode: code, killed });
34
+ });
35
+ child.on('error', (err) => {
36
+ clearTimeout(timer);
37
+ done({ output: err.message, exitCode: null, killed: false });
38
+ });
39
+ });
40
+ }
41
+ /** Today's way: bash on the machine that runs aigile, in the checkout. */
42
+ export class HostRunner {
43
+ kind = 'host';
44
+ description = 'the host';
45
+ run(command, options) {
46
+ const child = spawn('bash', ['-c', command], { cwd: options.cwd, env: commandEnv() });
47
+ return collect(child, options, () => { });
48
+ }
49
+ }
50
+ /**
51
+ * A fresh container per command: no network, bounded memory, cpus and
52
+ * processes, the work directory mounted at its own path so every absolute
53
+ * path (a worktree's `.git` file, the model's own) means the same thing
54
+ * inside, and the checkout as the working directory. Podman keeps the
55
+ * caller's uid with `--userns=keep-id`; docker runs as the caller's uid:gid.
56
+ * A timeout kills the container by name, not only the client.
57
+ */
58
+ export class ContainerRunner {
59
+ options;
60
+ kind = 'container';
61
+ description;
62
+ counter = 0;
63
+ constructor(options) {
64
+ this.options = options;
65
+ this.description = `${options.engine} container ${options.image}`;
66
+ }
67
+ /** The `run` command line, as a list; the shell command is its last argument. */
68
+ argsFor(command, cwd, name) {
69
+ const o = this.options;
70
+ const user = o.engine === 'podman' ? ['--userns=keep-id'] : ['--user', `${userInfo().uid}:${userInfo().gid}`];
71
+ return [
72
+ 'run',
73
+ '--rm',
74
+ '--name',
75
+ name,
76
+ '--network',
77
+ 'none',
78
+ '--memory',
79
+ o.memory,
80
+ '--cpus',
81
+ String(o.cpus),
82
+ '--pids-limit',
83
+ String(o.pids),
84
+ ...user,
85
+ ...o.mounts.flatMap((m) => ['-v', `${m}:${m}`]),
86
+ '-w',
87
+ cwd,
88
+ '-e',
89
+ 'HOME=/tmp',
90
+ // The mount's owner may map to another uid inside; git must still read the checkout.
91
+ ...['GIT_CONFIG_COUNT=1', 'GIT_CONFIG_KEY_0=safe.directory', 'GIT_CONFIG_VALUE_0=*'].flatMap((kv) => ['-e', kv]),
92
+ ...Object.entries(BASE_ENV).flatMap(([k, v]) => ['-e', `${k}=${v}`]),
93
+ ...o.extraArgs,
94
+ o.image,
95
+ 'bash',
96
+ '-lc',
97
+ command,
98
+ ];
99
+ }
100
+ run(command, options) {
101
+ const name = `aigile-${process.pid}-${++this.counter}`;
102
+ const child = spawn(this.options.engine, this.argsFor(command, options.cwd, name), { env: commandEnv({ ...process.env }) });
103
+ return collect(child, options, () => {
104
+ spawn(this.options.engine, ['kill', name], { stdio: 'ignore' }).on('error', () => { });
105
+ });
106
+ }
107
+ }
108
+ /** The first of podman and docker on PATH, or null. */
109
+ export function detectEngine(lookup = onPath) {
110
+ if (lookup('podman'))
111
+ return 'podman';
112
+ if (lookup('docker'))
113
+ return 'docker';
114
+ return null;
115
+ }
116
+ function onPath(name) {
117
+ for (const dir of (process.env.PATH ?? '').split(delimiter)) {
118
+ if (!dir)
119
+ continue;
120
+ try {
121
+ accessSync(join(dir, name), constants.X_OK);
122
+ return true;
123
+ }
124
+ catch {
125
+ // Not here.
126
+ }
127
+ }
128
+ return false;
129
+ }
130
+ /**
131
+ * The runner `agents.sandbox` asks for: a container when an engine is on
132
+ * PATH; the host only when the installation says `host` outright. In `auto`
133
+ * with no engine there is no quiet fallback: the agents' commands cannot
134
+ * run until podman or docker is there, or the installation opts into the
135
+ * host. `mounts` are the directories the command may see (the checkout and
136
+ * its worktree), at their own paths.
137
+ */
138
+ export function runnerFor(config, mounts, projectId, lookup) {
139
+ if (config.runtime === 'host')
140
+ return new HostRunner();
141
+ const engine = config.engine === 'auto' ? detectEngine(lookup) : config.engine;
142
+ if (!engine) {
143
+ throw new Error(config.runtime === 'container'
144
+ ? 'agents.sandbox.runtime is "container" but neither podman nor docker is on PATH'
145
+ : 'neither podman nor docker is on PATH; install one, or set agents.sandbox.runtime to "host" to run the agents’ commands unsandboxed');
146
+ }
147
+ return new ContainerRunner({ engine, image: config.imageByProject[projectId] ?? config.image, mounts, memory: config.memory, cpus: config.cpus, pids: config.pids, extraArgs: config.extraArgs });
148
+ }
149
+ //# sourceMappingURL=command-runner.js.map