@oyasmi/pipiclaw 0.7.7 → 0.8.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 (114) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/channel-runner.d.ts +4 -4
  3. package/dist/agent/channel-runner.js +25 -23
  4. package/dist/agent/commands.js +7 -2
  5. package/dist/agent/job-manager.d.ts +5 -5
  6. package/dist/agent/prompt-builder.d.ts +3 -13
  7. package/dist/agent/prompt-builder.js +49 -159
  8. package/dist/agent/run-queue.js +2 -1
  9. package/dist/agent/runner-factory.d.ts +1 -2
  10. package/dist/agent/runner-factory.js +2 -2
  11. package/dist/agent/status-render.d.ts +0 -7
  12. package/dist/agent/status-render.js +8 -3
  13. package/dist/agent/types.d.ts +2 -0
  14. package/dist/agent/workspace-resources.d.ts +1 -1
  15. package/dist/agent/workspace-resources.js +3 -15
  16. package/dist/executor.d.ts +20 -0
  17. package/dist/{sandbox.js → executor.js} +3 -95
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/log.d.ts +1 -1
  21. package/dist/log.js +1 -2
  22. package/dist/memory/files.js +0 -0
  23. package/dist/memory/lifecycle.js +6 -5
  24. package/dist/memory/maintenance-jobs.d.ts +0 -1
  25. package/dist/memory/maintenance-jobs.js +2 -2
  26. package/dist/memory/maintenance-state.js +2 -1
  27. package/dist/memory/post-turn-review.d.ts +0 -1
  28. package/dist/memory/post-turn-review.js +4 -4
  29. package/dist/memory/scheduler.d.ts +0 -1
  30. package/dist/memory/scheduler.js +2 -2
  31. package/dist/memory/session.js +2 -2
  32. package/dist/memory/task-digest.js +17 -0
  33. package/dist/paths.d.ts +2 -0
  34. package/dist/paths.js +11 -0
  35. package/dist/playbooks/catalog.d.ts +9 -0
  36. package/dist/playbooks/catalog.js +44 -0
  37. package/dist/playbooks/event-scheduling.md +43 -0
  38. package/dist/playbooks/memory-and-learning.md +45 -0
  39. package/dist/playbooks/runtime-orientation.md +48 -0
  40. package/dist/playbooks/task-closeout.md +45 -0
  41. package/dist/playbooks/task-delegation.md +44 -0
  42. package/dist/playbooks/task-driving.md +43 -0
  43. package/dist/playbooks/task-planning.md +47 -0
  44. package/dist/playbooks/task-recurring.md +42 -0
  45. package/dist/playbooks/task-repair.md +43 -0
  46. package/dist/runtime/bootstrap.d.ts +12 -11
  47. package/dist/runtime/bootstrap.js +81 -57
  48. package/dist/runtime/delivery.js +4 -3
  49. package/dist/runtime/dingtalk.d.ts +2 -0
  50. package/dist/runtime/dingtalk.js +15 -14
  51. package/dist/runtime/durable-dispatch.d.ts +30 -0
  52. package/dist/runtime/durable-dispatch.js +172 -0
  53. package/dist/runtime/event-commands.js +4 -4
  54. package/dist/runtime/events.d.ts +5 -3
  55. package/dist/runtime/events.js +17 -13
  56. package/dist/runtime/task-commands.d.ts +6 -0
  57. package/dist/runtime/task-commands.js +292 -6
  58. package/dist/runtime/task-driver.d.ts +32 -0
  59. package/dist/runtime/task-driver.js +268 -0
  60. package/dist/security/config.js +2 -1
  61. package/dist/security/network.js +9 -2
  62. package/dist/security/path-guard.js +12 -24
  63. package/dist/security/types.d.ts +0 -1
  64. package/dist/settings.d.ts +12 -0
  65. package/dist/settings.js +30 -0
  66. package/dist/shared/jsonl-appender.js +2 -1
  67. package/dist/shared/task-ledger.d.ts +35 -0
  68. package/dist/shared/task-ledger.js +229 -15
  69. package/dist/shared/text-utils.d.ts +1 -0
  70. package/dist/shared/text-utils.js +3 -0
  71. package/dist/subagents/discovery.js +3 -2
  72. package/dist/subagents/tool.d.ts +15 -3
  73. package/dist/subagents/tool.js +194 -17
  74. package/dist/tasks/artifact-subject.d.ts +6 -0
  75. package/dist/tasks/artifact-subject.js +29 -0
  76. package/dist/tasks/control.d.ts +83 -0
  77. package/dist/tasks/control.js +293 -0
  78. package/dist/tasks/store.d.ts +32 -0
  79. package/dist/tasks/store.js +142 -0
  80. package/dist/tasks/verification.d.ts +23 -0
  81. package/dist/tasks/verification.js +69 -0
  82. package/dist/tools/bash.d.ts +1 -1
  83. package/dist/tools/bash.js +3 -5
  84. package/dist/tools/command-optimizer.d.ts +1 -1
  85. package/dist/tools/command-optimizer.js +4 -6
  86. package/dist/tools/config.js +4 -3
  87. package/dist/tools/edit.d.ts +1 -1
  88. package/dist/tools/edit.js +0 -0
  89. package/dist/tools/event-manage.d.ts +0 -1
  90. package/dist/tools/event-manage.js +9 -14
  91. package/dist/tools/grep.d.ts +1 -1
  92. package/dist/tools/grep.js +4 -6
  93. package/dist/tools/index.d.ts +1 -3
  94. package/dist/tools/index.js +1 -4
  95. package/dist/tools/read.d.ts +1 -1
  96. package/dist/tools/read.js +1 -2
  97. package/dist/tools/registry.d.ts +2 -3
  98. package/dist/tools/registry.js +5 -11
  99. package/dist/tools/skill-manage.d.ts +0 -1
  100. package/dist/tools/skill-manage.js +7 -14
  101. package/dist/tools/task-manage.d.ts +37 -4
  102. package/dist/tools/task-manage.js +398 -39
  103. package/dist/tools/write-content.d.ts +1 -1
  104. package/dist/tools/write-content.js +0 -1
  105. package/dist/tools/write.d.ts +1 -1
  106. package/dist/tui/app.d.ts +0 -2
  107. package/dist/tui/app.js +12 -7
  108. package/dist/tui/cli.d.ts +0 -2
  109. package/dist/tui/cli.js +3 -25
  110. package/dist/tui/turn-controller.d.ts +7 -3
  111. package/dist/tui/turn-controller.js +9 -6
  112. package/dist/web/client.js +2 -1
  113. package/package.json +2 -2
  114. package/dist/sandbox.d.ts +0 -42
