@llblab/pi-actors 0.23.0 → 0.24.0

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 (161) hide show
  1. package/AGENTS.md +125 -60
  2. package/BACKLOG.md +93 -188
  3. package/CHANGELOG.md +22 -0
  4. package/README.md +13 -0
  5. package/dist/fixtures/protocol/actor-message-branch.json +13 -0
  6. package/dist/fixtures/protocol/artifact-manifest.json +9 -0
  7. package/dist/fixtures/protocol/mailbox-contract.json +15 -0
  8. package/dist/fixtures/protocol/recipe-summary.json +16 -0
  9. package/dist/fixtures/protocol/room-message.json +11 -0
  10. package/dist/fixtures/protocol/room-roster.json +11 -0
  11. package/dist/fixtures/protocol/run-inbox-message.json +9 -0
  12. package/dist/fixtures/protocol/run-outbox-event.json +9 -0
  13. package/dist/fixtures/protocol/run-state.json +10 -0
  14. package/dist/index.js +3 -2
  15. package/dist/lib/actor-inspector-tui.js +5 -32
  16. package/dist/lib/actor-rooms.d.ts +8 -0
  17. package/dist/lib/actor-rooms.js +64 -20
  18. package/dist/lib/actor-worker.d.ts +13 -0
  19. package/dist/lib/actor-worker.js +86 -0
  20. package/dist/lib/async-runner.d.ts +5 -0
  21. package/dist/lib/async-runner.js +134 -0
  22. package/dist/lib/async-runs.js +9 -28
  23. package/dist/lib/build-dist.d.ts +5 -0
  24. package/dist/lib/build-dist.js +24 -0
  25. package/dist/lib/conformance.d.ts +12 -0
  26. package/dist/lib/conformance.js +28 -0
  27. package/dist/lib/coordinator.d.ts +5 -0
  28. package/dist/lib/coordinator.js +557 -0
  29. package/dist/lib/locker.d.ts +5 -0
  30. package/dist/lib/locker.js +310 -0
  31. package/dist/lib/mailbox-loop.d.ts +41 -0
  32. package/dist/lib/mailbox-loop.js +62 -0
  33. package/dist/lib/observability.d.ts +2 -2
  34. package/dist/lib/observability.js +51 -53
  35. package/dist/lib/prompts.d.ts +1 -1
  36. package/dist/lib/prompts.js +1 -1
  37. package/dist/lib/recipe-references.js +25 -2
  38. package/dist/lib/recipe-utils.d.ts +5 -0
  39. package/dist/lib/recipe-utils.js +385 -0
  40. package/dist/lib/runtime-notifier.js +3 -7
  41. package/dist/lib/state-readers.d.ts +21 -0
  42. package/dist/lib/state-readers.js +74 -0
  43. package/dist/lib/tools.js +1 -1
  44. package/dist/lib/validate-recipe.d.ts +6 -0
  45. package/dist/lib/validate-recipe.js +104 -0
  46. package/dist/recipes/actor-worker.json +35 -0
  47. package/dist/recipes/coordinator-locker.json +45 -0
  48. package/dist/recipes/lens-swarm.json +66 -0
  49. package/dist/recipes/locker.json +45 -0
  50. package/dist/recipes/music-player.json +38 -0
  51. package/dist/recipes/pipeline-architect-coordinator.json +95 -0
  52. package/dist/recipes/pipeline-artifact-bundle.json +100 -0
  53. package/dist/recipes/pipeline-artifact-report.json +58 -0
  54. package/dist/recipes/pipeline-artifact-write.json +72 -0
  55. package/dist/recipes/pipeline-async-run-ops.json +70 -0
  56. package/dist/recipes/pipeline-checkpoint-continuation.json +67 -0
  57. package/dist/recipes/pipeline-development-tasking.json +81 -0
  58. package/dist/recipes/pipeline-docs-maintenance.json +80 -0
  59. package/dist/recipes/pipeline-media-library.json +59 -0
  60. package/dist/recipes/pipeline-quorum-review.json +79 -0
  61. package/dist/recipes/pipeline-release-readiness.json +110 -0
  62. package/dist/recipes/pipeline-release-summary.json +88 -0
  63. package/dist/recipes/pipeline-repo-health.json +89 -0
  64. package/dist/recipes/pipeline-research-synthesis.json +94 -0
  65. package/dist/recipes/pipeline-review-readiness.json +54 -0
  66. package/dist/recipes/pipeline-room-swarm.json +50 -0
  67. package/dist/recipes/subagent-artifact.json +32 -0
  68. package/dist/recipes/subagent-checkpoint.json +33 -0
  69. package/dist/recipes/subagent-conflict-report.json +32 -0
  70. package/dist/recipes/subagent-contradiction-map.json +33 -0
  71. package/dist/recipes/subagent-critic.json +35 -0
  72. package/dist/recipes/subagent-evidence-map.json +33 -0
  73. package/dist/recipes/subagent-followup.json +33 -0
  74. package/dist/recipes/subagent-judge.json +33 -0
  75. package/dist/recipes/subagent-merge.json +33 -0
  76. package/dist/recipes/subagent-message.json +34 -0
  77. package/dist/recipes/subagent-normalize.json +31 -0
  78. package/dist/recipes/subagent-plan.json +33 -0
  79. package/dist/recipes/subagent-prompt.json +28 -0
  80. package/dist/recipes/subagent-quorum.json +43 -0
  81. package/dist/recipes/subagent-review-coordinator.json +114 -0
  82. package/dist/recipes/subagent-review.json +37 -0
  83. package/dist/recipes/subagent-task-card.json +35 -0
  84. package/dist/recipes/subagent-tools.json +27 -0
  85. package/dist/recipes/subagent-verify.json +34 -0
  86. package/dist/recipes/subagents-prompts.json +51 -0
  87. package/dist/recipes/utility-actor-message.json +23 -0
  88. package/dist/recipes/utility-artifact-manifest.json +16 -0
  89. package/dist/recipes/utility-artifact-write.json +16 -0
  90. package/dist/recipes/utility-changelog-head.json +11 -0
  91. package/dist/recipes/utility-changelog-section.json +13 -0
  92. package/dist/recipes/utility-coordinator-lock-snapshot.json +13 -0
  93. package/dist/recipes/utility-git-log.json +11 -0
  94. package/dist/recipes/utility-git-status.json +9 -0
  95. package/dist/recipes/utility-jsonl-tail.json +10 -0
  96. package/dist/recipes/utility-markdown-index.json +14 -0
  97. package/dist/recipes/utility-package-summary.json +11 -0
  98. package/dist/recipes/utility-playlist-build.json +17 -0
  99. package/dist/recipes/utility-playlist-scan.json +11 -0
  100. package/dist/recipes/utility-run-ops-snapshot.json +17 -0
  101. package/dist/recipes/utility-run-state-files.json +13 -0
  102. package/dist/recipes/utility-run-summary.json +11 -0
  103. package/dist/recipes/utility-skill-summary.json +13 -0
  104. package/dist/recipes/utility-validate-recipe.json +13 -0
  105. package/dist/recipes/utility-validation-wrapper.json +13 -0
  106. package/dist/scripts/actor-worker.mjs +31 -0
  107. package/dist/scripts/async-runner.mjs +31 -0
  108. package/dist/scripts/build-dist.mjs +25 -0
  109. package/dist/scripts/conformance.mjs +33 -0
  110. package/dist/scripts/coordinator.mjs +31 -0
  111. package/dist/scripts/locker.mjs +33 -0
  112. package/dist/scripts/music-player.mjs +964 -0
  113. package/dist/scripts/recipe-utils.mjs +31 -0
  114. package/dist/scripts/validate-recipe.mjs +34 -0
  115. package/dist/skills/actors/SKILL.md +375 -0
  116. package/dist/skills/swarm/SKILL.md +467 -0
  117. package/dist/skills/swarm/references/development-swarm.md +596 -0
  118. package/docs/actor-messages.md +2 -2
  119. package/docs/async-runs.md +11 -0
  120. package/docs/template-recipes.md +1 -1
  121. package/fixtures/protocol/actor-message-branch.json +13 -0
  122. package/fixtures/protocol/artifact-manifest.json +9 -0
  123. package/fixtures/protocol/mailbox-contract.json +15 -0
  124. package/fixtures/protocol/recipe-summary.json +16 -0
  125. package/fixtures/protocol/room-message.json +11 -0
  126. package/fixtures/protocol/room-roster.json +11 -0
  127. package/fixtures/protocol/run-inbox-message.json +9 -0
  128. package/fixtures/protocol/run-outbox-event.json +9 -0
  129. package/fixtures/protocol/run-state.json +10 -0
  130. package/index.ts +3 -0
  131. package/lib/actor-inspector-tui.ts +11 -34
  132. package/lib/actor-rooms.ts +88 -18
  133. package/lib/actor-worker.ts +118 -0
  134. package/lib/async-runner.ts +173 -0
  135. package/lib/async-runs.ts +12 -22
  136. package/lib/build-dist.ts +30 -0
  137. package/lib/conformance.ts +46 -0
  138. package/lib/coordinator.ts +649 -0
  139. package/lib/locker.ts +340 -0
  140. package/lib/mailbox-loop.ts +148 -0
  141. package/lib/observability.ts +24 -19
  142. package/lib/prompts.ts +1 -1
  143. package/lib/recipe-references.ts +37 -2
  144. package/lib/recipe-utils.ts +486 -0
  145. package/lib/runtime-notifier.ts +4 -6
  146. package/lib/state-readers.ts +93 -0
  147. package/lib/tools.ts +1 -1
  148. package/lib/validate-recipe.ts +110 -0
  149. package/package.json +10 -2
  150. package/recipes/actor-worker.json +35 -0
  151. package/recipes/pipeline-quorum-review.json +12 -7
  152. package/scripts/actor-worker.mjs +31 -0
  153. package/scripts/async-runner.mjs +11 -201
  154. package/scripts/build-dist.mjs +25 -0
  155. package/scripts/conformance.mjs +21 -35
  156. package/scripts/coordinator.mjs +15 -625
  157. package/scripts/locker.mjs +20 -332
  158. package/scripts/recipe-utils.mjs +17 -477
  159. package/scripts/validate-recipe.mjs +18 -121
  160. package/skills/actors/SKILL.md +5 -2
  161. package/skills/swarm/SKILL.md +3 -1
