agentlane 0.0.0 → 0.4.0-rc.2

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 (146) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +27 -0
  3. package/README.md +167 -2
  4. package/dist/agents/claude-plugin.js +79 -0
  5. package/dist/agents/cli.js +258 -0
  6. package/dist/agents/detect.js +88 -0
  7. package/dist/agents/init.js +251 -0
  8. package/dist/agents/launcher.js +32 -0
  9. package/dist/agents/package.js +119 -0
  10. package/dist/agents/skills.js +59 -0
  11. package/dist/agents/toml.js +325 -0
  12. package/dist/agents/wiring-check.js +117 -0
  13. package/dist/agents/wiring.js +374 -0
  14. package/dist/bench/host.js +104 -0
  15. package/dist/bench/live.js +511 -0
  16. package/dist/bench/mcp-client.js +91 -0
  17. package/dist/bench/model.js +15 -0
  18. package/dist/bench/report.js +162 -0
  19. package/dist/bench/run.js +121 -0
  20. package/dist/bench/schedule.js +140 -0
  21. package/dist/bench/stats.js +59 -0
  22. package/dist/bench-cli.js +167 -0
  23. package/dist/browser/aria.js +184 -0
  24. package/dist/browser/control.js +203 -0
  25. package/dist/browser/env.js +118 -0
  26. package/dist/browser/evidence.js +44 -0
  27. package/dist/browser/install.js +361 -0
  28. package/dist/browser/kinds.js +10 -0
  29. package/dist/browser/lane-browser.js +224 -0
  30. package/dist/browser/libraries.js +56 -0
  31. package/dist/browser/paths.js +29 -0
  32. package/dist/browser/release.js +121 -0
  33. package/dist/browser/screen.js +19 -0
  34. package/dist/browser/signin.js +154 -0
  35. package/dist/browser/stop.js +163 -0
  36. package/dist/browser/tools.js +25 -0
  37. package/dist/cache/build.js +154 -0
  38. package/dist/cache/config.js +186 -0
  39. package/dist/cache/index.js +4 -0
  40. package/dist/cache/key.js +196 -0
  41. package/dist/cache/store.js +303 -0
  42. package/dist/cli.js +178 -0
  43. package/dist/clock.js +4 -0
  44. package/dist/devices/adb.js +160 -0
  45. package/dist/devices/android.js +214 -0
  46. package/dist/devices/backend.js +7 -0
  47. package/dist/devices/bundler.js +46 -0
  48. package/dist/devices/common.js +51 -0
  49. package/dist/devices/controls.js +65 -0
  50. package/dist/devices/dial.js +56 -0
  51. package/dist/devices/emulator.js +396 -0
  52. package/dist/devices/hygiene.js +202 -0
  53. package/dist/devices/index.js +5 -0
  54. package/dist/devices/launch.js +76 -0
  55. package/dist/devices/simctl.js +119 -0
  56. package/dist/devices/tools.js +1 -0
  57. package/dist/devices/variant.js +99 -0
  58. package/dist/devices/xcrun.js +265 -0
  59. package/dist/driver/absence.js +54 -0
  60. package/dist/driver/caller.js +51 -0
  61. package/dist/driver/client.js +312 -0
  62. package/dist/driver/diff.js +180 -0
  63. package/dist/driver/elements.js +70 -0
  64. package/dist/driver/engine-main.js +13 -0
  65. package/dist/driver/engine.js +499 -0
  66. package/dist/driver/errors.js +11 -0
  67. package/dist/driver/exec.js +66 -0
  68. package/dist/driver/failure.js +156 -0
  69. package/dist/driver/flow.js +94 -0
  70. package/dist/driver/idle.js +100 -0
  71. package/dist/driver/images.js +68 -0
  72. package/dist/driver/install.js +272 -0
  73. package/dist/driver/lock.js +101 -0
  74. package/dist/driver/look.js +223 -0
  75. package/dist/driver/maestro-child.js +194 -0
  76. package/dist/driver/maestro-runs.js +46 -0
  77. package/dist/driver/paths.js +105 -0
  78. package/dist/driver/pixels.js +144 -0
  79. package/dist/driver/plan.js +108 -0
  80. package/dist/driver/release.js +7 -0
  81. package/dist/driver/runner.js +42 -0
  82. package/dist/driver/selector.js +91 -0
  83. package/dist/driver/session.js +474 -0
  84. package/dist/driver/suggest.js +86 -0
  85. package/dist/driver/supervisor.js +251 -0
  86. package/dist/driver/tree.js +426 -0
  87. package/dist/driver-cli.js +865 -0
  88. package/dist/evidence/device.js +177 -0
  89. package/dist/evidence/evidence.js +304 -0
  90. package/dist/evidence/files.js +92 -0
  91. package/dist/hooks/env.js +81 -0
  92. package/dist/hooks/run.js +101 -0
  93. package/dist/mcp/server.js +69 -0
  94. package/dist/mcp/tools.js +246 -0
  95. package/dist/name.js +22 -0
  96. package/dist/plugin/aims.js +465 -0
  97. package/dist/plugin/conventions.js +73 -0
  98. package/dist/plugin/guard.js +163 -0
  99. package/dist/plugin/hook-cli.js +216 -0
  100. package/dist/plugin/session-name.js +28 -0
  101. package/dist/plugin/shell.js +254 -0
  102. package/dist/processes.js +77 -0
  103. package/dist/project/config.js +316 -0
  104. package/dist/project/schema.js +335 -0
  105. package/dist/project/validate.js +224 -0
  106. package/dist/registry/config.js +142 -0
  107. package/dist/registry/format.js +22 -0
  108. package/dist/registry/owner.js +265 -0
  109. package/dist/registry/paths.js +50 -0
  110. package/dist/registry/ports.js +26 -0
  111. package/dist/registry/prune.js +160 -0
  112. package/dist/registry/refusal.js +53 -0
  113. package/dist/registry/registry.js +1027 -0
  114. package/dist/registry/resources.js +117 -0
  115. package/dist/registry/rows.js +115 -0
  116. package/dist/registry/status.js +85 -0
  117. package/dist/registry/store.js +274 -0
  118. package/dist/registry/types.js +1 -0
  119. package/dist/registry-cli.js +544 -0
  120. package/dist/services/services.js +268 -0
  121. package/dist/services/system.js +189 -0
  122. package/dist/up/deps.js +1 -0
  123. package/dist/up/doctor.js +424 -0
  124. package/dist/up/exec.js +133 -0
  125. package/dist/up/lane-files.js +75 -0
  126. package/dist/up/lane-services.js +38 -0
  127. package/dist/up/maestro-env.js +172 -0
  128. package/dist/up/preflight.js +232 -0
  129. package/dist/up/release.js +148 -0
  130. package/dist/up/resources.js +178 -0
  131. package/dist/up/restart.js +87 -0
  132. package/dist/up/setup.js +28 -0
  133. package/dist/up/up.js +610 -0
  134. package/dist/up-cli.js +258 -0
  135. package/dist/usage.js +16 -0
  136. package/package.json +58 -3
  137. package/schema/agentlane.schema.json +675 -0
  138. package/skills/create-verification-skill/LICENSE +21 -0
  139. package/skills/create-verification-skill/SKILL.md +88 -0
  140. package/skills/dev-loop/LICENSE +21 -0
  141. package/skills/dev-loop/SKILL.md +61 -0
  142. package/skills/device/SKILL.md +8 -0
  143. package/skills/drive/SKILL.md +64 -0
  144. package/skills/maintain-verification-skill/LICENSE +21 -0
  145. package/skills/maintain-verification-skill/SKILL.md +42 -0
  146. package/skills/setup/SKILL.md +80 -0