@@ -0,0 +1,268 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import * as log from "../log.js";
4
+ import { PLAYBOOKS_DIR } from "../paths.js";
5
+ import { taskEventName } from "../shared/task-events.js";
6
+ import { readActiveTasks } from "../shared/task-ledger.js";
7
+ import { errorMessage } from "../shared/text-utils.js";
8
+ import { taskBudgetViolation } from "../tasks/control.js";
9
+ import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim } from "../tasks/store.js";
10
+ import { parseScheduledEventContent } from "./events.js";
11
+ const DEFAULT_SCAN_INTERVAL_MS = 60_000;
12
+ const LEGACY_CHECKIN_HANDOFF_GRACE_MS = 2 * 60_000;
13
+ const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
14
+ function isChannelId(value) {
15
+ return CHANNEL_ID_PATTERN.test(value);
16
+ }
17
+ export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
18
+ const channels = new Set();
19
+ for (const channelId of knownChannelIds) {
20
+ if (isChannelId(channelId))
21
+ channels.add(channelId);
22
+ }
23
+ try {
24
+ const entries = await readdir(workspaceDir, { withFileTypes: true });
25
+ for (const entry of entries) {
26
+ if (entry.isDirectory() && isChannelId(entry.name))
27
+ channels.add(entry.name);
28
+ }
29
+ }
30
+ catch {
31
+ // A missing/unreadable workspace simply has no tasks to drive this tick.
32
+ }
33
+ return Array.from(channels).sort();
34
+ }
35
+ function attemptKey(channelId, taskId) {
36
+ return `${channelId}\0${taskId}`;
37
+ }
38
+ async function taskFingerprint(_channelDir, entry) {
39
+ // Do not use mtime/size here. Runtime usage accounting deliberately rewrites
40
+ // task control after every attempt; treating that bookkeeping as progress made
41
+ // governed tasks retry at the short continuation interval forever.
42
+ const control = entry.frontmatter.control;
43
+ return [
44
+ entry.frontmatter.readable ? "readable" : "unreadable",
45
+ entry.frontmatter.status ?? "",
46
+ entry.frontmatter.wake ?? "",
47
+ entry.frontmatter.recurrence ?? "",
48
+ entry.latestNote ?? "",
49
+ control?.nextAction ?? "",
50
+ control?.blockedReason ?? "",
51
+ control?.verification.status ?? "",
52
+ control?.cycleId ?? "",
53
+ ].join("\0");
54
+ }
55
+ function isEligible(attempt, fingerprint, nowMs, settings) {
56
+ if (!attempt)
57
+ return true;
58
+ const changed = attempt.fingerprint !== fingerprint;
59
+ const delayMinutes = changed || !attempt.accepted ? settings.continuationDelayMinutes : settings.stalledRetryMinutes;
60
+ return nowMs - attempt.atMs >= delayMinutes * 60_000;
61
+ }
62
+ async function hasLiveLegacyCheckin(workspaceDir, channelId, taskId, nowMs) {
63
+ const name = taskEventName(channelId, taskId, "checkin");
64
+ const path = join(workspaceDir, "events", `${name}.json`);
65
+ try {
66
+ const event = parseScheduledEventContent(await readFile(path, "utf-8"), `${name}.json`);
67
+ if (event.type !== "one-shot")
68
+ return false;
69
+ const atMs = new Date(event.at).getTime();
70
+ return Number.isFinite(atMs) && atMs >= nowMs - LEGACY_CHECKIN_HANDOFF_GRACE_MS;
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ }
76
+ export function createTaskDriverEvent(channelId, entry, nowMs) {
77
+ const verification = entry.frontmatter.control?.verification;
78
+ const verificationInstruction = entry.frontmatter.status === "verifying"
79
+ ? verification?.status === "passed"
80
+ ? " Independent verification already passed; preserve its body/artifact hashes and follow the closeout playbook."
81
+ : " This is a checker-only turn: read the closeout playbook and do not continue implementation."
82
+ : "";
83
+ const repair = entry.frontmatter.readable
84
+ ? ""
85
+ : ` Its frontmatter is unreadable: also read ${join(PLAYBOOKS_DIR, "task-repair.md")}.`;
86
+ const control = entry.frontmatter.control;
87
+ const capsule = [
88
+ `Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "open"};`,
89
+ entry.latestNote ? `latest=${entry.latestNote};` : "",
90
+ control?.nextAction ? `next=${control.nextAction};` : "",
91
+ control ? `budget=${control.usage.attempts}/${control.budget.maxAttempts} attempts;` : "",
92
+ ]
93
+ .filter(Boolean)
94
+ .join(" ");
95
+ return {
96
+ type: channelId.startsWith("group_") ? "group" : "dm",
97
+ channelId,
98
+ user: "TASK_DRIVER",
99
+ userName: "TASK_DRIVER",
100
+ text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} ` +
101
+ `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-driving.md")} before acting. ` +
102
+ "Advance the next concrete step under the task's current control, acceptance, approval, and verification state. " +
103
+ `If complete or waiting, use the matching task_manage lifecycle/checkpoint action from the playbook.${verificationInstruction}`,
104
+ ts: String(nowMs),
105
+ conversationId: "",
106
+ conversationType: channelId.startsWith("group_") ? "2" : "1",
107
+ };
108
+ }
109
+ function taskEscalationEvent(channelId, entry, reason, nowMs) {
110
+ return {
111
+ type: channelId.startsWith("group_") ? "group" : "dm",
112
+ channelId,
113
+ user: "TASK_DRIVER",
114
+ userName: "TASK_DRIVER",
115
+ text: `[TASK_ESCALATION:${entry.id}] Task ${entry.id} (${entry.title}) was stopped by the deterministic task ` +
116
+ `governor: ${reason}. Read ${join(PLAYBOOKS_DIR, "task-repair.md")}, diagnose before changing control, ` +
117
+ "inform the user of the cause and recovery, and do not continue implementation in this run.",
118
+ ts: String(nowMs),
119
+ conversationId: "",
120
+ conversationType: channelId.startsWith("group_") ? "2" : "1",
121
+ };
122
+ }
123
+ function terminalDependencyReason(reason) {
124
+ return reason?.includes(" is missing") ||
125
+ reason?.includes(" is cancelled") ||
126
+ reason?.includes(" is escalated") ||
127
+ reason?.includes("dependency cycle")
128
+ ? reason
129
+ : undefined;
130
+ }
131
+ /**
132
+ * Native, token-gated driver for the persistent task ledger.
133
+ *
134
+ * The scan itself is deterministic and cheap. It wakes at most one actionable task
135
+ * per channel, skips active channels, backs off unchanged ledgers, and round-robins
136
+ * dispatches so a busy channel cannot starve the rest. `wake` is therefore sufficient
137
+ * to resume a task; users do not need to install a heartbeat event or sensor script.
138
+ */
139
+ export class TaskDriver {
140
+ constructor(options) {
141
+ this.options = options;
142
+ this.timer = null;
143
+ this.running = false;
144
+ this.nextChannelIndex = 0;
145
+ this.attempts = new Map();
146
+ }
147
+ start() {
148
+ if (this.timer)
149
+ return;
150
+ this.timer = setInterval(() => {
151
+ void this.runOnce().catch((error) => {
152
+ log.logWarning("Task driver tick failed", errorMessage(error));
153
+ });
154
+ }, this.options.intervalMs ?? DEFAULT_SCAN_INTERVAL_MS);
155
+ this.timer.unref?.();
156
+ }
157
+ stop() {
158
+ if (!this.timer)
159
+ return;
160
+ clearInterval(this.timer);
161
+ this.timer = null;
162
+ }
163
+ async runOnce(now = new Date()) {
164
+ const settings = this.options.getSettings();
165
+ if (!settings.enabled || this.running)
166
+ return;
167
+ this.running = true;
168
+ try {
169
+ const channels = await discoverTaskChannels(this.options.workspaceDir, this.options.getKnownChannelIds?.());
170
+ if (channels.length === 0) {
171
+ this.attempts.clear();
172
+ return;
173
+ }
174
+ const seen = new Set();
175
+ const start = this.nextChannelIndex % channels.length;
176
+ let dispatched = 0;
177
+ let lastDispatchOffset = -1;
178
+ for (let offset = 0; offset < channels.length; offset++) {
179
+ const channelId = channels[(start + offset) % channels.length];
180
+ if (!channelId)
181
+ continue;
182
+ const channelDir = join(this.options.workspaceDir, channelId);
183
+ const entries = await readActiveTasks(join(channelDir, "tasks"), now.getTime());
184
+ for (const entry of entries)
185
+ seen.add(attemptKey(channelId, entry.id));
186
+ if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
187
+ continue;
188
+ let governanceHandled = false;
189
+ for (const candidate of entries) {
190
+ const status = candidate.frontmatter.status;
191
+ const control = candidate.frontmatter.control;
192
+ if (!control ||
193
+ status === "done" ||
194
+ status === "cancelled" ||
195
+ status === "escalated" ||
196
+ status === "paused")
197
+ continue;
198
+ const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
199
+ const escalationReason = taskBudgetViolation(control, now.getTime()) ?? terminalDependencyReason(dependencies.reason);
200
+ if (!escalationReason)
201
+ continue;
202
+ governanceHandled = true;
203
+ const accepted = await this.options.dispatch(taskEscalationEvent(channelId, candidate, escalationReason, now.getTime()));
204
+ if (accepted && (await escalateTask(channelDir, candidate.id, escalationReason))) {
205
+ dispatched++;
206
+ lastDispatchOffset = offset;
207
+ log.logWarning(`[${channelId}] Task driver escalated ${candidate.id}`, escalationReason);
208
+ }
209
+ break;
210
+ }
211
+ if (governanceHandled)
212
+ continue;
213
+ const candidates = entries.filter((candidate) => candidate.actionable);
214
+ if (candidates.length === 0)
215
+ continue;
216
+ let entry;
217
+ for (const candidate of candidates) {
218
+ const control = candidate.frontmatter.control;
219
+ if (!control) {
220
+ entry = candidate;
221
+ break;
222
+ }
223
+ const dependencies = await dependencyState(channelDir, control.dependsOn, candidate.id);
224
+ if (!dependencies.ready)
225
+ continue;
226
+ entry = candidate;
227
+ break;
228
+ }
229
+ if (!entry || dispatched >= settings.maxDispatchesPerTick)
230
+ continue;
231
+ // Upgrade compatibility: while a legacy task-owned one-shot is still
232
+ // about to deliver this same wake, let it own the handoff. Once it is
233
+ // consumed (or stale for >2m), the native driver becomes the recovery path.
234
+ if (await hasLiveLegacyCheckin(this.options.workspaceDir, channelId, entry.id, now.getTime())) {
235
+ continue;
236
+ }
237
+ const key = attemptKey(channelId, entry.id);
238
+ let fingerprint = await taskFingerprint(channelDir, entry);
239
+ if (!isEligible(this.attempts.get(key), fingerprint, now.getTime(), settings))
240
+ continue;
241
+ const claim = entry.frontmatter.control ? await claimTaskAttempt(channelDir, entry.id, now) : undefined;
242
+ if (claim) {
243
+ fingerprint = await taskFingerprint(channelDir, entry);
244
+ }
245
+ const accepted = await this.options.dispatch(createTaskDriverEvent(channelId, entry, now.getTime()));
246
+ if (!accepted && claim)
247
+ await releaseTaskAttemptClaim(channelDir, entry.id, claim, now);
248
+ this.attempts.set(key, { fingerprint, atMs: now.getTime(), accepted });
249
+ if (accepted) {
250
+ dispatched++;
251
+ lastDispatchOffset = offset;
252
+ log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
253
+ }
254
+ else {
255
+ log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
256
+ }
257
+ }
258
+ for (const key of this.attempts.keys()) {
259
+ if (!seen.has(key))
260
+ this.attempts.delete(key);
261
+ }
262
+ this.nextChannelIndex = (start + (lastDispatchOffset >= 0 ? lastDispatchOffset + 1 : 1)) % channels.length;
263
+ }
264
+ finally {
265
+ this.running = false;
266
+ }
267
+ }
268
+ }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { APP_HOME_DIR } from "../paths.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
4
5
  import { isRecord } from "../shared/type-guards.js";