@@ -0,0 +1,385 @@
1
+ /**
2
+ * Recipe utility command bundle entrypoint logic.
3
+ * Zones: recipe utilities, deterministic helper subcommands
4
+ */
5
+ // @ts-nocheck
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, } from "node:fs";
7
+ import { dirname, extname, join, relative, resolve } from "node:path";
8
+ function usage() {
9
+ console.error(`Usage:
10
+ recipe-utils.mjs run-summary <state-root>
11
+ recipe-utils.mjs run-ops-snapshot <state-root> <run-id> [lines] [stale-minutes]
12
+ recipe-utils.mjs playlist <source-dir> [extensions] [max-depth] [paths|m3u|inline]
13
+ recipe-utils.mjs changelog-section <file> <version>
14
+ recipe-utils.mjs artifact-manifest <artifact-path> <title> <status> [summary]
15
+ recipe-utils.mjs artifact-write <artifact-path> [create|overwrite|append]
16
+ recipe-utils.mjs actor-message <type> [to] [from] [summary] [metadata-json] [correlation-id] [reply-to]
17
+ recipe-utils.mjs package-summary <package-json>
18
+ recipe-utils.mjs skill-summary <skill-md> [package-json]`);
19
+ }
20
+ function fail(message) {
21
+ console.error(message);
22
+ process.exit(1);
23
+ }
24
+ const ADDRESS_PATTERN = /^[A-Za-z0-9_.-]+$/;
25
+ const MESSAGE_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9_.:-]*$/;
26
+ function assertToken(value, label) {
27
+ const normalized = String(value ?? "").trim();
28
+ if (!normalized)
29
+ fail(`${label} is required`);
30
+ if (!ADDRESS_PATTERN.test(normalized))
31
+ fail(`${label} contains unsupported characters: ${value}`);
32
+ return normalized;
33
+ }
34
+ function validateActorAddress(address, label) {
35
+ const value = String(address ?? "").trim();
36
+ if (value === "coordinator")
37
+ return value;
38
+ const separator = value.indexOf(":");
39
+ if (separator < 0)
40
+ fail(`${label} must include an actor kind: ${address}`);
41
+ const kind = value.slice(0, separator);
42
+ const rest = value.slice(separator + 1);
43
+ if (kind === "branch") {
44
+ const [run, branch, ...extra] = rest.split("/");
45
+ if (extra.length > 0)
46
+ fail(`${label} branch address has too many parts: ${address}`);
47
+ return `branch:${assertToken(run, `${label} branch run`)}/${assertToken(branch, `${label} branch id`)}`;
48
+ }
49
+ if (["run", "session", "tool"].includes(kind))
50
+ return `${kind}:${assertToken(rest, label)}`;
51
+ fail(`${label} has unsupported actor kind: ${kind}`);
52
+ }
53
+ function validateMessageType(type) {
54
+ const value = String(type ?? "").trim();
55
+ if (!MESSAGE_TYPE_PATTERN.test(value))
56
+ fail(`Invalid actor message type: ${type}`);
57
+ return value;
58
+ }
59
+ function walkFiles(dir, maxDepth = 2, depth = 0, out = []) {
60
+ if (depth > maxDepth || !existsSync(dir))
61
+ return out;
62
+ for (const entry of readdirSync(dir)) {
63
+ const path = join(dir, entry);
64
+ const stat = statSync(path);
65
+ if (stat.isDirectory())
66
+ walkFiles(path, maxDepth, depth + 1, out);
67
+ else if (stat.isFile())
68
+ out.push(path);
69
+ }
70
+ return out;
71
+ }
72
+ function readJson(file) {
73
+ if (!existsSync(file))
74
+ return undefined;
75
+ try {
76
+ return JSON.parse(readFileSync(file, "utf8"));
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
82
+ function getRunStatus(run, progress, result) {
83
+ if (progress?.phase)
84
+ return progress.phase;
85
+ if (result?.code !== undefined)
86
+ return result.code === 0 ? "done" : "failed";
87
+ return run.status ?? "unknown";
88
+ }
89
+ function collectRunSummary(rootValue) {
90
+ const root = resolve(rootValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
91
+ const files = walkFiles(root, 2).filter((file) => file.endsWith("/run.json"));
92
+ const rows = [];
93
+ for (const file of files) {
94
+ const run = readJson(file);
95
+ if (!run) {
96
+ rows.push({
97
+ run: relative(root, file),
98
+ status: "invalid-json",
99
+ recipe: "",
100
+ updated: "",
101
+ });
102
+ continue;
103
+ }
104
+ const runDir = dirname(file);
105
+ const progress = readJson(join(runDir, "progress.json"));
106
+ const result = readJson(join(runDir, "result.json"));
107
+ rows.push({
108
+ run: run.run_id ?? run.run ?? relative(root, file).split("/")[0],
109
+ status: getRunStatus(run, progress, result),
110
+ recipe: run.recipe ?? run.recipe_file ?? "",
111
+ updated: progress?.updatedAt ??
112
+ result?.completedAt ??
113
+ run.updated_at ??
114
+ run.completed_at ??
115
+ run.started_at ??
116
+ "",
117
+ });
118
+ }
119
+ rows.sort((a, b) => `${a.status}:${a.run}`.localeCompare(`${b.status}:${b.run}`));
120
+ return rows;
121
+ }
122
+ function runSummary(rootValue) {
123
+ console.log(JSON.stringify(collectRunSummary(rootValue), null, 2));
124
+ }
125
+ function tailJsonl(fileValue, linesValue = "80") {
126
+ const file = resolve(fileValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
127
+ if (!existsSync(file))
128
+ return [];
129
+ const lines = Number.parseInt(linesValue, 10);
130
+ const count = Number.isFinite(lines) && lines > 0 ? lines : 80;
131
+ return readFileSync(file, "utf8")
132
+ .trimEnd()
133
+ .split("\n")
134
+ .filter(Boolean)
135
+ .slice(-count)
136
+ .map((line) => {
137
+ try {
138
+ return JSON.parse(line);
139
+ }
140
+ catch {
141
+ return { raw: line };
142
+ }
143
+ });
144
+ }
145
+ function runOpsSnapshot(rootValue, runIdValue = "music", linesValue = "80", staleMinutesValue = "60") {
146
+ const runs = collectRunSummary(rootValue);
147
+ const root = resolve(rootValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
148
+ const inspectedRun = String(runIdValue || "music");
149
+ const messageFile = join(root, inspectedRun, "outbox.jsonl");
150
+ const staleMs = Number(staleMinutesValue) * 60 * 1000;
151
+ const now = Date.now();
152
+ const recommendations = runs.flatMap((run) => {
153
+ const updatedMs = Date.parse(run.updated || "");
154
+ const stale = Number.isFinite(updatedMs) &&
155
+ Number.isFinite(staleMs) &&
156
+ now - updatedMs > staleMs;
157
+ if (run.status === "running" && stale) {
158
+ return [
159
+ {
160
+ run: run.run,
161
+ reason: "running-stale",
162
+ suggested_message: {
163
+ to: `run:${run.run}`,
164
+ type: "control.stop",
165
+ body: "stop",
166
+ },
167
+ },
168
+ ];
169
+ }
170
+ if (["failed", "exited", "killed"].includes(run.status)) {
171
+ return [
172
+ {
173
+ run: run.run,
174
+ reason: `terminal-${run.status}`,
175
+ suggested_inspect: { target: `run:${run.run}`, view: "tail" },
176
+ },
177
+ ];
178
+ }
179
+ return [];
180
+ });
181
+ console.log(JSON.stringify({
182
+ runs,
183
+ inspectedRun,
184
+ messages: tailJsonl(messageFile, linesValue),
185
+ recommendations,
186
+ }, null, 2));
187
+ }
188
+ function playlist(sourceValue, extensionsValue = ".mp3,.ogg,.wav,.flac,.m4a", maxDepthValue = "2", outputMode = "paths") {
189
+ const source = resolve(sourceValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
190
+ const maxDepth = Number.parseInt(maxDepthValue, 10);
191
+ const extensions = new Set(extensionsValue
192
+ .split(",")
193
+ .map((item) => item.trim().toLowerCase())
194
+ .filter(Boolean));
195
+ const files = walkFiles(source, Number.isFinite(maxDepth) ? maxDepth : 2)
196
+ .filter((file) => extensions.has(extname(file).toLowerCase()))
197
+ .sort((a, b) => a.localeCompare(b));
198
+ if (outputMode === "m3u")
199
+ console.log(["#EXTM3U", ...files].join("\n"));
200
+ else if (outputMode === "inline")
201
+ console.log(files.join("|"));
202
+ else
203
+ console.log(files.join("\n"));
204
+ }
205
+ function artifactManifest(pathValue, title = "Artifact", status = "draft", summary = "") {
206
+ const path = resolve(pathValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
207
+ const exists = existsSync(path);
208
+ const stat = exists ? statSync(path) : undefined;
209
+ console.log(JSON.stringify({
210
+ title,
211
+ status,
212
+ path,
213
+ exists,
214
+ bytes: stat?.size ?? 0,
215
+ modified: stat?.mtime?.toISOString?.() ?? null,
216
+ summary,
217
+ }, null, 2));
218
+ }
219
+ function artifactWrite(pathValue, mode = "create") {
220
+ const path = resolve(pathValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
221
+ if (!["create", "overwrite", "append"].includes(mode)) {
222
+ fail(`Invalid artifact write mode: ${mode}`);
223
+ }
224
+ if (mode === "create" && existsSync(path)) {
225
+ fail(`Artifact already exists: ${path}`);
226
+ }
227
+ const content = readFileSync(0, "utf8");
228
+ mkdirSync(dirname(path), { recursive: true });
229
+ if (mode === "append")
230
+ appendFileSync(path, content);
231
+ else
232
+ writeFileSync(path, content, "utf8");
233
+ const stat = statSync(path);
234
+ console.log(JSON.stringify({ path, mode, bytes: stat.size, written: true }, null, 2));
235
+ }
236
+ function actorMessage(type = "event", to = "coordinator", from = "run:{run_id}", summary = "", metadataValue = "", correlationId = "", replyTo = "") {
237
+ const messageType = validateMessageType(type);
238
+ const messageTo = validateActorAddress(to, "message.to");
239
+ const messageFrom = validateActorAddress(from, "message.from");
240
+ let metadata = {};
241
+ if (metadataValue) {
242
+ try {
243
+ const parsed = JSON.parse(metadataValue);
244
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
245
+ metadata = parsed;
246
+ else
247
+ fail("Actor message metadata must be a JSON object");
248
+ }
249
+ catch (error) {
250
+ fail(`Invalid actor message metadata JSON: ${error.message}`);
251
+ }
252
+ }
253
+ const bodyText = readFileSync(0, "utf8");
254
+ const trimmed = bodyText.trim();
255
+ let body = bodyText;
256
+ if (trimmed) {
257
+ try {
258
+ body = JSON.parse(trimmed);
259
+ }
260
+ catch {
261
+ body = bodyText;
262
+ }
263
+ }
264
+ console.log(JSON.stringify({
265
+ to: messageTo,
266
+ from: messageFrom,
267
+ type: messageType,
268
+ summary: summary || messageType,
269
+ body,
270
+ ...(correlationId ? { correlation_id: correlationId } : {}),
271
+ ...(replyTo ? { reply_to: replyTo } : {}),
272
+ metadata,
273
+ }, null, 2));
274
+ }
275
+ function packageSummary(fileValue = "package.json") {
276
+ const file = resolve(fileValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
277
+ const pkg = readJson(file);
278
+ if (!pkg)
279
+ fail(`Package JSON not found or invalid: ${fileValue}`);
280
+ const scripts = pkg.scripts && typeof pkg.scripts === "object"
281
+ ? Object.keys(pkg.scripts).sort()
282
+ : [];
283
+ const dependencies = pkg.dependencies && typeof pkg.dependencies === "object"
284
+ ? Object.keys(pkg.dependencies).sort()
285
+ : [];
286
+ const devDependencies = pkg.devDependencies && typeof pkg.devDependencies === "object"
287
+ ? Object.keys(pkg.devDependencies).sort()
288
+ : [];
289
+ console.log(JSON.stringify({
290
+ name: pkg.name ?? "",
291
+ version: pkg.version ?? "",
292
+ type: pkg.type ?? "",
293
+ private: Boolean(pkg.private),
294
+ packageManager: pkg.packageManager ?? "",
295
+ files: Array.isArray(pkg.files) ? pkg.files : [],
296
+ bin: pkg.bin ?? null,
297
+ main: pkg.main ?? "",
298
+ exports: pkg.exports ?? null,
299
+ scripts,
300
+ dependencyCount: dependencies.length,
301
+ devDependencyCount: devDependencies.length,
302
+ dependencies,
303
+ devDependencies,
304
+ }, null, 2));
305
+ }
306
+ function parseSkillFrontmatter(content) {
307
+ const frontmatter = content.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? "";
308
+ const fields = {};
309
+ for (const line of frontmatter.split(/\r?\n/)) {
310
+ const match = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
311
+ if (match)
312
+ fields[match[1]] = match[2].trim();
313
+ }
314
+ return { frontmatter, fields };
315
+ }
316
+ function skillSummary(skillValue, packageValue = "package.json") {
317
+ const skillFile = resolve(skillValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
318
+ const packageFile = resolve(packageValue.replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
319
+ const content = readFileSync(skillFile, "utf8");
320
+ const pkg = readJson(packageFile) ?? {};
321
+ const { frontmatter, fields } = parseSkillFrontmatter(content);
322
+ const scalarLines = frontmatter
323
+ .split(/\r?\n/)
324
+ .filter((line) => /^\w+:\s*\S/.test(line));
325
+ const extraColonLines = scalarLines.filter((line) => (line.match(/:/g) ?? []).length > 1);
326
+ const body = content.replace(/^---\n[\s\S]*?\n---\n?/, "");
327
+ const version = fields.version ??
328
+ frontmatter.match(/^\s+version:\s*([^\n]+)\s*$/m)?.[1]?.trim() ??
329
+ "";
330
+ console.log(JSON.stringify({
331
+ path: skillValue,
332
+ name: fields.name ?? "",
333
+ description: fields.description ?? "",
334
+ version,
335
+ packageVersion: pkg.version ?? "",
336
+ versionMatchesPackage: version === pkg.version,
337
+ frontmatterExtraColonLines: extraColonLines,
338
+ bodyLineCount: body.split(/\r?\n/).length,
339
+ headings: body.split(/\r?\n/).filter((line) => /^#{1,6}\s/.test(line)),
340
+ }, null, 2));
341
+ }
342
+ function changelogSection(fileValue, version) {
343
+ const file = resolve(fileValue);
344
+ const lines = readFileSync(file, "utf8").split(/\r?\n/);
345
+ const start = lines.findIndex((line) => line.startsWith("## ") && line.includes(version));
346
+ if (start < 0)
347
+ fail(`Version section not found: ${version}`);
348
+ let end = lines.length;
349
+ for (let index = start + 1; index < lines.length; index += 1) {
350
+ if (lines[index].startsWith("## ")) {
351
+ end = index;
352
+ break;
353
+ }
354
+ }
355
+ console.log(lines.slice(start, end).join("\n").trimEnd());
356
+ }
357
+ export function runRecipeUtils(argv = process.argv.slice(2)) {
358
+ const [command, ...args] = argv;
359
+ if (!command) {
360
+ usage();
361
+ process.exit(1);
362
+ }
363
+ if (command === "run-summary")
364
+ runSummary(args[0] ?? "~/.pi/agent/tmp/pi-actors/runs");
365
+ else if (command === "run-ops-snapshot")
366
+ runOpsSnapshot(args[0] ?? "~/.pi/agent/tmp/pi-actors/runs", args[1] ?? "music", args[2], args[3]);
367
+ else if (command === "playlist")
368
+ playlist(args[0] ?? "~/Music", args[1], args[2], args[3]);
369
+ else if (command === "changelog-section")
370
+ changelogSection(args[0] ?? "CHANGELOG.md", args[1] ?? "Unreleased");
371
+ else if (command === "artifact-manifest")
372
+ artifactManifest(args[0] ?? "artifact.md", args[1], args[2], args[3]);
373
+ else if (command === "artifact-write")
374
+ artifactWrite(args[0] ?? "artifact.md", args[1] ?? "create");
375
+ else if (command === "actor-message")
376
+ actorMessage(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
377
+ else if (command === "package-summary")
378
+ packageSummary(args[0] ?? "package.json");
379
+ else if (command === "skill-summary")
380
+ skillSummary(args[0] ?? "skills/actors/SKILL.md", args[1] ?? "package.json");
381
+ else {
382
+ usage();
383
+ fail(`Unknown command: ${command}`);
384
+ }
385
+ }
@@ -6,6 +6,7 @@
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, watch, } from "node:fs";
8
8
  import { basename, dirname, join } from "node:path";
9
+ import { readJsonlFileResilient } from "./state-readers.js";
9
10
  const DEFAULT_POLL_INTERVAL_MS = 1000;
10
11
  export function runtimeWakeFile(stateDir) {
11
12
  return join(stateDir, "wake.jsonl");
@@ -61,13 +62,8 @@ export function parseRuntimeWakeEventLine(line) {
61
62
  }
62
63
  }
63
64
  export function readRuntimeWakeEvents(stateDir) {
64
- const file = runtimeWakeFile(stateDir);
65
- if (!existsSync(file))
66
- return [];
67
- return readFileSync(file, "utf8")
68
- .split("\n")
69
- .filter((line) => line.trim())
70
- .map(parseRuntimeWakeEventLine)
65
+ return readJsonlFileResilient(runtimeWakeFile(stateDir))
66
+ .records.map((record) => parseRuntimeWakeEventLine(JSON.stringify(record)))
71
67
  .filter((event) => Boolean(event));
72
68
  }
73
69
  export function createFileRuntimeNotifier(stateDir, options = {}) {
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Resilient state readers.
3
+ * Zones: file-backed actor state, JSON/JSONL diagnostics, inspect safety
4
+ * Owns best-effort JSON and JSONL parsing helpers for operator-facing state reads.
5
+ */
6
+ export interface StateReadDiagnostic {
7
+ line?: number;
8
+ message: string;
9
+ path: string;
10
+ }
11
+ export interface JsonReadResult<T> {
12
+ diagnostics: StateReadDiagnostic[];
13
+ value: T;
14
+ }
15
+ export interface JsonlReadResult<T> {
16
+ diagnostics: StateReadDiagnostic[];
17
+ records: T[];
18
+ }
19
+ export declare function readJsonFileResilient<T>(path: string, fallback: T): JsonReadResult<T>;
20
+ export declare function readJsonlFileResilient<T>(path: string): JsonlReadResult<T>;
21
+ export declare function formatStateReadDiagnostics(diagnostics: StateReadDiagnostic[], limit?: number): string[];
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Resilient state readers.
3
+ * Zones: file-backed actor state, JSON/JSONL diagnostics, inspect safety
4
+ * Owns best-effort JSON and JSONL parsing helpers for operator-facing state reads.
5
+ */
6
+ import { readFileSync } from "node:fs";
7
+ function isEnoent(error) {
8
+ return error.code === "ENOENT";
9
+ }
10
+ function diagnosticMessage(error) {
11
+ return error instanceof Error ? error.message : String(error);
12
+ }
13
+ export function readJsonFileResilient(path, fallback) {
14
+ try {
15
+ return {
16
+ diagnostics: [],
17
+ value: JSON.parse(readFileSync(path, "utf8")),
18
+ };
19
+ }
20
+ catch (error) {
21
+ if (isEnoent(error))
22
+ return { diagnostics: [], value: fallback };
23
+ return {
24
+ diagnostics: [
25
+ {
26
+ message: diagnosticMessage(error),
27
+ path,
28
+ },
29
+ ],
30
+ value: fallback,
31
+ };
32
+ }
33
+ }
34
+ export function readJsonlFileResilient(path) {
35
+ try {
36
+ const records = [];
37
+ const diagnostics = [];
38
+ const lines = readFileSync(path, "utf8").split("\n");
39
+ for (const [index, line] of lines.entries()) {
40
+ if (!line.trim())
41
+ continue;
42
+ try {
43
+ records.push(JSON.parse(line));
44
+ }
45
+ catch (error) {
46
+ diagnostics.push({
47
+ line: index + 1,
48
+ message: diagnosticMessage(error),
49
+ path,
50
+ });
51
+ }
52
+ }
53
+ return { diagnostics, records };
54
+ }
55
+ catch (error) {
56
+ if (isEnoent(error))
57
+ return { diagnostics: [], records: [] };
58
+ return {
59
+ diagnostics: [
60
+ {
61
+ message: diagnosticMessage(error),
62
+ path,
63
+ },
64
+ ],
65
+ records: [],
66
+ };
67
+ }
68
+ }
69
+ export function formatStateReadDiagnostics(diagnostics, limit = 5) {
70
+ return diagnostics.slice(0, limit).map((diagnostic) => {
71
+ const line = diagnostic.line === undefined ? "" : `:${diagnostic.line}`;
72
+ return `${diagnostic.path}${line}: ${diagnostic.message}`;
73
+ });
74
+ }
package/dist/lib/tools.js CHANGED
@@ -241,7 +241,7 @@ function compactRoomRoster(roster) {
241
241
  .join("\n")}`;
242
242
  }
243
243
  function compactRoomStatus(status) {
244
- return `\nroom=${status.room} messages=${status.message_count} roster=${status.roster_count}${status.last_message_at ? ` last_message_at=${status.last_message_at}` : ""}${status.last_message_from ? ` last_from=${status.last_message_from}` : ""}${status.last_message_type ? ` last_type=${status.last_message_type}` : ""}${status.last_message_summary ? ` last_summary=${compactPreview(status.last_message_summary)}` : ""}`;
244
+ return `\nroom=${status.room} messages=${status.message_count} roster=${status.roster_count}${status.diagnostics_count ? ` diagnostics=${status.diagnostics_count}` : ""}${status.last_message_at ? ` last_message_at=${status.last_message_at}` : ""}${status.last_message_from ? ` last_from=${status.last_message_from}` : ""}${status.last_message_type ? ` last_type=${status.last_message_type}` : ""}${status.last_message_summary ? ` last_summary=${compactPreview(status.last_message_summary)}` : ""}`;
245
245
  }
246
246
  function compactCommunicationSnapshot(snapshot) {
247
247
  if (!snapshot)
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Template recipe validator CLI logic.
3
+ * Zones: recipe validation, installed script entrypoint
4
+ */
5
+ export declare function validateRecipeUsage(): string;
6
+ export declare function validateRecipes(argv: string[]): Record<string, unknown>;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Template recipe validator CLI logic.
3
+ * Zones: recipe validation, installed script entrypoint
4
+ */
5
+ import { existsSync, readdirSync, statSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { resolve } from "node:path";
8
+ import { readResolvedRecipeConfig } from "./recipe-references.js";
9
+ export function validateRecipeUsage() {
10
+ return `Usage:
11
+ validate-recipe.mjs <recipe-file-or-dir> [--all]
12
+
13
+ Validates one template recipe file, or all *.json/*.md files in a directory when --all is set.`;
14
+ }
15
+ function expandPath(value) {
16
+ return resolve(String(value).replace(/^~(?=\/|$)/, process.env.HOME ?? homedir()));
17
+ }
18
+ function templateKind(template) {
19
+ if (typeof template === "string")
20
+ return "leaf";
21
+ if (Array.isArray(template))
22
+ return "sequence";
23
+ if (template && typeof template === "object") {
24
+ const node = template;
25
+ if (typeof node.template === "string")
26
+ return "leaf";
27
+ if (Array.isArray(node.template))
28
+ return node.parallel === true ? "parallel" : "sequence";
29
+ if (node.parallel === true)
30
+ return "parallel";
31
+ return "object";
32
+ }
33
+ return "unknown";
34
+ }
35
+ function recipeFiles(target, all) {
36
+ if (!existsSync(target))
37
+ throw new Error(`Recipe path not found: ${target}`);
38
+ const stat = statSync(target);
39
+ if (stat.isFile())
40
+ return [target];
41
+ if (!stat.isDirectory())
42
+ throw new Error(`Recipe path is not a file or directory: ${target}`);
43
+ if (!all)
44
+ throw new Error("Directory validation requires --all.");
45
+ return readdirSync(target)
46
+ .filter((file) => file.endsWith(".json") || file.endsWith(".md"))
47
+ .sort((a, b) => a.localeCompare(b))
48
+ .map((file) => resolve(target, file));
49
+ }
50
+ function validateFile(file) {
51
+ try {
52
+ const config = readResolvedRecipeConfig(file);
53
+ if (!config?.template)
54
+ throw new Error("Recipe must define a non-empty template.");
55
+ return {
56
+ file,
57
+ ok: true,
58
+ name: config.name ?? "",
59
+ async: Boolean(config.async),
60
+ args: Array.isArray(config.args) ? config.args : [],
61
+ defaults: config.defaults && typeof config.defaults === "object"
62
+ ? Object.keys(config.defaults).sort()
63
+ : [],
64
+ imports: config.imports && typeof config.imports === "object"
65
+ ? Object.keys(config.imports).sort()
66
+ : [],
67
+ mailbox: config.mailbox && typeof config.mailbox === "object"
68
+ ? {
69
+ accepts: Array.isArray(config.mailbox.accepts)
70
+ ? config.mailbox.accepts
71
+ : [],
72
+ emits: Array.isArray(config.mailbox.emits)
73
+ ? config.mailbox.emits
74
+ : [],
75
+ }
76
+ : undefined,
77
+ template: templateKind(config.template),
78
+ };
79
+ }
80
+ catch (error) {
81
+ return {
82
+ file,
83
+ ok: false,
84
+ error: error instanceof Error ? error.message : String(error),
85
+ };
86
+ }
87
+ }
88
+ export function validateRecipes(argv) {
89
+ const targetArg = argv.find((arg) => !arg.startsWith("-"));
90
+ const all = argv.includes("--all");
91
+ if (!targetArg || argv.includes("--help") || argv.includes("-h")) {
92
+ return { help: true, ok: Boolean(targetArg), usage: validateRecipeUsage() };
93
+ }
94
+ const files = recipeFiles(expandPath(targetArg), all);
95
+ const results = files.map(validateFile);
96
+ const failed = results.filter((result) => !result.ok).length;
97
+ return {
98
+ ok: failed === 0,
99
+ total: results.length,
100
+ passed: results.length - failed,
101
+ failed,
102
+ results,
103
+ };
104
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "async": true,
3
+ "description": "Start a canonical mailbox-backed branch worker demo actor.",
4
+ "args": [
5
+ "repo:path",
6
+ "branch:string",
7
+ "poll_ms:int"
8
+ ],
9
+ "defaults": {
10
+ "repo": "~/.pi/agent/extensions/pi-actors",
11
+ "branch": "worker",
12
+ "poll_ms": "1000"
13
+ },
14
+ "mailbox": {
15
+ "accepts": [
16
+ "task.assign",
17
+ "control.stop",
18
+ "control.cancel",
19
+ "control.kill"
20
+ ],
21
+ "emits": [
22
+ "actor.join",
23
+ "task.claim",
24
+ "task.result",
25
+ "awaiting_assignment",
26
+ "actor.leave",
27
+ "run.done",
28
+ "run.failed"
29
+ ]
30
+ },
31
+ "artifacts": {
32
+ "journal": "{state_dir}/worker-events.jsonl"
33
+ },
34
+ "template": "{repo}/scripts/actor-worker.mjs --state-dir {state_dir} --run {run_id} --branch {branch} --poll-ms {poll_ms}"
35
+ }