@armadra/agent 0.20.0 → 0.22.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.
- package/CHANGELOG.md +21 -0
- package/CHANGELOG.zh-CN.md +21 -0
- package/dist/agent/session-subagent.js +1 -1
- package/dist/agent/session-tools.js +3 -1
- package/dist/agent/subagent-land.d.ts +4 -0
- package/dist/agent/subagent-land.js +23 -0
- package/dist/agent/subagent-registry.d.ts +1 -0
- package/dist/agent/subagent-registry.js +8 -7
- package/dist/agent/worktree-land.d.ts +22 -0
- package/dist/agent/worktree-land.js +91 -0
- package/dist/agent/worktree-setup.d.ts +12 -0
- package/dist/agent/worktree-setup.js +84 -0
- package/dist/agent/worktree.d.ts +22 -2
- package/dist/agent/worktree.js +104 -10
- package/dist/agents/catalog.d.ts +1 -0
- package/dist/agents/result.js +2 -0
- package/dist/agents/task-control.d.ts +3 -0
- package/dist/bundle/ama.cjs +1693 -1335
- package/dist/cli/compose-agents.js +4 -1
- package/dist/codemode/tool.js +6 -5
- package/dist/config/json-schema.js +1 -0
- package/dist/config/schema-w5.js +2 -0
- package/dist/config/types-w5.d.ts +5 -0
- package/dist/drivers/jsonrpc.d.ts +2 -2
- package/dist/i18n/catalog.d.ts +73 -70
- package/dist/i18n/messages/config-keys.d.ts +4 -0
- package/dist/i18n/messages/config-keys.js +4 -0
- package/dist/i18n/messages/config.d.ts +4 -0
- package/dist/i18n/messages/errors.d.ts +3 -3
- package/dist/i18n/messages/print.d.ts +2 -0
- package/dist/i18n/messages/print.js +4 -0
- package/dist/i18n/messages/report.d.ts +2 -2
- package/dist/i18n/messages/subcommands.d.ts +85 -85
- package/dist/modes/print/print-mode.js +3 -0
- package/dist/permissions/pipeline.d.ts +2 -0
- package/dist/permissions/pipeline.js +2 -0
- package/dist/tools/registry.d.ts +1 -1
- package/dist/tools/registry.js +4 -2
- package/dist/tools/task-land.d.ts +17 -0
- package/dist/tools/task-land.js +64 -0
- package/docs/guides/agents.md +17 -6
- package/package.json +11 -10
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,27 @@ English · [简体中文](CHANGELOG.zh-CN.md)
|
|
|
5
5
|
> This file is in English starting with 0.6.0. Release notes for 0.1 through 0.5.1 are in Chinese in
|
|
6
6
|
> [CHANGELOG.zh-CN.md](CHANGELOG.zh-CN.md). New entries go into both files.
|
|
7
7
|
|
|
8
|
+
## 0.22.0 (2026-11-24)
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`task_land`**: lands a worktree task's commits on the current branch through the permission pipeline. On conflict, or when parent uncommitted work would be overwritten, the parent is restored and the worktree is kept.
|
|
13
|
+
- **`subagents.worktreeSetup`**: a user-level command run once in each new task worktree, for example to link dependencies.
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- **Worktree tasks now see uncommitted work**: they start from a snapshot of staged, unstaged and untracked changes. The parent index and working tree are not touched, and inherited changes are not reported or landed.
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- **`-p` denial hint**: when the auto-mode classifier is unavailable, the summary states that cause instead of suggesting the mode already in use.
|
|
22
|
+
|
|
23
|
+
## 0.21.0 (2026-11-19)
|
|
24
|
+
|
|
25
|
+
### Maintenance
|
|
26
|
+
|
|
27
|
+
- **Patch release aligned with the unified version**: no changes in the agent.
|
|
28
|
+
|
|
8
29
|
## 0.20.0 (2026-11-17)
|
|
9
30
|
|
|
10
31
|
### Maintenance
|
package/CHANGELOG.zh-CN.md
CHANGED
|
@@ -4,6 +4,27 @@
|
|
|
4
4
|
|
|
5
5
|
> 从 0.6.0 起 [CHANGELOG.md](CHANGELOG.md) 为英文,本文件保留中文记录(0.1–0.5.1 的完整历史在此)。新条目两份都要加。
|
|
6
6
|
|
|
7
|
+
## 0.22.0(2026-11-24)
|
|
8
|
+
|
|
9
|
+
### 新增
|
|
10
|
+
|
|
11
|
+
- **`task_land`**:经权限管线把 worktree 任务的提交落到当前分支。遇到冲突或会覆盖父的未提交改动时,父仓库恢复原样,worktree 保留。
|
|
12
|
+
- **`subagents.worktreeSetup`**:只认用户级的命令,在每个新建的任务 worktree 里运行一次,例如链接依赖。
|
|
13
|
+
|
|
14
|
+
### 变更
|
|
15
|
+
|
|
16
|
+
- **worktree 任务能看到未提交改动**:任务从已暂存、未暂存、未跟踪改动的快照开始,父的索引与工作区不变,继承的改动不算产出,也不会被落地。
|
|
17
|
+
|
|
18
|
+
### 修复
|
|
19
|
+
|
|
20
|
+
- **`-p` 被拒提示**:auto 模式的分类器不可用时,摘要说明这个原因,不再建议切换到当前已在使用的模式。
|
|
21
|
+
|
|
22
|
+
## 0.21.0(2026-11-19)
|
|
23
|
+
|
|
24
|
+
### 维护
|
|
25
|
+
|
|
26
|
+
- **与统一版本对齐的发版**:代理本身没有改动。
|
|
27
|
+
|
|
7
28
|
## 0.20.0(2026-11-17)
|
|
8
29
|
|
|
9
30
|
### 维护
|
|
@@ -36,7 +36,7 @@ import { DEFAULT_SUBAGENT_CONCURRENCY, SubagentPool, TASK_CUSTOM_TYPE, subagentR
|
|
|
36
36
|
export { DEFAULT_SUBAGENT_CONCURRENCY, SubagentPool, TASK_CUSTOM_TYPE };
|
|
37
37
|
export const DEFAULT_SUBAGENT_MAX_TURNS = 30;
|
|
38
38
|
/** 子会话里保留在工具表、运行时拒绝的名字(深度 ≤ 1)。 */
|
|
39
|
-
export const PARENT_ONLY_TOOLS = ["task", "task_ctl"];
|
|
39
|
+
export const PARENT_ONLY_TOOLS = ["task", "task_ctl", "task_land"];
|
|
40
40
|
/** [#269] 子会话总是可用的工具(类型白名单 / 黑名单不能去掉;父会话里它运行时被拒)。 */
|
|
41
41
|
export const CHILD_ONLY_TOOLS = [REPORT_TOOL];
|
|
42
42
|
export const FINAL_REPORT_PROMPT = "You have reached the turn limit for this task. Do not call any tools. Reply now with your " +
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
import { randomUUID } from "node:crypto";
|
|
14
14
|
import { DEFAULT_APPROVAL_TIMEOUT_MS } from "../permissions/broker.js";
|
|
15
15
|
import { previewAction } from "../permissions/preview.js";
|
|
16
|
-
import { PermissionPipeline } from "../permissions/pipeline.js";
|
|
16
|
+
import { CLASSIFIER_UNAVAILABLE_MESSAGE, PermissionPipeline } from "../permissions/pipeline.js";
|
|
17
17
|
import { classifierRequest } from "./session-classifier.js";
|
|
18
18
|
import { runSingleToolCall } from "./tool-runner.js";
|
|
19
19
|
import { toolUnavailableText } from "./tool-availability.js";
|
|
@@ -203,6 +203,8 @@ export async function gateToolCall(core, call, ctx) {
|
|
|
203
203
|
autoDecision.cached = true;
|
|
204
204
|
if (judged.decision === "allow")
|
|
205
205
|
decision = "allow";
|
|
206
|
+
else if (judged.failed === true && decision === "deny")
|
|
207
|
+
denyMessage = CLASSIFIER_UNAVAILABLE_MESSAGE; // [#313] 说明真实原因
|
|
206
208
|
}
|
|
207
209
|
if (autoDecision !== undefined)
|
|
208
210
|
permission.recordAutoDecision?.(call.name, input, autoDecision);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** [#313] 注册表的 `land()`:任务状态检查与落地后的记录更新(落地本身在 worktree-land.ts)。 */
|
|
2
|
+
import type { TaskRecord } from "../agents/task-record.js";
|
|
3
|
+
import { type LandResult } from "./worktree-land.js";
|
|
4
|
+
export declare function landTask(record: TaskRecord | undefined, persist: (record: TaskRecord) => void): Promise<LandResult>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** [#313] 注册表的 `land()`:任务状态检查与落地后的记录更新(落地本身在 worktree-land.ts)。 */
|
|
2
|
+
import { landWorktree } from "./worktree-land.js";
|
|
3
|
+
export async function landTask(record, persist) {
|
|
4
|
+
if (record === undefined)
|
|
5
|
+
return { status: "blocked", reason: "unknown task" };
|
|
6
|
+
if (record.running !== undefined)
|
|
7
|
+
return { status: "blocked", reason: "the task is still running" };
|
|
8
|
+
const tree = record.worktree;
|
|
9
|
+
if (tree === undefined)
|
|
10
|
+
return {
|
|
11
|
+
status: "blocked",
|
|
12
|
+
reason: "this session holds no kept worktree for the task (it had no changes, or the session was resumed; use git on its branch)",
|
|
13
|
+
};
|
|
14
|
+
const description = record.info.description.trim().split("\n")[0] ?? "";
|
|
15
|
+
const message = `task ${record.info.taskId}: ${description === "" ? record.info.agent : description}`;
|
|
16
|
+
const result = await landWorktree(tree, message);
|
|
17
|
+
if (result.status !== "blocked") {
|
|
18
|
+
delete record.worktree;
|
|
19
|
+
delete record.worktreeOutcome;
|
|
20
|
+
persist(record);
|
|
21
|
+
}
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
@@ -81,6 +81,7 @@ export declare class SubagentRegistry implements TaskControl {
|
|
|
81
81
|
/** [#267] 续命一次(task_ctl extend)。 */
|
|
82
82
|
extend(taskId: string, ms?: number): ExtendOutcome;
|
|
83
83
|
/** [#267] 到点被停止、尚未经提醒通道通知的任务。 */
|
|
84
|
+
land(taskId: string): Promise<import("./worktree-land.js").LandResult>;
|
|
84
85
|
takeExpired(): ExpiredTask[];
|
|
85
86
|
list(): readonly TaskInfo[];
|
|
86
87
|
get(taskId: string): TaskInfo | undefined;
|
|
@@ -20,7 +20,9 @@ import { AgentCatalog, resolveAgentModel } from "../agents/catalog.js";
|
|
|
20
20
|
import { capTaskText, decorateTaskText, writeTaskOutput } from "../agents/result.js";
|
|
21
21
|
import { SubagentPool, TASK_CUSTOM_TYPE, TERMINAL_STATUSES, failedResult as failed, flushText, newRecord, rebuildRecords, recordData, taskStats, } from "../agents/task-record.js";
|
|
22
22
|
import { registerTaskControl, unregisterTaskControl, } from "../agents/task-control.js";
|
|
23
|
-
import {
|
|
23
|
+
import { finishWorktree } from "./worktree.js";
|
|
24
|
+
import { prepareTaskWorktree } from "./worktree-setup.js";
|
|
25
|
+
import { landTask } from "./subagent-land.js";
|
|
24
26
|
import { appendTraceEntry } from "./session-trace-writer.js";
|
|
25
27
|
import { directMessage, drainDirect, liveOf } from "./subagent-direct.js";
|
|
26
28
|
import { TaskNotifier, WaitDetach, backgroundRecords, blockingTasks, foregroundWaiter, settleTasks, startedResult, waitForTask, } from "./subagent-background.js";
|
|
@@ -94,6 +96,9 @@ export class SubagentRegistry {
|
|
|
94
96
|
return extendLifetime(record, this.lifetimeEnv(), () => record?.controller?.abort(), ms);
|
|
95
97
|
}
|
|
96
98
|
/** [#267] 到点被停止、尚未经提醒通道通知的任务。 */
|
|
99
|
+
land(taskId) {
|
|
100
|
+
return landTask(this.tasks.get(taskId), (record) => this.persist(record));
|
|
101
|
+
}
|
|
97
102
|
takeExpired() {
|
|
98
103
|
return takeExpiredTasks(this.tasks.values());
|
|
99
104
|
}
|
|
@@ -296,12 +301,8 @@ export class SubagentRegistry {
|
|
|
296
301
|
}
|
|
297
302
|
delete record.queued;
|
|
298
303
|
try {
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
const name = `${this.host.manager.id.slice(0, 8)}-${record.info.taskId}`;
|
|
302
|
-
record.worktree = await createWorktree(this.host.cwd, name);
|
|
303
|
-
record.cwd = record.worktree.cwd;
|
|
304
|
-
}
|
|
304
|
+
const setup = this.env.modelConfig?.subagents?.worktreeSetup;
|
|
305
|
+
await prepareTaskWorktree(record, this.host.cwd, this.host.manager.id, setup, signal);
|
|
305
306
|
const handle = await this.handleFor(record, request, ama, signal);
|
|
306
307
|
const onAbort = () => void handle.stop().catch(() => undefined);
|
|
307
308
|
if (signal.aborted)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [#313] 把 worktree 子任务的结果落到父仓库当前分支。
|
|
3
|
+
*
|
|
4
|
+
* - 遗留改动先在任务分支上提交,再 cherry-pick `起点..任务分支`:起点是未提交改动的快照时,快照本身不会
|
|
5
|
+
* 被落地;
|
|
6
|
+
* - 父仓库正在 merge / rebase / cherry-pick 时直接拒绝:失败回退用的 `--abort` 不能碰用户自己的操作;
|
|
7
|
+
* - 冲突或会覆盖父的未提交改动:`cherry-pick --abort` 恢复原状,保留 worktree,报告冲突文件;
|
|
8
|
+
* - 整个过程占用该仓库的串行队列,并行落地不会交错。
|
|
9
|
+
*/
|
|
10
|
+
import { type GitRunner, type Worktree } from "./worktree.js";
|
|
11
|
+
export type LandResult = {
|
|
12
|
+
status: "landed";
|
|
13
|
+
commits: string[];
|
|
14
|
+
cleanupError?: string;
|
|
15
|
+
} | {
|
|
16
|
+
status: "nothing";
|
|
17
|
+
} | {
|
|
18
|
+
status: "blocked";
|
|
19
|
+
reason: string;
|
|
20
|
+
files?: string[];
|
|
21
|
+
};
|
|
22
|
+
export declare function landWorktree(tree: Worktree, message: string, git?: GitRunner): Promise<LandResult>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [#313] 把 worktree 子任务的结果落到父仓库当前分支。
|
|
3
|
+
*
|
|
4
|
+
* - 遗留改动先在任务分支上提交,再 cherry-pick `起点..任务分支`:起点是未提交改动的快照时,快照本身不会
|
|
5
|
+
* 被落地;
|
|
6
|
+
* - 父仓库正在 merge / rebase / cherry-pick 时直接拒绝:失败回退用的 `--abort` 不能碰用户自己的操作;
|
|
7
|
+
* - 冲突或会覆盖父的未提交改动:`cherry-pick --abort` 恢复原状,保留 worktree,报告冲突文件;
|
|
8
|
+
* - 整个过程占用该仓库的串行队列,并行落地不会交错。
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { resolve } from "node:path";
|
|
12
|
+
import { removeWorktree, retryTransient, runGit, withRepoLock, } from "./worktree.js";
|
|
13
|
+
const IN_PROGRESS = [
|
|
14
|
+
"CHERRY_PICK_HEAD",
|
|
15
|
+
"MERGE_HEAD",
|
|
16
|
+
"REVERT_HEAD",
|
|
17
|
+
"BISECT_LOG",
|
|
18
|
+
"rebase-merge",
|
|
19
|
+
"rebase-apply",
|
|
20
|
+
"sequencer",
|
|
21
|
+
];
|
|
22
|
+
const lines = (text) => text
|
|
23
|
+
.split("\n")
|
|
24
|
+
.map((line) => line.trim())
|
|
25
|
+
.filter((line) => line !== "");
|
|
26
|
+
const errorText = (error) => (error instanceof Error ? error.message : String(error)).split("\n").slice(0, 6).join("\n");
|
|
27
|
+
async function gitPathExists(repo, name, git) {
|
|
28
|
+
return existsSync(resolve(repo, (await git(["rev-parse", "--git-path", name], repo)).trim()));
|
|
29
|
+
}
|
|
30
|
+
async function operationInProgress(repo, git) {
|
|
31
|
+
for (const name of IN_PROGRESS)
|
|
32
|
+
if (await gitPathExists(repo, name, git))
|
|
33
|
+
return name;
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
/** 回退这次 cherry-pick;返回 HEAD 是否回到了开始时的提交。 */
|
|
37
|
+
async function rollback(repo, before, git) {
|
|
38
|
+
if ((await gitPathExists(repo, "CHERRY_PICK_HEAD", git)) ||
|
|
39
|
+
(await gitPathExists(repo, "sequencer", git)))
|
|
40
|
+
await git(["cherry-pick", "--abort"], repo);
|
|
41
|
+
return (await git(["rev-parse", "HEAD"], repo)).trim() === before;
|
|
42
|
+
}
|
|
43
|
+
async function landLocked(tree, message, git) {
|
|
44
|
+
const repo = tree.repo;
|
|
45
|
+
if ((await git(["status", "--porcelain"], tree.path)).trim() !== "") {
|
|
46
|
+
try {
|
|
47
|
+
await git(["add", "-A"], tree.path);
|
|
48
|
+
await git(["commit", "-q", "-m", message], tree.path);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
return {
|
|
52
|
+
status: "blocked",
|
|
53
|
+
reason: `could not commit the task's changes: ${errorText(error)}`,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const range = `${tree.base}..${tree.branch}`;
|
|
58
|
+
const commits = lines(await git(["rev-list", "--reverse", range], repo));
|
|
59
|
+
if (commits.length === 0) {
|
|
60
|
+
await removeWorktree(tree, git, true);
|
|
61
|
+
return { status: "nothing" };
|
|
62
|
+
}
|
|
63
|
+
if (lines(await git(["rev-list", "--merges", range], repo)).length > 0)
|
|
64
|
+
return { status: "blocked", reason: "the task branch contains merge commits" };
|
|
65
|
+
const busy = await operationInProgress(repo, git);
|
|
66
|
+
if (busy !== undefined)
|
|
67
|
+
return { status: "blocked", reason: `the parent repository has an operation open (${busy})` };
|
|
68
|
+
const before = (await git(["rev-parse", "HEAD"], repo)).trim();
|
|
69
|
+
try {
|
|
70
|
+
await git(["-c", "core.editor=true", "cherry-pick", ...commits], repo);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
const files = lines(await git(["diff", "--name-only", "--diff-filter=U"], repo).catch(() => ""));
|
|
74
|
+
const restored = await rollback(repo, before, git).catch(() => false);
|
|
75
|
+
const reason = restored
|
|
76
|
+
? `not landed, parent restored: ${errorText(error)}`
|
|
77
|
+
: `cherry-pick failed and the parent could not be restored to ${before}: ${errorText(error)}`;
|
|
78
|
+
return files.length > 0 ? { status: "blocked", reason, files } : { status: "blocked", reason };
|
|
79
|
+
}
|
|
80
|
+
const landed = lines(await git(["rev-list", "--reverse", `${before}..HEAD`], repo));
|
|
81
|
+
try {
|
|
82
|
+
await retryTransient(() => removeWorktree(tree, git, true));
|
|
83
|
+
return { status: "landed", commits: landed };
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
return { status: "landed", commits: landed, cleanupError: errorText(error) };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
export function landWorktree(tree, message, git = runGit) {
|
|
90
|
+
return withRepoLock(tree.repo, () => landLocked(tree, message, git), git);
|
|
91
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [#313] worktree 初始化:`subagents.worktreeSetup`(只认用户级,项目配置不能借此执行命令)。
|
|
3
|
+
*
|
|
4
|
+
* 只在新建 worktree 时运行一次,cwd 是 worktree 根,`AMA_WORKTREE_PARENT` 指向父仓库(例如链接依赖目录)。
|
|
5
|
+
* 失败、超时或被中止时删除这个 worktree 并让任务失败,不带着坏环境继续。
|
|
6
|
+
*/
|
|
7
|
+
import type { TaskRecord } from "../agents/task-record.js";
|
|
8
|
+
import { type Worktree } from "./worktree.js";
|
|
9
|
+
export declare const WORKTREE_SETUP_TIMEOUT_MS = 600000;
|
|
10
|
+
export declare function runWorktreeSetup(command: string, tree: Pick<Worktree, "path" | "repo">, signal?: AbortSignal, timeoutMs?: number): Promise<void>;
|
|
11
|
+
/** 注册表 `execute()`:需要隔离且还没有 worktree 时建好(含初始化),子会话 cwd 指过去。 */
|
|
12
|
+
export declare function prepareTaskWorktree(record: TaskRecord, cwd: string, sessionId: string, setup: string | undefined, signal?: AbortSignal): Promise<void>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [#313] worktree 初始化:`subagents.worktreeSetup`(只认用户级,项目配置不能借此执行命令)。
|
|
3
|
+
*
|
|
4
|
+
* 只在新建 worktree 时运行一次,cwd 是 worktree 根,`AMA_WORKTREE_PARENT` 指向父仓库(例如链接依赖目录)。
|
|
5
|
+
* 失败、超时或被中止时删除这个 worktree 并让任务失败,不带着坏环境继续。
|
|
6
|
+
*/
|
|
7
|
+
import { spawnShell } from "../tools/bash.js";
|
|
8
|
+
import { killProcessTree, trackProcessGroup, untrackProcessGroup } from "../tools/process-tree.js";
|
|
9
|
+
import { resolveShell } from "../tools/shell.js";
|
|
10
|
+
import { createWorktree, removeWorktree } from "./worktree.js";
|
|
11
|
+
export const WORKTREE_SETUP_TIMEOUT_MS = 600_000;
|
|
12
|
+
const OUTPUT_TAIL_CHARS = 2000;
|
|
13
|
+
export function runWorktreeSetup(command, tree, signal, timeoutMs = WORKTREE_SETUP_TIMEOUT_MS) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
if (signal?.aborted) {
|
|
16
|
+
reject(new Error("aborted"));
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const detached = process.platform !== "win32";
|
|
20
|
+
const child = spawnShell(resolveShell(), command, {
|
|
21
|
+
cwd: tree.path,
|
|
22
|
+
env: { ...process.env, AMA_WORKTREE_PARENT: tree.repo },
|
|
23
|
+
detached,
|
|
24
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
25
|
+
});
|
|
26
|
+
const pid = child.pid;
|
|
27
|
+
if (pid !== undefined && detached)
|
|
28
|
+
trackProcessGroup(pid);
|
|
29
|
+
let tail = "";
|
|
30
|
+
let stopped;
|
|
31
|
+
const collect = (chunk) => {
|
|
32
|
+
tail = (tail + chunk.toString("utf8")).slice(-OUTPUT_TAIL_CHARS);
|
|
33
|
+
};
|
|
34
|
+
child.stdout?.on("data", collect);
|
|
35
|
+
child.stderr?.on("data", collect);
|
|
36
|
+
const stop = (reason) => {
|
|
37
|
+
stopped ??= reason;
|
|
38
|
+
if (pid !== undefined)
|
|
39
|
+
void killProcessTree(pid).catch(() => undefined);
|
|
40
|
+
};
|
|
41
|
+
const onAbort = () => stop("aborted");
|
|
42
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
43
|
+
const timer = setTimeout(() => stop(`timed out after ${timeoutMs} ms`), timeoutMs);
|
|
44
|
+
timer.unref?.();
|
|
45
|
+
const settle = (error) => {
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
signal?.removeEventListener("abort", onAbort);
|
|
48
|
+
if (pid !== undefined && detached)
|
|
49
|
+
untrackProcessGroup(pid);
|
|
50
|
+
if (error === undefined)
|
|
51
|
+
resolve();
|
|
52
|
+
else
|
|
53
|
+
reject(error);
|
|
54
|
+
};
|
|
55
|
+
child.once("error", (error) => settle(error));
|
|
56
|
+
child.once("close", (code) => {
|
|
57
|
+
if (stopped === undefined && code === 0)
|
|
58
|
+
settle();
|
|
59
|
+
else {
|
|
60
|
+
const why = stopped ?? `exit code ${String(code)}`;
|
|
61
|
+
settle(new Error(tail.trim() === "" ? why : `${why}: ${tail.trim()}`));
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** 注册表 `execute()`:需要隔离且还没有 worktree 时建好(含初始化),子会话 cwd 指过去。 */
|
|
67
|
+
export async function prepareTaskWorktree(record, cwd, sessionId, setup, signal) {
|
|
68
|
+
if (record.isolation !== "worktree" || record.worktree !== undefined)
|
|
69
|
+
return;
|
|
70
|
+
// 名字带会话 id 前缀:不同会话的 t1 不会撞到同一个 worktree / 分支
|
|
71
|
+
const tree = await createWorktree(cwd, `${sessionId.slice(0, 8)}-${record.info.taskId}`);
|
|
72
|
+
if (setup !== undefined && setup.trim() !== "" && tree.created === true) {
|
|
73
|
+
try {
|
|
74
|
+
await runWorktreeSetup(setup, tree, signal);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
await removeWorktree(tree).catch(() => undefined);
|
|
78
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
79
|
+
throw new Error(`worktree setup failed (subagents.worktreeSetup): ${message}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
record.worktree = tree;
|
|
83
|
+
record.cwd = tree.cwd;
|
|
84
|
+
}
|
package/dist/agent/worktree.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 子 Agent 的 git worktree 隔离(docs/history/wave5-plan.md §7.4,D24)。[W5-G]
|
|
3
3
|
*
|
|
4
|
-
* - `git worktree add -b ama/task-<taskId> <repo>/.ama/worktrees/<taskId>
|
|
4
|
+
* - `git worktree add -b ama/task-<taskId> <repo>/.ama/worktrees/<taskId> <起点>`;子会话 cwd 指向
|
|
5
5
|
* worktree 里与父 cwd 对应的子目录;
|
|
6
|
+
* - [#313] 起点:父工作区有未提交改动(已暂存、未暂存、未跟踪,不含已忽略)时,经临时索引写成一个合成
|
|
7
|
+
* 提交,父的索引与工作区不动;没有改动就是 HEAD。起点记在 `refs/ama/base/<taskId>`,重开时取回,
|
|
8
|
+
* 有无改动、diff 摘要与落地都以它为基准,继承来的改动不算任务产出。快照失败回落 HEAD 并在结果里说明;
|
|
6
9
|
* - 结束时没有改动(工作区干净且 HEAD 未动)→ `git worktree remove --force` 并删分支;有改动则保留,
|
|
7
10
|
* 结果里给分支名与 `git diff --stat`;
|
|
8
11
|
* - 非 git 目录直接报错,不回落到共享目录;`.ama/worktrees/.gitignore` 写 `*`,父会话的 git 与
|
|
@@ -18,9 +21,13 @@ export interface Worktree {
|
|
|
18
21
|
/** 子会话 cwd(worktree 里与父 cwd 对应的目录)。 */
|
|
19
22
|
cwd: string;
|
|
20
23
|
branch: string;
|
|
21
|
-
/**
|
|
24
|
+
/** 任务的起点提交(HEAD 或 [#313] 未提交改动的快照),判断有无新提交与落地都以它为基准。 */
|
|
22
25
|
base: string;
|
|
23
26
|
repo: string;
|
|
27
|
+
/** [#313] 快照失败、回落到 HEAD 时的原因。 */
|
|
28
|
+
snapshotError?: string;
|
|
29
|
+
/** [#313] 这次调用新建的(重开已有的不带),初始化命令只跑一次。 */
|
|
30
|
+
created?: true;
|
|
24
31
|
}
|
|
25
32
|
export interface WorktreeOutcome {
|
|
26
33
|
branch: string;
|
|
@@ -29,6 +36,8 @@ export interface WorktreeOutcome {
|
|
|
29
36
|
diffStat?: string;
|
|
30
37
|
/** 保留时的路径。 */
|
|
31
38
|
path?: string;
|
|
39
|
+
/** [#313] 未提交改动没能带进 worktree 的原因。 */
|
|
40
|
+
snapshotError?: string;
|
|
32
41
|
}
|
|
33
42
|
export type GitRunner = (args: readonly string[], cwd: string) => Promise<string>;
|
|
34
43
|
export declare const runGit: GitRunner;
|
|
@@ -38,7 +47,18 @@ export declare function retryTransient<T>(run: () => Promise<T>, options?: {
|
|
|
38
47
|
delayMs?: number;
|
|
39
48
|
}): Promise<T>;
|
|
40
49
|
export declare function worktreeBranch(taskId: string): string;
|
|
50
|
+
/** [#313] 记录任务起点的 ref(不进分支列表,随 worktree 一起删)。 */
|
|
51
|
+
export declare function worktreeBaseRef(branch: string): string;
|
|
52
|
+
/**
|
|
53
|
+
* [#313] 把父工作区写成 `head` 之上的合成提交;没有未提交改动返回 undefined。全程用临时索引,这里不用
|
|
54
|
+
* 可注入的 GitRunner:它不传环境变量时 `git add` 会落到用户真实的索引上。
|
|
55
|
+
*/
|
|
56
|
+
export declare function snapshotWorkingTree(repo: string, head: string): Promise<string | undefined>;
|
|
41
57
|
/** 在父 cwd 所在仓库里为任务建 worktree;非 git 目录抛错。 */
|
|
42
58
|
export declare function createWorktree(cwd: string, taskId: string, git?: GitRunner): Promise<Worktree>;
|
|
59
|
+
/** 删除 worktree、任务分支与起点 ref(调用方已持有该仓库的串行队列时传 `direct`)。 */
|
|
60
|
+
export declare function removeWorktree(tree: Worktree, git?: GitRunner, direct?: boolean): Promise<void>;
|
|
61
|
+
/** 仓库的串行队列:落地这类多步操作整体占用,避免与并行的增删 worktree 交错。 */
|
|
62
|
+
export declare function withRepoLock<T>(repo: string, run: () => Promise<T>, git?: GitRunner): Promise<T>;
|
|
43
63
|
/** 运行结束:无改动删除 worktree 与分支;有改动保留并给 diff 摘要。 */
|
|
44
64
|
export declare function finishWorktree(tree: Worktree, git?: GitRunner): Promise<WorktreeOutcome>;
|
package/dist/agent/worktree.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 子 Agent 的 git worktree 隔离(docs/history/wave5-plan.md §7.4,D24)。[W5-G]
|
|
3
3
|
*
|
|
4
|
-
* - `git worktree add -b ama/task-<taskId> <repo>/.ama/worktrees/<taskId>
|
|
4
|
+
* - `git worktree add -b ama/task-<taskId> <repo>/.ama/worktrees/<taskId> <起点>`;子会话 cwd 指向
|
|
5
5
|
* worktree 里与父 cwd 对应的子目录;
|
|
6
|
+
* - [#313] 起点:父工作区有未提交改动(已暂存、未暂存、未跟踪,不含已忽略)时,经临时索引写成一个合成
|
|
7
|
+
* 提交,父的索引与工作区不动;没有改动就是 HEAD。起点记在 `refs/ama/base/<taskId>`,重开时取回,
|
|
8
|
+
* 有无改动、diff 摘要与落地都以它为基准,继承来的改动不算任务产出。快照失败回落 HEAD 并在结果里说明;
|
|
6
9
|
* - 结束时没有改动(工作区干净且 HEAD 未动)→ `git worktree remove --force` 并删分支;有改动则保留,
|
|
7
10
|
* 结果里给分支名与 `git diff --stat`;
|
|
8
11
|
* - 非 git 目录直接报错,不回落到共享目录;`.ama/worktrees/.gitignore` 写 `*`,父会话的 git 与
|
|
@@ -13,7 +16,8 @@
|
|
|
13
16
|
* 公共 git 目录串行;跨进程(两个 ama 同时开隔离任务)的同类瞬时错误短暂重试。
|
|
14
17
|
*/
|
|
15
18
|
import { execFile } from "node:child_process";
|
|
16
|
-
import { existsSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
|
|
19
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync, } from "node:fs";
|
|
20
|
+
import { tmpdir } from "node:os";
|
|
17
21
|
import { join, relative, resolve } from "node:path";
|
|
18
22
|
const TIMEOUT_MS = 30_000;
|
|
19
23
|
export const runGit = (args, cwd) => new Promise((resolve, reject) => {
|
|
@@ -81,6 +85,57 @@ function mutate(key, git, args, cwd) {
|
|
|
81
85
|
export function worktreeBranch(taskId) {
|
|
82
86
|
return `ama/task-${taskId}`;
|
|
83
87
|
}
|
|
88
|
+
/** [#313] 记录任务起点的 ref(不进分支列表,随 worktree 一起删)。 */
|
|
89
|
+
export function worktreeBaseRef(branch) {
|
|
90
|
+
return `refs/ama/base/${branch.replace(/^ama\/task-/, "")}`;
|
|
91
|
+
}
|
|
92
|
+
function gitWithEnv(args, cwd, env) {
|
|
93
|
+
return new Promise((done, reject) => {
|
|
94
|
+
execFile("git", [...args], {
|
|
95
|
+
cwd,
|
|
96
|
+
env: { ...process.env, ...env },
|
|
97
|
+
timeout: TIMEOUT_MS,
|
|
98
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
99
|
+
windowsHide: true,
|
|
100
|
+
}, (error, stdout, stderr) => {
|
|
101
|
+
if (error)
|
|
102
|
+
reject(new Error(String(stderr).trim() || error.message));
|
|
103
|
+
else
|
|
104
|
+
done(String(stdout));
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* [#313] 把父工作区写成 `head` 之上的合成提交;没有未提交改动返回 undefined。全程用临时索引,这里不用
|
|
110
|
+
* 可注入的 GitRunner:它不传环境变量时 `git add` 会落到用户真实的索引上。
|
|
111
|
+
*/
|
|
112
|
+
export async function snapshotWorkingTree(repo, head) {
|
|
113
|
+
const dir = mkdtempSync(join(tmpdir(), "ama-snapshot-"));
|
|
114
|
+
try {
|
|
115
|
+
const index = join(dir, "index");
|
|
116
|
+
const current = resolve(repo, (await runGit(["rev-parse", "--git-path", "index"], repo)).trim());
|
|
117
|
+
if (existsSync(current))
|
|
118
|
+
copyFileSync(current, index);
|
|
119
|
+
const env = { GIT_INDEX_FILE: index };
|
|
120
|
+
await gitWithEnv(["add", "-A", "--", "."], repo, env);
|
|
121
|
+
const tree = (await gitWithEnv(["write-tree"], repo, env)).trim();
|
|
122
|
+
const headTree = (await runGit(["rev-parse", `${head}^{tree}`], repo)).trim();
|
|
123
|
+
if (tree === headTree)
|
|
124
|
+
return undefined;
|
|
125
|
+
const identity = {
|
|
126
|
+
GIT_AUTHOR_NAME: "ama",
|
|
127
|
+
GIT_AUTHOR_EMAIL: "ama@localhost",
|
|
128
|
+
GIT_COMMITTER_NAME: "ama",
|
|
129
|
+
GIT_COMMITTER_EMAIL: "ama@localhost",
|
|
130
|
+
};
|
|
131
|
+
const message = "ama: snapshot of uncommitted changes";
|
|
132
|
+
const args = ["commit-tree", tree, "-p", head, "-m", message];
|
|
133
|
+
return (await gitWithEnv(args, repo, identity)).trim();
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
rmSync(dir, { recursive: true, force: true });
|
|
137
|
+
}
|
|
138
|
+
}
|
|
84
139
|
/** 在父 cwd 所在仓库里为任务建 worktree;非 git 目录抛错。 */
|
|
85
140
|
export async function createWorktree(cwd, taskId, git = runGit) {
|
|
86
141
|
let repo;
|
|
@@ -90,7 +145,7 @@ export async function createWorktree(cwd, taskId, git = runGit) {
|
|
|
90
145
|
catch {
|
|
91
146
|
throw new Error(`isolation "worktree" needs a git repository; ${cwd} is not inside one`);
|
|
92
147
|
}
|
|
93
|
-
const
|
|
148
|
+
const head = (await git(["rev-parse", "HEAD"], repo)).trim();
|
|
94
149
|
const root = join(repo, ".ama", "worktrees");
|
|
95
150
|
mkdirSync(root, { recursive: true });
|
|
96
151
|
const ignore = join(root, ".gitignore");
|
|
@@ -99,22 +154,58 @@ export async function createWorktree(cwd, taskId, git = runGit) {
|
|
|
99
154
|
const path = join(root, taskId);
|
|
100
155
|
const branch = worktreeBranch(taskId);
|
|
101
156
|
const key = await commonDir(repo, git);
|
|
102
|
-
|
|
157
|
+
const ref = worktreeBaseRef(branch);
|
|
158
|
+
let base = head;
|
|
159
|
+
let snapshotError;
|
|
160
|
+
const created = !existsSync(path);
|
|
161
|
+
if (!created) {
|
|
162
|
+
// 重开保留的 worktree:起点取创建时记下的,不重新快照
|
|
163
|
+
const saved = await git(["rev-parse", "--verify", "--quiet", ref], repo).catch(() => "");
|
|
164
|
+
if (saved.trim() !== "")
|
|
165
|
+
base = saved.trim();
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
try {
|
|
169
|
+
base = (await snapshotWorkingTree(repo, head)) ?? head;
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
snapshotError = error instanceof Error ? error.message : String(error);
|
|
173
|
+
}
|
|
103
174
|
await mutate(key, git, ["worktree", "add", "-b", branch, path, base], repo);
|
|
175
|
+
await git(["update-ref", ref, base], repo);
|
|
176
|
+
}
|
|
104
177
|
const sub = relative(repo, realPath(cwd));
|
|
105
178
|
const childCwd = sub === "" || sub.startsWith("..") ? path : join(path, sub);
|
|
106
179
|
mkdirSync(childCwd, { recursive: true });
|
|
107
|
-
|
|
180
|
+
const tree = { path, cwd: childCwd, branch, base, repo };
|
|
181
|
+
if (snapshotError !== undefined)
|
|
182
|
+
tree.snapshotError = snapshotError;
|
|
183
|
+
if (created)
|
|
184
|
+
tree.created = true;
|
|
185
|
+
return tree;
|
|
186
|
+
}
|
|
187
|
+
/** 删除 worktree、任务分支与起点 ref(调用方已持有该仓库的串行队列时传 `direct`)。 */
|
|
188
|
+
export async function removeWorktree(tree, git = runGit, direct = false) {
|
|
189
|
+
const key = await commonDir(tree.repo, git);
|
|
190
|
+
const run = (args) => direct ? retryTransient(() => git(args, tree.repo)) : mutate(key, git, args, tree.repo);
|
|
191
|
+
await run(["worktree", "remove", "--force", tree.path]);
|
|
192
|
+
await run(["branch", "-D", tree.branch]).catch(() => "");
|
|
193
|
+
await run(["update-ref", "-d", worktreeBaseRef(tree.branch)]).catch(() => "");
|
|
194
|
+
}
|
|
195
|
+
/** 仓库的串行队列:落地这类多步操作整体占用,避免与并行的增删 worktree 交错。 */
|
|
196
|
+
export async function withRepoLock(repo, run, git = runGit) {
|
|
197
|
+
return serialized(await commonDir(repo, git), run);
|
|
108
198
|
}
|
|
109
199
|
/** 运行结束:无改动删除 worktree 与分支;有改动保留并给 diff 摘要。 */
|
|
110
200
|
export async function finishWorktree(tree, git = runGit) {
|
|
111
201
|
const status = (await git(["status", "--porcelain"], tree.path)).trim();
|
|
112
202
|
const head = (await git(["rev-parse", "HEAD"], tree.path)).trim();
|
|
113
203
|
if (status === "" && head === tree.base) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
204
|
+
await removeWorktree(tree, git);
|
|
205
|
+
const clean = { branch: tree.branch, changed: false };
|
|
206
|
+
if (tree.snapshotError !== undefined)
|
|
207
|
+
clean.snapshotError = tree.snapshotError;
|
|
208
|
+
return clean;
|
|
118
209
|
}
|
|
119
210
|
const stat = (await git(["diff", "--stat", tree.base], tree.path).catch(() => "")).trim();
|
|
120
211
|
const untracked = status
|
|
@@ -124,10 +215,13 @@ export async function finishWorktree(tree, git = runGit) {
|
|
|
124
215
|
const parts = [stat];
|
|
125
216
|
if (untracked.length > 0)
|
|
126
217
|
parts.push(`untracked: ${untracked.join(", ")}`);
|
|
127
|
-
|
|
218
|
+
const kept = {
|
|
128
219
|
branch: tree.branch,
|
|
129
220
|
changed: true,
|
|
130
221
|
diffStat: parts.filter((part) => part !== "").join("\n"),
|
|
131
222
|
path: tree.path,
|
|
132
223
|
};
|
|
224
|
+
if (tree.snapshotError !== undefined)
|
|
225
|
+
kept.snapshotError = tree.snapshotError;
|
|
226
|
+
return kept;
|
|
133
227
|
}
|
package/dist/agents/catalog.d.ts
CHANGED
package/dist/agents/result.js
CHANGED
|
@@ -22,6 +22,8 @@ export function decorateTaskText(capped, status, report, outcome) {
|
|
|
22
22
|
text = withReportLines(text, report);
|
|
23
23
|
if (outcome?.changed === true)
|
|
24
24
|
text += `\n\n[worktree kept: branch ${outcome.branch} at ${outcome.path ?? "?"}]\n${outcome.diffStat ?? ""}`;
|
|
25
|
+
if (outcome?.snapshotError !== undefined)
|
|
26
|
+
text += `\n\n[worktree started from HEAD: uncommitted parent changes were not included (${outcome.snapshotError})]`;
|
|
25
27
|
return text;
|
|
26
28
|
}
|
|
27
29
|
/** 去掉按字节切开时残留的半个字符(U+FFFD)。 */
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* 注册表(agent/subagent-registry.ts)建好后登记、会话 dispose 时注销。单独成文件是为了让
|
|
5
5
|
* tools/task-ctl.ts 不 import agent/ 的实现(agent/tool-runner → tools/registry → task-ctl 会成环)。
|
|
6
6
|
*/
|
|
7
|
+
import type { LandResult } from "../agent/worktree-land.js";
|
|
7
8
|
import type { ExtendOutcome } from "../tools/background-jobs.js";
|
|
8
9
|
import type { SubagentResult, TaskRegistryView } from "../tools/types.js";
|
|
9
10
|
/** [#267] 到达寿命上限被停止的后台任务(提醒通道取走一次)。 */
|
|
@@ -34,6 +35,8 @@ export interface TaskControl extends TaskRegistryView {
|
|
|
34
35
|
extend(taskId: string, ms?: number): ExtendOutcome;
|
|
35
36
|
/** [#267] 取走到达寿命上限、已停止且尚未通知的任务(提醒通道用)。 */
|
|
36
37
|
takeExpired(): ExpiredTask[];
|
|
38
|
+
/** [#313] 把 worktree 任务的提交落到父当前分支(`task_land`)。 */
|
|
39
|
+
land?(taskId: string): Promise<LandResult>;
|
|
37
40
|
}
|
|
38
41
|
export declare function registerTaskControl(sessionId: string, control: TaskControl): void;
|
|
39
42
|
export declare function unregisterTaskControl(sessionId: string, control: TaskControl): void;
|