5
6
  export const DEFAULT_SECURITY_CONFIG = {
6
7
  enabled: true,
@@ -122,7 +123,7 @@ export function loadSecurityConfigWithDiagnostics(appHomeDir = APP_HOME_DIR) {
122
123
  source: "security",
123
124
  path: configPath,
124
125
  severity: "error",
125
- message: error instanceof Error ? error.message : String(error),
126
+ message: errorMessage(error),
126
127
  },
127
128
  ],
128
129
  };
@@ -1,5 +1,6 @@
1
1
  import { lookup } from "node:dns/promises";
2
2
  import { isIP } from "node:net";
3
+ import { errorMessage } from "../shared/text-utils.js";
3
4
  export class NetworkGuardError extends Error {
4
5
  constructor(options) {
5
6
  super(options.message);
@@ -24,7 +25,13 @@ const PRIVATE_IPV4_CIDRS = [
24
25
  ];
25
26
  const PRIVATE_IPV6_CIDRS = ["::1/128", "::/128", "fc00::/7", "fe80::/10"];
26
27
  function normalizeHost(host) {
27
- return host.trim().replace(/\.$/, "").toLowerCase();
28
+ // WHATWG URL.hostname keeps the brackets on an IPv6 literal (e.g. "[::1]"),
29
+ // but isIP()/DNS resolution both expect the bare address — without stripping
30
+ // them, every IPv6 literal URL (public or private) falls through to a DNS
31
+ // lookup of the literal bracketed string, which fails and rejects the
32
+ // request regardless of whether the address was actually private.
33
+ const unbracketed = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
34
+ return unbracketed.trim().replace(/\.$/, "").toLowerCase();
28
35
  }
29
36
  function parseIpv4(ip) {
30
37
  const parts = ip.split(".");
@@ -208,7 +215,7 @@ async function validateUrlTarget(rawUrl, context, stage) {
208
215
  url: rawUrl,
209
216
  stage,
210
217
  category: "dns-failure",
211
- message: `Failed to resolve host ${hostname}: ${error instanceof Error ? error.message : String(error)}`,
218
+ message: `Failed to resolve host ${hostname}: ${errorMessage(error)}`,
212
219
  resolvedHost: hostname,
213
220
  });
214
221
  }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, realpathSync } from "node:fs";