@@ -0,0 +1,186 @@
1
+ import { envName } from "../name.js";
2
+ export const INPUT_PLATFORMS = ['ios', 'android'];
3
+ export function inputsFor(inputs, platform) {
4
+ return inputs.filter(input => input.platforms === undefined || input.platforms.includes(platform));
5
+ }
6
+ const platformsSchema = {
7
+ type: 'array',
8
+ minItems: 1,
9
+ uniqueItems: true,
10
+ items: { enum: INPUT_PLATFORMS },
11
+ description: 'The platforms whose key includes this input. Leave it out to include it for every platform.',
12
+ };
13
+ export const DEFAULT_MAX_AGE_DAYS = 14;
14
+ export const DEFAULT_MAX_ENTRIES = 6;
15
+ export const buildCacheSchema = {
16
+ $id: 'buildCache',
17
+ type: 'object',
18
+ description: `Lets the toolkit skip the native build when its inputs have not changed. The key also covers the platform, the build variant, the toolchain and the contents of the env file the build uses. The toolchain is the Xcode version for iOS. For Android it is the version of the JDK at ${envName('JAVA_HOME')} or JAVA_HOME (else the JDK 17 the toolkit finds), which the build hook gets as JAVA_HOME, the Gradle distribution in android/gradle/wrapper/gradle-wrapper.properties when that file is not git-ignored (a generated wrapper follows the inputs that generate it, such as the lockfile), and the revision of every installed Android SDK build-tools, platform, NDK and CMake package.`,
19
+ additionalProperties: false,
20
+ required: ['inputs', 'cacheableVariants'],
21
+ properties: {
22
+ inputs: {
23
+ type: 'array',
24
+ minItems: 1,
25
+ items: {
26
+ oneOf: [
27
+ {
28
+ type: 'object',
29
+ additionalProperties: false,
30
+ required: ['kind', 'paths'],
31
+ properties: {
32
+ kind: { const: 'files' },
33
+ paths: {
34
+ type: 'array',
35
+ minItems: 1,
36
+ items: { type: 'string', minLength: 1 },
37
+ description: 'Files, directories or globs (`*`, `**`), relative to the directory holding the config file. Matched as git glob pathspecs over tracked files and untracked files git does not ignore; each enters the key by path, mode and content.',
38
+ },
39
+ exclude: {
40
+ type: 'array',
41
+ items: { type: 'string', minLength: 1 },
42
+ description: 'Files, directories or globs to leave out of `paths`.',
43
+ },
44
+ platforms: platformsSchema,
45
+ },
46
+ },
47
+ {
48
+ type: 'object',
49
+ additionalProperties: false,
50
+ required: ['kind', 'run'],
51
+ properties: {
52
+ kind: { const: 'command' },
53
+ run: {
54
+ type: 'string',
55
+ minLength: 1,
56
+ description: "A shell command run with `sh -c` in the config file's directory, with the lane's environment. Its stdout enters the key; a non-zero exit means no key, so the build runs uncached.",
57
+ },
58
+ platforms: platformsSchema,
59
+ },
60
+ },
61
+ ],
62
+ },
63
+ },
64
+ cacheableVariants: {
65
+ type: 'array',
66
+ items: { type: 'string', minLength: 1 },
67
+ description: 'The build variants whose output may be stored and served. Leave out any variant that embeds its JS bundle, such as a Release build.',
68
+ },
69
+ envFile: {
70
+ type: 'string',
71
+ minLength: 1,
72
+ description: "An env file the build bakes in, relative to the config file's directory. Its contents enter the key; a missing file counts as absent. Use this for files git ignores, which a files input never sees.",
73
+ },
74
+ maxAgeDays: {
75
+ type: 'number',
76
+ exclusiveMinimum: 0,
77
+ default: DEFAULT_MAX_AGE_DAYS,
78
+ description: 'An entry unused for longer than this is pruned.',
79
+ },
80
+ maxEntries: {
81
+ type: 'integer',
82
+ minimum: 1,
83
+ default: DEFAULT_MAX_ENTRIES,
84
+ description: 'Only the most recently used entries up to this count are kept.',
85
+ },
86
+ },
87
+ };
88
+ export const exampleBuildCacheConfig = {
89
+ inputs: [
90
+ {
91
+ kind: 'files',
92
+ paths: [
93
+ 'apps/mobile/ios',
94
+ 'apps/mobile/modules',
95
+ 'apps/mobile/package.json',
96
+ 'apps/mobile/react-native.config.js',
97
+ 'pnpm-lock.yaml',
98
+ ],
99
+ exclude: ['apps/mobile/ios/Podfile.lock'],
100
+ },
101
+ {
102
+ kind: 'command',
103
+ run: "grep -Ev '^ (hermes-engine|React-Core-prebuilt|ReactNativeDependencies): [0-9a-f]+$' apps/mobile/ios/Podfile.lock",
104
+ },
105
+ ],
106
+ cacheableVariants: ['Debug'],
107
+ };
108
+ export class BuildCacheConfigError extends Error {
109
+ name = 'BuildCacheConfigError';
110
+ }
111
+ function isRecord(value) {
112
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
113
+ }
114
+ function stringList(value, where, minItems) {
115
+ if (!Array.isArray(value) || value.length < minItems || !value.every(v => typeof v === 'string' && v.length > 0)) {
116
+ throw new BuildCacheConfigError(`${where} must be a list of non-empty strings${minItems > 0 ? ` with at least ${String(minItems)} item` : ''}`);
117
+ }
118
+ return value;
119
+ }
120
+ function onlyKeys(value, allowed, where) {
121
+ const extra = Object.keys(value).filter(k => !allowed.includes(k));
122
+ if (extra.length > 0)
123
+ throw new BuildCacheConfigError(`${where} has unknown field(s): ${extra.join(', ')}`);
124
+ }
125
+ function parsePlatforms(value, where) {
126
+ const list = stringList(value, where, 1);
127
+ const unknown = list.filter(p => !INPUT_PLATFORMS.includes(p));
128
+ if (unknown.length > 0)
129
+ throw new BuildCacheConfigError(`${where} has unknown platform(s): ${unknown.join(', ')}`);
130
+ if (new Set(list).size !== list.length)
131
+ throw new BuildCacheConfigError(`${where} lists a platform twice`);
132
+ return list;
133
+ }
134
+ function parseInput(value, where) {
135
+ if (!isRecord(value))
136
+ throw new BuildCacheConfigError(`${where} must be an object`);
137
+ let input;
138
+ if (value.kind === 'files') {
139
+ onlyKeys(value, ['kind', 'paths', 'exclude', 'platforms'], where);
140
+ input = { kind: 'files', paths: stringList(value.paths, `${where}.paths`, 1) };
141
+ if (value.exclude !== undefined)
142
+ input.exclude = stringList(value.exclude, `${where}.exclude`, 0);
143
+ }
144
+ else if (value.kind === 'command') {
145
+ onlyKeys(value, ['kind', 'run', 'platforms'], where);
146
+ if (typeof value.run !== 'string' || value.run.length === 0)
147
+ throw new BuildCacheConfigError(`${where}.run must be a non-empty string`);
148
+ input = { kind: 'command', run: value.run };
149
+ }
150
+ else {
151
+ throw new BuildCacheConfigError(`${where}.kind must be 'files' or 'command'`);
152
+ }
153
+ if (value.platforms !== undefined)
154
+ input.platforms = parsePlatforms(value.platforms, `${where}.platforms`);
155
+ return input;
156
+ }
157
+ export function parseBuildCacheConfig(value, where = 'buildCache') {
158
+ if (!isRecord(value))
159
+ throw new BuildCacheConfigError(`${where} must be an object`);
160
+ onlyKeys(value, ['inputs', 'cacheableVariants', 'envFile', 'maxAgeDays', 'maxEntries'], where);
161
+ if (!Array.isArray(value.inputs) || value.inputs.length === 0) {
162
+ throw new BuildCacheConfigError(`${where}.inputs must be a list with at least 1 item`);
163
+ }
164
+ const config = {
165
+ inputs: value.inputs.map((input, i) => parseInput(input, `${where}.inputs[${String(i)}]`)),
166
+ cacheableVariants: stringList(value.cacheableVariants, `${where}.cacheableVariants`, 0),
167
+ };
168
+ if (value.envFile !== undefined) {
169
+ if (typeof value.envFile !== 'string' || value.envFile.length === 0)
170
+ throw new BuildCacheConfigError(`${where}.envFile must be a non-empty string`);
171
+ config.envFile = value.envFile;
172
+ }
173
+ if (value.maxAgeDays !== undefined) {
174
+ if (typeof value.maxAgeDays !== 'number' || !(value.maxAgeDays > 0)) {
175
+ throw new BuildCacheConfigError(`${where}.maxAgeDays must be a number above 0`);
176
+ }
177
+ config.maxAgeDays = value.maxAgeDays;
178
+ }
179
+ if (value.maxEntries !== undefined) {
180
+ if (typeof value.maxEntries !== 'number' || !Number.isInteger(value.maxEntries) || value.maxEntries < 1) {
181
+ throw new BuildCacheConfigError(`${where}.maxEntries must be an integer of at least 1`);
182
+ }
183
+ config.maxEntries = value.maxEntries;
184
+ }
185
+ return config;
186
+ }
@@ -0,0 +1,4 @@
1
+ export { buildCacheSchema, BuildCacheConfigError, DEFAULT_MAX_AGE_DAYS, DEFAULT_MAX_ENTRIES, exampleBuildCacheConfig, INPUT_PLATFORMS, inputsFor, parseBuildCacheConfig, } from "./config.js";
2
+ export { ANDROID_SDK_PACKAGE_DIRS, androidToolchain, CacheKeyError, computeKey, GRADLE_WRAPPER_PROPERTIES, xcodeVersion, } from "./key.js";
3
+ export { BuildCache, CACHE_DIR_PARTS, cacheDirFor, CacheEvictError, isCacheKey, } from "./store.js";
4
+ export { cachedBuild, } from "./build.js";
@@ -0,0 +1,196 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { createReadStream } from 'node:fs';
4
+ import fs from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { inputsFor } from "./config.js";
8
+ const execFileAsync = promisify(execFile);
9
+ const KEY_SCHEMA = 'build-cache-key v1';
10
+ const HASH_CONCURRENCY = 32;
11
+ const COMMAND_TIMEOUT_MS = 120_000;
12
+ const COMMAND_MAX_BUFFER = 256 * 1024 * 1024;
13
+ export class CacheKeyError extends Error {
14
+ name = 'CacheKeyError';
15
+ }
16
+ function sha256(data) {
17
+ return createHash('sha256').update(data).digest('hex');
18
+ }
19
+ async function sha256File(file) {
20
+ const hash = createHash('sha256');
21
+ for await (const chunk of createReadStream(file))
22
+ hash.update(chunk);
23
+ return hash.digest('hex');
24
+ }
25
+ function errorText(error) {
26
+ if (!(error instanceof Error))
27
+ return String(error);
28
+ const { code, signal, stderr } = error;
29
+ const status = typeof code === 'number' ? `exit code ${String(code)}` : typeof signal === 'string' ? `killed by ${signal}` : error.message;
30
+ const detail = (typeof stderr === 'string' ? stderr : Buffer.isBuffer(stderr) ? stderr.toString('utf8') : '').trim();
31
+ return detail ? `${status}: ${detail.slice(-2000)}` : status;
32
+ }
33
+ async function listFiles(root, input) {
34
+ const pathspecs = [...input.paths.map(p => `:(glob)${p}`), ...(input.exclude ?? []).map(p => `:(exclude,glob)${p}`)];
35
+ let stdout;
36
+ try {
37
+ ({ stdout } = await execFileAsync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', ...pathspecs], { maxBuffer: COMMAND_MAX_BUFFER }));
38
+ }
39
+ catch (error) {
40
+ throw new CacheKeyError(`listing the files input ${JSON.stringify(input.paths)} failed: ${errorText(error)}`);
41
+ }
42
+ const names = [...new Set(stdout.split('\0').filter(name => name.length > 0))];
43
+ return names.sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
44
+ }
45
+ async function describeFile(root, name) {
46
+ const full = path.join(root, name);
47
+ let stat;
48
+ try {
49
+ stat = await fs.lstat(full);
50
+ }
51
+ catch (error) {
52
+ if (error.code === 'ENOENT')
53
+ return `deleted ${name}`;
54
+ throw error;
55
+ }
56
+ if (stat.isSymbolicLink())
57
+ return `link ${sha256(await fs.readlink(full))} ${name}`;
58
+ if (stat.isDirectory())
59
+ return `dir ${name}`;
60
+ const exec = (stat.mode & 0o111) !== 0 ? 'x' : '-';
61
+ return `file${exec} ${await sha256File(full)} ${name}`;
62
+ }
63
+ async function hashFiles(root, input) {
64
+ const names = await listFiles(root, input);
65
+ const lines = [];
66
+ for (let i = 0; i < names.length; i += HASH_CONCURRENCY) {
67
+ lines.push(...(await Promise.all(names.slice(i, i + HASH_CONCURRENCY).map(name => describeFile(root, name)))));
68
+ }
69
+ return sha256(lines.join('\n'));
70
+ }
71
+ async function hashCommand(root, run, env) {
72
+ try {
73
+ const { stdout } = await execFileAsync('/bin/sh', ['-c', run], {
74
+ cwd: root,
75
+ ...(env ? { env } : {}),
76
+ encoding: 'buffer',
77
+ maxBuffer: COMMAND_MAX_BUFFER,
78
+ timeout: COMMAND_TIMEOUT_MS,
79
+ });
80
+ return sha256(stdout);
81
+ }
82
+ catch (error) {
83
+ throw new CacheKeyError(`the command input ${JSON.stringify(run)} failed: ${errorText(error)}`);
84
+ }
85
+ }
86
+ async function hashEnvFile(root, envFile) {
87
+ if (envFile === undefined)
88
+ return 'none';
89
+ try {
90
+ return await sha256File(path.resolve(root, envFile));
91
+ }
92
+ catch (error) {
93
+ if (error.code === 'ENOENT')
94
+ return 'absent';
95
+ throw new CacheKeyError(`reading the env file ${envFile} failed: ${errorText(error)}`);
96
+ }
97
+ }
98
+ async function hashInput(root, input, env) {
99
+ return input.kind === 'files' ? hashFiles(root, input) : hashCommand(root, input.run, env);
100
+ }
101
+ export async function computeKey(options) {
102
+ const lines = [
103
+ KEY_SCHEMA,
104
+ `platform=${JSON.stringify(options.platform)}`,
105
+ `variant=${JSON.stringify(options.variant)}`,
106
+ `toolchain=${JSON.stringify(options.toolchain)}`,
107
+ `env=${await hashEnvFile(options.root, options.envFile)}`,
108
+ ];
109
+ const inputs = inputsFor(options.inputs, options.platform);
110
+ const digests = await Promise.all(inputs.map(input => hashInput(options.root, input, options.env)));
111
+ inputs.forEach((input, i) => {
112
+ lines.push(`input=${JSON.stringify(input)} ${digests[i] ?? ''}`);
113
+ });
114
+ return sha256(lines.join('\n'));
115
+ }
116
+ export const ANDROID_SDK_PACKAGE_DIRS = ['build-tools', 'platforms', 'ndk', 'cmake'];
117
+ export const GRADLE_WRAPPER_PROPERTIES = 'android/gradle/wrapper/gradle-wrapper.properties';
118
+ async function javaVersionText(javaHome) {
119
+ const java = path.join(javaHome, 'bin', 'java');
120
+ try {
121
+ const { stdout, stderr } = await execFileAsync(java, ['-version'], { timeout: COMMAND_TIMEOUT_MS });
122
+ return `${stderr}${stdout}`
123
+ .trim()
124
+ .split(/\s*\n\s*/)
125
+ .join(' ');
126
+ }
127
+ catch (error) {
128
+ throw new CacheKeyError(`${java} -version failed: ${errorText(error)}`);
129
+ }
130
+ }
131
+ async function subdirectories(dir) {
132
+ try {
133
+ const entries = await fs.readdir(dir, { withFileTypes: true });
134
+ return entries
135
+ .filter(entry => entry.isDirectory())
136
+ .map(entry => entry.name)
137
+ .sort();
138
+ }
139
+ catch (error) {
140
+ if (error.code === 'ENOENT')
141
+ return [];
142
+ throw error;
143
+ }
144
+ }
145
+ async function packageRevision(dir) {
146
+ try {
147
+ const properties = await fs.readFile(path.join(dir, 'source.properties'), 'utf8');
148
+ return /^Pkg\.Revision\s*=(.*)$/m.exec(properties)?.[1]?.trim() ?? 'unknown';
149
+ }
150
+ catch (error) {
151
+ if (error.code === 'ENOENT')
152
+ return 'unknown';
153
+ throw error;
154
+ }
155
+ }
156
+ async function sdkPackages(sdkRoot) {
157
+ const lines = [];
158
+ for (const kind of ANDROID_SDK_PACKAGE_DIRS) {
159
+ for (const name of await subdirectories(path.join(sdkRoot, kind))) {
160
+ lines.push(`${kind}/${name} ${await packageRevision(path.join(sdkRoot, kind, name))}`);
161
+ }
162
+ }
163
+ return lines;
164
+ }
165
+ async function gradleWrapper(root) {
166
+ const listed = await listFiles(root, { kind: 'files', paths: [GRADLE_WRAPPER_PROPERTIES] });
167
+ if (listed.length === 0)
168
+ return 'generated by the build';
169
+ const properties = await fs.readFile(path.join(root, GRADLE_WRAPPER_PROPERTIES), 'utf8');
170
+ return /^distributionUrl=(.*)$/m.exec(properties)?.[1]?.trim() ?? 'no distributionUrl';
171
+ }
172
+ /**
173
+ * The Android toolchain part of a build cache key: the JDK's version, the Gradle distribution the project's wrapper
174
+ * pins when the wrapper is a project file (a git-ignored one, generated by the build, follows the project's inputs),
175
+ * and the revision of every installed SDK build-tools, platform, NDK and CMake package.
176
+ */
177
+ export async function androidToolchain(options) {
178
+ const [java, gradle, packages] = await Promise.all([
179
+ javaVersionText(options.javaHome),
180
+ gradleWrapper(options.root),
181
+ sdkPackages(options.sdkRoot),
182
+ ]);
183
+ return [`jdk ${java}`, `gradle ${gradle}`, `sdk ${packages.join(', ')}`].join('; ');
184
+ }
185
+ export async function xcodeVersion() {
186
+ try {
187
+ const { stdout } = await execFileAsync('xcodebuild', ['-version'], { timeout: COMMAND_TIMEOUT_MS });
188
+ return stdout
189
+ .trim()
190
+ .split(/\s*\n\s*/)
191
+ .join(' ');
192
+ }
193
+ catch (error) {
194
+ throw new CacheKeyError(`xcodebuild -version failed: ${errorText(error)}`);
195
+ }
196
+ }
@@ -0,0 +1,303 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { constants as fsConstants } from 'node:fs';
4
+ import fs from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { DEFAULT_MAX_AGE_DAYS, DEFAULT_MAX_ENTRIES } from "./config.js";
8
+ const execFileAsync = promisify(execFile);
9
+ export const CACHE_DIR_PARTS = ['agentlane', 'build-cache'];
10
+ const OBJECTS = '.objects';
11
+ const STAGING = '.staging';
12
+ const META = 'meta.json';
13
+ const OUT = 'out';
14
+ const KEY_PATTERN = /^[0-9a-f]{64}$/;
15
+ const DAY_MS = 24 * 60 * 60 * 1000;
16
+ export const UNREFERENCED_GRACE_MS = 60 * 60 * 1000;
17
+ export const STAGING_GRACE_MS = DAY_MS;
18
+ export function isCacheKey(value) {
19
+ return KEY_PATTERN.test(value);
20
+ }
21
+ export async function cacheDirFor(worktree) {
22
+ const { stdout } = await execFileAsync('git', ['-C', worktree, 'rev-parse', '--path-format=absolute', '--git-common-dir']);
23
+ return path.join(stdout.trim(), ...CACHE_DIR_PARTS);
24
+ }
25
+ export class CacheEvictError extends Error {
26
+ name = 'CacheEvictError';
27
+ }
28
+ function isMissing(error) {
29
+ const code = error.code;
30
+ return code === 'ENOENT' || code === 'ENOTDIR';
31
+ }
32
+ function newId() {
33
+ return `${Date.now().toString(36)}-${randomBytes(8).toString('hex')}`;
34
+ }
35
+ function objectIdOf(entry) {
36
+ return path.basename(path.dirname(path.dirname(entry.output)));
37
+ }
38
+ function parseMeta(text) {
39
+ let value;
40
+ try {
41
+ value = JSON.parse(text);
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ if (typeof value !== 'object' || value === null)
47
+ return undefined;
48
+ const meta = value;
49
+ const fields = [meta.key, meta.variant, meta.worktree, meta.storedAt, meta.output];
50
+ if (meta.schema !== 1 || !fields.every(f => typeof f === 'string'))
51
+ return undefined;
52
+ return meta;
53
+ }
54
+ export class BuildCache {
55
+ dir;
56
+ cacheableVariants;
57
+ maxAgeMs;
58
+ maxEntries;
59
+ #now;
60
+ constructor(options) {
61
+ this.dir = options.dir;
62
+ this.cacheableVariants = [...options.config.cacheableVariants];
63
+ this.maxAgeMs = (options.config.maxAgeDays ?? DEFAULT_MAX_AGE_DAYS) * DAY_MS;
64
+ this.maxEntries = options.config.maxEntries ?? DEFAULT_MAX_ENTRIES;
65
+ this.#now = options.now ?? (() => new Date());
66
+ }
67
+ isCacheable(variant) {
68
+ return this.cacheableVariants.includes(variant);
69
+ }
70
+ async lookup(key, variant) {
71
+ if (!this.isCacheable(variant))
72
+ return { hit: false, reason: 'not-cacheable' };
73
+ if (!isCacheKey(key))
74
+ return { hit: false, reason: 'absent' };
75
+ const objectDir = await this.#objectOf(key);
76
+ if (objectDir === undefined)
77
+ return { hit: false, reason: 'absent' };
78
+ const entry = await this.#readEntry(key, objectDir);
79
+ if (entry?.variant !== variant)
80
+ return { hit: false, reason: 'broken' };
81
+ const now = this.#now();
82
+ await fs.utimes(objectDir, now, now).catch(() => undefined);
83
+ return { hit: true, entry: { ...entry, lastUsed: now } };
84
+ }
85
+ async store(request) {
86
+ if (!isCacheKey(request.key))
87
+ throw new Error(`'${request.key}' is not a cache key`);
88
+ if (!this.isCacheable(request.variant))
89
+ return { stored: false, reason: 'not-cacheable' };
90
+ const link = path.join(this.dir, request.key);
91
+ if (!request.replace && (await this.#objectOf(request.key)) !== undefined)
92
+ return { stored: false, reason: 'exists' };
93
+ const id = newId();
94
+ const staging = path.join(this.dir, STAGING, id);
95
+ const objectDir = path.join(this.dir, OBJECTS, id);
96
+ const source = await fs.realpath(request.output);
97
+ const name = path.basename(source);
98
+ const storedAt = this.#now();
99
+ await fs.mkdir(path.join(staging, OUT), { recursive: true });
100
+ await fs.mkdir(path.join(this.dir, OBJECTS), { recursive: true });
101
+ try {
102
+ await fs.cp(source, path.join(staging, OUT, name), {
103
+ recursive: true,
104
+ verbatimSymlinks: true,
105
+ errorOnExist: true,
106
+ force: false,
107
+ mode: fsConstants.COPYFILE_FICLONE,
108
+ });
109
+ const meta = {
110
+ schema: 1,
111
+ key: request.key,
112
+ variant: request.variant,
113
+ worktree: request.worktree,
114
+ storedAt: storedAt.toISOString(),
115
+ output: name,
116
+ };
117
+ await fs.writeFile(path.join(staging, META), `${JSON.stringify(meta, null, 2)}\n`);
118
+ await fs.rename(staging, objectDir);
119
+ }
120
+ catch (error) {
121
+ await fs.rm(staging, { recursive: true, force: true });
122
+ throw error;
123
+ }
124
+ await fs.utimes(objectDir, storedAt, storedAt);
125
+ const target = path.join(OBJECTS, id);
126
+ try {
127
+ if (request.replace) {
128
+ const tmpLink = path.join(this.dir, STAGING, `link-${id}`);
129
+ await fs.symlink(target, tmpLink);
130
+ await fs.rename(tmpLink, link);
131
+ }
132
+ else {
133
+ await fs.symlink(target, link);
134
+ }
135
+ }
136
+ catch (error) {
137
+ await fs.rm(objectDir, { recursive: true, force: true });
138
+ if (!request.replace && error.code === 'EEXIST')
139
+ return { stored: false, reason: 'exists' };
140
+ throw error;
141
+ }
142
+ return {
143
+ stored: true,
144
+ entry: {
145
+ key: request.key,
146
+ variant: request.variant,
147
+ output: path.join(objectDir, OUT, name),
148
+ origin: { worktree: request.worktree, storedAt },
149
+ lastUsed: storedAt,
150
+ },
151
+ };
152
+ }
153
+ async list() {
154
+ const entries = [];
155
+ for (const key of await this.#keys()) {
156
+ const objectDir = await this.#objectOf(key);
157
+ if (objectDir === undefined)
158
+ continue;
159
+ const entry = await this.#readEntry(key, objectDir);
160
+ if (entry !== undefined)
161
+ entries.push(entry);
162
+ }
163
+ return entries.sort((a, b) => b.lastUsed.getTime() - a.lastUsed.getTime());
164
+ }
165
+ async prune() {
166
+ const now = this.#now().getTime();
167
+ const removed = [];
168
+ const live = new Set();
169
+ const entries = await this.list();
170
+ for (const [index, entry] of entries.entries()) {
171
+ if (index >= this.maxEntries || now - entry.lastUsed.getTime() > this.maxAgeMs) {
172
+ await fs.rm(path.join(this.dir, entry.key), { force: true });
173
+ removed.push(entry.key);
174
+ }
175
+ else {
176
+ live.add(objectIdOf(entry));
177
+ }
178
+ }
179
+ const seen = new Set(entries.map(entry => entry.key));
180
+ for (const key of await this.#keys()) {
181
+ if (seen.has(key))
182
+ continue;
183
+ const objectDir = await this.#objectOf(key);
184
+ const entry = objectDir === undefined ? undefined : await this.#readEntry(key, objectDir);
185
+ if (entry !== undefined) {
186
+ live.add(objectIdOf(entry));
187
+ continue;
188
+ }
189
+ const stat = await fs.lstat(path.join(this.dir, key)).catch(() => undefined);
190
+ if (stat?.isSymbolicLink()) {
191
+ await fs.rm(path.join(this.dir, key), { force: true });
192
+ removed.push(key);
193
+ }
194
+ }
195
+ const objectsRemoved = await this.#sweep(OBJECTS, UNREFERENCED_GRACE_MS, now, live);
196
+ await this.#sweep(STAGING, STAGING_GRACE_MS, now, new Set());
197
+ return { removed, objectsRemoved };
198
+ }
199
+ async evict(target) {
200
+ if (target === 'all')
201
+ return this.#evictAll();
202
+ if (!isCacheKey(target)) {
203
+ throw new CacheEvictError(`'${target}' is not a cache key: pass a key exactly as the cache lists it, or 'all'`);
204
+ }
205
+ const link = path.join(this.dir, target);
206
+ const stat = await fs.lstat(link).catch((error) => {
207
+ if (isMissing(error))
208
+ return undefined;
209
+ throw error;
210
+ });
211
+ if (!stat?.isSymbolicLink())
212
+ throw new CacheEvictError(`there is no cache entry ${target} in ${this.dir}`);
213
+ const objectDir = await this.#objectOf(target);
214
+ await fs.rm(link, { force: true });
215
+ if (objectDir !== undefined)
216
+ await fs.rm(objectDir, { recursive: true, force: true });
217
+ return [target];
218
+ }
219
+ async #evictAll() {
220
+ let names;
221
+ try {
222
+ names = await fs.readdir(this.dir);
223
+ }
224
+ catch (error) {
225
+ if (isMissing(error))
226
+ return [];
227
+ throw error;
228
+ }
229
+ for (const name of names)
230
+ await fs.rm(path.join(this.dir, name), { recursive: true, force: true });
231
+ return names.filter(isCacheKey);
232
+ }
233
+ async #keys() {
234
+ try {
235
+ return (await fs.readdir(this.dir)).filter(isCacheKey);
236
+ }
237
+ catch (error) {
238
+ if (isMissing(error))
239
+ return [];
240
+ throw error;
241
+ }
242
+ }
243
+ async #objectOf(key) {
244
+ let target;
245
+ try {
246
+ target = await fs.readlink(path.join(this.dir, key));
247
+ }
248
+ catch {
249
+ return undefined;
250
+ }
251
+ const objects = path.join(this.dir, OBJECTS);
252
+ const objectDir = path.resolve(this.dir, target);
253
+ if (path.dirname(objectDir) !== objects)
254
+ return undefined;
255
+ return objectDir;
256
+ }
257
+ async #readEntry(key, objectDir) {
258
+ let meta;
259
+ let lastUsed;
260
+ try {
261
+ meta = parseMeta(await fs.readFile(path.join(objectDir, META), 'utf8'));
262
+ lastUsed = (await fs.stat(objectDir)).mtime;
263
+ }
264
+ catch {
265
+ return undefined;
266
+ }
267
+ if (meta?.key !== key)
268
+ return undefined;
269
+ const output = path.join(objectDir, OUT, meta.output);
270
+ if (!(await fs.lstat(output).then(() => true, () => false)))
271
+ return undefined;
272
+ return {
273
+ key,
274
+ variant: meta.variant,
275
+ output,
276
+ origin: { worktree: meta.worktree, storedAt: new Date(meta.storedAt) },
277
+ lastUsed,
278
+ };
279
+ }
280
+ async #sweep(sub, graceMs, now, keep) {
281
+ const dir = path.join(this.dir, sub);
282
+ let names;
283
+ try {
284
+ names = await fs.readdir(dir);
285
+ }
286
+ catch (error) {
287
+ if (isMissing(error))
288
+ return 0;
289
+ throw error;
290
+ }
291
+ let removed = 0;
292
+ for (const name of names) {
293
+ if (keep.has(name))
294
+ continue;
295
+ const stat = await fs.lstat(path.join(dir, name)).catch(() => undefined);
296
+ if (stat === undefined || now - stat.mtime.getTime() <= graceMs)
297
+ continue;
298
+ await fs.rm(path.join(dir, name), { recursive: true, force: true });
299
+ removed += 1;
300
+ }
301
+ return removed;
302
+ }
303
+ }