@oyasmi/pipiclaw 0.9.3-beta.6 → 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/channel/channel-index.d.ts +9 -2
- package/dist/channel/channel-index.js +25 -6
- package/dist/runtime/bootstrap.js +3 -4
- package/dist/runtime/task-commands.js +1 -1
- package/dist/runtime/task-driver.d.ts +2 -1
- package/dist/runtime/task-driver.js +2 -2
- package/dist/runtime/task-migration.d.ts +7 -2
- package/dist/runtime/task-migration.js +227 -58
- package/dist/tasks/store.d.ts +18 -1
- package/dist/tasks/store.js +57 -7
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -22,7 +22,7 @@ In DingTalk daemon mode, external tasks keep running in the background after dis
|
|
|
22
22
|
|
|
23
23
|
### Work does not end when a conversation ends
|
|
24
24
|
|
|
25
|
-
Every channel has its own persistent conversation, long-term memory index, and daily journal.
|
|
25
|
+
Every channel has its own persistent conversation, long-term memory index, and daily journal. Each task is a one-off project with goals, done criteria, and work items in a Markdown contract, and steps, dispatches, and settlements in a JSONL loop log; the built-in task driver advances runnable tasks, redeems due time tickets, and handles ticket expiry. Scheduled and recurring work uses event templates to create an independent task instance per occurrence. The runtime stops with a notice when a budget, idle-loop, or repeated-expiry boundary is reached.
|
|
26
26
|
|
|
27
27
|
### Natively at home in DingTalk
|
|
28
28
|
|
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ Pipiclaw 同时支持两类委派:内置子智能体在进程内完成检索
|
|
|
22
22
|
|
|
23
23
|
### 工作不会随着一次对话结束
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
每个频道都有独立的持久会话、长期记忆索引和按天日志。任务是一次性项目,用 Markdown 保存目标、完成标准和工作项,用 JSONL 循环日志记录步骤、派发与结算;内建 task driver 推进可运行任务、兑现到期等待票并处理兜底超时,周期与定时工作由事件模板每次生成独立任务实例,预算耗尽、空转或连续无法兑现等待时会停止并告诉你。
|
|
26
26
|
|
|
27
27
|
### 原生工作在钉钉里
|
|
28
28
|
|
|
@@ -69,7 +69,14 @@ export declare function renderChannelIndex(entries: ChannelIndexEntry[]): string
|
|
|
69
69
|
*/
|
|
70
70
|
export declare function parseChannelIndex(content: string): ChannelIndexEntry[];
|
|
71
71
|
/** Channel ids recorded in the index, i.e. every channel that has ever received a message. */
|
|
72
|
-
export declare function readChannelIndexIds(workspaceDir: string): Promise<string[]>;
|
|
72
|
+
export declare function readChannelIndexIds(workspaceDir: string, options?: DiscoverOptions): Promise<string[]>;
|
|
73
|
+
export interface DiscoverOptions {
|
|
74
|
+
/**
|
|
75
|
+
* Throw on anything other than "does not exist" instead of reporting no channels. For the one-shot
|
|
76
|
+
* migration, where an unreadable workspace must not look like an empty one.
|
|
77
|
+
*/
|
|
78
|
+
strict?: boolean;
|
|
79
|
+
}
|
|
73
80
|
/**
|
|
74
81
|
* Every channel this workspace knows about, for the background workers that must visit
|
|
75
82
|
* channels nobody has spoken to since the process started (memory maintenance, the task
|
|
@@ -85,7 +92,7 @@ export declare function readChannelIndexIds(workspaceDir: string): Promise<strin
|
|
|
85
92
|
* name is the escaped form of an already-indexed id are skipped, so a channel is never visited
|
|
86
93
|
* twice under two spellings.
|
|
87
94
|
*/
|
|
88
|
-
export declare function discoverWorkspaceChannelIds(workspaceDir: string): Promise<string[]>;
|
|
95
|
+
export declare function discoverWorkspaceChannelIds(workspaceDir: string, options?: DiscoverOptions): Promise<string[]>;
|
|
89
96
|
export interface CreateChannelIndexOptions {
|
|
90
97
|
workspaceDir: string;
|
|
91
98
|
/** Override the timestamp-only debounce; tests use a short one. */
|
|
@@ -140,17 +140,23 @@ export function parseChannelIndex(content) {
|
|
|
140
140
|
}
|
|
141
141
|
// === Discovery ===
|
|
142
142
|
/** Channel ids recorded in the index, i.e. every channel that has ever received a message. */
|
|
143
|
-
export async function readChannelIndexIds(workspaceDir) {
|
|
143
|
+
export async function readChannelIndexIds(workspaceDir, options = {}) {
|
|
144
144
|
try {
|
|
145
145
|
const content = await readFile(join(workspaceDir, CHANNELS_INDEX_FILENAME), "utf-8");
|
|
146
146
|
return parseChannelIndex(content)
|
|
147
147
|
.map((entry) => entry.channelId)
|
|
148
148
|
.filter(isChannelId);
|
|
149
149
|
}
|
|
150
|
-
catch {
|
|
150
|
+
catch (error) {
|
|
151
|
+
if (options.strict && !isMissing(error))
|
|
152
|
+
throw error;
|
|
151
153
|
return [];
|
|
152
154
|
}
|
|
153
155
|
}
|
|
156
|
+
function isMissing(error) {
|
|
157
|
+
const code = error.code;
|
|
158
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
159
|
+
}
|
|
154
160
|
/**
|
|
155
161
|
* Every channel this workspace knows about, for the background workers that must visit
|
|
156
162
|
* channels nobody has spoken to since the process started (memory maintenance, the task
|
|
@@ -166,19 +172,32 @@ export async function readChannelIndexIds(workspaceDir) {
|
|
|
166
172
|
* name is the escaped form of an already-indexed id are skipped, so a channel is never visited
|
|
167
173
|
* twice under two spellings.
|
|
168
174
|
*/
|
|
169
|
-
export async function discoverWorkspaceChannelIds(workspaceDir) {
|
|
170
|
-
const channelIds = new Set(await readChannelIndexIds(workspaceDir));
|
|
175
|
+
export async function discoverWorkspaceChannelIds(workspaceDir, options = {}) {
|
|
176
|
+
const channelIds = new Set(await readChannelIndexIds(workspaceDir, options));
|
|
171
177
|
const indexedDirNames = new Set([...channelIds].map(getChannelDirName));
|
|
172
178
|
try {
|
|
173
179
|
const dirents = await readdir(workspaceDir, { withFileTypes: true });
|
|
174
180
|
for (const entry of dirents) {
|
|
181
|
+
// A directory id containing `__` may be an escaped group id (`/` → `__`). The
|
|
182
|
+
// workspace scan cannot recover the original id, which is required in task event
|
|
183
|
+
// templates. Background discovery keeps its historical best-effort behavior; a
|
|
184
|
+
// one-shot migration must stop instead of writing events to a fake channel id.
|
|
185
|
+
if (options.strict &&
|
|
186
|
+
entry.isDirectory() &&
|
|
187
|
+
/^(dm|group)_/.test(entry.name) &&
|
|
188
|
+
entry.name.includes("__") &&
|
|
189
|
+
!indexedDirNames.has(entry.name)) {
|
|
190
|
+
throw new Error(`Cannot recover the real channel id for escaped workspace directory ${entry.name}; restore ${CHANNELS_INDEX_FILENAME} from backup before migration.`);
|
|
191
|
+
}
|
|
175
192
|
if (!entry.isDirectory() || indexedDirNames.has(entry.name) || !isChannelId(entry.name))
|
|
176
193
|
continue;
|
|
177
194
|
channelIds.add(entry.name);
|
|
178
195
|
}
|
|
179
196
|
}
|
|
180
|
-
catch {
|
|
181
|
-
//
|
|
197
|
+
catch (error) {
|
|
198
|
+
// Outside strict mode a missing or unreadable workspace simply has no channels to report.
|
|
199
|
+
if (options.strict && !isMissing(error))
|
|
200
|
+
throw error;
|
|
182
201
|
}
|
|
183
202
|
return [...channelIds].sort();
|
|
184
203
|
}
|
|
@@ -910,12 +910,11 @@ export async function createRuntimeContext(options) {
|
|
|
910
910
|
});
|
|
911
911
|
}
|
|
912
912
|
if (startServices) {
|
|
913
|
-
// Convert
|
|
913
|
+
// Convert supported v3 task files and their schedules (v4 beta files are skipped) before services rely
|
|
914
914
|
// on the v5 layout (spec 052, D12). Marker-gated and awaited: the pass writes event
|
|
915
915
|
// templates the watcher is about to load, so the services must not start underneath it.
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
});
|
|
916
|
+
// A failed or partial conversion throws and aborts startup: nothing may run on half-migrated state.
|
|
917
|
+
await migrateTasksToV5(options.paths.workspaceDir, join(options.paths.appHomeDir, "state"));
|
|
919
918
|
eventsWatcher.start();
|
|
920
919
|
memoryMaintenanceScheduler.start();
|
|
921
920
|
taskDriver.start();
|
|
@@ -266,7 +266,7 @@ async function doctor(options) {
|
|
|
266
266
|
continue;
|
|
267
267
|
}
|
|
268
268
|
if (entry.legacy) {
|
|
269
|
-
problems.push(issue(`${entry.id} 仍含旧版本的字段(
|
|
269
|
+
problems.push(issue(`${entry.id} 仍含旧版本的字段(status / enabled / control / wake / schedule)`, "保留原件,按 docs/events-and-tasks.md 的升级步骤处理;不要仅删旧字段"));
|
|
270
270
|
}
|
|
271
271
|
const by = entry.fields.ticket ? parseLocalTime(entry.fields.ticket.by) : undefined;
|
|
272
272
|
if (entry.expired && !entry.fields.paused && by !== undefined && by < now - EXPIRED_GRACE_MS) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
2
|
+
import { type DiscoverOptions } from "../channel/channel-index.js";
|
|
2
3
|
import { type PipiclawTaskDriverSettings } from "../settings.js";
|
|
3
4
|
import { type TaskLedgerEntry } from "../tasks/ledger.js";
|
|
4
5
|
export interface TaskDriverOptions {
|
|
@@ -21,7 +22,7 @@ export interface TaskDriverOptions {
|
|
|
21
22
|
* Channels this driver should scan. Live ids come first so a channel discovered on disk under
|
|
22
23
|
* its escaped directory name never displaces the real id the runner map already knows.
|
|
23
24
|
*/
|
|
24
|
-
export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string
|
|
25
|
+
export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>, options?: DiscoverOptions): Promise<string[]>;
|
|
25
26
|
/** The task a `[TASK_DRIVER:<id>]` dispatch text names, if it is one. */
|
|
26
27
|
export declare function parseDriverTaskId(text: string | undefined): string | undefined;
|
|
27
28
|
export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): ChannelEvent;
|
|
@@ -20,10 +20,10 @@ const REDISPATCH_GUARD_MS = 30_000;
|
|
|
20
20
|
* Channels this driver should scan. Live ids come first so a channel discovered on disk under
|
|
21
21
|
* its escaped directory name never displaces the real id the runner map already knows.
|
|
22
22
|
*/
|
|
23
|
-
export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
|
|
23
|
+
export async function discoverTaskChannels(workspaceDir, knownChannelIds = [], options = {}) {
|
|
24
24
|
return dedupeChannelIdsByDirectory([
|
|
25
25
|
...[...knownChannelIds].filter(isChannelId),
|
|
26
|
-
...(await discoverWorkspaceChannelIds(workspaceDir)),
|
|
26
|
+
...(await discoverWorkspaceChannelIds(workspaceDir, options)),
|
|
27
27
|
]);
|
|
28
28
|
}
|
|
29
29
|
function attemptKey(channelId, taskId) {
|
|
@@ -3,7 +3,9 @@ interface V3Fields {
|
|
|
3
3
|
enabled?: boolean;
|
|
4
4
|
schedule?: string;
|
|
5
5
|
stopReason?: string;
|
|
6
|
-
/**
|
|
6
|
+
/** `control.stop` is present (with or without a usable reason). */
|
|
7
|
+
stopped: boolean;
|
|
8
|
+
/** A state key is present: skip this file, whether v4 or v5. */
|
|
7
9
|
v5: boolean;
|
|
8
10
|
}
|
|
9
11
|
/** Minimal reader for the v3 frontmatter block; the only place that still understands it. */
|
|
@@ -20,6 +22,9 @@ interface TemplateOutcome {
|
|
|
20
22
|
* exactly what the template exists to keep), and every checkbox is reset.
|
|
21
23
|
*/
|
|
22
24
|
export declare function buildTemplate(id: string, body: string): TemplateOutcome;
|
|
23
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* Convert every v3 task file in every known channel. Any failure leaves no marker, writes
|
|
27
|
+
* `state/task-migration-v5.failed.json`, and throws so the caller does not start services.
|
|
28
|
+
*/
|
|
24
29
|
export declare function migrateTasksToV5(workspaceDir: string, stateDir: string): Promise<void>;
|
|
25
30
|
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { existsSync } from "node:fs";
|
|
2
|
-
import { copyFile, mkdir, readdir, readFile,
|
|
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";
|
|
@@ -12,7 +12,7 @@ import { validateTaskContractInput } from "../tasks/contract-input.js";
|
|
|
12
12
|
import { extractTaskTitle, findTaskSectionBounds, normalizeTaskId, parseTaskItems, taskBody } from "../tasks/ledger.js";
|
|
13
13
|
import { appendTaskLog } from "../tasks/log.js";
|
|
14
14
|
import { withTaskMutation } from "../tasks/mutation-lock.js";
|
|
15
|
-
import { archiveTask, readStoredTask, writeStoredTask } from "../tasks/store.js";
|
|
15
|
+
import { ArchiveUndoError, archiveTask, readStoredTask, writeStoredTask } from "../tasks/store.js";
|
|
16
16
|
import { discoverTaskChannels } from "./task-driver.js";
|
|
17
17
|
/**
|
|
18
18
|
* One-time, deterministic, no-LLM conversion of v3 task files (0.9.2: `status` / `enabled` /
|
|
@@ -25,12 +25,26 @@ import { discoverTaskChannels } from "./task-driver.js";
|
|
|
25
25
|
* flight finish as an instance of the event.
|
|
26
26
|
* - **Nothing is parked.** v3 waits (`wake`, `waitingFor`) have no v5 equivalent; the task is
|
|
27
27
|
* reopened, and `enabled: false` / `control.stop` become a pause, so a disabled task never
|
|
28
|
-
* starts running because of the upgrade.
|
|
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.
|
|
29
30
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
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.
|
|
32
44
|
*/
|
|
33
45
|
const MIGRATION_MARKER = "task-migration-v5.done";
|
|
46
|
+
const FAILURE_REPORT = "task-migration-v5.failed.json";
|
|
47
|
+
const DEFAULT_STOP_REASON = "v3 中已停用。";
|
|
34
48
|
const BACKUP_DIRNAME = ".v3";
|
|
35
49
|
const ITEMS_NAMES = ["Plan", "计划"];
|
|
36
50
|
/** v3 per-cycle bookkeeping; v5 keeps this in the loop log instead of the contract. */
|
|
@@ -51,7 +65,7 @@ export function parseV3Frontmatter(content) {
|
|
|
51
65
|
const end = content.indexOf("\n---", 3);
|
|
52
66
|
if (end === -1)
|
|
53
67
|
return undefined;
|
|
54
|
-
const fields = { v5: false };
|
|
68
|
+
const fields = { v5: false, stopped: false };
|
|
55
69
|
for (const line of content.slice(3, end).split("\n")) {
|
|
56
70
|
const idx = line.indexOf(":");
|
|
57
71
|
if (idx === -1)
|
|
@@ -73,8 +87,11 @@ export function parseV3Frontmatter(content) {
|
|
|
73
87
|
break;
|
|
74
88
|
case "control": {
|
|
75
89
|
const stop = parseJson(value)?.stop;
|
|
76
|
-
if (isPlainObject(stop)
|
|
77
|
-
fields.
|
|
90
|
+
if (isPlainObject(stop)) {
|
|
91
|
+
fields.stopped = true;
|
|
92
|
+
if (typeof stop.reason === "string" && stop.reason.trim())
|
|
93
|
+
fields.stopReason = stop.reason.trim();
|
|
94
|
+
}
|
|
78
95
|
break;
|
|
79
96
|
}
|
|
80
97
|
default:
|
|
@@ -166,6 +183,57 @@ async function writeTemplateEvent(workspaceDir, channelId, id, body, schedule) {
|
|
|
166
183
|
await writeFileAtomically(join(eventsDir, `${name}.json`), `${JSON.stringify(event, null, 2)}\n`);
|
|
167
184
|
return { name };
|
|
168
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 });
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (error.code !== "ENOTDIR")
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
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;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
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;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
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;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
169
237
|
async function convertOneTask(workspaceDir, channelId, channelDir, id, now) {
|
|
170
238
|
return withTaskMutation(channelDir, id, async () => {
|
|
171
239
|
const path = join(channelDir, "tasks", `${id}.md`);
|
|
@@ -173,57 +241,91 @@ async function convertOneTask(workspaceDir, channelId, channelDir, id, now) {
|
|
|
173
241
|
const v3 = parseV3Frontmatter(content);
|
|
174
242
|
if (!v3 || v3.v5 || v3.status === undefined)
|
|
175
243
|
return false;
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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。先核对真实状态,再决定继续还是重新停泊。");
|
|
191
284
|
}
|
|
192
|
-
|
|
193
|
-
|
|
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");
|
|
194
293
|
}
|
|
294
|
+
log.logInfo(`Task ${id} converted to v5`, `state=${fields.state}${fields.paused ? " paused" : ""}${origin ? ` origin=${origin}` : ""}${retire ? " (retired)" : ""}`);
|
|
295
|
+
return true;
|
|
195
296
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
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
|
+
}
|
|
203
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("; "));
|
|
204
322
|
}
|
|
205
|
-
if (v3.status === "waiting") {
|
|
206
|
-
notes.push("转换到 v5:该任务此前在等待外部条件,v5 没有对应的等待来源,已改为 open。先核对真实状态,再决定继续还是重新停泊。");
|
|
207
|
-
}
|
|
208
|
-
await writeStoredTask({ id, path, fields, body: convertBody(original) });
|
|
209
|
-
for (const note of notes)
|
|
210
|
-
await appendTaskLog(channelDir, id, { kind: "note", note });
|
|
211
|
-
if (retire)
|
|
212
|
-
await archiveTask(channelDir, id, "cancelled");
|
|
213
|
-
log.logInfo(`Task ${id} converted to v5`, `state=${fields.state}${fields.paused ? " paused" : ""}${origin ? ` origin=${origin}` : ""}${retire ? " (retired)" : ""}`);
|
|
214
|
-
return true;
|
|
215
323
|
});
|
|
216
324
|
}
|
|
217
325
|
/** Move task-owned sensor events (`task.<channelId>.<taskId>.<use>`) out of the way: v5 has no `signal` ticket. */
|
|
218
326
|
async function moveTaskOwnedEvents(workspaceDir, channelId, channelDir) {
|
|
219
327
|
const eventsDir = join(workspaceDir, "events");
|
|
220
|
-
|
|
221
|
-
try {
|
|
222
|
-
names = (await readdir(eventsDir)).filter((name) => name.endsWith(".json"));
|
|
223
|
-
}
|
|
224
|
-
catch {
|
|
225
|
-
return;
|
|
226
|
-
}
|
|
328
|
+
const names = (await listDirectory(eventsDir)).filter((name) => name.endsWith(".json"));
|
|
227
329
|
const prefix = `task.${channelId}.`;
|
|
228
330
|
for (const name of names) {
|
|
229
331
|
if (!name.startsWith(prefix))
|
|
@@ -231,9 +333,11 @@ async function moveTaskOwnedEvents(workspaceDir, channelId, channelDir) {
|
|
|
231
333
|
const rest = name.slice(prefix.length, -".json".length);
|
|
232
334
|
const lastDot = rest.lastIndexOf(".");
|
|
233
335
|
const ownerId = lastDot > 0 ? rest.slice(0, lastDot) : undefined;
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
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);
|
|
237
341
|
if (ownerId && (await readStoredTask(channelDir, ownerId).catch(() => undefined))) {
|
|
238
342
|
await appendTaskLog(channelDir, ownerId, {
|
|
239
343
|
kind: "note",
|
|
@@ -242,21 +346,73 @@ async function moveTaskOwnedEvents(workspaceDir, channelId, channelDir) {
|
|
|
242
346
|
}
|
|
243
347
|
}
|
|
244
348
|
}
|
|
245
|
-
/**
|
|
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
|
+
*/
|
|
246
374
|
export async function migrateTasksToV5(workspaceDir, stateDir) {
|
|
247
375
|
const markerPath = join(stateDir, MIGRATION_MARKER);
|
|
248
376
|
if (existsSync(markerPath))
|
|
249
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
|
+
}
|
|
250
394
|
const now = new Date();
|
|
251
395
|
let converted = 0;
|
|
252
|
-
|
|
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) {
|
|
253
407
|
const channelDir = getChannelDir(workspaceDir, channelId);
|
|
254
408
|
let filenames = [];
|
|
255
409
|
try {
|
|
256
|
-
filenames = (await
|
|
410
|
+
filenames = (await listDirectory(join(channelDir, "tasks"))).filter((name) => name.endsWith(".md"));
|
|
257
411
|
}
|
|
258
|
-
catch {
|
|
259
|
-
//
|
|
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" });
|
|
260
416
|
}
|
|
261
417
|
for (const filename of filenames) {
|
|
262
418
|
const id = filename.slice(0, -".md".length);
|
|
@@ -266,13 +422,26 @@ export async function migrateTasksToV5(workspaceDir, stateDir) {
|
|
|
266
422
|
}
|
|
267
423
|
catch (error) {
|
|
268
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
|
+
});
|
|
269
432
|
}
|
|
270
433
|
}
|
|
271
434
|
await moveTaskOwnedEvents(workspaceDir, channelId, channelDir).catch((error) => {
|
|
272
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" });
|
|
273
437
|
});
|
|
274
438
|
}
|
|
275
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 });
|
|
276
445
|
await writeFile(markerPath, `${formatLocalTime(now)}\n`, "utf-8");
|
|
277
446
|
if (converted > 0)
|
|
278
447
|
log.logInfo("Task conversion to v5 complete", `${converted} task(s)`);
|
package/dist/tasks/store.d.ts
CHANGED
|
@@ -59,5 +59,22 @@ export declare function expireTicket(channelDir: string, id: string, limit?: num
|
|
|
59
59
|
outcome: TicketExpiryOutcome;
|
|
60
60
|
ticket: string;
|
|
61
61
|
} | undefined>;
|
|
62
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* `archiveTask` failed and could not fully put things back: `stranded` lists files that now live
|
|
64
|
+
* only at the archive path (`<archive path> -> <original path>`), plus any archive contract it
|
|
65
|
+
* could not remove. Callers must not delete anything archive-side on seeing this.
|
|
66
|
+
*/
|
|
67
|
+
export declare class ArchiveUndoError extends Error {
|
|
68
|
+
readonly cause: unknown;
|
|
69
|
+
readonly stranded: string[];
|
|
70
|
+
readonly undoFailures: string[];
|
|
71
|
+
constructor(cause: unknown, stranded: string[], undoFailures: string[]);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Move a closed task (and its log) into `tasks/archive/`. It never overwrites an existing archive
|
|
75
|
+
* entry (it throws before touching anything), and any failure after the first write undoes what it
|
|
76
|
+
* did so the task stays fully active: a caller can trust "resolved" to mean the contract and every
|
|
77
|
+
* log shard are in the archive, and "rejected" to mean the pre-call state still stands (or, if the
|
|
78
|
+
* undo itself failed, the error says so).
|
|
79
|
+
*/
|
|
63
80
|
export declare function archiveTask(channelDir: string, id: string, outcome: TaskArchiveOutcome): Promise<void>;
|
package/dist/tasks/store.js
CHANGED
|
@@ -4,6 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import * as log from "../log.js";
|
|
5
5
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
6
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
7
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
7
8
|
import { createUsage } from "./budget.js";
|
|
8
9
|
import { normalizeTaskFrontmatter, parseTaskFrontmatter, } from "./frontmatter.js";
|
|
9
10
|
import { normalizeTaskId, renderTaskDocument, taskBody } from "./ledger.js";
|
|
@@ -149,7 +150,27 @@ export async function expireTicket(channelDir, id, limit = 2) {
|
|
|
149
150
|
});
|
|
150
151
|
return { document, outcome, ticket: summary };
|
|
151
152
|
}
|
|
152
|
-
|
|
153
|
+
const LOG_SUFFIXES = ["", ".1", ".2"];
|
|
154
|
+
/**
|
|
155
|
+
* `archiveTask` failed and could not fully put things back: `stranded` lists files that now live
|
|
156
|
+
* only at the archive path (`<archive path> -> <original path>`), plus any archive contract it
|
|
157
|
+
* could not remove. Callers must not delete anything archive-side on seeing this.
|
|
158
|
+
*/
|
|
159
|
+
export class ArchiveUndoError extends Error {
|
|
160
|
+
constructor(cause, stranded, undoFailures) {
|
|
161
|
+
super(`${errorMessage(cause)} (undo of partial archive failed: ${undoFailures.join("; ")}${stranded.length > 0 ? `; still at archive path, move back by hand: ${stranded.join(", ")}` : ""})`);
|
|
162
|
+
this.cause = cause;
|
|
163
|
+
this.stranded = stranded;
|
|
164
|
+
this.undoFailures = undoFailures;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Move a closed task (and its log) into `tasks/archive/`. It never overwrites an existing archive
|
|
169
|
+
* entry (it throws before touching anything), and any failure after the first write undoes what it
|
|
170
|
+
* did so the task stays fully active: a caller can trust "resolved" to mean the contract and every
|
|
171
|
+
* log shard are in the archive, and "rejected" to mean the pre-call state still stands (or, if the
|
|
172
|
+
* undo itself failed, the error says so).
|
|
173
|
+
*/
|
|
153
174
|
export async function archiveTask(channelDir, id, outcome) {
|
|
154
175
|
const normalized = normalizeTaskId(id);
|
|
155
176
|
const archiveDir = join(tasksDir(channelDir), "archive");
|
|
@@ -157,19 +178,48 @@ export async function archiveTask(channelDir, id, outcome) {
|
|
|
157
178
|
const document = await readStoredTask(channelDir, normalized);
|
|
158
179
|
if (!document)
|
|
159
180
|
return;
|
|
181
|
+
const archiveMd = archivedTaskPath(channelDir, normalized);
|
|
182
|
+
const archiveLog = join(archiveDir, `${normalized}.jsonl`);
|
|
183
|
+
for (const target of [archiveMd, ...LOG_SUFFIXES.map((suffix) => `${archiveLog}${suffix}`)]) {
|
|
184
|
+
if (existsSync(target))
|
|
185
|
+
throw new Error(`archive entry already exists, refusing to overwrite: ${target}`);
|
|
186
|
+
}
|
|
160
187
|
document.fields.outcome = outcome;
|
|
161
188
|
document.fields.closedAt = formatLocalTime();
|
|
162
|
-
await writeStoredTask({ ...document, path: archivedTaskPath(channelDir, normalized) });
|
|
163
|
-
await rm(taskPath(channelDir, normalized), { force: true });
|
|
164
189
|
// The loop log travels with its contract so an archived task stays inspectable — including
|
|
165
190
|
// whatever has already rotated into `.1`/`.2` (R9). Moving only the current file stranded
|
|
166
191
|
// those shards in the now-empty active `tasks/` dir, permanently split from the record they
|
|
167
192
|
// belong to and outside anywhere `readTaskLog` looks for an archived task.
|
|
168
193
|
const logFrom = taskLogPath(channelDir, normalized);
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
194
|
+
const movedLogs = [];
|
|
195
|
+
let wroteArchive = false;
|
|
196
|
+
try {
|
|
197
|
+
for (const suffix of LOG_SUFFIXES) {
|
|
198
|
+
const from = `${logFrom}${suffix}`;
|
|
199
|
+
if (!existsSync(from))
|
|
200
|
+
continue;
|
|
201
|
+
const to = `${archiveLog}${suffix}`;
|
|
202
|
+
await rename(from, to);
|
|
203
|
+
movedLogs.push([from, to]);
|
|
204
|
+
}
|
|
205
|
+
await writeStoredTask({ ...document, path: archiveMd });
|
|
206
|
+
wroteArchive = true;
|
|
207
|
+
await rm(taskPath(channelDir, normalized), { force: true });
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
const undoFailures = [];
|
|
211
|
+
if (wroteArchive || existsSync(archiveMd)) {
|
|
212
|
+
await rm(archiveMd, { force: true }).catch((e) => undoFailures.push(errorMessage(e)));
|
|
213
|
+
}
|
|
214
|
+
const stranded = [];
|
|
215
|
+
for (const [from, to] of movedLogs.reverse()) {
|
|
216
|
+
await rename(to, from).catch((e) => {
|
|
217
|
+
undoFailures.push(errorMessage(e));
|
|
218
|
+
stranded.push(`${to} -> ${from}`);
|
|
219
|
+
});
|
|
173
220
|
}
|
|
221
|
+
if (undoFailures.length > 0)
|
|
222
|
+
throw new ArchiveUndoError(error, stranded, undoFailures);
|
|
223
|
+
throw error;
|
|
174
224
|
}
|
|
175
225
|
}
|
package/package.json
CHANGED