2
2
  import { homedir, tmpdir } from "node:os";
3
3
  import { basename, dirname, isAbsolute, normalize, resolve } from "node:path";
4
+ import { PLAYBOOKS_DIR } from "../paths.js";
4
5
  const PRIVATE_KEY_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
5
6
  const PRIVATE_KEY_NAME_HINTS = /(id_rsa|id_ed25519|private|secret|credentials)/i;
6
7
  const PROC_MEM_PATH = /^\/proc\/\d+\/mem(?:\/|$)/;
@@ -63,41 +64,24 @@ function maybeExpandHome(path, homeDir) {
63
64
  function resolveHomeConfiguredPath(rawPath, homeDir) {
64
65
  return normalize(maybeExpandHome(stripNullAndNormalize(rawPath), homeDir));
65
66
  }
66
- function translateRuntimeWorkspacePath(path, ctx) {
67
- if (!isAbsolute(path)) {
68
- return path;
69
- }
70
- if (!ctx.workspacePath || ctx.workspacePath === ctx.workspaceDir) {
71
- return path;
72
- }
73
- if (path === ctx.workspacePath) {
74
- return ctx.workspaceDir;
75
- }
76
- if (path.startsWith(withTrailingSlash(ctx.workspacePath))) {
77
- return resolve(ctx.workspaceDir, path.slice(ctx.workspacePath.length + 1));
78
- }
79
- return path;
80
- }
81
67
  function resolveConfiguredPath(rawPath, ctx) {
82
68
  const homeDir = ctx.homeDir ?? homedir();
83
69
  const normalized = stripNullAndNormalize(rawPath);
84
70
  const expanded = maybeExpandHome(normalized, homeDir);
85
- const translated = translateRuntimeWorkspacePath(expanded, ctx);
86
- if (isAbsolute(translated)) {
87
- return normalize(translated);
71
+ if (isAbsolute(expanded)) {
72
+ return normalize(expanded);
88
73
  }
89
- return resolve(ctx.workspaceDir, translated);
74
+ return resolve(ctx.workspaceDir, expanded);
90
75
  }
91
76
  function resolveTargetPath(rawPath, ctx) {
92
77
  const homeDir = ctx.homeDir ?? homedir();
93
78
  const cwd = ctx.cwd ?? process.cwd();
94
79
  const normalized = stripNullAndNormalize(rawPath);
95
80
  const expanded = maybeExpandHome(normalized, homeDir);
96
- const translated = translateRuntimeWorkspacePath(expanded, ctx);
97
- if (isAbsolute(translated)) {
98
- return normalize(translated);
81
+ if (isAbsolute(expanded)) {
82
+ return normalize(expanded);
99
83
  }
100
- return resolve(cwd, translated);
84
+ return resolve(cwd, expanded);
101
85
  }
102
86
  function resolveExistingAncestor(path) {
103
87
  let current = normalize(path);
@@ -183,6 +167,10 @@ function pathAllowedByDefaults(path, ctx) {
183
167
  const homeDir = ctx.homeDir ?? homedir();
184
168
  return isWithinWorkspace(path, ctx.workspaceDir) || isWithinTemp(path) || isWithinHome(path, homeDir);
185
169
  }
170
+ /** The runtime's own bundled playbooks are readable regardless of where the package is installed. */
171
+ function isBundledPlaybookRead(path, operation) {
172
+ return operation === "read" && startsWithPathPrefix(path, normalize(PLAYBOOKS_DIR));
173
+ }
186
174
  function formatBlockedResult(operation, rawPath, resolvedPath, category, reason) {
187
175
  return {
188
176
  allowed: false,
@@ -227,7 +215,7 @@ export function guardPath(rawPath, operation, ctx) {
227
215
  if (matchesConfiguredPath(guardedPath, operation === "read" ? effectiveCtx.config.readAllow : effectiveCtx.config.writeAllow, effectiveCtx)) {
228
216
  return { allowed: true, operation, rawPath, resolvedPath: guardedPath };
229
217
  }
230
- if (pathAllowedByDefaults(guardedPath, effectiveCtx)) {
218
+ if (pathAllowedByDefaults(guardedPath, effectiveCtx) || isBundledPlaybookRead(guardedPath, operation)) {
231
219
  return { allowed: true, operation, rawPath, resolvedPath: guardedPath };
232
220
  }
233
221
  if (isDeniedSystemPath(guardedPath)) {
@@ -27,7 +27,6 @@ export interface SecurityConfig {
27
27
  }
28
28
  export interface SecurityRuntimeContext {
29
29
  workspaceDir: string;
30
- workspacePath: string;
31
30
  cwd?: string;
32
31
  homeDir?: string;
33
32
  }
@@ -65,6 +65,16 @@ export interface PipiclawTaskDigestSettings {
65
65
  maxTasks: number;
66
66
  maxChars: number;
67
67
  }
68
+ export interface PipiclawTaskDriverSettings {
69
+ /** Native runtime wake-up for actionable task-ledger entries. */
70
+ enabled: boolean;
71
+ /** Earliest continuation after a task changed during its previous run. */
72
+ continuationDelayMinutes: number;
73
+ /** Retry delay when a dispatched task made no observable ledger progress. */
74
+ stalledRetryMinutes: number;
75
+ /** Global enqueue cap per scan, with round-robin fairness across channels. */
76
+ maxDispatchesPerTick: number;
77
+ }
68
78
  export interface PipiclawSessionMemorySettings {
69
79
  enabled: boolean;
70
80
  minTurnsBetweenUpdate: number;
@@ -124,6 +134,7 @@ export interface PipiclawSettings {
124
134
  retry?: Partial<PipiclawRetrySettings>;
125
135
  memoryRecall?: Partial<PipiclawMemoryRecallSettings>;
126
136
  taskDigest?: Partial<PipiclawTaskDigestSettings>;
137
+ taskDriver?: Partial<PipiclawTaskDriverSettings>;
127
138
  sessionMemory?: Partial<PipiclawSessionMemorySettings>;
128
139
  memoryGrowth?: Partial<PipiclawMemoryGrowthSettings>;
129
140
  memoryMaintenance?: Partial<PipiclawMemoryMaintenanceSettings>;
@@ -163,6 +174,7 @@ export declare class PipiclawSettingsManager {
163
174
  getRetrySettings(): PipiclawRetrySettings;
164
175
  getMemoryRecallSettings(): PipiclawMemoryRecallSettings;
165
176
  getTaskDigestSettings(): PipiclawTaskDigestSettings;
177
+ getTaskDriverSettings(): PipiclawTaskDriverSettings;
166
178
  getSessionMemorySettings(): PipiclawSessionMemorySettings;
167
179
  getMemoryGrowthSettings(): PipiclawMemoryGrowthSettings;
168
180
  getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
package/dist/settings.js CHANGED
@@ -36,6 +36,15 @@ const DEFAULT_TASK_DIGEST = {
36
36
  maxTasks: 8,
37
37
  maxChars: 1000,
38
38
  };
39
+ // The driver makes `wake` an executable task property rather than a convention
40
+ // that requires users to install a heartbeat event and sensor script. A changed
41
+ // task can continue promptly; an unchanged task backs off to avoid token loops.
42
+ const DEFAULT_TASK_DRIVER = {
43
+ enabled: true,
44
+ continuationDelayMinutes: 5,
45
+ stalledRetryMinutes: 60,
46
+ maxDispatchesPerTick: 4,
47
+ };
39
48
  const DEFAULT_SESSION_MEMORY = {
40
49
  enabled: true,
41
50
  minTurnsBetweenUpdate: 2,
@@ -180,6 +189,27 @@ export class PipiclawSettingsManager {
180
189
  ...this.settings.taskDigest,
181
190
  };
182
191
  }
192
+ getTaskDriverSettings() {
193
+ const configured = {
194
+ ...DEFAULT_TASK_DRIVER,
195
+ ...this.settings.taskDriver,
196
+ };
197
+ const continuationDelayMinutes = Number.isFinite(configured.continuationDelayMinutes)
198
+ ? Math.min(60, Math.max(1, Math.floor(configured.continuationDelayMinutes)))
199
+ : DEFAULT_TASK_DRIVER.continuationDelayMinutes;
200
+ const stalledRetryMinutes = Number.isFinite(configured.stalledRetryMinutes)
201
+ ? Math.min(24 * 60, Math.max(continuationDelayMinutes, Math.floor(configured.stalledRetryMinutes)))
202
+ : DEFAULT_TASK_DRIVER.stalledRetryMinutes;
203
+ const maxDispatchesPerTick = Number.isFinite(configured.maxDispatchesPerTick)
204
+ ? Math.min(20, Math.max(1, Math.floor(configured.maxDispatchesPerTick)))
205
+ : DEFAULT_TASK_DRIVER.maxDispatchesPerTick;
206
+ return {
207
+ enabled: configured.enabled !== false,
208
+ continuationDelayMinutes,
209
+ stalledRetryMinutes,
210
+ maxDispatchesPerTick,
211
+ };
212
+ }
183
213
  getSessionMemorySettings() {
184
214
  return {
185
215
  ...DEFAULT_SESSION_MEMORY,
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, renameSync, statSync } from "node:fs";
2
2
  import { appendFile } from "node:fs/promises";
3
3
  import { dirname } from "node:path";
4
4
  import { createSerialQueue } from "./serial-queue.js";
5
+ import { errorMessage } from "./text-utils.js";
5
6
  /**
6
7
  * Append-only JSONL writer shared by the runtime log and the usage ledger.
7
8
  *
@@ -77,7 +78,7 @@ export function createJsonlAppender(options) {
77
78
  catch (error) {
78
79
  if (!warned) {
79
80
  warned = true;
80
- console.warn(`[jsonl-appender] Failed to append to ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
81
+ console.warn(`[jsonl-appender] Failed to append to ${filePath}: ${errorMessage(error)}`);
81
82
  }
82
83
  }
83
84
  },
@@ -1,3 +1,4 @@
1
+ import { type TaskControl, type TaskVerificationMode } from "../tasks/control.js";
1
2
  /**
2
3
  * Shared reader for the task ledger (`workspace/<channelId>/tasks/*.md`).
3
4
  *
@@ -14,6 +15,9 @@ export interface TaskFrontmatter {
14
15
  status?: string;
15
16
  wake?: string;
16
17
  recurrence?: string;
18
+ control?: TaskControl;
19
+ /** false only when a control field exists but cannot be parsed/validated. */
20
+ controlReadable?: boolean;
17
21
  }
18
22
  export interface TaskLedgerEntry {
19
23
  /** Filename without `.md`; the task id. */
@@ -33,6 +37,8 @@ export interface TaskSkeletonInput {
33
37
  goal: string;
34
38
  dod: string;
35
39
  manual?: string;
40
+ verificationPlan?: string;
41
+ verificationMode?: TaskVerificationMode;
36
42
  }
37
43
  export declare const DEFAULT_TASK_MANUAL = "- Follow the DoD, keep the current cycle log updated, and schedule check-ins when waiting.";
38
44
  export declare const STANDARD_TASK_SECTIONS: readonly [{
@@ -44,6 +50,9 @@ export declare const STANDARD_TASK_SECTIONS: readonly [{
44
50
  }, {
45
51
  readonly label: "Manual";
46
52
  readonly names: readonly ["Manual", "手册"];
53
+ }, {
54
+ readonly label: "Verification";
55
+ readonly names: readonly ["Verification", "验收"];
47
56
  }, {
48
57
  readonly label: "Current Cycle";
49
58
  readonly names: readonly ["Current Cycle", "当前周期"];
@@ -67,7 +76,33 @@ export declare function isTaskActionable(frontmatter: TaskFrontmatter, now: numb
67
76
  export declare function extractTaskTitle(content: string, fallbackId: string): string;
68
77
  export declare function hasTaskHeading(content: string, names: readonly string[]): boolean;
69
78
  export declare function missingStandardTaskSections(content: string): string[];
79
+ /**
80
+ * Unchecked Markdown acceptance boxes under the DoD section, plus a synthetic
81
+ * entry when DoD has content but no checkbox syntax at all.
82
+ *
83
+ * Without the "no checklist items" case, a DoD written as prose or a numbered
84
+ * list (no `- [ ]` anywhere) makes this function return an empty array —
85
+ * indistinguishable from "everything is checked" — which would silently let
86
+ * `task_manage candidate`/`done` through with nothing ever actually verified.
87
+ */
88
+ export declare function uncheckedTaskAcceptanceItems(content: string): string[];
70
89
  export declare function renderStandardTaskBody(input: TaskSkeletonInput): string;
90
+ export interface TaskDocumentFields {
91
+ status: string;
92
+ wake?: string;
93
+ recurrence?: string;
94
+ control?: TaskControl;
95
+ }
96
+ export declare function renderTaskDocument(fields: TaskDocumentFields, body: string): string;
97
+ /** Append one progress bullet to the standard Current Cycle section. */
98
+ export declare function appendCurrentCycleNote(content: string, note: string): string;
99
+ /**
100
+ * Close the visible current-cycle notes into History and open a fresh cycle.
101
+ * Periodic task cycles deliberately use this small, deterministic transformation
102
+ * instead of asking the model to hand-edit headings and risk appending future
103
+ * checkpoints to the previous cycle.
104
+ */
105
+ export declare function startTaskCycle(content: string, cycleId: string): string;
71
106
  /** Actionable first; then earliest wake first (unset wake sorts as "ready now"); then id. */
72
107
  export declare function compareTaskEntries(a: TaskLedgerEntry, b: TaskLedgerEntry): number;
73
108
  /**