@fitlab-ai/agent-infra 0.7.3 → 0.7.4

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 (41) hide show
  1. package/README.md +32 -790
  2. package/README.zh-CN.md +32 -763
  3. package/bin/cli.ts +1 -1
  4. package/dist/bin/cli.js +1 -1
  5. package/dist/lib/sandbox/commands/create.js +44 -3
  6. package/dist/lib/sandbox/commands/rm.js +99 -19
  7. package/dist/lib/sandbox/index.js +3 -1
  8. package/dist/lib/sandbox/readme-scaffold.js +6 -6
  9. package/dist/lib/task/artifacts.js +58 -0
  10. package/dist/lib/task/commands/cat.js +38 -0
  11. package/dist/lib/task/commands/files.js +47 -0
  12. package/dist/lib/task/commands/grep.js +143 -0
  13. package/dist/lib/task/commands/log.js +75 -0
  14. package/dist/lib/task/commands/show.js +5 -114
  15. package/dist/lib/task/commands/status.js +239 -0
  16. package/dist/lib/task/index.js +37 -0
  17. package/dist/lib/task/resolve-ref.js +150 -0
  18. package/lib/sandbox/commands/create.ts +47 -4
  19. package/lib/sandbox/commands/rm.ts +128 -19
  20. package/lib/sandbox/index.ts +3 -1
  21. package/lib/sandbox/readme-scaffold.ts +6 -6
  22. package/lib/task/artifacts.ts +72 -0
  23. package/lib/task/commands/cat.ts +39 -0
  24. package/lib/task/commands/files.ts +53 -0
  25. package/lib/task/commands/grep.ts +147 -0
  26. package/lib/task/commands/log.ts +80 -0
  27. package/lib/task/commands/show.ts +5 -117
  28. package/lib/task/commands/status.ts +302 -0
  29. package/lib/task/index.ts +37 -0
  30. package/lib/task/resolve-ref.ts +160 -0
  31. package/package.json +1 -1
  32. package/templates/.agents/README.en.md +1 -0
  33. package/templates/.agents/README.zh-CN.md +1 -0
  34. package/templates/.agents/rules/README.en.md +41 -0
  35. package/templates/.agents/rules/README.zh-CN.md +40 -0
  36. package/templates/.agents/rules/debugging-guide.en.md +25 -0
  37. package/templates/.agents/rules/debugging-guide.zh-CN.md +25 -0
  38. package/templates/.agents/skills/code-task/SKILL.en.md +2 -0
  39. package/templates/.agents/skills/code-task/SKILL.zh-CN.md +2 -0
  40. package/templates/.agents/skills/watch-pr/SKILL.en.md +1 -1
  41. package/templates/.agents/skills/watch-pr/SKILL.zh-CN.md +1 -1
@@ -840,7 +840,34 @@ export function ensureClaudeSettings(toolDir: string, hostHomeDir?: string): voi
840
840
  }
841
841
  }
842
842
 
