@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +2 -0
  3. package/dist/agent/channel-runner.d.ts +43 -2
  4. package/dist/agent/channel-runner.js +135 -75
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +14 -0
  40. package/dist/memory/render.js +28 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/playbooks/agent-delegation.md +4 -2
  54. package/dist/playbooks/background-jobs.md +1 -1
  55. package/dist/playbooks/event-scheduling.md +6 -2
  56. package/dist/playbooks/memory-and-learning.md +18 -11
  57. package/dist/playbooks/outbound-media.md +1 -1
  58. package/dist/playbooks/runtime-orientation.md +9 -8
  59. package/dist/playbooks/task-loop.md +88 -0
  60. package/dist/runtime/bootstrap.d.ts +3 -3
  61. package/dist/runtime/bootstrap.js +66 -41
  62. package/dist/runtime/events.d.ts +9 -0
  63. package/dist/runtime/events.js +43 -4
  64. package/dist/runtime/task-commands.d.ts +14 -15
  65. package/dist/runtime/task-commands.js +249 -485
  66. package/dist/runtime/task-driver.d.ts +41 -29
  67. package/dist/runtime/task-driver.js +170 -317
  68. package/dist/runtime/task-migration.d.ts +34 -30
  69. package/dist/runtime/task-migration.js +229 -183
  70. package/dist/runtime/task-wake.d.ts +6 -3
  71. package/dist/runtime/task-wake.js +26 -19
  72. package/dist/settings.d.ts +0 -29
  73. package/dist/settings.js +12 -35
  74. package/dist/shared/markdown-sections.d.ts +0 -1
  75. package/dist/shared/markdown-sections.js +0 -3
  76. package/dist/subagents/discovery.d.ts +2 -2
  77. package/dist/subagents/discovery.js +21 -10
  78. package/dist/subagents/external/progress-tail.js +6 -1
  79. package/dist/subagents/external/run.js +1 -0
  80. package/dist/subagents/runs.d.ts +19 -2
  81. package/dist/subagents/runs.js +73 -4
  82. package/dist/subagents/tool.d.ts +10 -8
  83. package/dist/subagents/tool.js +55 -94
  84. package/dist/tasks/brief.d.ts +17 -0
  85. package/dist/tasks/brief.js +57 -0
  86. package/dist/tasks/budget.d.ts +26 -0
  87. package/dist/tasks/budget.js +59 -0
  88. package/dist/tasks/cycle.d.ts +48 -0
  89. package/dist/tasks/cycle.js +94 -0
  90. package/dist/tasks/frontmatter.d.ts +73 -0
  91. package/dist/tasks/frontmatter.js +175 -0
  92. package/dist/tasks/ledger.d.ts +66 -106
  93. package/dist/tasks/ledger.js +90 -546
  94. package/dist/tasks/log.d.ts +88 -0
  95. package/dist/tasks/log.js +97 -0
  96. package/dist/tasks/rounds.d.ts +43 -0
  97. package/dist/tasks/rounds.js +57 -0
  98. package/dist/tasks/session-path.d.ts +9 -0
  99. package/dist/tasks/session-path.js +16 -0
  100. package/dist/tasks/steer.d.ts +8 -0
  101. package/dist/tasks/steer.js +79 -0
  102. package/dist/tasks/store.d.ts +60 -35
  103. package/dist/tasks/store.js +166 -107
  104. package/dist/tasks/ticket.d.ts +102 -0
  105. package/dist/tasks/ticket.js +209 -0
  106. package/dist/tasks/verification.d.ts +16 -0
  107. package/dist/tasks/verification.js +40 -1
  108. package/dist/tools/index.d.ts +13 -4
  109. package/dist/tools/index.js +5 -10
  110. package/dist/tools/memory-manage.d.ts +6 -16
  111. package/dist/tools/memory-manage.js +108 -129
  112. package/dist/tools/presentation.js +2 -1
  113. package/dist/tools/registry.d.ts +11 -2
  114. package/dist/tools/registry.js +17 -6
  115. package/dist/tools/subagent-manage.d.ts +0 -9
  116. package/dist/tools/subagent-manage.js +8 -17
  117. package/dist/tools/task-manage/create.js +2 -2
  118. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  119. package/dist/tools/task-manage/lifecycle.js +139 -187
  120. package/dist/tools/task-manage/log-view.d.ts +8 -0
  121. package/dist/tools/task-manage/log-view.js +24 -0
  122. package/dist/tools/task-manage/schema.d.ts +38 -14
  123. package/dist/tools/task-manage/schema.js +46 -27
  124. package/dist/tools/task-manage/shared.d.ts +24 -31
  125. package/dist/tools/task-manage/shared.js +103 -141
  126. package/dist/tools/task-manage/step-end.d.ts +11 -0
  127. package/dist/tools/task-manage/step-end.js +136 -0
  128. package/dist/tools/task-manage/types.d.ts +23 -32
  129. package/dist/tools/task-manage.d.ts +4 -3
  130. package/dist/tools/task-manage.js +30 -15
  131. package/dist/tools/tool-details.d.ts +1 -1
  132. package/dist/tui/app.js +0 -2
  133. package/package.json +1 -1
  134. package/dist/agent/effect-ledger.d.ts +0 -32
  135. package/dist/agent/effect-ledger.js +0 -89
  136. package/dist/memory/bootstrap.d.ts +0 -17
  137. package/dist/memory/bootstrap.js +0 -120
  138. package/dist/memory/candidates.d.ts +0 -26
  139. package/dist/memory/candidates.js +0 -202
  140. package/dist/memory/consolidation.d.ts +0 -54
  141. package/dist/memory/consolidation.js +0 -292
  142. package/dist/memory/extraction.d.ts +0 -54
  143. package/dist/memory/extraction.js +0 -240
  144. package/dist/memory/files.d.ts +0 -71
  145. package/dist/memory/files.js +0 -419
  146. package/dist/memory/maintenance-jobs.d.ts +0 -41
  147. package/dist/memory/maintenance-jobs.js +0 -265
  148. package/dist/memory/metadata.d.ts +0 -57
  149. package/dist/memory/metadata.js +0 -142
  150. package/dist/memory/probation.d.ts +0 -17
  151. package/dist/memory/probation.js +0 -44
  152. package/dist/memory/promotion.d.ts +0 -38
  153. package/dist/memory/promotion.js +0 -36
  154. package/dist/memory/recall.d.ts +0 -59
  155. package/dist/memory/recall.js +0 -746
  156. package/dist/memory/session.d.ts +0 -24
  157. package/dist/memory/session.js +0 -273
  158. package/dist/playbooks/task-driving.md +0 -92
  159. package/dist/playbooks/task-planning.md +0 -58
  160. package/dist/tasks/control.d.ts +0 -56
  161. package/dist/tasks/control.js +0 -169
  162. package/dist/tasks/transitions.d.ts +0 -16
  163. package/dist/tasks/transitions.js +0 -48
  164. package/dist/tools/task-manage/verification.d.ts +0 -19
  165. package/dist/tools/task-manage/verification.js +0 -91
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The task's append-only loop log (spec 051, D5) — `tasks/<id>.jsonl`.
3
+ *
4
+ * v3 kept this history inline in the task file under `## History`, capped at 24 KB / 8 entries.
5
+ * Both long-lived tasks on the author's machine sat permanently *at* that cap: 79% of a 30 KB
6
+ * task file was closed cycles the model re-read on every single wake and never acted on. Moving
7
+ * it here keeps the contract small enough to inject whole (INV-6) while making the history
8
+ * *longer*, not shorter — nothing is folded away any more.
9
+ *
10
+ * The log is append-only and is never rewritten; the contract's `## 上次结果` is a projection of
11
+ * its latest `close`, not a replacement for it.
12
+ */
13
+ export type TaskStepOutcome = "continue" | "park" | "done" | "blocked";
14
+ export interface TaskStepRecord {
15
+ ts: string;
16
+ cycle: string;
17
+ kind: "step";
18
+ seq: number;
19
+ outcome: TaskStepOutcome;
20
+ note: string;
21
+ tools: string[];
22
+ usd?: number;
23
+ usdEstimated?: boolean;
24
+ units?: number;
25
+ }
26
+ export interface TaskRoundRecord {
27
+ ts: string;
28
+ cycle: string;
29
+ kind: "round";
30
+ n: number;
31
+ workRunId?: string;
32
+ verifyRunId: string;
33
+ verdict: "pass" | "fail";
34
+ strength: "enforced" | "advisory";
35
+ /** Why an attested PASS was downgraded to a fail; absent when the attestation held. */
36
+ reason?: string;
37
+ }
38
+ export interface TaskExpiredRecord {
39
+ ts: string;
40
+ cycle: string;
41
+ kind: "expired";
42
+ ticket: string;
43
+ action: "reopened" | "paused";
44
+ }
45
+ export interface TaskCloseRecord {
46
+ ts: string;
47
+ cycle: string;
48
+ kind: "close";
49
+ outcome: "done" | "cancelled";
50
+ summary: string;
51
+ evidence?: string;
52
+ residualRisk?: string;
53
+ steps: number;
54
+ rounds: number;
55
+ usd: number;
56
+ }
57
+ export type TaskLogRecord = TaskStepRecord | TaskRoundRecord | TaskExpiredRecord | TaskCloseRecord;
58
+ export declare function taskLogPath(channelDir: string, id: string): string;
59
+ /** Test seam: drop cached appenders so a temp-dir fixture does not leak into the next case. */
60
+ export declare function resetTaskLogAppenders(): Promise<void>;
61
+ export type TaskLogInput = (Omit<TaskStepRecord, "ts"> & {
62
+ ts?: string;
63
+ }) | (Omit<TaskRoundRecord, "ts"> & {
64
+ ts?: string;
65
+ }) | (Omit<TaskExpiredRecord, "ts"> & {
66
+ ts?: string;
67
+ }) | (Omit<TaskCloseRecord, "ts"> & {
68
+ ts?: string;
69
+ });
70
+ /**
71
+ * Append one record. `appendStrict` rather than `append`: the loop log is the only durable trace
72
+ * of what a step did, so a dropped record would make the next brief lie about the task's history.
73
+ */
74
+ export declare function appendTaskLog(channelDir: string, id: string, record: TaskLogInput): Promise<void>;
75
+ export interface ReadTaskLogOptions {
76
+ /** Only records from this cycle. */
77
+ cycle?: string;
78
+ /** Keep at most this many, counted from the end (the most recent). */
79
+ limit?: number;
80
+ kinds?: readonly TaskLogRecord["kind"][];
81
+ }
82
+ /**
83
+ * Read the log back, newest-last. Unparseable lines are skipped rather than failing the read: a
84
+ * hand-edited or half-written line must not make a task's whole history unreadable.
85
+ */
86
+ export declare function readTaskLog(channelDir: string, id: string, options?: ReadTaskLogOptions): Promise<TaskLogRecord[]>;
87
+ /** One line per record, for the step brief and `/tasks show`. */
88
+ export declare function renderTaskLogLine(record: TaskLogRecord): string;
@@ -0,0 +1,97 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { createJsonlAppender } from "../shared/jsonl-appender.js";
5
+ import { formatLocalTime } from "../shared/local-time.js";
6
+ import { clipText } from "../shared/text-utils.js";
7
+ import { isPlainObject } from "../shared/type-guards.js";
8
+ import { normalizeTaskId } from "./ledger.js";
9
+ /** Same rotation shape as the channel archive: the log is working history, not an audit trail. */
10
+ const MAX_LOG_BYTES = 4 * 1024 * 1024;
11
+ const NOTE_MAX_CHARS = 4_000;
12
+ export function taskLogPath(channelDir, id) {
13
+ return join(channelDir, "tasks", `${normalizeTaskId(id)}.jsonl`);
14
+ }
15
+ const appenders = new Map();
16
+ function appenderFor(path) {
17
+ const existing = appenders.get(path);
18
+ if (existing)
19
+ return existing;
20
+ const appender = createJsonlAppender({ path, maxSizeBytes: MAX_LOG_BYTES, maxRotations: 2 });
21
+ appenders.set(path, appender);
22
+ return appender;
23
+ }
24
+ /** Test seam: drop cached appenders so a temp-dir fixture does not leak into the next case. */
25
+ export async function resetTaskLogAppenders() {
26
+ const open = [...appenders.values()];
27
+ appenders.clear();
28
+ await Promise.all(open.map((appender) => appender.close()));
29
+ }
30
+ /**
31
+ * Append one record. `appendStrict` rather than `append`: the loop log is the only durable trace
32
+ * of what a step did, so a dropped record would make the next brief lie about the task's history.
33
+ */
34
+ export async function appendTaskLog(channelDir, id, record) {
35
+ const withTs = { ts: record.ts ?? formatLocalTime(), ...record };
36
+ if (withTs.kind === "step")
37
+ withTs.note = clipText(withTs.note, NOTE_MAX_CHARS);
38
+ await appenderFor(taskLogPath(channelDir, id)).appendStrict(withTs);
39
+ }
40
+ function toRecord(value) {
41
+ if (!isPlainObject(value) || typeof value.ts !== "string" || typeof value.cycle !== "string")
42
+ return undefined;
43
+ const kind = value.kind;
44
+ if (kind !== "step" && kind !== "round" && kind !== "expired" && kind !== "close")
45
+ return undefined;
46
+ return value;
47
+ }
48
+ /**
49
+ * Read the log back, newest-last. Unparseable lines are skipped rather than failing the read: a
50
+ * hand-edited or half-written line must not make a task's whole history unreadable.
51
+ */
52
+ export async function readTaskLog(channelDir, id, options = {}) {
53
+ const path = taskLogPath(channelDir, id);
54
+ if (!existsSync(path))
55
+ return [];
56
+ let content;
57
+ try {
58
+ content = await readFile(path, "utf-8");
59
+ }
60
+ catch {
61
+ return [];
62
+ }
63
+ const records = [];
64
+ for (const line of content.split("\n")) {
65
+ if (!line.trim())
66
+ continue;
67
+ let parsed;
68
+ try {
69
+ parsed = JSON.parse(line);
70
+ }
71
+ catch {
72
+ continue;
73
+ }
74
+ const record = toRecord(parsed);
75
+ if (!record)
76
+ continue;
77
+ if (options.cycle && record.cycle !== options.cycle)
78
+ continue;
79
+ if (options.kinds && !options.kinds.includes(record.kind))
80
+ continue;
81
+ records.push(record);
82
+ }
83
+ return options.limit !== undefined && records.length > options.limit ? records.slice(-options.limit) : records;
84
+ }
85
+ /** One line per record, for the step brief and `/tasks show`. */
86
+ export function renderTaskLogLine(record) {
87
+ switch (record.kind) {
88
+ case "step":
89
+ return `- [${record.ts}] step ${record.seq} → ${record.outcome}: ${record.note}`;
90
+ case "round":
91
+ return `- [${record.ts}] round ${record.n} ${record.verdict.toUpperCase()} (${record.strength}) verify=${record.verifyRunId}${record.workRunId ? ` work=${record.workRunId}` : ""}${record.reason ? ` — ${record.reason}` : ""}`;
92
+ case "expired":
93
+ return `- [${record.ts}] 等待票过期(${record.ticket})→ ${record.action}`;
94
+ case "close":
95
+ return `- [${record.ts}] cycle ${record.cycle} ${record.outcome}: ${record.summary}`;
96
+ }
97
+ }
@@ -0,0 +1,43 @@
1
+ import { type TaskRoundRecord } from "./log.js";
2
+ /**
3
+ * Rework accounting (spec 051, D7).
4
+ *
5
+ * The trace this exists for: one real task ran seven builder→reviewer rounds, six advisory FAILs
6
+ * before a PASS, over 2.4 hours of delegation wall time — and its stored state said
7
+ * `{"verification":{"required":false,"status":"pending"}}`. The rounds were invisible, so nothing
8
+ * could bound them and the user could not see them. Recording a round is bookkeeping the runtime
9
+ * already has the facts for at settlement, so it happens there rather than costing a tool call
10
+ * and a model decision (`task_verify`, retired).
11
+ */
12
+ export interface RoundInput {
13
+ channelDir: string;
14
+ taskId: string;
15
+ verifyRunId: string;
16
+ verdict: "pass" | "fail";
17
+ strength: "enforced" | "advisory";
18
+ /** The delegation this verdict judged, when the caller could identify it. */
19
+ workRunId?: string;
20
+ /** Attributable cost of this run; `estimated` marks a fallback rather than reported usage. */
21
+ usd?: number;
22
+ usdEstimated?: boolean;
23
+ /** Set when the attestation did not hold; the round is then recorded as a fail with this reason. */
24
+ reason?: string;
25
+ }
26
+ export interface RoundResult {
27
+ cycleId: string;
28
+ round: number;
29
+ /** True once `cycle.rounds` has reached the task's rework ceiling. */
30
+ overBudget: boolean;
31
+ }
32
+ /**
33
+ * Record one verification round against the task's current cycle and return where that leaves the
34
+ * rework budget. Callers must guard this with their own idempotency marker: a replayed settlement
35
+ * must not write a second round.
36
+ */
37
+ export declare function recordVerificationRound(input: RoundInput, roundsBudget: number): Promise<RoundResult | undefined>;
38
+ /** Add one run's cost to the task's current cycle. Used for `purpose=work` runs and background jobs. */
39
+ export declare function recordTaskCost(channelDir: string, taskId: string, usd: number, estimated: boolean): Promise<void>;
40
+ /** The rework rounds recorded in one cycle, oldest first — `/tasks show`'s verdict trail. */
41
+ export declare function readCycleRounds(channelDir: string, taskId: string, cycle: string | undefined): Promise<TaskRoundRecord[]>;
42
+ /** Whether this cycle already carries a real PASS — the only thing that may unlock `done`. */
43
+ export declare function hasPassingRound(channelDir: string, taskId: string, cycle: string | undefined): Promise<boolean>;
@@ -0,0 +1,57 @@
1
+ import { appendTaskLog, readTaskLog } from "./log.js";
2
+ import { updateStoredTask } from "./store.js";
3
+ /**
4
+ * Record one verification round against the task's current cycle and return where that leaves the
5
+ * rework budget. Callers must guard this with their own idempotency marker: a replayed settlement
6
+ * must not write a second round.
7
+ */
8
+ export async function recordVerificationRound(input, roundsBudget) {
9
+ let result;
10
+ const document = await updateStoredTask(input.channelDir, input.taskId, (task) => {
11
+ const cycle = task.fields.cycle;
12
+ if (!cycle)
13
+ return;
14
+ const rounds = cycle.rounds + 1;
15
+ task.fields.cycle = {
16
+ ...cycle,
17
+ rounds,
18
+ usd: cycle.usd + (input.usd ?? 0),
19
+ usdEstimated: cycle.usdEstimated || Boolean(input.usdEstimated),
20
+ };
21
+ const ceiling = task.fields.budget?.rounds ?? roundsBudget;
22
+ result = { cycleId: cycle.id, round: rounds, overBudget: rounds >= ceiling };
23
+ });
24
+ if (!document || !result)
25
+ return undefined;
26
+ await appendTaskLog(input.channelDir, input.taskId, {
27
+ cycle: result.cycleId,
28
+ kind: "round",
29
+ n: result.round,
30
+ workRunId: input.workRunId,
31
+ verifyRunId: input.verifyRunId,
32
+ verdict: input.verdict,
33
+ strength: input.strength,
34
+ reason: input.reason,
35
+ });
36
+ return result;
37
+ }
38
+ /** Add one run's cost to the task's current cycle. Used for `purpose=work` runs and background jobs. */
39
+ export async function recordTaskCost(channelDir, taskId, usd, estimated) {
40
+ if (usd <= 0 && !estimated)
41
+ return;
42
+ await updateStoredTask(channelDir, taskId, (task) => {
43
+ const cycle = task.fields.cycle;
44
+ if (!cycle)
45
+ return;
46
+ task.fields.cycle = { ...cycle, usd: cycle.usd + usd, usdEstimated: cycle.usdEstimated || estimated };
47
+ });
48
+ }
49
+ /** The rework rounds recorded in one cycle, oldest first — `/tasks show`'s verdict trail. */
50
+ export async function readCycleRounds(channelDir, taskId, cycle) {
51
+ const records = await readTaskLog(channelDir, taskId, { cycle, kinds: ["round"] });
52
+ return records.filter((record) => record.kind === "round");
53
+ }
54
+ /** Whether this cycle already carries a real PASS — the only thing that may unlock `done`. */
55
+ export async function hasPassingRound(channelDir, taskId, cycle) {
56
+ return (await readCycleRounds(channelDir, taskId, cycle)).some((record) => record.verdict === "pass");
57
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Where a task cycle's own agent session lives (spec 051, D3) — one file per cycle, closed and
3
+ * left behind when the cycle ends. Kept out of `<channelDir>` root and under a dot-directory so
4
+ * `session_search`'s channel scan and `/new`'s session listing do not mistake a task transcript
5
+ * for the channel's conversation.
6
+ */
7
+ export declare const TASK_SESSIONS_DIRNAME = ".sessions";
8
+ export declare function taskSessionsDir(channelDir: string): string;
9
+ export declare function taskSessionPath(channelDir: string, taskId: string, cycleId: string): string;
@@ -0,0 +1,16 @@
1
+ import { join } from "node:path";
2
+ import { normalizeTaskId } from "./ledger.js";
3
+ /**
4
+ * Where a task cycle's own agent session lives (spec 051, D3) — one file per cycle, closed and
5
+ * left behind when the cycle ends. Kept out of `<channelDir>` root and under a dot-directory so
6
+ * `session_search`'s channel scan and `/new`'s session listing do not mistake a task transcript
7
+ * for the channel's conversation.
8
+ */
9
+ export const TASK_SESSIONS_DIRNAME = ".sessions";
10
+ export function taskSessionsDir(channelDir) {
11
+ return join(channelDir, "tasks", TASK_SESSIONS_DIRNAME);
12
+ }
13
+ export function taskSessionPath(channelDir, taskId, cycleId) {
14
+ const safeCycle = cycleId.replace(/[^A-Za-z0-9._-]/g, "-");
15
+ return join(taskSessionsDir(channelDir), `${normalizeTaskId(taskId)}-${safeCycle}.jsonl`);
16
+ }
@@ -0,0 +1,8 @@
1
+ /** Queue guidance for the task's next step. Repeated calls append, so nothing is silently lost. */
2
+ export declare function queueTaskSteer(channelDir: string, id: string, text: string, label?: string): Promise<void>;
3
+ /** Read and clear the pending guidance. Returns `undefined` when there is none. */
4
+ export declare function consumeTaskSteer(channelDir: string, id: string): Promise<string | undefined>;
5
+ /** Whether guidance is waiting, without consuming it (for `/tasks show`). */
6
+ export declare function hasTaskSteer(channelDir: string, id: string): boolean;
7
+ export declare function queueTaskNotice(channelDir: string, id: string, text: string): Promise<void>;
8
+ export declare function consumeTaskNotice(channelDir: string, id: string): Promise<string | undefined>;
@@ -0,0 +1,79 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readFile, rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { formatLocalTime } from "../shared/local-time.js";
6
+ import { normalizeTaskId } from "./ledger.js";
7
+ /**
8
+ * Out-of-band guidance for a running task loop (spec 051, D11) — `/tasks steer` and `/tasks reply`.
9
+ *
10
+ * Kept as one small file per task rather than a frontmatter field or a log record: it is a
11
+ * *pending instruction*, not durable task state, so it must not enter the contract (which the
12
+ * loop injects whole and which has a hard size budget) and must be consumed exactly once. The
13
+ * next step reads it, deletes it, and puts the text at the top of its own brief; nothing is left
14
+ * behind for a later step to act on twice.
15
+ */
16
+ function steerDir(channelDir) {
17
+ return join(channelDir, "tasks", ".steer");
18
+ }
19
+ function steerPath(channelDir, id) {
20
+ return join(steerDir(channelDir), `${normalizeTaskId(id)}.md`);
21
+ }
22
+ /** Queue guidance for the task's next step. Repeated calls append, so nothing is silently lost. */
23
+ export async function queueTaskSteer(channelDir, id, text, label = "用户指示") {
24
+ const trimmed = text.trim();
25
+ if (!trimmed)
26
+ return;
27
+ await mkdir(steerDir(channelDir), { recursive: true });
28
+ const path = steerPath(channelDir, id);
29
+ const existing = existsSync(path) ? `${await readFile(path, "utf-8")}\n` : "";
30
+ await writeFileAtomically(path, `${existing}- [${formatLocalTime()}] ${label}:${trimmed}\n`);
31
+ }
32
+ /** Read and clear the pending guidance. Returns `undefined` when there is none. */
33
+ export async function consumeTaskSteer(channelDir, id) {
34
+ const path = steerPath(channelDir, id);
35
+ if (!existsSync(path))
36
+ return undefined;
37
+ try {
38
+ const text = (await readFile(path, "utf-8")).trim();
39
+ await rm(path, { force: true });
40
+ return text || undefined;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
46
+ /** Whether guidance is waiting, without consuming it (for `/tasks show`). */
47
+ export function hasTaskSteer(channelDir, id) {
48
+ return existsSync(steerPath(channelDir, id));
49
+ }
50
+ /**
51
+ * The other direction: what a step asked the runtime to tell the user (`task_step_end`'s
52
+ * `notify`). Held in a file rather than returned inline because the tool result never reaches the
53
+ * transport — the runtime reads and clears this after the step ends, and delivers it once.
54
+ */
55
+ function noticePath(channelDir, id) {
56
+ return join(steerDir(channelDir), `${normalizeTaskId(id)}.out.md`);
57
+ }
58
+ export async function queueTaskNotice(channelDir, id, text) {
59
+ const trimmed = text.trim();
60
+ if (!trimmed)
61
+ return;
62
+ await mkdir(steerDir(channelDir), { recursive: true });
63
+ const path = noticePath(channelDir, id);
64
+ const existing = existsSync(path) ? `${await readFile(path, "utf-8")}\n\n` : "";
65
+ await writeFileAtomically(path, `${existing}${trimmed}`);
66
+ }
67
+ export async function consumeTaskNotice(channelDir, id) {
68
+ const path = noticePath(channelDir, id);
69
+ if (!existsSync(path))
70
+ return undefined;
71
+ try {
72
+ const text = (await readFile(path, "utf-8")).trim();
73
+ await rm(path, { force: true });
74
+ return text || undefined;
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
@@ -1,56 +1,81 @@
1
- import { type TaskWaitingFor } from "./control.js";
2
- import { type TaskDocumentFields } from "./ledger.js";
1
+ import { type TaskArchiveOutcome, type TaskFrontmatterV4, type TaskPaused } from "./frontmatter.js";
2
+ import { type Ticket } from "./ticket.js";
3
3
  export interface StoredTaskDocument {
4
4
  id: string;
5
5
  path: string;
6
- fields: TaskDocumentFields;
6
+ fields: TaskFrontmatterV4;
7
7
  body: string;
8
8
  }
9
9
  /**
10
- * Hash the task's *contract* segment (Goal/DoD/Manual/Verification), not the whole body, so
11
- * verification PASS survives routine Current Cycle / History logging and only breaks when the
12
- * contract itself changes (spec 029, D4). Old attestations that hashed the
13
- * whole body naturally fail this check after upgrade and are re-verified — verification should
14
- * always reflect current content, so there is no compatibility burden.
10
+ * The contract's size budget (INV-6).
11
+ *
12
+ * v3 task files on the author's machine sat permanently at 30 KB, 79% of it closed-cycle history,
13
+ * and every wake read all of it. The contract is injected whole into every step brief, so what it
14
+ * must guarantee is that **runtime-written history cannot grow it** — not that the file is under
15
+ * some number no matter what the user wrote.
16
+ *
17
+ * So the budget is enforced against `## 上次结果` only, the one section the runtime authors and
18
+ * whose full content is always recoverable from `task_log`. Everything else — Goal, DoD, Manual,
19
+ * Verification, Plan — is authored by the user or the planning turn, and the runtime does not get
20
+ * to delete it to hit a number. A contract that still exceeds the budget on authored text alone is
21
+ * written as-is and warned about.
22
+ *
23
+ * The first version clipped the body's tail instead, and the migration rehearsal on real data
24
+ * showed exactly why that was wrong: two tasks with a legitimately long `## Manual` silently lost
25
+ * their `## Verification` and `## Plan` sections — the verifier's instructions and the task's own
26
+ * agenda — to make room.
15
27
  */
16
- export declare function taskBodyHash(body: string): string;
17
- export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean, allowInvalidControl?: boolean): Promise<StoredTaskDocument | undefined>;
28
+ export declare const MAX_CONTRACT_BYTES: number;
29
+ export declare function tasksDir(channelDir: string): string;
30
+ export declare function taskPath(channelDir: string, id: string): string;
31
+ export declare function archivedTaskPath(channelDir: string, id: string): string;
32
+ export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean): Promise<StoredTaskDocument | undefined>;
18
33
  export declare function writeStoredTask(document: StoredTaskDocument): Promise<void>;
19
34
  export declare function updateStoredTask(channelDir: string, id: string, update: (document: StoredTaskDocument) => void, includeArchive?: boolean): Promise<StoredTaskDocument | undefined>;
20
35
  /**
21
- * A governor stop: disable the task without changing its lifecycle stage or wake. The structured
22
- * stop record is the durable recovery receipt; notification is handled by the runtime driver.
36
+ * Park a task on a ticket. The ticket must already have been through `resolveTicket` — this
37
+ * function persists a decision, it does not make one.
23
38
  */
24
- export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
25
- export interface WakeTaskTransitionHooks {
26
- /** Test-only fault seam, called immediately before the atomic activation write. */
27
- beforeActivation?: () => void;
28
- }
39
+ export declare function parkTask(channelDir: string, id: string, ticket: Ticket): Promise<StoredTaskDocument | undefined>;
29
40
  /**
30
- * Atomically convert a due/completion-woken task to active. Idempotent by construction: once a
31
- * task is no longer `waiting`, a redelivered wake or retry finds `status !== "waiting"` and is a
32
- * safe no-op, so no separate claim/handoff bookkeeping is needed to detect a duplicate activation.
41
+ * Redeem a ticket: the single, idempotent transition from `parked` back to `open`.
33
42
  *
34
- * Wake legitimacy is entirely the caller's responsibility (spec 043's `waitingFor`
35
- * de-authorization): a completion wake reaches here only after the caller has verified an
36
- * actually-settled run/job whose own recorded `taskId` names this task (`task-wake.ts`'s
37
- * `isVerified*Wake`). `waitingFor` itself is display-only and never gates activation.
43
+ * Idempotent by construction — a task that is no longer parked, or is parked on a *different*
44
+ * ticket, is a no-op. That is what lets every producer (run settlement, job settlement, the
45
+ * events watcher, `/tasks reply`, the driver's timer) push at-least-once without any of them
46
+ * needing its own claim bookkeeping: the outermost wake-claim in `wake-claim.ts` still guards
47
+ * duplicate delivery, and this guards duplicate application.
38
48
  */
39
- export declare function activateWaitingTask(channelDir: string, id: string, hooks?: WakeTaskTransitionHooks): Promise<StoredTaskDocument | undefined>;
40
- /** Return a task to waiting after a transport failed to accept its just-activated turn. */
41
- export declare function rollbackWaitingTask(channelDir: string, id: string, waitingFor: TaskWaitingFor): Promise<void>;
49
+ export declare function redeemTicket(channelDir: string, id: string, matches: (ticket: Ticket) => boolean): Promise<{
50
+ document: StoredTaskDocument;
51
+ ticket: Ticket;
52
+ } | undefined>;
53
+ /** Disable a task without losing its stage. `paused` present *is* the disabled state (D1). */
54
+ export declare function pauseTask(channelDir: string, id: string, paused: Omit<TaskPaused, "at"> & {
55
+ at?: string;
56
+ }): Promise<StoredTaskDocument | undefined>;
57
+ export declare function resumeTask(channelDir: string, id: string): Promise<StoredTaskDocument | undefined>;
42
58
  /**
43
- * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
44
- * with a `-N` suffix when the same task is reopened more than once on the same local day.
59
+ * The backstop transition (D2): a parked task whose `by` has passed goes back to `open` so its
60
+ * next step can re-check reality, and the second expiry in the same cycle stops the task and
61
+ * hands the user a deterministic receipt instead of burning another wake.
62
+ *
63
+ * Returns what the caller should do about it, or `undefined` when nothing applied.
45
64
  */
46
- export declare function nextCycleId(previousCycleId: string | undefined, occurrence: Date): string;
65
+ export type TicketExpiryOutcome = "reopened" | "paused";
66
+ export declare function expireTicket(channelDir: string, id: string, limit?: number): Promise<{
67
+ document: StoredTaskDocument;
68
+ outcome: TicketExpiryOutcome;
69
+ ticket: string;
70
+ } | undefined>;
47
71
  /**
48
- * Open the next cycle of a sleeping recurring task entirely in the runtime (spec 029, D2):
49
- * fold the previous cycle's log into History, reset per-cycle control, clear the wake, and
50
- * mark it `active`. This is the deterministic replacement for the retired
51
- * no LLM turn is spent just to reopen a cycle.
72
+ * Open the next cycle: fresh counters, a fresh cycle id, and (for a recurring task) a Plan and
73
+ * acceptance checklist reset. Deterministic and zero-token — no LLM turn is spent just to start
74
+ * a cycle, which is why a missed occurrence can self-heal without waking anything.
52
75
  */
53
- export declare function openRecurringTaskCycle(channelDir: string, id: string, now: Date, force?: boolean): Promise<{
76
+ export declare function openCycle(channelDir: string, id: string, now?: Date): Promise<{
54
77
  document: StoredTaskDocument;
55
78
  cycleId: string;
56
79
  } | undefined>;
80
+ /** Move a closed task (and its log) into `tasks/archive/`. */
81
+ export declare function archiveTask(channelDir: string, id: string, outcome: TaskArchiveOutcome): Promise<void>;