@oyasmi/pipiclaw 0.9.3-beta.4 → 0.9.3-beta.6

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 (162) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +15 -35
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +43 -3
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-context.d.ts +2 -2
  11. package/dist/channel/channel-context.js +2 -2
  12. package/dist/channel/channel-event.d.ts +3 -3
  13. package/dist/channel/project-scope-store.d.ts +20 -0
  14. package/dist/channel/project-scope-store.js +22 -7
  15. package/dist/commands/catalog.js +6 -12
  16. package/dist/events/event-commands.js +2 -2
  17. package/dist/events/events.d.ts +51 -30
  18. package/dist/events/events.js +70 -98
  19. package/dist/memory/journal.d.ts +2 -3
  20. package/dist/memory/journal.js +2 -3
  21. package/dist/memory/maintenance-tuning.d.ts +0 -1
  22. package/dist/memory/maintenance-tuning.js +0 -1
  23. package/dist/memory/scheduler.js +8 -16
  24. package/dist/memory/search.js +2 -3
  25. package/dist/memory/session-search.js +3 -9
  26. package/dist/memory/store.d.ts +1 -1
  27. package/dist/memory/store.js +9 -1
  28. package/dist/memory/task-digest.js +10 -11
  29. package/dist/memory/tombstones.js +2 -4
  30. package/dist/models/provider-login.d.ts +1 -1
  31. package/dist/models/provider-login.js +1 -1
  32. package/dist/playbooks/agent-delegation.md +18 -14
  33. package/dist/playbooks/background-jobs.md +2 -2
  34. package/dist/playbooks/event-scheduling.md +22 -13
  35. package/dist/playbooks/memory-and-learning.md +2 -2
  36. package/dist/playbooks/outbound-media.md +1 -1
  37. package/dist/playbooks/runtime-orientation.md +5 -3
  38. package/dist/playbooks/task-lead.md +82 -0
  39. package/dist/runtime/bootstrap.js +107 -196
  40. package/dist/runtime/delivery.d.ts +1 -2
  41. package/dist/runtime/delivery.js +57 -62
  42. package/dist/runtime/dingtalk.d.ts +15 -8
  43. package/dist/runtime/dingtalk.js +101 -35
  44. package/dist/runtime/durable-dispatch.js +30 -3
  45. package/dist/runtime/report-commands.d.ts +30 -0
  46. package/dist/runtime/report-commands.js +71 -0
  47. package/dist/runtime/subagent-commands.js +1 -1
  48. package/dist/runtime/task-commands.d.ts +0 -8
  49. package/dist/runtime/task-commands.js +48 -85
  50. package/dist/runtime/task-driver.d.ts +13 -9
  51. package/dist/runtime/task-driver.js +34 -39
  52. package/dist/runtime/task-migration.d.ts +18 -29
  53. package/dist/runtime/task-migration.js +195 -183
  54. package/dist/runtime/task-spawn.d.ts +24 -0
  55. package/dist/runtime/task-spawn.js +49 -0
  56. package/dist/runtime/task-wake.d.ts +33 -46
  57. package/dist/runtime/task-wake.js +15 -90
  58. package/dist/security/network.js +44 -9
  59. package/dist/settings.d.ts +1 -8
  60. package/dist/settings.js +1 -8
  61. package/dist/subagents/discovery.js +7 -17
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +3 -1
  65. package/dist/subagents/external/run.js +14 -23
  66. package/dist/subagents/external/settlement.d.ts +4 -16
  67. package/dist/subagents/external/settlement.js +16 -67
  68. package/dist/subagents/runs.d.ts +15 -29
  69. package/dist/subagents/runs.js +71 -160
  70. package/dist/subagents/tool.d.ts +20 -4
  71. package/dist/subagents/tool.js +63 -87
  72. package/dist/subagents/verification-outcome.d.ts +13 -19
  73. package/dist/subagents/verification-outcome.js +8 -22
  74. package/dist/subagents/workspace-summary.d.ts +8 -0
  75. package/dist/subagents/workspace-summary.js +29 -0
  76. package/dist/tasks/board.d.ts +43 -0
  77. package/dist/tasks/board.js +134 -0
  78. package/dist/tasks/brief.d.ts +10 -5
  79. package/dist/tasks/brief.js +78 -26
  80. package/dist/tasks/budget.d.ts +13 -14
  81. package/dist/tasks/budget.js +21 -40
  82. package/dist/tasks/contract-input.d.ts +19 -0
  83. package/dist/tasks/contract-input.js +55 -0
  84. package/dist/tasks/create.d.ts +17 -0
  85. package/dist/tasks/create.js +36 -0
  86. package/dist/tasks/frontmatter.d.ts +20 -27
  87. package/dist/tasks/frontmatter.js +18 -31
  88. package/dist/tasks/ledger.d.ts +61 -117
  89. package/dist/tasks/ledger.js +78 -223
  90. package/dist/tasks/log.d.ts +62 -35
  91. package/dist/tasks/log.js +51 -29
  92. package/dist/tasks/session-path.d.ts +3 -3
  93. package/dist/tasks/session-path.js +4 -5
  94. package/dist/tasks/store.d.ts +11 -29
  95. package/dist/tasks/store.js +39 -83
  96. package/dist/tasks/ticket.d.ts +33 -66
  97. package/dist/tasks/ticket.js +31 -120
  98. package/dist/tasks/work-log.d.ts +20 -0
  99. package/dist/tasks/work-log.js +42 -0
  100. package/dist/tools/bash.d.ts +1 -1
  101. package/dist/tools/bash.js +1 -1
  102. package/dist/tools/event-manage.d.ts +16 -2
  103. package/dist/tools/event-manage.js +30 -12
  104. package/dist/tools/index.d.ts +5 -3
  105. package/dist/tools/index.js +5 -5
  106. package/dist/tools/registry.d.ts +6 -4
  107. package/dist/tools/registry.js +1 -4
  108. package/dist/tools/subagent-manage.js +4 -2
  109. package/dist/tools/task-manage/create.js +11 -27
  110. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  111. package/dist/tools/task-manage/lifecycle.js +23 -106
  112. package/dist/tools/task-manage/log-view.d.ts +3 -2
  113. package/dist/tools/task-manage/log-view.js +6 -6
  114. package/dist/tools/task-manage/schema.d.ts +10 -30
  115. package/dist/tools/task-manage/schema.js +33 -49
  116. package/dist/tools/task-manage/shared.d.ts +35 -42
  117. package/dist/tools/task-manage/shared.js +53 -192
  118. package/dist/tools/task-manage/step-end.d.ts +6 -6
  119. package/dist/tools/task-manage/step-end.js +61 -98
  120. package/dist/tools/task-manage/types.d.ts +8 -9
  121. package/dist/tools/task-manage.js +5 -5
  122. package/dist/tui/app.js +11 -38
  123. package/dist/tui/commands.d.ts +18 -8
  124. package/dist/tui/commands.js +2 -9
  125. package/dist/tui/turn-controller.d.ts +2 -14
  126. package/dist/tui/turn-controller.js +1 -17
  127. package/dist/web/client.js +9 -1
  128. package/examples/sub-agents/README.md +67 -80
  129. package/examples/sub-agents/agents/claude-high.md +23 -0
  130. package/examples/sub-agents/agents/claude-main.md +23 -0
  131. package/examples/sub-agents/agents/codex-flash.md +23 -0
  132. package/examples/sub-agents/agents/codex-high.md +23 -0
  133. package/examples/sub-agents/agents/codex-main.md +23 -0
  134. package/examples/sub-agents/agents/codex-review.md +23 -0
  135. package/examples/sub-agents/agents/glm-flash.md +23 -0
  136. package/examples/sub-agents/agents/glm-high.md +23 -0
  137. package/examples/sub-agents/{verifier.md → roles/verifier.md} +1 -1
  138. package/package.json +1 -1
  139. package/dist/memory/maintenance-migration.d.ts +0 -5
  140. package/dist/memory/maintenance-migration.js +0 -91
  141. package/dist/memory/migrate.d.ts +0 -15
  142. package/dist/memory/migrate.js +0 -364
  143. package/dist/playbooks/task-loop.md +0 -90
  144. package/dist/tasks/artifact-subject.d.ts +0 -40
  145. package/dist/tasks/artifact-subject.js +0 -334
  146. package/dist/tasks/cycle.d.ts +0 -48
  147. package/dist/tasks/cycle.js +0 -94
  148. package/dist/tasks/rounds.d.ts +0 -41
  149. package/dist/tasks/rounds.js +0 -53
  150. package/dist/tasks/task-events.d.ts +0 -6
  151. package/dist/tasks/task-events.js +0 -14
  152. package/dist/tasks/task-schedule.d.ts +0 -18
  153. package/dist/tasks/task-schedule.js +0 -50
  154. package/dist/tasks/verification.d.ts +0 -114
  155. package/dist/tasks/verification.js +0 -226
  156. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  157. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  158. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  159. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  160. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  161. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  162. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -6,17 +6,17 @@ const SELECTION_FILENAME = "project.json";