843
- export function ensureCodexModelInheritance(toolDir: string, hostHomeDir?: string): void {
843
+ function resolveHostCatalogPath(value: unknown, hostHomeDir: string): string | null {
844
+ if (typeof value !== 'string' || value === '') {
845
+ return null;
846
+ }
847
+ let resolved: string;
848
+ if (value === '~' || value.startsWith('~/') || value.startsWith('~\\')) {
849
+ resolved = path.join(hostHomeDir, value.slice(1).replace(/^[/\\]+/, ''));
850
+ } else if (path.isAbsolute(value)) {
851
+ resolved = value;
852
+ } else {
853
+ resolved = path.join(hostHomeDir, '.codex', value);
854
+ }
855
+ try {
856
+ if (!fs.statSync(resolved).isFile()) {
857
+ return null;
858
+ }
859
+ fs.accessSync(resolved, fs.constants.R_OK);
860
+ return resolved;
861
+ } catch {
862
+ return null;
863
+ }
864
+ }
865
+
866
+ export function ensureCodexModelInheritance(
867
+ toolDir: string,
868
+ hostHomeDir?: string,
869
+ containerCodexDir: string = '/home/devuser/.codex'
870
+ ): void {
844
871
  if (!hostHomeDir) {
845
872
  return;
846
873
  }
@@ -890,6 +917,22 @@ export function ensureCodexModelInheritance(toolDir: string, hostHomeDir?: strin
890
917
  changed = true;
891
918
  }
892
919
 
920
+ if (!Object.hasOwn(sandboxParsed, 'model_catalog_json')) {
921
+ const hostCatalogPath = resolveHostCatalogPath(hostParsed['model_catalog_json'], hostHomeDir);
922
+ if (hostCatalogPath) {
923
+ try {
924
+ const basename = path.basename(hostCatalogPath);
925
+ const destDir = path.join(toolDir, 'model-catalogs');
926
+ fs.mkdirSync(destDir, { recursive: true });
927
+ fs.copyFileSync(hostCatalogPath, path.join(destDir, basename));
928
+ sandboxParsed['model_catalog_json'] = path.posix.join(containerCodexDir, 'model-catalogs', basename);
929
+ changed = true;
930
+ } catch {
931
+ // Copy failed (e.g. permissions): skip catalog, keep scalar inheritance intact.
932
+ }
933
+ }
934
+ }
935
+
893
936
  if (changed) {
894
937
  fs.writeFileSync(sandboxConfigPath, `${toml.stringify(sandboxParsed)}\n`, 'utf8');
895
938
  }
@@ -1042,7 +1085,7 @@ function runEngineTaskCommand(engine: string, cmd: string, args: string[], opts:
1042
1085
  }
1043
1086
 
1044
1087
  export function buildImage(
1045
- config: SandboxCreateConfig,
1088
+ config: Pick<SandboxCreateConfig, 'project' | 'imageName' | 'repoRoot'> & { engine?: string | null },
1046
1089
  tools: SandboxTool[],
1047
1090
  dockerfilePath: string,
1048
1091
  imageSignature: string,
@@ -1060,7 +1103,7 @@ export function buildImage(
1060
1103
  env?: NodeJS.ProcessEnv;
1061
1104
  } = {}
1062
1105
  ): void {
1063
- const selectedEngine = engine ?? detectEngine(config);
1106
+ const selectedEngine = engine ?? detectEngine({ engine: config.engine });
1064
1107
  const { uid: hostUid, gid: hostGid } = resolveBuildUid({
1065
1108
  engine: selectedEngine,
1066
1109
  runFn,
@@ -1342,7 +1385,7 @@ export async function create(args: string[]): Promise<void> {
1342
1385
  }
1343
1386
  const codexEntry = effectiveResolvedTools.find(({ tool }) => tool.id === 'codex');
1344
1387
  if (codexEntry) {
1345
- ensureCodexModelInheritance(codexEntry.dir, effectiveConfig.home);
1388
+ ensureCodexModelInheritance(codexEntry.dir, effectiveConfig.home, codexEntry.tool.containerMount);
1346
1389
  ensureCodexWorkspaceTrust(codexEntry.dir);
1347
1390
  }
1348
1391
  const geminiEntry = effectiveResolvedTools.find(({ tool }) => tool.id === 'gemini-cli');
@@ -21,15 +21,27 @@ import { runOk, runSafe, runSafeEngine } from '../shell.ts';
21
21
  import { resolveTaskBranch } from '../task-resolver.ts';
22
22
  import { resolveTools, toolConfigDirCandidates, toolProjectDirCandidates } from '../tools.ts';
23
23
  import type { SandboxTool } from '../tools.ts';
24
+ import { fetchSandboxRows } from './list-running.ts';
25
+ import { lookupShortIdByBranch } from '../../task/short-id.ts';
24
26
 
25
- const USAGE = `Usage: ai sandbox rm <branch> [--all]`;
27
+ const USAGE = `Usage:
28
+ ai sandbox rm <branch> Remove one sandbox (branch | TASK-id | short id)
29
+ ai sandbox rm --all [--dry-run] [--yes] Remove every sandbox not bound to an active task
30
+ ai sandbox rm --purge Tear down ALL sandboxes for the project (containers, worktrees, image, VM)`;
26
31
  export { assertManagedPath } from '../managed-fs.ts';
27
32
 
28
33
  function projectToolDirs(config: SandboxConfig, tools: SandboxTool[]): string[] {
29
34
  return tools.flatMap((tool) => toolProjectDirCandidates(tool, config.project));
30
35
  }
31
36
 
32
- async function rmOne(config: SandboxConfig, tools: SandboxTool[], branch: string): Promise<void> {
37
+ type RmOneOptions = { assumeYes?: boolean; quiet?: boolean };
38
+
39
+ async function rmOne(
40
+ config: SandboxConfig,
41
+ tools: SandboxTool[],
42
+ branch: string,
43
+ options: RmOneOptions = {}
44
+ ): Promise<void> {
33
45
  assertValidBranchName(branch);
34
46
  const engine = detectEngine(config);
35
47
  let effectiveBranch = branch;
@@ -39,7 +51,9 @@ async function rmOne(config: SandboxConfig, tools: SandboxTool[], branch: string
39
51
  candidates: toolConfigDirCandidates(tool, config.project, branch)
40
52
  }));
41
53
 
42
- p.intro(pc.cyan(`Removing sandbox for ${branch}`));
54
+ if (!options.quiet) {
55
+ p.intro(pc.cyan(`Removing sandbox for ${branch}`));
56
+ }
43
57
 
44
58
  const existing = runSafeEngine(engine, 'docker', ['ps', '-a', '--format', '{{.Names}}']).split('\n').filter(Boolean);
45
59
  const matchedContainers = containerNameCandidates(config, branch)
@@ -74,10 +88,12 @@ async function rmOne(config: SandboxConfig, tools: SandboxTool[], branch: string
74
88
 
75
89
  const existingWorktrees = worktreeCandidates.filter((candidate) => fs.existsSync(candidate));
76
90
  if (existingWorktrees.length > 0) {
77
- const shouldRemoveWorktree = await p.confirm({
78
- message: `Remove worktree(s): ${existingWorktrees.join(', ')}?`,
79
- initialValue: true
80
- });
91
+ const shouldRemoveWorktree = options.assumeYes
92
+ ? true
93
+ : await p.confirm({
94
+ message: `Remove worktree(s): ${existingWorktrees.join(', ')}?`,
95
+ initialValue: true
96
+ });
81
97
 
82
98
  if (p.isCancel(shouldRemoveWorktree)) {
83
99
  p.outro('Cancelled');
@@ -89,10 +105,12 @@ async function rmOne(config: SandboxConfig, tools: SandboxTool[], branch: string
89
105
  removeWorktreeDir(config.repoRoot, config.worktreeBase, worktree);
90
106
  }
91
107
 
92
- const shouldDeleteBranch = await p.confirm({
93
- message: `Also delete local branch '${effectiveBranch}'?`,
94
- initialValue: true
95
- });
108
+ const shouldDeleteBranch = options.assumeYes
109
+ ? true
110
+ : await p.confirm({
111
+ message: `Also delete local branch '${effectiveBranch}'?`,
112
+ initialValue: true
113
+ });
96
114
 
97
115
  if (!p.isCancel(shouldDeleteBranch) && shouldDeleteBranch) {
98
116
  if (!runOk('git', ['-C', config.repoRoot, 'branch', '-D', effectiveBranch])) {
@@ -116,20 +134,24 @@ async function rmOne(config: SandboxConfig, tools: SandboxTool[], branch: string
116
134
 
117
135
  const shareBranch = shareBranchDir(config, effectiveBranch);
118
136
  if (fs.existsSync(shareBranch)) {
119
- const shouldRemoveShare = await p.confirm({
120
- message: `Remove share dir for branch '${effectiveBranch}' (${shareBranch})?`,
121
- initialValue: true
122
- });
137
+ const shouldRemoveShare = options.assumeYes
138
+ ? true
139
+ : await p.confirm({
140
+ message: `Remove share dir for branch '${effectiveBranch}' (${shareBranch})?`,
141
+ initialValue: true
142
+ });
123
143
  if (!p.isCancel(shouldRemoveShare) && shouldRemoveShare) {
124
144
  removeManagedDir(config.shareBase, shareBranch);
125
145
  p.log.success(`Share dir removed: ${shareBranch}`);
126
146
  }
127
147
  }
128
148
 
129
- p.outro(pc.green('Sandbox removed'));
149
+ if (!options.quiet) {
150
+ p.outro(pc.green('Sandbox removed'));
151
+ }
130
152
  }
131
153
 
132
- async function rmAll(config: SandboxConfig, tools: SandboxTool[]): Promise<void> {
154
+ async function rmPurge(config: SandboxConfig, tools: SandboxTool[]): Promise<void> {
133
155
  const engine = detectEngine(config);
134
156
  p.intro(pc.cyan(`Removing all sandboxes for ${config.project}`));
135
157
 
@@ -231,6 +253,70 @@ async function rmAll(config: SandboxConfig, tools: SandboxTool[]): Promise<void>
231
253
  p.outro(pc.green('All project sandboxes removed'));
232
254
  }
233
255
 
256
+ async function rmUnbound(
257
+ config: SandboxConfig,
258
+ tools: SandboxTool[],
259
+ options: { dryRun: boolean; assumeYes: boolean }
260
+ ): Promise<void> {
261
+ const engine = detectEngine(config);
262
+ const { running, nonRunning } = fetchSandboxRows(engine, sandboxLabel(config), sandboxBranchLabel(config));
263
+ const removable = [...running, ...nonRunning].filter(
264
+ (row) => row.branch && lookupShortIdByBranch(row.branch, config.repoRoot) === null
265
+ );
266
+
267
+ p.intro(pc.cyan(`Removing sandboxes not bound to an active task for ${config.project}`));
268
+
269
+ if (removable.length === 0) {
270
+ p.outro('No removable sandboxes: every container is bound to an active task (or none exist)');
271
+ return;
272
+ }
273
+
274
+ for (const row of removable) {
275
+ p.log.message(`${row.name} ${row.branch}`);
276
+ }
277
+
278
+ if (options.dryRun) {
279
+ p.outro(`Dry run: ${removable.length} sandbox(es) would be removed, nothing deleted`);
280
+ return;
281
+ }
282
+
283
+ if (!options.assumeYes) {
284
+ if (!process.stdin.isTTY) {
285
+ throw new Error(
286
+ 'Refusing to remove sandboxes without confirmation in a non-interactive shell; pass --yes to proceed.'
287
+ );
288
+ }
289
+ const confirmed = await p.confirm({
290
+ message: `Remove these ${removable.length} sandbox(es)?`,
291
+ initialValue: false
292
+ });
293
+ if (p.isCancel(confirmed) || !confirmed) {
294
+ p.outro('Cancelled');
295
+ return;
296
+ }
297
+ }
298
+
299
+ const failures: { branch: string; message: string }[] = [];
300
+ for (const row of removable) {
301
+ try {
302
+ await rmOne(config, tools, row.branch, { assumeYes: true, quiet: true });
303
+ } catch (error) {
304
+ failures.push({ branch: row.branch, message: error instanceof Error ? error.message : String(error) });
305
+ }
306
+ }
307
+
308
+ if (failures.length > 0) {
309
+ for (const failure of failures) {
310
+ p.log.error(`Failed to remove '${failure.branch}': ${failure.message}`);
311
+ }
312
+ throw new Error(
313
+ `Removed ${removable.length - failures.length}/${removable.length} sandbox(es); ${failures.length} failed`
314
+ );
315
+ }
316
+
317
+ p.outro(pc.green(`Removed ${removable.length} sandbox(es)`));
318
+ }
319
+
234
320
  export async function rm(args: string[]): Promise<void> {
235
321
  const { values, positionals } = parseArgs({
236
322
  args,
@@ -238,6 +324,9 @@ export async function rm(args: string[]): Promise<void> {
238
324
  strict: true,
239
325
  options: {
240
326
  all: { type: 'boolean' },
327
+ purge: { type: 'boolean' },
328
+ 'dry-run': { type: 'boolean' },
329
+ yes: { type: 'boolean', short: 'y' },
241
330
  help: { type: 'boolean', short: 'h' }
242
331
  }
243
332
  });
@@ -247,15 +336,35 @@ export async function rm(args: string[]): Promise<void> {
247
336
  return;
248
337
  }
249
338
 
250
- if (!values.all && positionals.length !== 1) {
339
+ if (values.all && values.purge) {
340
+ throw new Error('--all and --purge are mutually exclusive');
341
+ }
342
+
343
+ if ((values['dry-run'] || values.yes) && !values.all) {
344
+ throw new Error('--dry-run and --yes only apply to --all');
345
+ }
346
+
347
+ if ((values.all || values.purge) && positionals.length > 0) {
348
+ throw new Error(`${values.all ? '--all' : '--purge'} does not take a branch argument`);
349
+ }
350
+
351
+ if (!values.all && !values.purge && positionals.length !== 1) {
251
352
  throw new Error(USAGE);
252
353
  }
253
354
 
254
355
  const config = loadConfig();
255
356
  const tools = resolveTools(config);
256
357
 
358
+ if (values.purge) {
359
+ await rmPurge(config, tools);
360
+ return;
361
+ }
362
+
257
363
  if (values.all) {
258
- await rmAll(config, tools);
364
+ await rmUnbound(config, tools, {
365
+ dryRun: Boolean(values['dry-run']),
366
+ assumeYes: Boolean(values.yes)
367
+ });
259
368
  return;
260
369
  }
261
370
 
@@ -16,7 +16,9 @@ Commands:
16
16
  rebuild [--quiet] [--refresh]
17
17
  Rebuild the sandbox image (--refresh pulls base + tools)
18
18
  refresh Sync host Claude Code credentials to all sandbox copies
19
- rm <branch> [--all] Remove a sandbox or all sandboxes
19
+ rm <branch> | --all | --purge
20
+ Remove one sandbox, all sandboxes not bound to an
21
+ active task (--all), or tear down everything (--purge)
20
22
  vm status|start|stop Manage the sandbox VM (macOS) or check the backend (Windows)
21
23
 
22
24
  Run 'ai sandbox <command> --help' for details.`;
@@ -18,7 +18,7 @@ symlink under \`$HOME\` (e.g. \`.tmux.conf\` -> \`/home/devuser/.tmux.conf\`),
18
18
  overriding image defaults so your editor, shell, and tool preferences follow
19
19
  you across \`ai sandbox destroy + create\`.
20
20
 
21
- See: https://github.com/fitlab-ai/agent-infra/blob/main/README.md#user-level-dotfiles-channel
21
+ See: https://github.com/fitlab-ai/agent-infra/blob/main/docs/en/sandbox.md#user-level-dotfiles-channel
22
22
 
23
23
  Common usage - drop files or symlinks here:
24
24
 
@@ -46,7 +46,7 @@ only writes \`README.md\` when it is missing, never when it already exists.
46
46
  (例如 \`.tmux.conf -> /home/devuser/.tmux.conf\`),覆盖镜像默认值,让你的编辑器、
47
47
  shell、工具偏好跨 \`ai sandbox destroy + create\` 持久存在。
48
48
 
49
- 参考:https://github.com/fitlab-ai/agent-infra/blob/main/README.zh-CN.md#用户级-dotfiles-通道
49
+ 参考:https://github.com/fitlab-ai/agent-infra/blob/main/docs/zh-CN/sandbox.md#用户级-dotfiles-通道
50
50
 
51
51
  常见用法:把文件或符号链接放进来:
52
52
 
@@ -72,7 +72,7 @@ This directory is mounted **read-write** into every sandbox container of this
72
72
  project at \`/share/common\`, regardless of branch. Drop files here to share
73
73
  between host and any sandbox without polluting the git worktree.
74
74
 
75
- See: https://github.com/fitlab-ai/agent-infra/blob/main/README.md#host-sandbox-file-exchange
75
+ See: https://github.com/fitlab-ai/agent-infra/blob/main/docs/en/sandbox.md#host-sandbox-file-exchange
76
76
 
77
77
  This file is safe to delete; the next \`ai sandbox create\` will re-create it.
78
78
 
@@ -83,7 +83,7 @@ This file is safe to delete; the next \`ai sandbox create\` will re-create it.
83
83
  该目录被以**读写**方式挂载到本项目所有 sandbox 容器的 \`/share/common\`,
84
84
  跨分支可见。可用来在宿主和任意 sandbox 之间传文件,无需弄脏 git worktree。
85
85
 
86
- 参考:https://github.com/fitlab-ai/agent-infra/blob/main/README.zh-CN.md#宿主-沙箱文件交换
86
+ 参考:https://github.com/fitlab-ai/agent-infra/blob/main/docs/zh-CN/sandbox.md#宿主-沙箱文件交换
87
87
 
88
88
  该文件可以安全删除;下一次 \`ai sandbox create\` 会重新生成。
89
89
  `;
@@ -94,7 +94,7 @@ This directory is mounted **read-write** into the sandbox container of this
94
94
  project's current branch at \`/share/branch\`. Files here are exclusive to this
95
95
  branch's sandbox and do not leak across branches.
96
96
 
97
- See: https://github.com/fitlab-ai/agent-infra/blob/main/README.md#host-sandbox-file-exchange
97
+ See: https://github.com/fitlab-ai/agent-infra/blob/main/docs/en/sandbox.md#host-sandbox-file-exchange
98
98
 
99
99
  This file is safe to delete; the next \`ai sandbox create\` will re-create it.
100
100
 
@@ -105,7 +105,7 @@ This file is safe to delete; the next \`ai sandbox create\` will re-create it.
105
105
  该目录被以**读写**方式挂载到本项目当前分支 sandbox 容器的 \`/share/branch\`,
106
106
  仅当前分支可见,不会跨分支泄漏。
107
107
 
108
- 参考:https://github.com/fitlab-ai/agent-infra/blob/main/README.zh-CN.md#宿主-沙箱文件交换
108
+ 参考:https://github.com/fitlab-ai/agent-infra/blob/main/docs/zh-CN/sandbox.md#宿主-沙箱文件交换
109
109
 
110
110
  该文件可以安全删除;下一次 \`ai sandbox create\` 会重新生成。
111
111
  `;
@@ -0,0 +1,72 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ type Artifact = {
5
+ index: number;
6
+ name: string;
7
+ path: string;
8
+ size: number;
9
+ mtimeMs: number;
10
+ };
11
+
12
+ /**
13
+ * Enumerate a task directory's artifacts ordered by modification time, oldest
14
+ * first, so the listing reads like the task's timeline. Filename ascending is a
15
+ * deterministic tiebreak when two files share the same mtime (e.g. written in
16
+ * the same millisecond).
17
+ *
18
+ * Only top-level regular files are included; subdirectories and dotfiles are
19
+ * skipped so every entry is something `cat` can print. The returned 1-based
20
+ * `index` is the source of truth shared by `files` and `cat`.
21
+ */
22
+ function enumerateArtifacts(taskDir: string): Artifact[] {
23
+ const entries = fs
24
+ .readdirSync(taskDir, { withFileTypes: true })
25
+ .filter((dirent) => dirent.isFile() && !dirent.name.startsWith('.'))
26
+ .map((dirent) => {
27
+ const abs = path.join(taskDir, dirent.name);
28
+ const stat = fs.statSync(abs);
29
+ return { name: dirent.name, path: abs, size: stat.size, mtimeMs: stat.mtimeMs };
30
+ });
31
+
32
+ entries.sort((a, b) => {
33
+ if (a.mtimeMs !== b.mtimeMs) return a.mtimeMs - b.mtimeMs;
34
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
35
+ });
36
+
37
+ return entries.map((entry, i) => ({ index: i + 1, ...entry }));
38
+ }
39
+
40
+ /**
41
+ * Resolve an artifact selector to an absolute path within `taskDir`. The
42
+ * selector is either a 1-based index `N` (as listed by `files`) or a filename
43
+ * (with or without the `.md` suffix). Throws with a clear message on failure.
44
+ */
45
+ function resolveArtifact(taskDir: string, artifactOrN: string): string {
46
+ if (path.basename(artifactOrN) !== artifactOrN) {
47
+ throw new Error('artifact name must not contain path separators');
48
+ }
49
+
50
+ if (/^\d+$/.test(artifactOrN)) {
51
+ const n = Number(artifactOrN);
52
+ const match = enumerateArtifacts(taskDir).find((a) => a.index === n);
53
+ if (!match) {
54
+ throw new Error(`invalid artifact index ${n} (run 'ai task files <ref>' to list)`);
55
+ }
56
+ return match.path;
57
+ }
58
+
59
+ const candidates = artifactOrN.endsWith('.md')
60
+ ? [artifactOrN]
61
+ : [artifactOrN, `${artifactOrN}.md`];
62
+ for (const candidate of candidates) {
63
+ const abs = path.join(taskDir, candidate);
64
+ if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
65
+ return abs;
66
+ }
67
+ }
68
+ throw new Error(`artifact '${artifactOrN}' not found in task directory`);
69
+ }
70
+
71
+ export { enumerateArtifacts, resolveArtifact };
72
+ export type { Artifact };
@@ -0,0 +1,39 @@
1
+ import fs from 'node:fs';
2
+ import { resolveTaskRef } from '../resolve-ref.ts';
3
+ import { resolveArtifact } from '../artifacts.ts';
4
+
5
+ const USAGE = `Usage: ai task cat <N | #N | TASK-id> <artifact | N>
6
+
7
+ Prints a task artifact's raw content to stdout.
8
+ <ref> Bare numeric / '#N' short id, or a full TASK-YYYYMMDD-HHMMSS id.
9
+ <artifact | N> Artifact filename (with or without '.md'), or the number from 'ai task files'.
10
+ `;
11
+
12
+ function cat(args: string[] = []): void {
13
+ if (args[0] === '--help' || args[0] === '-h') {
14
+ process.stdout.write(USAGE);
15
+ return;
16
+ }
17
+ if (args.length < 2) {
18
+ process.stdout.write(USAGE);
19
+ process.exitCode = 1;
20
+ return;
21
+ }
22
+ const resolved = resolveTaskRef(args[0]!);
23
+ if (!resolved.ok) {
24
+ process.stderr.write(`ai task cat: ${resolved.message}\n`);
25
+ process.exitCode = 1;
26
+ return;
27
+ }
28
+ let artifactPath: string;
29
+ try {
30
+ artifactPath = resolveArtifact(resolved.taskDir, args[1]!);
31
+ } catch (e) {
32
+ process.stderr.write(`ai task cat: ${(e as Error).message}\n`);
33
+ process.exitCode = 1;
34
+ return;
35
+ }
36
+ process.stdout.write(fs.readFileSync(artifactPath, 'utf8'));
37
+ }
38
+
39
+ export { cat };
@@ -0,0 +1,53 @@
1
+ import { formatTable } from '../../table.ts';
2
+ import { resolveTaskRef } from '../resolve-ref.ts';
3
+ import { enumerateArtifacts } from '../artifacts.ts';
4
+
5
+ const USAGE = `Usage: ai task files <N | #N | TASK-id>
6
+
7
+ Lists the artifacts in a task directory with stable numbers.
8
+ <ref> Bare numeric / '#N' short id, or a full TASK-YYYYMMDD-HHMMSS id.
9
+
10
+ Columns: # (artifact number, usable with 'ai task cat') / NAME / SIZE (bytes) / MTIME
11
+ `;
12
+
13
+ const TABLE_HEADERS = ['#', 'NAME', 'SIZE', 'MTIME'] as const;
14
+
15
+ function pad2(n: number): string {
16
+ return String(n).padStart(2, '0');
17
+ }
18
+
19
+ function formatMtime(mtimeMs: number): string {
20
+ const d = new Date(mtimeMs);
21
+ return (
22
+ `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ` +
23
+ `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
24
+ );
25
+ }
26
+
27
+ function files(args: string[] = []): void {
28
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
29
+ process.stdout.write(USAGE);
30
+ if (args.length === 0) process.exitCode = 1;
31
+ return;
32
+ }
33
+ const resolved = resolveTaskRef(args[0]!);
34
+ if (!resolved.ok) {
35
+ process.stderr.write(`ai task files: ${resolved.message}\n`);
36
+ process.exitCode = 1;
37
+ return;
38
+ }
39
+ const artifacts = enumerateArtifacts(resolved.taskDir);
40
+ // Show the name without the `.md` suffix so the NAME column is exactly what
41
+ // `ai task cat <ref> <name>` accepts (the resolver re-adds `.md`).
42
+ const rows = artifacts.map((a) => [
43
+ String(a.index),
44
+ a.name.replace(/\.md$/, ''),
45
+ String(a.size),
46
+ formatMtime(a.mtimeMs)
47
+ ]);
48
+ for (const line of formatTable(TABLE_HEADERS, rows, { zebra: Boolean(process.stdout.isTTY) })) {
49
+ process.stdout.write(`${line}\n`);
50
+ }
51
+ }
52
+
53
+ export { files };
@@ -0,0 +1,147 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { resolveTaskRef, detectRepoRoot, enumerateTaskDirs } from '../resolve-ref.ts';
4
+ import { enumerateArtifacts, resolveArtifact } from '../artifacts.ts';
5
+ import { loadShortIdByTaskId } from '../short-id.ts';
6
+
7
+ const USAGE = `Usage: ai task grep <pattern> [ref] [artifact | N]
8
+
9
+ Literal (non-regex) line search across task artifacts.
10
+ <pattern> Literal substring to match (NOT a regex). Case-sensitive by default.
11
+ [ref] Bare numeric / '#N' short id, or a full TASK-YYYYMMDD-HHMMSS id.
12
+ Omit to scan every task under active / blocked / completed
13
+ (archive is skipped). With a ref, narrows to that single task
14
+ (a TASK-id ref can also resolve an archived task).
15
+ [artifact | N] Only valid with <ref>. Artifact filename (with or without '.md')
16
+ or the number from 'ai task files'. Narrows to a single artifact.
17
+
18
+ Options:
19
+ -i, --ignore-case Case-insensitive matching.
20
+ -- Treat the rest as positional (use for patterns starting with '-').
21
+
22
+ Output: '{taskId} [#short] {fileStem}:{line}: {matched-line}' (short id only for active tasks).
23
+ Exits 1 with no output when nothing matches.
24
+ `;
25
+
26
+ function makeMatcher(pattern: string, ignoreCase: boolean): (line: string) => boolean {
27
+ if (ignoreCase) {
28
+ const needle = pattern.toLowerCase();
29
+ return (line) => line.toLowerCase().includes(needle);
30
+ }
31
+ return (line) => line.includes(pattern);
32
+ }
33
+
34
+ // Split content into lines with grep-like semantics: a trailing newline does
35
+ // not yield a phantom final empty line, but genuine interior blank lines stay.
36
+ function splitLines(content: string): string[] {
37
+ const lines = content.split(/\r?\n/);
38
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
39
+ return lines;
40
+ }
41
+
42
+ function scanArtifact(
43
+ taskId: string,
44
+ shortToken: string | undefined,
45
+ artifactPath: string,
46
+ matcher: (line: string) => boolean,
47
+ emit: (line: string) => void
48
+ ): number {
49
+ const content = fs.readFileSync(artifactPath, 'utf8');
50
+ const stem = path.basename(artifactPath).replace(/\.md$/, '');
51
+ const prefix = shortToken ? `${taskId} ${shortToken}` : taskId;
52
+ let count = 0;
53
+ splitLines(content).forEach((line, i) => {
54
+ if (matcher(line)) {
55
+ emit(`${prefix} ${stem}:${i + 1}: ${line}\n`);
56
+ count++;
57
+ }
58
+ });
59
+ return count;
60
+ }
61
+
62
+ function grep(args: string[] = []): void {
63
+ const positional: string[] = [];
64
+ let ignoreCase = false;
65
+ let optsEnded = false;
66
+ for (const a of args) {
67
+ if (!optsEnded && a === '--') { optsEnded = true; continue; }
68
+ if (!optsEnded && (a === '-h' || a === '--help')) {
69
+ process.stdout.write(USAGE);
70
+ return;
71
+ }
72
+ if (!optsEnded && (a === '-i' || a === '--ignore-case')) { ignoreCase = true; continue; }
73
+ if (!optsEnded && a.startsWith('-') && a !== '-') {
74
+ process.stderr.write(`ai task grep: unknown flag: ${a}\n`);
75
+ process.exitCode = 1;
76
+ return;
77
+ }
78
+ positional.push(a);
79
+ }
80
+
81
+ if (positional.length === 0) {
82
+ process.stdout.write(USAGE);
83
+ process.exitCode = 1;
84
+ return;
85
+ }
86
+ if (positional.length > 3) {
87
+ process.stderr.write('ai task grep: too many arguments\n');
88
+ process.exitCode = 1;
89
+ return;
90
+ }
91
+
92
+ const [pattern, ref, artifactOrN] = positional;
93
+ const matcher = makeMatcher(pattern!, ignoreCase);
94
+ const chunks: string[] = [];
95
+ const emit = (line: string) => chunks.push(line);
96
+ let total = 0;
97
+
98
+ if (ref === undefined) {
99
+ // No ref: full scan across active / blocked / completed (no archive).
100
+ let repoRoot: string;
101
+ try {
102
+ repoRoot = detectRepoRoot();
103
+ } catch (e) {
104
+ process.stderr.write(`ai task grep: ${(e as Error).message}\n`);
105
+ process.exitCode = 1;
106
+ return;
107
+ }
108
+ const shortMap = loadShortIdByTaskId(repoRoot);
109
+ for (const { taskId, taskDir } of enumerateTaskDirs(repoRoot)) {
110
+ const shortToken = shortMap.get(taskId);
111
+ for (const a of enumerateArtifacts(taskDir)) {
112
+ total += scanArtifact(taskId, shortToken, a.path, matcher, emit);
113
+ }
114
+ }
115
+ } else {
116
+ const resolved = resolveTaskRef(ref);
117
+ if (!resolved.ok) {
118
+ process.stderr.write(`ai task grep: ${resolved.message}\n`);
119
+ process.exitCode = 1;
120
+ return;
121
+ }
122
+ const shortToken = loadShortIdByTaskId(resolved.repoRoot).get(resolved.taskId);
123
+ if (artifactOrN !== undefined) {
124
+ let artifactPath: string;
125
+ try {
126
+ artifactPath = resolveArtifact(resolved.taskDir, artifactOrN);
127
+ } catch (e) {
128
+ process.stderr.write(`ai task grep: ${(e as Error).message}\n`);
129
+ process.exitCode = 1;
130
+ return;
131
+ }
132
+ total += scanArtifact(resolved.taskId, shortToken, artifactPath, matcher, emit);
133
+ } else {
134
+ for (const a of enumerateArtifacts(resolved.taskDir)) {
135
+ total += scanArtifact(resolved.taskId, shortToken, a.path, matcher, emit);
136
+ }
137
+ }
138
+ }
139
+
140
+ if (total === 0) {
141
+ process.exitCode = 1;
142
+ return;
143
+ }
144
+ process.stdout.write(chunks.join(''));
145
+ }
146
+
147
+ export { grep };