@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.3
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/README.en.md +1 -1
- package/README.md +1 -1
- package/dist/agent/channel-runner.d.ts +4 -8
- package/dist/agent/channel-runner.js +14 -34
- package/dist/agent/job-manager.d.ts +12 -0
- package/dist/agent/job-manager.js +42 -1
- package/dist/agent/prompt/sections.js +2 -2
- package/dist/agent/runner-factory.d.ts +2 -2
- package/dist/agent/types.d.ts +11 -7
- package/dist/channel/channel-index.d.ts +9 -2
- package/dist/channel/channel-index.js +25 -6
- package/dist/channel/project-scope-store.d.ts +20 -0
- package/dist/channel/project-scope-store.js +22 -7
- package/dist/commands/catalog.js +6 -12
- package/dist/events/event-commands.js +2 -2
- package/dist/events/events.d.ts +51 -30
- package/dist/events/events.js +70 -98
- package/dist/memory/journal.d.ts +2 -3
- package/dist/memory/journal.js +2 -3
- package/dist/memory/maintenance-tuning.d.ts +0 -1
- package/dist/memory/maintenance-tuning.js +0 -1
- package/dist/memory/scheduler.js +8 -16
- package/dist/memory/search.js +2 -3
- package/dist/memory/session-search.js +3 -9
- package/dist/memory/store.d.ts +1 -1
- package/dist/memory/store.js +9 -1
- package/dist/memory/task-digest.js +10 -11
- package/dist/memory/tombstones.js +2 -4
- package/dist/models/provider-login.d.ts +1 -1
- package/dist/models/provider-login.js +1 -1
- package/dist/playbooks/agent-delegation.md +6 -6
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/event-scheduling.md +22 -13
- package/dist/playbooks/memory-and-learning.md +2 -2
- package/dist/playbooks/outbound-media.md +1 -1
- package/dist/playbooks/runtime-orientation.md +3 -3
- package/dist/playbooks/task-lead.md +82 -0
- package/dist/runtime/bootstrap.js +94 -187
- package/dist/runtime/durable-dispatch.js +30 -3
- package/dist/runtime/report-commands.d.ts +30 -0
- package/dist/runtime/report-commands.js +71 -0
- package/dist/runtime/subagent-commands.js +1 -1
- package/dist/runtime/task-commands.d.ts +0 -8
- package/dist/runtime/task-commands.js +48 -85
- package/dist/runtime/task-driver.d.ts +15 -10
- package/dist/runtime/task-driver.js +36 -41
- package/dist/runtime/task-migration.d.ts +23 -29
- package/dist/runtime/task-migration.js +364 -183
- package/dist/runtime/task-spawn.d.ts +24 -0
- package/dist/runtime/task-spawn.js +49 -0
- package/dist/runtime/task-wake.d.ts +33 -46
- package/dist/runtime/task-wake.js +15 -90
- package/dist/security/network.js +44 -9
- package/dist/settings.d.ts +1 -8
- package/dist/settings.js +1 -8
- package/dist/subagents/discovery.js +3 -15
- package/dist/subagents/external/run.d.ts +3 -1
- package/dist/subagents/external/run.js +2 -20
- package/dist/subagents/external/settlement.d.ts +4 -16
- package/dist/subagents/external/settlement.js +16 -67
- package/dist/subagents/runs.d.ts +15 -29
- package/dist/subagents/runs.js +70 -158
- package/dist/subagents/tool.d.ts +20 -4
- package/dist/subagents/tool.js +63 -87
- package/dist/subagents/verification-outcome.d.ts +13 -19
- package/dist/subagents/verification-outcome.js +8 -22
- package/dist/subagents/workspace-summary.d.ts +8 -0
- package/dist/subagents/workspace-summary.js +29 -0
- package/dist/tasks/board.d.ts +43 -0
- package/dist/tasks/board.js +134 -0
- package/dist/tasks/brief.d.ts +10 -5
- package/dist/tasks/brief.js +78 -26
- package/dist/tasks/budget.d.ts +13 -14
- package/dist/tasks/budget.js +21 -40
- package/dist/tasks/contract-input.d.ts +19 -0
- package/dist/tasks/contract-input.js +55 -0
- package/dist/tasks/create.d.ts +17 -0
- package/dist/tasks/create.js +36 -0
- package/dist/tasks/frontmatter.d.ts +20 -27
- package/dist/tasks/frontmatter.js +18 -31
- package/dist/tasks/ledger.d.ts +61 -117
- package/dist/tasks/ledger.js +78 -223
- package/dist/tasks/log.d.ts +62 -35
- package/dist/tasks/log.js +51 -29
- package/dist/tasks/session-path.d.ts +3 -3
- package/dist/tasks/session-path.js +4 -5
- package/dist/tasks/store.d.ts +27 -28
- package/dist/tasks/store.js +89 -83
- package/dist/tasks/ticket.d.ts +33 -66
- package/dist/tasks/ticket.js +31 -120
- package/dist/tasks/work-log.d.ts +20 -0
- package/dist/tasks/work-log.js +42 -0
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +1 -1
- package/dist/tools/event-manage.d.ts +16 -2
- package/dist/tools/event-manage.js +30 -12
- package/dist/tools/index.d.ts +5 -3
- package/dist/tools/index.js +5 -5
- package/dist/tools/registry.d.ts +6 -4
- package/dist/tools/registry.js +1 -4
- package/dist/tools/subagent-manage.js +4 -2
- package/dist/tools/task-manage/create.js +11 -27
- package/dist/tools/task-manage/lifecycle.d.ts +6 -7
- package/dist/tools/task-manage/lifecycle.js +23 -106
- package/dist/tools/task-manage/log-view.d.ts +3 -2
- package/dist/tools/task-manage/log-view.js +6 -6
- package/dist/tools/task-manage/schema.d.ts +10 -30
- package/dist/tools/task-manage/schema.js +33 -49
- package/dist/tools/task-manage/shared.d.ts +35 -42
- package/dist/tools/task-manage/shared.js +53 -192
- package/dist/tools/task-manage/step-end.d.ts +6 -6
- package/dist/tools/task-manage/step-end.js +61 -98
- package/dist/tools/task-manage/types.d.ts +8 -9
- package/dist/tools/task-manage.js +5 -5
- package/dist/tui/app.js +11 -38
- package/dist/tui/commands.d.ts +18 -8
- package/dist/tui/commands.js +2 -9
- package/dist/tui/turn-controller.d.ts +2 -14
- package/dist/tui/turn-controller.js +1 -17
- package/dist/web/client.js +9 -1
- package/examples/sub-agents/README.md +7 -4
- package/examples/sub-agents/agents/codex-flash.md +2 -2
- package/examples/sub-agents/agents/codex-high.md +1 -1
- package/examples/sub-agents/agents/codex-main.md +1 -1
- package/examples/sub-agents/agents/codex-review.md +23 -0
- package/examples/sub-agents/roles/verifier.md +1 -1
- package/package.json +1 -1
- package/dist/memory/maintenance-migration.d.ts +0 -5
- package/dist/memory/maintenance-migration.js +0 -91
- package/dist/memory/migrate.d.ts +0 -15
- package/dist/memory/migrate.js +0 -364
- package/dist/playbooks/task-loop.md +0 -90
- package/dist/tasks/artifact-subject.d.ts +0 -40
- package/dist/tasks/artifact-subject.js +0 -334
- package/dist/tasks/cycle.d.ts +0 -48
- package/dist/tasks/cycle.js +0 -94
- package/dist/tasks/rounds.d.ts +0 -41
- package/dist/tasks/rounds.js +0 -53
- package/dist/tasks/task-events.d.ts +0 -6
- package/dist/tasks/task-events.js +0 -14
- package/dist/tasks/task-schedule.d.ts +0 -18
- package/dist/tasks/task-schedule.js +0 -50
- package/dist/tasks/verification.d.ts +0 -114
- package/dist/tasks/verification.js +0 -226
|
@@ -1,42 +1,71 @@
|
|
|
1
|
-
import { existsSync } from "node:fs";
|
|
2
|
-
import { copyFile, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
|
1
|
+
import { constants, existsSync } from "node:fs";
|
|
2
|
+
import { copyFile, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { getChannelDir } from "../channel/channel-paths.js";
|
|
5
5
|
import * as log from "../log.js";
|
|
6
|
-
import {
|
|
6
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
7
|
+
import { formatLocalTime } from "../shared/local-time.js";
|
|
7
8
|
import { errorMessage } from "../shared/text-utils.js";
|
|
8
9
|
import { isPlainObject } from "../shared/type-guards.js";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
10
|
+
import { createUsage } from "../tasks/budget.js";
|
|
11
|
+
import { validateTaskContractInput } from "../tasks/contract-input.js";
|
|
12
|
+
import { extractTaskTitle, findTaskSectionBounds, normalizeTaskId, parseTaskItems, taskBody } from "../tasks/ledger.js";
|
|
11
13
|
import { appendTaskLog } from "../tasks/log.js";
|
|
12
14
|
import { withTaskMutation } from "../tasks/mutation-lock.js";
|
|
13
|
-
import { writeStoredTask } from "../tasks/store.js";
|
|
14
|
-
import { nextTaskWake } from "../tasks/task-schedule.js";
|
|
15
|
+
import { ArchiveUndoError, archiveTask, readStoredTask, writeStoredTask } from "../tasks/store.js";
|
|
15
16
|
import { discoverTaskChannels } from "./task-driver.js";
|
|
16
17
|
/**
|
|
17
|
-
* One-time, deterministic, no-LLM
|
|
18
|
+
* One-time, deterministic, no-LLM conversion of v3 task files (0.9.2: `status` / `enabled` /
|
|
19
|
+
* `wake` / `schedule` / `control` frontmatter) to v5 (spec 052). It ships with the release that
|
|
20
|
+
* introduces v5 and is deleted in the next minor release.
|
|
18
21
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
22
|
+
* - **Recurring tasks become event templates.** A v3 task with a `schedule` is, from v5's point of
|
|
23
|
+
* view, an event that spawns an instance per occurrence. The converter writes that event, then
|
|
24
|
+
* retires the task if it was only sleeping until its next occurrence, or lets the occurrence in
|
|
25
|
+
* flight finish as an instance of the event.
|
|
26
|
+
* - **Nothing is parked.** v3 waits (`wake`, `waitingFor`) have no v5 equivalent; the task is
|
|
27
|
+
* reopened, and `enabled: false` / `control.stop` become a pause, so a disabled task never
|
|
28
|
+
* starts running as an instance because of the upgrade. Generated recurring events have no
|
|
29
|
+
* disabled flag: review/isolate them before enabling production scheduling.
|
|
26
30
|
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
31
|
+
* v4 beta files are NOT supported: any `state:` line skips conversion, even alongside
|
|
32
|
+
* `status:`. Preserve/isolate v4 originals and rebuild through v5 tools before enabling
|
|
33
|
+
* the daemon (docs/events-and-tasks.md).
|
|
34
|
+
*
|
|
35
|
+
* Failure handling: a task whose conversion throws is rolled back (original restored, template
|
|
36
|
+
* event and archive copy removed). If any task or event move failed, the marker is NOT written, a
|
|
37
|
+
* `task-migration-v5.failed.json` report is left in the state dir, and this function throws so
|
|
38
|
+
* bootstrap does not start services. A report that records a failed rollback keeps blocking every
|
|
39
|
+
* later start until the operator resolves it and deletes the report.
|
|
40
|
+
*
|
|
41
|
+
* Originals are copied to `tasks/.v3/` and never deleted or overwritten (a differing existing
|
|
42
|
+
* backup is kept and the new copy gets a numeric suffix). Any file carrying `state:` frontmatter,
|
|
43
|
+
* including unsupported v4 files, is left alone.
|
|
29
44
|
*/
|
|
30
|
-
const MIGRATION_MARKER = "task-migration-
|
|
45
|
+
const MIGRATION_MARKER = "task-migration-v5.done";
|
|
46
|
+
const FAILURE_REPORT = "task-migration-v5.failed.json";
|
|
47
|
+
const DEFAULT_STOP_REASON = "v3 中已停用。";
|
|
48
|
+
const BACKUP_DIRNAME = ".v3";
|
|
49
|
+
const ITEMS_NAMES = ["Plan", "计划"];
|
|
50
|
+
/** v3 per-cycle bookkeeping; v5 keeps this in the loop log instead of the contract. */
|
|
51
|
+
const CYCLE_SECTION_NAMES = ["Current Cycle", "当前周期", "History", "历史"];
|
|
52
|
+
function parseJson(value) {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(value);
|
|
55
|
+
return isPlainObject(parsed) ? parsed : undefined;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
31
61
|
/** Minimal reader for the v3 frontmatter block; the only place that still understands it. */
|
|
32
|
-
function
|
|
62
|
+
export function parseV3Frontmatter(content) {
|
|
33
63
|
if (!content.startsWith("---"))
|
|
34
64
|
return undefined;
|
|
35
65
|
const end = content.indexOf("\n---", 3);
|
|
36
66
|
if (end === -1)
|
|
37
67
|
return undefined;
|
|
38
|
-
const fields = {
|
|
39
|
-
let sawLegacy = false;
|
|
68
|
+
const fields = { v5: false, stopped: false };
|
|
40
69
|
for (const line of content.slice(3, end).split("\n")) {
|
|
41
70
|
const idx = line.indexOf(":");
|
|
42
71
|
if (idx === -1)
|
|
@@ -44,36 +73,24 @@ function parseLegacyFrontmatter(content) {
|
|
|
44
73
|
const key = line.slice(0, idx).trim();
|
|
45
74
|
const value = line.slice(idx + 1).trim();
|
|
46
75
|
switch (key) {
|
|
76
|
+
case "state":
|
|
77
|
+
fields.v5 = true;
|
|
78
|
+
break;
|
|
47
79
|
case "status":
|
|
48
80
|
fields.status = value;
|
|
49
|
-
sawLegacy = true;
|
|
50
81
|
break;
|
|
51
82
|
case "enabled":
|
|
52
83
|
fields.enabled = value !== "false";
|
|
53
|
-
sawLegacy = true;
|
|
54
|
-
break;
|
|
55
|
-
case "wake":
|
|
56
|
-
fields.wake = value || undefined;
|
|
57
84
|
break;
|
|
58
85
|
case "schedule":
|
|
59
86
|
fields.schedule = value || undefined;
|
|
60
87
|
break;
|
|
61
|
-
case "outcome":
|
|
62
|
-
if (value === "completed" || value === "cancelled")
|
|
63
|
-
fields.outcome = value;
|
|
64
|
-
break;
|
|
65
|
-
case "closedAt":
|
|
66
|
-
fields.closedAt = value || undefined;
|
|
67
|
-
break;
|
|
68
88
|
case "control": {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
if (
|
|
73
|
-
fields.
|
|
74
|
-
}
|
|
75
|
-
catch {
|
|
76
|
-
// An unparseable control block is exactly why the task needs migrating; drop it.
|
|
89
|
+
const stop = parseJson(value)?.stop;
|
|
90
|
+
if (isPlainObject(stop)) {
|
|
91
|
+
fields.stopped = true;
|
|
92
|
+
if (typeof stop.reason === "string" && stop.reason.trim())
|
|
93
|
+
fields.stopReason = stop.reason.trim();
|
|
77
94
|
}
|
|
78
95
|
break;
|
|
79
96
|
}
|
|
@@ -81,187 +98,351 @@ function parseLegacyFrontmatter(content) {
|
|
|
81
98
|
break;
|
|
82
99
|
}
|
|
83
100
|
}
|
|
84
|
-
|
|
85
|
-
if (/^state:/m.test(content.slice(3, end)))
|
|
86
|
-
return undefined;
|
|
87
|
-
return sawLegacy || fields.outcome ? fields : undefined;
|
|
101
|
+
return fields;
|
|
88
102
|
}
|
|
89
|
-
function
|
|
90
|
-
|
|
103
|
+
function sectionText(body, names) {
|
|
104
|
+
const lines = body.split("\n");
|
|
105
|
+
const bounds = findTaskSectionBounds(lines, names);
|
|
106
|
+
if (!bounds)
|
|
91
107
|
return undefined;
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
108
|
+
const text = lines
|
|
109
|
+
.slice(bounds.headingIndex + 1, bounds.end)
|
|
110
|
+
.join("\n")
|
|
111
|
+
.trim();
|
|
112
|
+
return text || undefined;
|
|
113
|
+
}
|
|
114
|
+
/** Rename `## Plan` to `## Work Items` and drop the per-cycle sections, the two body changes v5 makes. */
|
|
115
|
+
export function convertBody(body) {
|
|
116
|
+
const lines = body.split("\n");
|
|
117
|
+
const items = findTaskSectionBounds(lines, ITEMS_NAMES);
|
|
118
|
+
if (items)
|
|
119
|
+
lines[items.headingIndex] = "## Work Items";
|
|
120
|
+
for (const names of [CYCLE_SECTION_NAMES.slice(0, 2), CYCLE_SECTION_NAMES.slice(2)]) {
|
|
121
|
+
const bounds = findTaskSectionBounds(lines, names);
|
|
122
|
+
if (bounds)
|
|
123
|
+
lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex);
|
|
124
|
+
}
|
|
125
|
+
return lines
|
|
126
|
+
.join("\n")
|
|
127
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
128
|
+
.trimEnd();
|
|
101
129
|
}
|
|
102
130
|
/**
|
|
103
|
-
*
|
|
104
|
-
*
|
|
131
|
+
* Build the event template a recurring v3 task becomes. The original Manual and Verification text
|
|
132
|
+
* is carried into the Goal (v5 has no such sections, and a recurring job's accumulated rules are
|
|
133
|
+
* exactly what the template exists to keep), and every checkbox is reset.
|
|
105
134
|
*/
|
|
106
|
-
export function
|
|
107
|
-
const
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
135
|
+
export function buildTemplate(id, body) {
|
|
136
|
+
const title = extractTaskTitle(`---\n---\n${body}`, id);
|
|
137
|
+
const goal = sectionText(body, ["Goal", "目标"]) ?? title;
|
|
138
|
+
const manual = sectionText(body, ["Manual", "手册"]);
|
|
139
|
+
const verification = sectionText(body, ["Verification", "验收"])
|
|
140
|
+
?.split("\n")
|
|
141
|
+
.filter((line) => !/^Independent verification:/i.test(line.trim()))
|
|
142
|
+
.join("\n")
|
|
143
|
+
.trim();
|
|
144
|
+
const dod = (sectionText(body, ["DoD"]) ?? "")
|
|
145
|
+
.split("\n")
|
|
146
|
+
.map((line) => line.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]"))
|
|
147
|
+
.join("\n")
|
|
148
|
+
.trim();
|
|
149
|
+
const items = parseTaskItems(convertBody(body))?.items.map((item) => ({ text: item.text })) ?? [];
|
|
150
|
+
const template = {
|
|
151
|
+
title,
|
|
152
|
+
goal: [
|
|
153
|
+
goal,
|
|
154
|
+
manual ? `原手册(每次执行都适用):\n${manual}` : undefined,
|
|
155
|
+
verification ? `原检查要求:\n${verification}` : undefined,
|
|
156
|
+
]
|
|
157
|
+
.filter(Boolean)
|
|
158
|
+
.join("\n\n"),
|
|
159
|
+
dod: dod || "- [ ] 完成上述目标",
|
|
160
|
+
...(items.length > 0 ? { items } : {}),
|
|
113
161
|
};
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
if (legacy.outcome) {
|
|
118
|
-
fields.outcome = legacy.outcome;
|
|
119
|
-
fields.closedAt = legacy.closedAt ?? formatLocalTime(now);
|
|
120
|
-
fields.state = "done";
|
|
121
|
-
return { fields };
|
|
162
|
+
try {
|
|
163
|
+
validateTaskContractInput(template);
|
|
164
|
+
return { template };
|
|
122
165
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
by: control?.stop?.by === "governor" ? "runtime" : "user",
|
|
126
|
-
reason: control?.stop?.reason ?? "迁移前该任务已被停用。",
|
|
127
|
-
at: control?.stop?.at ?? formatLocalTime(now),
|
|
128
|
-
};
|
|
166
|
+
catch (error) {
|
|
167
|
+
return { reason: errorMessage(error) };
|
|
129
168
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
169
|
+
}
|
|
170
|
+
/** Write the event template for a recurring task; returns the event name, or why it could not be expressed. */
|
|
171
|
+
async function writeTemplateEvent(workspaceDir, channelId, id, body, schedule) {
|
|
172
|
+
const { template, reason } = buildTemplate(id, body);
|
|
173
|
+
if (!template)
|
|
174
|
+
return { reason };
|
|
175
|
+
const eventsDir = join(workspaceDir, "events");
|
|
176
|
+
await mkdir(eventsDir, { recursive: true });
|
|
177
|
+
let name = id;
|
|
178
|
+
if (existsSync(join(eventsDir, `${name}.json`)))
|
|
179
|
+
name = `${id}-task`;
|
|
180
|
+
if (existsSync(join(eventsDir, `${name}.json`)))
|
|
181
|
+
return { reason: `event ${name} already exists` };
|
|
182
|
+
const event = { type: "periodic", channelId, schedule, task: template };
|
|
183
|
+
await writeFileAtomically(join(eventsDir, `${name}.json`), `${JSON.stringify(event, null, 2)}\n`);
|
|
184
|
+
return { name };
|
|
185
|
+
}
|
|
186
|
+
/** `rm` that also treats "a parent is not a directory" as already gone. */
|
|
187
|
+
async function removeIfPresent(path) {
|
|
188
|
+
try {
|
|
189
|
+
await rm(path, { force: true });
|
|
138
190
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
fields.ticket = { kind: "time", at, by: at };
|
|
143
|
-
return { fields };
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (error.code !== "ENOTDIR")
|
|
193
|
+
throw error;
|
|
144
194
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
195
|
+
}
|
|
196
|
+
class TaskConversionError extends Error {
|
|
197
|
+
constructor(stage, cause, rollback) {
|
|
198
|
+
super(`${stage}: ${errorMessage(cause)} (rollback: ${rollback})`);
|
|
199
|
+
this.stage = stage;
|
|
200
|
+
this.cause = cause;
|
|
201
|
+
this.rollback = rollback;
|
|
152
202
|
}
|
|
153
|
-
return { fields };
|
|
154
203
|
}
|
|
155
|
-
/**
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
204
|
+
/**
|
|
205
|
+
* Copy `path` into `dir` as `<stem><ext>` without ever overwriting an existing file: an identical
|
|
206
|
+
* one counts as already backed up, a differing one is kept and this copy gets `<stem>.backup-<n><ext>`.
|
|
207
|
+
*/
|
|
208
|
+
async function copyWithoutOverwrite(dir, stem, ext, path, content) {
|
|
209
|
+
await mkdir(dir, { recursive: true });
|
|
210
|
+
for (let n = 0;; n++) {
|
|
211
|
+
const target = join(dir, n === 0 ? `${stem}${ext}` : `${stem}.backup-${n}${ext}`);
|
|
212
|
+
try {
|
|
213
|
+
await copyFile(path, target, constants.COPYFILE_EXCL);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
if (error.code !== "EEXIST")
|
|
218
|
+
throw error;
|
|
219
|
+
if ((await readFile(target, "utf-8")) === content)
|
|
220
|
+
return;
|
|
170
221
|
}
|
|
171
|
-
current.push(line);
|
|
172
|
-
}
|
|
173
|
-
if (current.length > 0)
|
|
174
|
-
entries.push(current.join("\n").trim());
|
|
175
|
-
const kept = entries.filter(Boolean);
|
|
176
|
-
for (const [index, entry] of kept.entries()) {
|
|
177
|
-
await appendTaskLog(channelDir, id, {
|
|
178
|
-
cycle: cycleId,
|
|
179
|
-
kind: "step",
|
|
180
|
-
seq: index + 1,
|
|
181
|
-
outcome: "continue",
|
|
182
|
-
note: entry,
|
|
183
|
-
tools: [],
|
|
184
|
-
});
|
|
185
222
|
}
|
|
186
|
-
return kept.length;
|
|
187
223
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
continue;
|
|
200
|
-
if (names[0] === "Current Cycle") {
|
|
201
|
-
const text = lines
|
|
202
|
-
.slice(bounds.headingIndex + 1, bounds.end)
|
|
203
|
-
.join("\n")
|
|
204
|
-
.trim();
|
|
205
|
-
if (text)
|
|
206
|
-
lastNote = text;
|
|
207
|
-
}
|
|
208
|
-
lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex);
|
|
209
|
-
working = lines.join("\n");
|
|
224
|
+
const backupOriginal = (backupDir, id, path, content) => copyWithoutOverwrite(backupDir, id, ".md", path, content);
|
|
225
|
+
/** `readdir` that treats only "no such directory" as empty; any other failure (EACCES, EIO, ...) must surface. */
|
|
226
|
+
async function listDirectory(dir) {
|
|
227
|
+
try {
|
|
228
|
+
return await readdir(dir);
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
const code = error.code;
|
|
232
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
233
|
+
return [];
|
|
234
|
+
throw error;
|
|
210
235
|
}
|
|
211
|
-
return { body: working.replace(/\n{3,}/g, "\n\n").trimEnd(), lastNote };
|
|
212
236
|
}
|
|
213
|
-
async function
|
|
237
|
+
async function convertOneTask(workspaceDir, channelId, channelDir, id, now) {
|
|
214
238
|
return withTaskMutation(channelDir, id, async () => {
|
|
215
239
|
const path = join(channelDir, "tasks", `${id}.md`);
|
|
216
240
|
const content = await readFile(path, "utf-8");
|
|
217
|
-
const
|
|
218
|
-
if (!
|
|
241
|
+
const v3 = parseV3Frontmatter(content);
|
|
242
|
+
if (!v3 || v3.v5 || v3.status === undefined)
|
|
219
243
|
return false;
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
244
|
+
let stage = "backup";
|
|
245
|
+
let createdEvent;
|
|
246
|
+
const logPath = join(channelDir, "tasks", `${id}.jsonl`);
|
|
247
|
+
const hadLog = existsSync(logPath);
|
|
248
|
+
try {
|
|
249
|
+
await backupOriginal(join(channelDir, "tasks", BACKUP_DIRNAME), id, path, content);
|
|
250
|
+
const original = taskBody(content);
|
|
251
|
+
const notes = [];
|
|
252
|
+
const stopped = v3.enabled === false || v3.stopped;
|
|
253
|
+
let origin;
|
|
254
|
+
let retire = false;
|
|
255
|
+
if (v3.schedule && stopped) {
|
|
256
|
+
// Event templates have no disabled state, so a stopped recurring task must not get one: it would start running.
|
|
257
|
+
notes.push(`转换到 v5:该周期任务在 v3 中已停用,未生成事件模板(原周期 ${v3.schedule} 未迁移),任务保持暂停;原件在 tasks/.v3/。要恢复周期执行,请人工核对后用 event_manage 新建模板。`);
|
|
258
|
+
}
|
|
259
|
+
else if (v3.schedule) {
|
|
260
|
+
stage = "template";
|
|
261
|
+
const written = await writeTemplateEvent(workspaceDir, channelId, id, original, v3.schedule);
|
|
262
|
+
if (written.name) {
|
|
263
|
+
createdEvent = join(workspaceDir, "events", `${written.name}.json`);
|
|
264
|
+
origin = written.name;
|
|
265
|
+
retire = v3.status === "sleeping";
|
|
266
|
+
notes.push(retire
|
|
267
|
+
? `转换到 v5:周期性已移到事件模板 ${written.name}(${v3.schedule}),每次触发会生成一个新的任务实例;本任务不再重复。`
|
|
268
|
+
: `转换到 v5:周期性已移到事件模板 ${written.name}(${v3.schedule})。本次正在进行的执行作为它的一个实例继续,下一次由事件生成。`);
|
|
269
|
+
}
|
|
270
|
+
else {
|
|
271
|
+
notes.push(`转换到 v5:无法把周期性转换为事件模板(${written.reason}),该任务已暂停,需要人工处理。`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const fields = { state: "open", origin, usage: createUsage(now) };
|
|
275
|
+
if (stopped || (v3.schedule && !origin)) {
|
|
276
|
+
fields.paused = {
|
|
277
|
+
by: stopped ? "user" : "runtime",
|
|
278
|
+
reason: stopped ? (v3.stopReason ?? DEFAULT_STOP_REASON) : "周期性无法转换为事件模板,需要人工处理。",
|
|
279
|
+
at: formatLocalTime(now),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
if (v3.status === "waiting") {
|
|
283
|
+
notes.push("转换到 v5:该任务此前在等待外部条件,v5 没有对应的等待来源,已改为 open。先核对真实状态,再决定继续还是重新停泊。");
|
|
284
|
+
}
|
|
285
|
+
stage = "task";
|
|
286
|
+
await writeStoredTask({ id, path, fields, body: convertBody(original) });
|
|
287
|
+
stage = "log";
|
|
288
|
+
for (const note of notes)
|
|
289
|
+
await appendTaskLog(channelDir, id, { kind: "note", note });
|
|
290
|
+
if (retire) {
|
|
291
|
+
stage = "archive";
|
|
292
|
+
await archiveTask(channelDir, id, "cancelled");
|
|
293
|
+
}
|
|
294
|
+
log.logInfo(`Task ${id} converted to v5`, `state=${fields.state}${fields.paused ? " paused" : ""}${origin ? ` origin=${origin}` : ""}${retire ? " (retired)" : ""}`);
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
// Leave nothing runnable behind: put the v3 original back and drop the artifacts this attempt created.
|
|
299
|
+
const failed = [];
|
|
300
|
+
const attempt = async (what, fn) => {
|
|
301
|
+
try {
|
|
302
|
+
await fn();
|
|
303
|
+
}
|
|
304
|
+
catch (rollbackError) {
|
|
305
|
+
failed.push(`${what}: ${errorMessage(rollbackError)}`);
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
if (stage !== "backup") {
|
|
309
|
+
// archiveTask undoes its own partial work. When that undo failed, archive-side files may be the
|
|
310
|
+
// only copy of the old logs: leave them (and the log) alone and report the rollback as failed.
|
|
311
|
+
if (error instanceof ArchiveUndoError)
|
|
312
|
+
failed.push(`rollback failed, archive undo incomplete: ${errorMessage(error)}`);
|
|
313
|
+
else if (!hadLog)
|
|
314
|
+
await attempt("remove log", () => removeIfPresent(logPath));
|
|
315
|
+
if (createdEvent) {
|
|
316
|
+
const eventFile = createdEvent;
|
|
317
|
+
await attempt("remove template event", () => removeIfPresent(eventFile));
|
|
318
|
+
}
|
|
319
|
+
await attempt("restore original", () => writeFileAtomically(path, content));
|
|
320
|
+
}
|
|
321
|
+
throw new TaskConversionError(stage, error, failed.length === 0 ? "ok" : failed.join("; "));
|
|
322
|
+
}
|
|
234
323
|
});
|
|
235
324
|
}
|
|
236
|
-
/**
|
|
237
|
-
|
|
325
|
+
/** Move task-owned sensor events (`task.<channelId>.<taskId>.<use>`) out of the way: v5 has no `signal` ticket. */
|
|
326
|
+
async function moveTaskOwnedEvents(workspaceDir, channelId, channelDir) {
|
|
327
|
+
const eventsDir = join(workspaceDir, "events");
|
|
328
|
+
const names = (await listDirectory(eventsDir)).filter((name) => name.endsWith(".json"));
|
|
329
|
+
const prefix = `task.${channelId}.`;
|
|
330
|
+
for (const name of names) {
|
|
331
|
+
if (!name.startsWith(prefix))
|
|
332
|
+
continue;
|
|
333
|
+
const rest = name.slice(prefix.length, -".json".length);
|
|
334
|
+
const lastDot = rest.lastIndexOf(".");
|
|
335
|
+
const ownerId = lastDot > 0 ? rest.slice(0, lastDot) : undefined;
|
|
336
|
+
const source = join(eventsDir, name);
|
|
337
|
+
// Copy (never overwriting a same-named backup), then remove the live file: if the removal
|
|
338
|
+
// fails the event is still in place and the retry finds an identical backup.
|
|
339
|
+
await copyWithoutOverwrite(join(channelDir, "tasks", BACKUP_DIRNAME, "events"), name.slice(0, -".json".length), ".json", source, await readFile(source, "utf-8"));
|
|
340
|
+
await rm(source);
|
|
341
|
+
if (ownerId && (await readStoredTask(channelDir, ownerId).catch(() => undefined))) {
|
|
342
|
+
await appendTaskLog(channelDir, ownerId, {
|
|
343
|
+
kind: "note",
|
|
344
|
+
note: `转换到 v5:传感器事件 ${name.slice(0, -".json".length)} 已移到 tasks/.v3/events/(v5 没有 signal 票);需要等待外部条件时,改用带超时的后台作业。`,
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Validate a failure report written by this module: a non-empty `failures` array whose entries
|
|
351
|
+
* carry string `channelId` / `stage` / `error` / `rollback` (and an optional string `task`).
|
|
352
|
+
* Anything else is untrustworthy and must block rather than count as "no failed rollback".
|
|
353
|
+
*/
|
|
354
|
+
function parseFailureReport(raw) {
|
|
355
|
+
const failures = parseJson(raw)?.failures;
|
|
356
|
+
if (!Array.isArray(failures) || failures.length === 0)
|
|
357
|
+
return undefined;
|
|
358
|
+
for (const entry of failures) {
|
|
359
|
+
if (!isPlainObject(entry))
|
|
360
|
+
return undefined;
|
|
361
|
+
for (const key of ["channelId", "stage", "error", "rollback"]) {
|
|
362
|
+
if (typeof entry[key] !== "string")
|
|
363
|
+
return undefined;
|
|
364
|
+
}
|
|
365
|
+
if (entry.task !== undefined && typeof entry.task !== "string")
|
|
366
|
+
return undefined;
|
|
367
|
+
}
|
|
368
|
+
return failures;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Convert every v3 task file in every known channel. Any failure leaves no marker, writes
|
|
372
|
+
* `state/task-migration-v5.failed.json`, and throws so the caller does not start services.
|
|
373
|
+
*/
|
|
374
|
+
export async function migrateTasksToV5(workspaceDir, stateDir) {
|
|
238
375
|
const markerPath = join(stateDir, MIGRATION_MARKER);
|
|
239
376
|
if (existsSync(markerPath))
|
|
240
377
|
return;
|
|
378
|
+
const reportPath = join(stateDir, FAILURE_REPORT);
|
|
379
|
+
if (existsSync(reportPath)) {
|
|
380
|
+
const blocked = (reason) => new Error(`v3 → v5 task conversion is blocked: ${reportPath} ${reason}. The report was kept and no marker was written. Inspect it, restore any listed originals from tasks/.v3/ or your backup, then delete the report.`);
|
|
381
|
+
let raw;
|
|
382
|
+
try {
|
|
383
|
+
raw = await readFile(reportPath, "utf-8");
|
|
384
|
+
}
|
|
385
|
+
catch (error) {
|
|
386
|
+
throw blocked(`could not be read (${errorMessage(error)})`);
|
|
387
|
+
}
|
|
388
|
+
const failures = parseFailureReport(raw);
|
|
389
|
+
if (!failures)
|
|
390
|
+
throw blocked("is not a valid failure report (unparseable or unexpected structure)");
|
|
391
|
+
if (failures.some((entry) => entry.rollback !== "ok"))
|
|
392
|
+
throw blocked("records a failed rollback");
|
|
393
|
+
}
|
|
241
394
|
const now = new Date();
|
|
242
|
-
let
|
|
243
|
-
|
|
395
|
+
let converted = 0;
|
|
396
|
+
const failures = [];
|
|
397
|
+
let channelIds = [];
|
|
398
|
+
try {
|
|
399
|
+
channelIds = await discoverTaskChannels(workspaceDir, [], { strict: true });
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
// An undiscoverable workspace is not an empty one: no task was looked at, so no marker.
|
|
403
|
+
log.logWarning("Channels of the workspace could not be discovered", errorMessage(error));
|
|
404
|
+
failures.push({ channelId: "*", stage: "discover", error: errorMessage(error), rollback: "ok" });
|
|
405
|
+
}
|
|
406
|
+
for (const channelId of channelIds) {
|
|
244
407
|
const channelDir = getChannelDir(workspaceDir, channelId);
|
|
245
|
-
let filenames;
|
|
408
|
+
let filenames = [];
|
|
246
409
|
try {
|
|
247
|
-
filenames = (await
|
|
410
|
+
filenames = (await listDirectory(join(channelDir, "tasks"))).filter((name) => name.endsWith(".md"));
|
|
248
411
|
}
|
|
249
|
-
catch {
|
|
250
|
-
|
|
412
|
+
catch (error) {
|
|
413
|
+
// An unreadable task directory is not an empty one: the originals were not looked at.
|
|
414
|
+
log.logWarning(`Tasks of ${channelId} could not be listed`, errorMessage(error));
|
|
415
|
+
failures.push({ channelId, stage: "scan", error: errorMessage(error), rollback: "ok" });
|
|
251
416
|
}
|
|
252
417
|
for (const filename of filenames) {
|
|
253
418
|
const id = filename.slice(0, -".md".length);
|
|
254
419
|
try {
|
|
255
|
-
if (await
|
|
256
|
-
|
|
420
|
+
if (await convertOneTask(workspaceDir, channelId, channelDir, normalizeTaskId(id), now))
|
|
421
|
+
converted++;
|
|
257
422
|
}
|
|
258
423
|
catch (error) {
|
|
259
|
-
log.logWarning(`Task ${id} could not be
|
|
424
|
+
log.logWarning(`Task ${id} could not be converted to v5`, errorMessage(error));
|
|
425
|
+
failures.push({
|
|
426
|
+
channelId,
|
|
427
|
+
task: id,
|
|
428
|
+
stage: error instanceof TaskConversionError ? error.stage : "scan",
|
|
429
|
+
error: errorMessage(error instanceof TaskConversionError ? error.cause : error),
|
|
430
|
+
rollback: error instanceof TaskConversionError ? error.rollback : "ok",
|
|
431
|
+
});
|
|
260
432
|
}
|
|
261
433
|
}
|
|
434
|
+
await moveTaskOwnedEvents(workspaceDir, channelId, channelDir).catch((error) => {
|
|
435
|
+
log.logWarning(`Task-owned events of ${channelId} could not be moved`, errorMessage(error));
|
|
436
|
+
failures.push({ channelId, stage: "events", error: errorMessage(error), rollback: "ok" });
|
|
437
|
+
});
|
|
262
438
|
}
|
|
263
439
|
await mkdir(stateDir, { recursive: true });
|
|
440
|
+
if (failures.length > 0) {
|
|
441
|
+
await writeFileAtomically(reportPath, `${JSON.stringify({ at: formatLocalTime(now), failures }, null, 2)}\n`);
|
|
442
|
+
throw new Error(`v3 → v5 task conversion failed for ${failures.length} item(s); services were not started and no marker was written. See ${reportPath}; fix the cause and restart to retry.`);
|
|
443
|
+
}
|
|
444
|
+
await rm(reportPath, { force: true });
|
|
264
445
|
await writeFile(markerPath, `${formatLocalTime(now)}\n`, "utf-8");
|
|
265
|
-
if (
|
|
266
|
-
log.logInfo("Task
|
|
446
|
+
if (converted > 0)
|
|
447
|
+
log.logInfo("Task conversion to v5 complete", `${converted} task(s)`);
|
|
267
448
|
}
|