6
6
  export function getProjectSelectionPath(channelDir) {
7
7
  return join(channelDir, SELECTION_FILENAME);
8
8
  }
9
- export function readProjectSelection(channelDir) {
9
+ export function readProjectSelectionResult(channelDir) {
10
10
  const path = getProjectSelectionPath(channelDir);
11
11
  if (!existsSync(path)) {
12
- return undefined;
12
+ return { kind: "missing" };
13
13
  }
14
14
  let raw;
15
15
  try {
16
16
  raw = JSON.parse(readFileSync(path, "utf-8"));
17
17
  }
18
18
  catch {
19
- return undefined;
19
+ return { kind: "corrupt" };
20
20
  }
21
21
  if (!raw ||
22
22
  typeof raw !== "object" ||
@@ -24,9 +24,17 @@ export function readProjectSelection(channelDir) {
24
24
  typeof raw.projectRoot !== "string" ||
25
25
  typeof raw.updatedAt !== "string" ||
26
26
  typeof raw.updatedBy !== "string") {
27
- return undefined;
27
+ return { kind: "corrupt" };
28
28
  }
29
- return raw;
29
+ return { kind: "valid", selection: raw };
30
+ }
31
+ /** Collapses `corrupt` into `undefined` alongside `missing`, for display-only callers (`/project
32
+ * show`) that already have their own "not chosen yet" wording and do not make a resolution
33
+ * decision. `resolveProjectScope` uses {@link readProjectSelectionResult} directly instead,
34
+ * because it must not conflate the two. */
35
+ export function readProjectSelection(channelDir) {
36
+ const result = readProjectSelectionResult(channelDir);
37
+ return result.kind === "valid" ? result.selection : undefined;
30
38
  }
31
39
  /** Used only for the one-time, in-constructor migration write (D3.3); every explicit mutation
32
40
  * (`/project set|reset`) goes through the async `writeFileAtomically` in `commitProjectSelection`
@@ -54,8 +62,14 @@ export async function commitProjectSelection(channelDir, projectRoot, updatedBy)
54
62
  export function resolveProjectScope(channelDir, resolution) {
55
63
  const sandbox = currentProjectSandboxStatus();
56
64
  const boundary = resolution.configured ? "project" : "unbounded";
57
- const existing = readProjectSelection(channelDir);
58
- if (!existing) {
65
+ const result = readProjectSelectionResult(channelDir);
66
+ if (result.kind === "corrupt") {
67
+ return {
68
+ kind: "blocked",
69
+ reason: `项目选择文件已损坏:${getProjectSelectionPath(channelDir)}。请检查该文件,或在频道空闲时执行 /project set <path> 或 /project reset 重新选择——不会自动回退到默认项目。`,
70
+ };
71
+ }
72
+ if (result.kind === "missing") {
59
73
  const selection = {
60
74
  version: 1,
61
75
  projectRoot: resolution.policy.defaultRoot,
@@ -65,6 +79,7 @@ export function resolveProjectScope(channelDir, resolution) {
65
79
  writeProjectSelectionSync(channelDir, selection);
66
80
  return { kind: "ready", scope: { projectRoot: resolution.policy.defaultRoot, boundary, sandbox }, selection };
67
81
  }
82
+ const existing = result.selection;
68
83
  if (!existsSync(existing.projectRoot)) {
69
84
  return {
70
85
  kind: "blocked",
@@ -72,7 +72,7 @@ export const BUILT_IN_COMMANDS = [
72
72
  },
73
73
  {
74
74
  name: "tasks",
75
- argumentHint: "[show <id>|log <id>|steer <id> <内容>|reply <id> <内容>|pause <id>|resume <id> [+steps N]|run <id>|archive|doctor]",
75
+ argumentHint: "[show <id>|log <id>|steer <id> <内容>|reply <id> <内容>|pause <id>|resume <id> [+steps N|+usd X]|archive|doctor]",
76
76
  description: "查看、指挥并诊断本频道的长程任务;pause 只停用执行,保留阶段与等待票",
77
77
  availableWhileBusy: true,
78
78
  subcommands: [
@@ -80,13 +80,13 @@ export const BUILT_IN_COMMANDS = [
80
80
  {
81
81
  name: "show",
82
82
  args: "<id>",
83
- description: "查看契约、最近日志、返工轮次与成本",
83
+ description: "查看契约、团队看板、最近日志与用量",
84
84
  example: "/tasks show weekly-report",
85
85
  },
86
86
  {
87
87
  name: "log",
88
- args: "<id> [cycle]",
89
- description: "翻看该任务的循环日志",
88
+ args: "<id>",
89
+ description: "翻看该任务的循环日志(含派发与结算记录)",
90
90
  example: "/tasks log weekly-report",
91
91
  },
92
92
  { name: "archive", description: "列出已归档(已关闭)的任务", example: "/tasks archive" },
@@ -98,16 +98,10 @@ export const BUILT_IN_COMMANDS = [
98
98
  },
99
99
  {
100
100
  name: "resume",
101
- args: "<id> [+steps N|+rounds N|+usd X]",
102
- description: "重新启用该任务,可同时追加本周期预算",
101
+ args: "<id> [+steps N|+usd X]",
102
+ description: "重新启用该任务,可同时追加预算",
103
103
  example: "/tasks resume weekly-report +steps 20",
104
104
  },
105
- {
106
- name: "run",
107
- args: "<id>",
108
- description: "恢复并立即排入一次执行(需要运行时可用)",
109
- example: "/tasks run weekly-report",
110
- },
111
105
  {
112
106
  name: "steer",
113
107
  args: "<id> <内容>",
@@ -5,7 +5,7 @@ import { renderSubcommandUsage } from "../commands/catalog.js";
5
5
  import { capReply } from "../commands/reply-limits.js";
6
6
  import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
7
  import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
8
- import { parseScheduledEventContent } from "./events.js";
8
+ import { describeEventPayload, parseScheduledEventContent, } from "./events.js";
9
9
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
10
10
  const DEFAULT_HISTORY_LIMIT = 20;
11
11
  const TEXT_PREVIEW_MAX_CHARS = 100;
@@ -63,7 +63,7 @@ function formatEventSummary(name, event) {
63
63
  if (event.type === "periodic") {
64
64
  lines.push(`- schedule:${event.schedule}`);
65
65
  }
66
- lines.push(`- 内容:${clipText(event.text)}`);
66
+ lines.push(`- 内容:${clipText(describeEventPayload(event))}`);
67
67
  return lines.join("\n");
68
68
  }
69
69
  async function listEvents(workspaceDir) {
@@ -2,29 +2,30 @@ import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import type { Executor } from "../executor.js";
3
3
  import type { DingTalkBot } from "../runtime/dingtalk.js";
4
4
  import type { SecurityConfig } from "../security/types.js";
5
+ import { type TaskCreateInput } from "../tasks/contract-input.js";
5
6
  export interface EventAction {
6
7
  type: "bash";
7
8
  command: string;
8
9
  timeout?: number;
9
10
  }
10
- export interface OneShotEvent {
11
+ /**
12
+ * What an event delivers when it fires: a chat `text`, or a `task` template that spawns a fresh
13
+ * task instance (spec 052, D2). Exactly one is present — `parseScheduledEventContent` enforces it.
14
+ */
15
+ interface EventPayload {
16
+ text?: string;
17
+ task?: TaskCreateInput;
18
+ }
19
+ export interface OneShotEvent extends EventPayload {
11
20
  type: "one-shot";
12
21
  channelId: string;
13
- text: string;
14
22
  at: string;
15
23
  preAction?: EventAction;
16
24
  }
17
- export interface PeriodicEvent {
25
+ export interface PeriodicEvent extends EventPayload {
18
26
  type: "periodic";
19
27
  channelId: string;
20
- text: string;
21
28
  schedule: string;
22
- /**
23
- * Legacy field only. Pre-027 events carried an IANA `timezone`; it is no longer part of
24
- * the contract (cron follows the host timezone) but is preserved here on load so the
25
- * watcher can warn when it disagrees with the host, without rejecting or rewriting the file.
26
- */
27
- legacyTimezone?: string;
28
29
  preAction?: EventAction;
29
30
  }
30
31
  export type ScheduledEvent = OneShotEvent | PeriodicEvent;
@@ -54,11 +55,43 @@ export interface EventHistoryRecord {
54
55
  accepted: boolean;
55
56
  };
56
57
  }
58
+ /** One occurrence of a template event asking for a task instance (spec 052, D2). */
59
+ export interface SpawnTaskRequest {
60
+ /** The event's name (filename without `.json`); becomes the instance's `origin`. */
61
+ eventName: string;
62
+ channelId: string;
63
+ template: TaskCreateInput;
64
+ /** The moment this occurrence was due — deterministic per occurrence, so a replay maps to the same instance. */
65
+ occurrence: Date;
66
+ }
67
+ export type SpawnTaskResult =
68
+ /** A new instance was created. */
69
+ {
70
+ outcome: "spawned";
71
+ id: string;
72
+ }
73
+ /** This occurrence's instance already exists: an idempotent replay. */
74
+ | {
75
+ outcome: "exists";
76
+ id: string;
77
+ }
78
+ /** Another instance of the same event is still running; the user was told. */
79
+ | {
80
+ outcome: "skipped";
81
+ id: string;
82
+ };
57
83
  export interface EventsWatcherOptions {
58
84
  historyPath?: string;
85
+ /**
86
+ * Creates the task instance a template event asks for. Injected by the runtime so the events
87
+ * subsystem never reads or writes task files (spec 052, INV-8).
88
+ */
89
+ spawnTask?: (request: SpawnTaskRequest) => Promise<SpawnTaskResult>;
59
90
  /** Persist synthetic work before it enters the in-memory channel queue. */
60
91
  dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
61
92
  }
93
+ /** The one-line description of what an event delivers, for history records and listings. */
94
+ export declare function describeEventPayload(event: Pick<ScheduledEvent, "text" | "task">): string;
62
95
  export declare function parseScheduledEventContent(content: string, filename: string): ScheduledEvent;
63
96
  export declare class EventsWatcher {
64
97
  private eventsDir;
@@ -104,27 +137,14 @@ export declare class EventsWatcher {
104
137
  private wasWrittenAfterStart;
105
138
  private handleOneShot;
106
139
  private handlePeriodic;
140
+ private execute;
107
141
  /**
108
- * A task-owned event outlives its task whenever close-out fails or the task file is deleted
109
- * by hand, and then wakes the channel forever about work that no longer exists. Checking the
110
- * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
111
- *
112
- * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
113
- * owning channel is taken from the event definition and the id is parsed with the same
114
- * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
115
- * split that would cut a dotted task id short.
116
- */
117
- private orphanedOwnerReason;
118
- /**
119
- * Redeem the owning task's `signal` ticket, if this is a task-owned event and that task is
120
- * parked on a ticket naming exactly this event. Returns whether the ticket was redeemed.
121
- *
122
- * The name match is strict (INV-7): a ticket only accepts the event it names, so an unrelated
123
- * task-owned event can never resume a task, and a task parked on anything else still gets its
124
- * ordinary chat wake.
142
+ * Deliver a template event: ask the runtime for a fresh task instance (spec 052, D2). The
143
+ * occurrence is the one this trigger was *due* for — a one-shot's `at`, a periodic's cron tick —
144
+ * so a post-restart replay of the same occurrence lands on the same instance instead of making a
145
+ * second one.
125
146
  */
126
- private redeemTaskSignal;
127
- private execute;
147
+ private spawnTaskInstance;
128
148
  private runPreAction;
129
149
  private deleteFile;
130
150
  private getInvalidMarkerPath;
@@ -135,4 +155,5 @@ export declare class EventsWatcher {
135
155
  /**
136
156
  * Create and start an events watcher.
137
157
  */
138
- export declare function createEventsWatcher(workspaceDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string, dispatch?: EventsWatcherOptions["dispatch"]): EventsWatcher;
158
+ export declare function createEventsWatcher(workspaceDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string, dispatch?: EventsWatcherOptions["dispatch"], spawnTask?: EventsWatcherOptions["spawnTask"]): EventsWatcher;
159
+ export {};
@@ -2,7 +2,6 @@ import { Cron } from "croner";
2
2
  import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
3
3
  import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
- import { getChannelDir } from "../channel/channel-paths.js";
6
5
  import * as log from "../log.js";
7
6
  import { guardCommand } from "../security/command-guard.js";
8
7
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
@@ -10,9 +9,7 @@ import { createJsonlAppender } from "../shared/jsonl-appender.js";
10
9
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
11
10
  import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
12
11
  import { isPlainObject } from "../shared/type-guards.js";
13
- import { parseTaskFrontmatterV4 } from "../tasks/frontmatter.js";
14
- import { redeemTicket } from "../tasks/store.js";
15
- import { parseTaskEventName } from "../tasks/task-events.js";
12
+ import { validateTaskContractInput } from "../tasks/contract-input.js";
16
13
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
17
14
  // ============================================================================
18
15
  // EventsWatcher
@@ -23,16 +20,36 @@ const RETRY_BASE_MS = 100;
23
20
  const SCAN_CONCURRENCY = 4;
24
21
  const DEFAULT_PRE_ACTION_TIMEOUT_MS = 10_000;
25
22
  const TEXT_PREVIEW_MAX_CHARS = 160;
23
+ /** The one-line description of what an event delivers, for history records and listings. */
24
+ export function describeEventPayload(event) {
25
+ return event.task ? `任务模板:${event.task.title}` : (event.text ?? "");
26
+ }
26
27
  function truncateTextPreview(text) {
27
28
  return clipText(text, TEXT_PREVIEW_MAX_CHARS, { headRatio: 1, omitHint: "…", collapseWhitespace: true });
28
29
  }
29
30
  function readRequiredString(data, field, filename) {
30
31
  const value = data[field];
31
32
  if (typeof value !== "string" || value.trim().length === 0) {
32
- throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
33
+ throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
33
34
  }
34
35
  return value;
35
36
  }
37
+ /** `text` xor `task`: a chat message, or a template for a task instance (spec 052, D2). */
38
+ function parsePayload(data, filename) {
39
+ const hasText = typeof data.text === "string" && data.text.trim().length > 0;
40
+ const hasTask = data.task !== undefined;
41
+ if (hasText === hasTask) {
42
+ throw new Error(`An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
43
+ }
44
+ if (hasText)
45
+ return { text: data.text };
46
+ try {
47
+ return { task: validateTaskContractInput(data.task) };
48
+ }
49
+ catch (error) {
50
+ throw new Error(`Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
51
+ }
52
+ }
36
53
  function parsePreAction(data, filename) {
37
54
  if (!data.preAction)
38
55
  return undefined;
@@ -60,11 +77,11 @@ function parsePreAction(data, filename) {
60
77
  export function parseScheduledEventContent(content, filename) {
61
78
  const data = JSON.parse(content);
62
79
  if (!isPlainObject(data)) {
63
- throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
80
+ throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
64
81
  }
65
82
  const type = readRequiredString(data, "type", filename);
66
83
  const channelId = readRequiredString(data, "channelId", filename);
67
- const text = readRequiredString(data, "text", filename);
84
+ const payload = parsePayload(data, filename);
68
85
  const preAction = parsePreAction(data, filename);
69
86
  switch (type) {
70
87
  // Removed in spec 031 (D4): an event that fires the moment it is written is a
@@ -78,21 +95,17 @@ export function parseScheduledEventContent(content, filename) {
78
95
  if (typeof data.at !== "string" || data.at.trim().length === 0) {
79
96
  throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
80
97
  }
81
- return { type, channelId, text, at: data.at, ...(preAction ? { preAction } : {}) };
98
+ return { type, channelId, ...payload, at: data.at, ...(preAction ? { preAction } : {}) };
82
99
  }
83
100
  case "periodic": {
84
101
  if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
85
102
  throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
86
103
  }
87
- // A legacy `timezone` is tolerated (never a parse error) and carried through only for
88
- // the host-mismatch warning; the cron itself is always host-timezone.
89
- const legacyTimezone = typeof data.timezone === "string" && data.timezone.trim().length > 0 ? data.timezone : undefined;
90
104
  return {
91
105
  type,
92
106
  channelId,
93
- text,
107
+ ...payload,
94
108
  schedule: data.schedule,
95
- ...(legacyTimezone ? { legacyTimezone } : {}),
96
109
  ...(preAction ? { preAction } : {}),
97
110
  };
98
111
  }
@@ -220,7 +233,7 @@ export class EventsWatcher {
220
233
  channelId: event.channelId,
221
234
  action,
222
235
  result,
223
- textPreview: truncateTextPreview(event.text),
236
+ textPreview: truncateTextPreview(describeEventPayload(event)),
224
237
  ...(event.type === "one-shot" ? { at: event.at } : {}),
225
238
  ...(event.type === "periodic" ? { schedule: event.schedule } : {}),
226
239
  ...extra,
@@ -446,15 +459,6 @@ export class EventsWatcher {
446
459
  this.timers.set(filename, timer);
447
460
  }
448
461
  handlePeriodic(filename, event) {
449
- if (event.legacyTimezone) {
450
- const hostTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
451
- if (event.legacyTimezone !== hostTimezone) {
452
- log.logWarning(`Event ${filename} carries a legacy timezone ${event.legacyTimezone} that differs from the host ${hostTimezone}`, "The cron is now interpreted in the host timezone; trigger times may shift.");
453
- this.appendEventHistory(filename, event, "loaded", "ok", {
454
- reason: `legacy timezone ${event.legacyTimezone} ignored; using host ${hostTimezone}`,
455
- });
456
- }
457
- }
458
462
  try {
459
463
  const cron = new Cron(event.schedule, { protect: true, catch: true }, async () => {
460
464
  try {
@@ -483,69 +487,7 @@ export class EventsWatcher {
483
487
  this.markInvalid(filename, `Invalid cron schedule: ${event.schedule}\n${String(err)}`);
484
488
  }
485
489
  }
486
- /**
487
- * A task-owned event outlives its task whenever close-out fails or the task file is deleted
488
- * by hand, and then wakes the channel forever about work that no longer exists. Checking the
489
- * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
490
- *
491
- * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
492
- * owning channel is taken from the event definition and the id is parsed with the same
493
- * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
494
- * split that would cut a dotted task id short.
495
- */
496
- async orphanedOwnerReason(filename, event) {
497
- const parsed = parseTaskEventName(eventNameFromFilename(filename), event.channelId);
498
- if (!parsed)
499
- return undefined;
500
- const taskId = parsed.id;
501
- const taskPath = join(getChannelDir(dirname(this.eventsDir), event.channelId), "tasks", `${taskId}.md`);
502
- let content;
503
- try {
504
- content = await readFile(taskPath, "utf-8");
505
- }
506
- catch {
507
- return `owning task ${taskId} no longer exists`;
508
- }
509
- const frontmatter = parseTaskFrontmatterV4(content);
510
- return frontmatter.fields.outcome
511
- ? `owning task ${taskId} is archived (${frontmatter.fields.outcome})`
512
- : undefined;
513
- }
514
- /**
515
- * Redeem the owning task's `signal` ticket, if this is a task-owned event and that task is
516
- * parked on a ticket naming exactly this event. Returns whether the ticket was redeemed.
517
- *
518
- * The name match is strict (INV-7): a ticket only accepts the event it names, so an unrelated
519
- * task-owned event can never resume a task, and a task parked on anything else still gets its
520
- * ordinary chat wake.
521
- */
522
- async redeemTaskSignal(filename, event) {
523
- const name = eventNameFromFilename(filename);
524
- const parsed = parseTaskEventName(name, event.channelId);
525
- if (!parsed)
526
- return false;
527
- const channelDir = getChannelDir(dirname(this.eventsDir), event.channelId);
528
- try {
529
- const redeemed = await redeemTicket(channelDir, parsed.id, (ticket) => ticket.kind === "signal" && ticket.event === name);
530
- if (!redeemed)
531
- return false;
532
- log.logInfo(`Event ${name} redeemed the signal ticket for task ${parsed.id}`);
533
- return true;
534
- }
535
- catch (error) {
536
- log.logWarning(`Could not redeem signal ticket for task ${parsed.id}`, errorMessage(error));
537
- return false;
538
- }
539
- }
540
490
  async execute(filename, event, deleteAfter = true, occurrence = new Date()) {
541
- const orphaned = await this.orphanedOwnerReason(filename, event);
542
- if (orphaned) {
543
- log.logInfo(`Retiring orphaned task event: ${filename} (${orphaned})`);
544
- this.appendEventHistory(filename, event, "skipped", "skipped", { reason: orphaned });
545
- this.cancelScheduled(filename);
546
- this.deleteFile(filename);
547
- return;
548
- }
549
491
  if (event.preAction) {
550
492
  try {
551
493
  this.appendEventHistory(filename, event, "pre_action_started", "ok", {
@@ -586,16 +528,8 @@ export class EventsWatcher {
586
528
  return;
587
529
  }
588
530
  }
589
- // Spec 051, D8: the *only* touchpoint between the events subsystem and the task loop. When a
590
- // task-owned sensor fires and the owning task is parked on a `signal` ticket naming this very
591
- // event, redeem the ticket and stop — the task's own loop takes it from here, and delivering
592
- // a chat wake as well would both duplicate the work and route it into the wrong session.
593
- // Anything else (an ordinary event, or a task that is not waiting on this signal) falls
594
- // through to the unchanged delivery path below.
595
- if (await this.redeemTaskSignal(filename, event)) {
596
- this.appendEventHistory(filename, event, "triggered", "ok", { reason: "redeemed task signal ticket" });
597
- if (deleteAfter)
598
- this.deleteFile(filename);
531
+ if (event.task) {
532
+ await this.spawnTaskInstance(filename, event, event.task, deleteAfter, occurrence);
599
533
  return;
600
534
  }
601
535
  let scheduleInfo;
@@ -612,7 +546,7 @@ export class EventsWatcher {
612
546
  const periodicContract = event.type === "periodic"
613
547
  ? " This is a periodic runtime wake. If it produces no user-visible change or result, reply with exactly [SILENT]."
614
548
  : "";
615
- const message = `[EVENT:${filename}:${event.type}:${scheduleInfo}] ${event.text}${periodicContract}`;
549
+ const message = `[EVENT:${filename}:${event.type}:${scheduleInfo}] ${event.text ?? ""}${periodicContract}`;
616
550
  // Create synthetic ChannelEvent
617
551
  const syntheticEvent = {
618
552
  type: "dm",
@@ -647,6 +581,44 @@ export class EventsWatcher {
647
581
  this.markInvalid(filename, `Event queue was full at ${new Date().toISOString()}; this occurrence was not delivered.`);
648
582
  }
649
583
  }
584
+ /**
585
+ * Deliver a template event: ask the runtime for a fresh task instance (spec 052, D2). The
586
+ * occurrence is the one this trigger was *due* for — a one-shot's `at`, a periodic's cron tick —
587
+ * so a post-restart replay of the same occurrence lands on the same instance instead of making a
588
+ * second one.
589
+ */
590
+ async spawnTaskInstance(filename, event, template, deleteAfter, occurrence) {
591
+ const spawn = this.options.spawnTask;
592
+ const due = event.type === "one-shot" ? new Date(parseLocalTime(event.at) ?? occurrence.getTime()) : occurrence;
593
+ try {
594
+ if (!spawn)
595
+ throw new Error("this runtime cannot create task instances");
596
+ const result = await spawn({
597
+ eventName: eventNameFromFilename(filename),
598
+ channelId: event.channelId,
599
+ template,
600
+ occurrence: due,
601
+ });
602
+ const delivered = result.outcome === "spawned";
603
+ this.appendEventHistory(filename, event, delivered ? "enqueued" : "skipped", "ok", {
604
+ reason: result.outcome === "spawned"
605
+ ? `spawned task ${result.id}`
606
+ : result.outcome === "exists"
607
+ ? `task ${result.id} already exists for this occurrence`
608
+ : `previous instance ${result.id} is still running`,
609
+ });
610
+ if (deleteAfter)
611
+ this.deleteFile(filename);
612
+ }
613
+ catch (err) {
614
+ const reason = errorMessage(err);
615
+ log.logWarning(`Could not spawn a task for event: ${filename}`, reason);
616
+ this.appendEventHistory(filename, event, "skipped", "error", { reason });
617
+ if (deleteAfter) {
618
+ this.markInvalid(filename, `Could not create the task instance at ${new Date().toISOString()}: ${reason}`);
619
+ }
620
+ }
621
+ }
650
622
  async runPreAction(action, filename) {
651
623
  const startedAt = Date.now();
652
624
  if (this.commandGuardConfig?.enabled) {
@@ -726,7 +698,7 @@ export class EventsWatcher {
726
698
  /**
727
699
  * Create and start an events watcher.
728
700
  */
729
- export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig, historyPath, dispatch) {
701
+ export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig, historyPath, dispatch, spawnTask) {
730
702
  const eventsDir = join(workspaceDir, "events");
731
- return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig, { historyPath, dispatch });
703
+ return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig, { historyPath, dispatch, spawnTask });
732
704
  }
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
3
- * `SESSION.md` (current state) and `HISTORY.md` (folded older history) — a day is never
4
- * folded or rewritten, only appended to, so it stays a plain, growing record.
2
+ * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day — never folded or
3
+ * rewritten, so it stays a plain, growing record.
5
4
  */
6
5
  export declare function getJournalDir(channelDir: string): string;
7
6
  export declare function getJournalPath(channelDir: string, date: string): string;
@@ -4,9 +4,8 @@ import { writeFileAtomically } from "../shared/atomic-file.js";
4
4
  import { localDayKey } from "../shared/local-time.js";
5
5
  import { isNodeError, readOptionalTextFile } from "../shared/os.js";
6
6
  /**
7
- * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
8
- * `SESSION.md` (current state) and `HISTORY.md` (folded older history) — a day is never
9
- * folded or rewritten, only appended to, so it stays a plain, growing record.
7
+ * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day — never folded or
8
+ * rewritten, so it stays a plain, growing record.
10
9
  */
11
10
  export function getJournalDir(channelDir) {
12
11
  return join(channelDir, "journal");
@@ -11,7 +11,6 @@ export interface MemoryMaintenanceTuning {
11
11
  minIdleMinutesBeforeLlmWork: number;
12
12
  /** Idle cadence of the reflect pass. */
13
13
  reflectIntervalMinutes: number;
14
- maxConcurrentChannels: number;
15
14
  failureBackoffMinutes: number;
16
15
  }
17
16
  export declare function getMemoryMaintenanceTuning(env?: NodeJS.ProcessEnv): MemoryMaintenanceTuning;
@@ -9,7 +9,6 @@
9
9
  const PRODUCTION_TUNING = {
10
10
  minIdleMinutesBeforeLlmWork: 10,
11
11
  reflectIntervalMinutes: 20,
12
- maxConcurrentChannels: 1,
13
12
  failureBackoffMinutes: 30,
14
13
  };
15
14
  /**
@@ -60,9 +60,6 @@ export async function discoverMemoryMaintenanceChannels(input) {
60
60
  ...(await listStateChannels(input.appHomeDir)),
61
61
  ]);
62
62
  }
63
- function normalizeMaxConcurrentChannels(value) {
64
- return Number.isFinite(value) ? Math.max(1, Math.floor(value)) : 1;
65
- }
66
63
  export class MemoryMaintenanceScheduler {
67
64
  constructor(options) {
68
65
  this.options = options;
@@ -103,30 +100,25 @@ export class MemoryMaintenanceScheduler {
103
100
  workspaceDir: this.options.workspaceDir,
104
101
  knownChannelIds: this.options.getKnownChannelIds?.(),
105
102
  });
106
- const maxConcurrent = normalizeMaxConcurrentChannels(settings.memoryMaintenance.maxConcurrentChannels);
107
103
  if (channelIds.length === 0) {
108
104
  return;
109
105
  }
110
- const selected = [];
111
- let scanned = 0;
106
+ // One channel per tick, round-robin: a reflect pass is an LLM call, and the first due
107
+ // channel is as good a place to spend it as any.
108
+ let selected;
112
109
  let index = this.nextChannelIndex % channelIds.length;
113
- while (scanned < channelIds.length && selected.length < maxConcurrent) {
110
+ for (let scanned = 0; scanned < channelIds.length && !selected; scanned++) {
114
111
  const channelId = channelIds[index];
115
112
  if (channelId &&
116
113
  !this.options.isChannelActive(channelId) &&
117
- (await mightReflectBeDue({
118
- appHomeDir: this.options.appHomeDir,
119
- channelId,
120
- settings,
121
- now,
122
- }))) {
123
- selected.push(channelId);
114
+ (await mightReflectBeDue({ appHomeDir: this.options.appHomeDir, channelId, settings, now }))) {
115
+ selected = channelId;
124
116
  }
125
117
  index = (index + 1) % channelIds.length;
126
- scanned++;
127
118
  }
128
119
  this.nextChannelIndex = index;
129
- await Promise.all(selected.map((channelId) => this.runChannelOnce(channelId, now)));
120
+ if (selected)
121
+ await this.runChannelOnce(selected, now);
130
122
  }
131
123
  finally {
132
124
  this.running = false;
@@ -24,9 +24,8 @@ export function recencyBoostByAge(timestamp, weights) {
24
24
  return 0;
25
25
  }
26
26
  /**
27
- * Spec 050, D3/D4: the lexical tokenizer, moved here from the retired `recall.ts`. It now serves
28
- * exactly two callers — `memory_search` and `memory_save`'s deterministic near-duplicate guard.
29
- * Per-turn recall scoring, intent seeding, and the usage-count boost are gone.
27
+ * Spec 050, D3/D4: the lexical tokenizer. It serves exactly two callers — `memory_search` and
28
+ * `memory_save`'s deterministic near-duplicate guard.
30
29
  */
31
30
  const TOKEN_PART_REGEX = /[\p{Script=Han}]+|[\p{L}\p{N}_./-]+/gu;
32
31
  const ASCII_SPLIT_REGEX = /[._/-]+/g;
@@ -53,15 +53,9 @@ function scoreDocument(document, lowerQuery, queryTokens) {
53
53
  matches.push(token);
54
54
  }
55
55
  }
56
- // `recall.ts` deliberately dropped a coverage-ratio term (`matched / queryTokens.length`) in
57
- // favor of absolute specificity-weighted evidence, because normalizing by query length made
58
- // detailed messages score worse the more context they gave (see the long comment on
59
- // `MIN_MATCH_EVIDENCE` there). This scorer still uses coverage, kept as a small, capped (0-2)
60
- // tiebreaker behind the dominant `matchedTokens * 1.4` term rather than removed outright:
61
- // `session_search` is an explicit on-demand query over raw transcript chunks, not the passive
62
- // per-turn injection recall.ts drives, so it has no eval pinning its current ranking and no
63
- // reported failure mode from this term. Changing it blind, without that guardrail, risks
64
- // swapping one unverified scoring bias for another.
56
+ // Coverage (`matched / queryTokens.length`) is a small, capped (0-2) tiebreaker behind the
57
+ // dominant `matchedTokens * 1.4` term. Normalizing by query length alone would make detailed
58
+ // queries score worse the more context they give, so it must stay a tiebreaker.
65
59
  const coverage = queryTokens.length > 0 ? matchedTokens / queryTokens.length : 0;
66
60
  const exactHit = Boolean(lowerQuery) && lowerText.includes(lowerQuery);
67
61
  const score = matchedTokens * 1.4 + coverage * 2 + (exactHit ? 1 : 0) + computeRecencyBoost(document.timestamp);