@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +2 -0
  3. package/dist/agent/channel-runner.d.ts +43 -2
  4. package/dist/agent/channel-runner.js +135 -75
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +14 -0
  40. package/dist/memory/render.js +28 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/playbooks/agent-delegation.md +4 -2
  54. package/dist/playbooks/background-jobs.md +1 -1
  55. package/dist/playbooks/event-scheduling.md +6 -2
  56. package/dist/playbooks/memory-and-learning.md +18 -11
  57. package/dist/playbooks/outbound-media.md +1 -1
  58. package/dist/playbooks/runtime-orientation.md +9 -8
  59. package/dist/playbooks/task-loop.md +88 -0
  60. package/dist/runtime/bootstrap.d.ts +3 -3
  61. package/dist/runtime/bootstrap.js +66 -41
  62. package/dist/runtime/events.d.ts +9 -0
  63. package/dist/runtime/events.js +43 -4
  64. package/dist/runtime/task-commands.d.ts +14 -15
  65. package/dist/runtime/task-commands.js +249 -485
  66. package/dist/runtime/task-driver.d.ts +41 -29
  67. package/dist/runtime/task-driver.js +170 -317
  68. package/dist/runtime/task-migration.d.ts +34 -30
  69. package/dist/runtime/task-migration.js +229 -183
  70. package/dist/runtime/task-wake.d.ts +6 -3
  71. package/dist/runtime/task-wake.js +26 -19
  72. package/dist/settings.d.ts +0 -29
  73. package/dist/settings.js +12 -35
  74. package/dist/shared/markdown-sections.d.ts +0 -1
  75. package/dist/shared/markdown-sections.js +0 -3
  76. package/dist/subagents/discovery.d.ts +2 -2
  77. package/dist/subagents/discovery.js +21 -10
  78. package/dist/subagents/external/progress-tail.js +6 -1
  79. package/dist/subagents/external/run.js +1 -0
  80. package/dist/subagents/runs.d.ts +19 -2
  81. package/dist/subagents/runs.js +73 -4
  82. package/dist/subagents/tool.d.ts +10 -8
  83. package/dist/subagents/tool.js +55 -94
  84. package/dist/tasks/brief.d.ts +17 -0
  85. package/dist/tasks/brief.js +57 -0
  86. package/dist/tasks/budget.d.ts +26 -0
  87. package/dist/tasks/budget.js +59 -0
  88. package/dist/tasks/cycle.d.ts +48 -0
  89. package/dist/tasks/cycle.js +94 -0
  90. package/dist/tasks/frontmatter.d.ts +73 -0
  91. package/dist/tasks/frontmatter.js +175 -0
  92. package/dist/tasks/ledger.d.ts +66 -106
  93. package/dist/tasks/ledger.js +90 -546
  94. package/dist/tasks/log.d.ts +88 -0
  95. package/dist/tasks/log.js +97 -0
  96. package/dist/tasks/rounds.d.ts +43 -0
  97. package/dist/tasks/rounds.js +57 -0
  98. package/dist/tasks/session-path.d.ts +9 -0
  99. package/dist/tasks/session-path.js +16 -0
  100. package/dist/tasks/steer.d.ts +8 -0
  101. package/dist/tasks/steer.js +79 -0
  102. package/dist/tasks/store.d.ts +60 -35
  103. package/dist/tasks/store.js +166 -107
  104. package/dist/tasks/ticket.d.ts +102 -0
  105. package/dist/tasks/ticket.js +209 -0
  106. package/dist/tasks/verification.d.ts +16 -0
  107. package/dist/tasks/verification.js +40 -1
  108. package/dist/tools/index.d.ts +13 -4
  109. package/dist/tools/index.js +5 -10
  110. package/dist/tools/memory-manage.d.ts +6 -16
  111. package/dist/tools/memory-manage.js +108 -129
  112. package/dist/tools/presentation.js +2 -1
  113. package/dist/tools/registry.d.ts +11 -2
  114. package/dist/tools/registry.js +17 -6
  115. package/dist/tools/subagent-manage.d.ts +0 -9
  116. package/dist/tools/subagent-manage.js +8 -17
  117. package/dist/tools/task-manage/create.js +2 -2
  118. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  119. package/dist/tools/task-manage/lifecycle.js +139 -187
  120. package/dist/tools/task-manage/log-view.d.ts +8 -0
  121. package/dist/tools/task-manage/log-view.js +24 -0
  122. package/dist/tools/task-manage/schema.d.ts +38 -14
  123. package/dist/tools/task-manage/schema.js +46 -27
  124. package/dist/tools/task-manage/shared.d.ts +24 -31
  125. package/dist/tools/task-manage/shared.js +103 -141
  126. package/dist/tools/task-manage/step-end.d.ts +11 -0
  127. package/dist/tools/task-manage/step-end.js +136 -0
  128. package/dist/tools/task-manage/types.d.ts +23 -32
  129. package/dist/tools/task-manage.d.ts +4 -3
  130. package/dist/tools/task-manage.js +30 -15
  131. package/dist/tools/tool-details.d.ts +1 -1
  132. package/dist/tui/app.js +0 -2
  133. package/package.json +1 -1
  134. package/dist/agent/effect-ledger.d.ts +0 -32
  135. package/dist/agent/effect-ledger.js +0 -89
  136. package/dist/memory/bootstrap.d.ts +0 -17
  137. package/dist/memory/bootstrap.js +0 -120
  138. package/dist/memory/candidates.d.ts +0 -26
  139. package/dist/memory/candidates.js +0 -202
  140. package/dist/memory/consolidation.d.ts +0 -54
  141. package/dist/memory/consolidation.js +0 -292
  142. package/dist/memory/extraction.d.ts +0 -54
  143. package/dist/memory/extraction.js +0 -240
  144. package/dist/memory/files.d.ts +0 -71
  145. package/dist/memory/files.js +0 -419
  146. package/dist/memory/maintenance-jobs.d.ts +0 -41
  147. package/dist/memory/maintenance-jobs.js +0 -265
  148. package/dist/memory/metadata.d.ts +0 -57
  149. package/dist/memory/metadata.js +0 -142
  150. package/dist/memory/probation.d.ts +0 -17
  151. package/dist/memory/probation.js +0 -44
  152. package/dist/memory/promotion.d.ts +0 -38
  153. package/dist/memory/promotion.js +0 -36
  154. package/dist/memory/recall.d.ts +0 -59
  155. package/dist/memory/recall.js +0 -746
  156. package/dist/memory/session.d.ts +0 -24
  157. package/dist/memory/session.js +0 -273
  158. package/dist/playbooks/task-driving.md +0 -92
  159. package/dist/playbooks/task-planning.md +0 -58
  160. package/dist/tasks/control.d.ts +0 -56
  161. package/dist/tasks/control.js +0 -169
  162. package/dist/tasks/transitions.d.ts +0 -16
  163. package/dist/tasks/transitions.js +0 -48
  164. package/dist/tools/task-manage/verification.d.ts +0 -19
  165. package/dist/tools/task-manage/verification.js +0 -91
@@ -1,6 +1,6 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
2
  import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
3
- import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SettingsManager as SDKSettingsManager, SessionManager, } from "@earendil-works/pi-coding-agent";
3
+ import { AgentSession, AgentSessionRuntime, convertToLlm, DefaultResourceLoader, SettingsManager as SDKSettingsManager, SessionManager, } from "@earendil-works/pi-coding-agent";
4
4
  import { mkdir, readFile, writeFile } from "fs/promises";
5
5
  import { dirname, join, resolve } from "path";
6
6
  import { commitActiveSessionRef, resolveActiveSessionFile } from "../channel/active-session-store.js";
@@ -8,13 +8,14 @@ import { MAX_INBOUND_IMAGE_BYTES } from "../channel/channel-event.js";
8
8
  import { resolveProjectScope } from "../channel/project-scope-store.js";
9
9
  import { isKnownCommandName, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
10
10
  import * as log from "../log.js";
11
- import { buildFirstTurnMemoryBootstrapResult, FIRST_TURN_BOOTSTRAP_MAX_UNITS, } from "../memory/bootstrap.js";
12
- import { createMemoryCandidateStore } from "../memory/candidates.js";
13
11
  import { handleMemoryCommand } from "../memory/commands.js";
14
- import { getChannelMemoryPath } from "../memory/files.js";
12
+ import { buildChannelIndexForBootstrap, clipJournalTailForBootstrap, clipWorkspaceMemoryForBootstrap, } from "../memory/index-budget.js";
13
+ import { readJournalDay } from "../memory/journal.js";
15
14
  import { MemoryLifecycle } from "../memory/lifecycle.js";
16
15
  import { createMemoryActivityRecorder, } from "../memory/maintenance-state.js";
17
- import { findPreviousUserText, MEMORY_RECALL_MAX_UNITS, recallRelevantMemory } from "../memory/recall.js";
16
+ import { isChannelMigratedToV2, migrateChannelMemoryToV2 } from "../memory/migrate.js";
17
+ import { renderMemoryBootstrap } from "../memory/render.js";
18
+ import { listMemoryEntries } from "../memory/store.js";
18
19
  import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js";
19
20
  import { getApiKeyForModel } from "../models/api-keys.js";
20
21
  import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
@@ -22,11 +23,12 @@ import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks
22
23
  import { resolveProjectAccessPolicy } from "../security/project-scope.js";
23
24
  import { TASK_DIGEST_SETTINGS } from "../settings.js";
24
25
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
25
- import { formatLocalTime, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
26
+ import { formatLocalTime, localDayKey, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
26
27
  import { errorMessage } from "../shared/text-utils.js";
27
28
  import { isRecord } from "../shared/type-guards.js";
28
29
  import { withTimeout } from "../shared/with-timeout.js";
29
30
  import { discoverSubAgents } from "../subagents/discovery.js";
31
+ import { TASK_SESSIONS_DIRNAME, taskSessionPath } from "../tasks/session-path.js";
30
32
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
31
33
  import { createPipiclawTools } from "../tools/index.js";
32
34
  import { formatSize } from "../tools/truncate.js";
@@ -45,7 +47,7 @@ import { SessionResourceGate } from "./session-resource-gate.js";
45
47
  import { assembleTurnPrompt } from "./turn-prompt.js";
46
48
  import { recoverInterruptedTurn } from "./turn-recovery.js";
47
49
  import { TurnStateMachine } from "./turn-state.js";
48
- import { getLastAssistantUsage } from "./type-guards.js";
50
+ import { getLastAssistantUsage, isAutoCompactionEndEvent } from "./type-guards.js";
49
51
  import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
50
52
  import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
51
53
  function isSilentOutcome(outcome) {
@@ -126,6 +128,10 @@ export function initializeThinkingLevelCompat(agent, model, sessionManager, conf
126
128
  */
127
129
  const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
128
130
  const SESSION_RELOAD_TIMEOUT_MS = 30_000;
131
+ /** Task sessions live under `<channelDir>/tasks/.sessions/`; nothing else may be mistaken for one. */
132
+ function isTaskSessionPath(sessionFile) {
133
+ return sessionFile?.replace(/\\/g, "/").includes(`/${TASK_SESSIONS_DIRNAME}/`) === true;
134
+ }
129
135
  export class ChannelRunner {
130
136
  constructor(channelId, channelDir, paths, deps) {
131
137
  this.ledger = getUsageLedger();
@@ -148,6 +154,8 @@ export class ChannelRunner {
148
154
  this.primaryFailedAt = null;
149
155
  // --- Per run ---
150
156
  this.runState = createEmptyRunState();
157
+ /** Spec 050 §5: migrate this channel's memory to v2 on first use, before any turn reads it. */
158
+ this.memoryMigrationChecked = false;
151
159
  this.channelId = channelId;
152
160
  this.channelDir = channelDir;
153
161
  this.appHomeDir = paths.appHomeDir;
@@ -200,7 +208,6 @@ export class ChannelRunner {
200
208
  }
201
209
  this.settingsManager = paths.settingsManager;
202
210
  this.reportSettingsDiagnostics();
203
- this.memoryCandidateStore = createMemoryCandidateStore();
204
211
  this.memoryActivityRecorder = createMemoryActivityRecorder({
205
212
  appHomeDir: this.appHomeDir,
206
213
  onError: (channelId, error) => log.logWarning(`[${channelId}] Failed to record memory maintenance state`, errorMessage(error)),
@@ -224,12 +231,12 @@ export class ChannelRunner {
224
231
  this.memoryLifecycle = new MemoryLifecycle({
225
232
  channelId: this.channelId,
226
233
  channelDir: this.channelDir,
234
+ workspaceDir: this.workspaceDir,
227
235
  appHomeDir: this.appHomeDir,
228
236
  getMessages: () => this.session.messages,
229
237
  getSessionEntries: () => this.sessionManager.getBranch(),
230
238
  getModel: () => this.session.model ?? this.activeModel,
231
239
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
232
- getSessionMemorySettings: () => this.settingsManager.getSessionMemorySettings(),
233
240
  recordMemoryActivity: (event) => this.recordMemoryActivity(event),
234
241
  });
235
242
  this.sessionResourceGate = new SessionResourceGate(async () => {
@@ -276,14 +283,13 @@ export class ChannelRunner {
276
283
  let fallbackTargetRef;
277
284
  // Hoisted so the debug dump in `finally` can report the turn as it was actually sent.
278
285
  let promptText = "";
279
- let recalledContextText = "";
280
286
  let taskDigestText = "";
281
287
  let durableMemoryBootstrapText = "";
282
288
  let channelCapsuleText = "";
283
- let bootstrapCandidateIds = [];
284
289
  let bootstrapPrepared = false;
285
290
  try {
286
291
  await this.ensureSessionReady();
292
+ await this.ensureMemoryMigrated();
287
293
  await this.maybeRestorePrimaryModel();
288
294
  this.memoryLifecycle.noteUserTurnStarted();
289
295
  const normalizedInputLength = ctx.message.text.replace(/\r/g, "").trim().length;
@@ -304,47 +310,19 @@ export class ChannelRunner {
304
310
  // system prompt is what lets every channel in a workspace share one cached prefix.
305
311
  channelCapsuleText = this.renderChannelTurnContext();
306
312
  // The task digest reads the whole tasks/ directory and depends on nothing the memory
307
- // work below produces, so it runs alongside the bootstrap and recall rather than
308
- // queuing behind them. Settled into a result object rather than left as a bare
309
- // promise: if recall throws first we would otherwise leave a rejection unobserved,
310
- // which Node's default policy turns into a process exit. Rethrown at the await, so a
311
- // digest failure still fails the turn exactly as it did when this ran inline.
313
+ // bootstrap below produces, so it runs alongside it rather than queuing behind it.
314
+ // Settled into a result object rather than left as a bare promise: if the bootstrap
315
+ // throws first we would otherwise leave a rejection unobserved, which Node's default
316
+ // policy turns into a process exit. Rethrown at the await, so a digest failure still
317
+ // fails the turn exactly as it did when this ran inline.
312
318
  const taskDigestPromise = (this.tasksEnabled ? this.buildTaskDigestForTurn() : Promise.resolve("")).then((text) => ({ text }), (error) => ({ error }));
319
+ // Spec 050, D1: the memory index is injected in full on the first turn of a session
320
+ // (and the first turn after compaction — see `subscribeToSessionEvents`), never per
321
+ // turn. Mid-session, the model uses `memory_search` to look things up.
313
322
  if (this.firstTurnMemoryBootstrapPending) {
314
- const bootstrap = await this.buildFirstTurnMemoryBootstrap();
315
- durableMemoryBootstrapText = bootstrap.renderedText;
316
- bootstrapCandidateIds = bootstrap.includedCandidateIds;
323
+ durableMemoryBootstrapText = await this.buildFirstTurnMemoryBootstrap();
317
324
  bootstrapPrepared = true;
318
325
  }
319
- const recallSettings = this.settingsManager.getMemoryRecallSettings();
320
- if (recallSettings.enabled) {
321
- const recall = await recallRelevantMemory({
322
- query: clippedInput,
323
- contextQuery: findPreviousUserText(this.session.messages),
324
- channelId: this.channelId,
325
- workspaceDir: this.workspaceDir,
326
- channelDir: this.channelDir,
327
- maxCandidates: recallSettings.maxCandidates,
328
- maxInjected: recallSettings.maxInjected,
329
- maxChars: recallSettings.maxChars,
330
- // The configured char cap and the runtime unit cap both apply; first to bind clips.
331
- maxUnits: MEMORY_RECALL_MAX_UNITS,
332
- rerankWithModel: recallSettings.rerankWithModel,
333
- excludedCandidateIds: bootstrapCandidateIds,
334
- // `rerankWithModel` is passed through as configured; `shouldUseModelRerank`
335
- // owns the decision. Under "auto" it reranks whenever the shortlist is
336
- // over-full *and* the local ranking has no clear winner — script-independent,
337
- // so a Chinese turn is treated exactly like an English one. That rerank is an
338
- // LLM call on the critical path of the turn, capped at
339
- // MEMORY_RECALL_RERANK_TIMEOUT_MS and failing open to the local ranking.
340
- model: this.session.model ?? this.activeModel,
341
- resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
342
- candidateStore: this.memoryCandidateStore,
343
- });
344
- if (recall.renderedText) {
345
- recalledContextText = recall.renderedText;
346
- }
347
- }
348
326
  const taskDigestResult = await taskDigestPromise;
349
327
  if (taskDigestResult.error !== undefined) {
350
328
  throw taskDigestResult.error;
@@ -358,7 +336,6 @@ export class ChannelRunner {
358
336
  channelCapsule: channelCapsuleText,
359
337
  durableMemoryBootstrap: durableMemoryBootstrapText,
360
338
  taskDigest: taskDigestText,
361
- recalledMemory: recalledContextText,
362
339
  });
363
340
  promptText = assembled.text;
364
341
  // Resolved before the compaction estimate below (which needs the image count) and
@@ -462,7 +439,6 @@ export class ChannelRunner {
462
439
  promptText,
463
440
  durableMemoryBootstrapText,
464
441
  taskDigestText,
465
- recalledContextText,
466
442
  });
467
443
  }
468
444
  return {
@@ -496,7 +472,6 @@ export class ChannelRunner {
496
472
  messages: this.session.messages,
497
473
  durableMemoryBootstrap: input.durableMemoryBootstrapText || undefined,
498
474
  taskDigest: input.taskDigestText || undefined,
499
- recalledContext: input.recalledContextText || undefined,
500
475
  newUserMessage: input.promptText,
501
476
  };
502
477
  await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarning(`[${this.channelId}] Failed to write last_prompt.json`, errorMessage(error)));
@@ -716,16 +691,14 @@ export class ChannelRunner {
716
691
  return {
717
692
  channelId: this.channelId,
718
693
  channelDir: this.channelDir,
694
+ workspaceDir: this.workspaceDir,
719
695
  // Snapshot only when a maintenance job actually needs the transcript; most ticks
720
696
  // stop at a schedule gate and never call these.
721
697
  messages: () => [...this.session.messages],
722
698
  sessionEntries: () => [...this.sessionManager.getBranch()],
723
699
  model: this.session.model ?? this.activeModel,
724
700
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
725
- settings: {
726
- sessionMemory: this.settingsManager.getSessionMemorySettings(),
727
- memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings(),
728
- },
701
+ settings: { memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings() },
729
702
  };
730
703
  }
731
704
  getStatusSnapshot() {
@@ -835,7 +808,7 @@ export class ChannelRunner {
835
808
  return [
836
809
  "<runtime_turn_context>",
837
810
  `Channel directory: ${this.channelDir}`,
838
- "SESSION.md, MEMORY.md, HISTORY.md and tasks/ live there and are runtime-maintained. Prefer the context supplied with this turn and the channel-bound tools; read those files directly only when you need detail they did not provide.",
811
+ "The channel `MEMORY.md` index, `memory/`, `journal/` and `tasks/` live there. Prefer the context supplied with this turn and the channel-bound tools; read those files directly only when you need detail they did not provide.",
839
812
  "</runtime_turn_context>",
840
813
  ].join("\n");
841
814
  }
@@ -1104,11 +1077,16 @@ export class ChannelRunner {
1104
1077
  // the pointer before we rebuild and rebind to it, so a crash between "SDK created
1105
1078
  // session" and "we finished rebinding" leaves the old ref (and old session)
1106
1079
  // authoritative rather than an orphaned new file (spec 043, D1.3).
1107
- await commitActiveSessionRef(this.channelDir, sessionManager);
1108
- const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
1080
+ // A task session is not the channel's chat session: never repoint the active-session
1081
+ // ref at it, or `/new` and restart recovery would adopt a task's transcript as the
1082
+ // conversation (spec 051, D3).
1083
+ if (!isTaskSessionPath(sessionManager.getSessionFile())) {
1084
+ await commitActiveSessionRef(this.channelDir, sessionManager);
1085
+ }
1086
+ const next = await this.createSessionRuntime(sessionManager, sessionStartEvent);
1109
1087
  return {
1110
1088
  session: next.session,
1111
- extensionsResult: this.createEmptyExtensionsResult(),
1089
+ extensionsResult: next.resourceLoader.getExtensions(),
1112
1090
  services: this.createAgentSessionServices(next.resourceLoader),
1113
1091
  diagnostics: [],
1114
1092
  };
@@ -1167,6 +1145,24 @@ export class ChannelRunner {
1167
1145
  async ensureSessionReady() {
1168
1146
  await this.sessionReady;
1169
1147
  }
1148
+ async ensureMemoryMigrated() {
1149
+ if (this.memoryMigrationChecked) {
1150
+ return;
1151
+ }
1152
+ this.memoryMigrationChecked = true;
1153
+ if (isChannelMigratedToV2(this.channelDir)) {
1154
+ return;
1155
+ }
1156
+ try {
1157
+ const result = await migrateChannelMemoryToV2(this.channelDir);
1158
+ if (result.migrated) {
1159
+ log.logInfo(`[${this.channelId}] Migrated channel memory to v2 (${result.entries} entries, ${result.journalDays} journal days)`);
1160
+ }
1161
+ }
1162
+ catch (error) {
1163
+ log.logWarning(`[${this.channelId}] Channel memory v2 migration failed`, errorMessage(error));
1164
+ }
1165
+ }
1170
1166
  async maybeRunPreventiveCompactionForIncomingText(incomingText, imageCount = 0) {
1171
1167
  const currentModel = this.session.model ?? this.activeModel;
1172
1168
  const contextUsage = this.session.getContextUsage();
@@ -1297,7 +1293,12 @@ export class ChannelRunner {
1297
1293
  refreshSessionResources: async () => {
1298
1294
  await this.refreshSessionResources();
1299
1295
  },
1300
- runMemoryCommand: async (args) => handleMemoryCommand({ channelDir: this.channelDir, args }),
1296
+ runMemoryCommand: async (args) => handleMemoryCommand({
1297
+ channelId: this.channelId,
1298
+ channelDir: this.channelDir,
1299
+ appHomeDir: this.appHomeDir,
1300
+ args,
1301
+ }),
1301
1302
  }),
1302
1303
  ],
1303
1304
  // Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
@@ -1328,12 +1329,23 @@ export class ChannelRunner {
1328
1329
  diagnostics: [],
1329
1330
  };
1330
1331
  }
1331
- createEmptyExtensionsResult() {
1332
- return {
1333
- extensions: [],
1334
- errors: [],
1335
- runtime: createExtensionRuntime(),
1336
- };
1332
+ /**
1333
+ * Load a freshly constructed ResourceLoader before an `AgentSession` is built on top of it.
1334
+ *
1335
+ * `AgentSession` reads `resourceLoader.getExtensions()` in its constructor, and a loader that
1336
+ * has never been loaded answers with an *empty* set. Skipping this leaves a replacement session
1337
+ * with no extensions at all — no command extension (so `/model`, `/thinking`, `/session`,
1338
+ * `/compact` and `/memory` fall through to the model as plain text), no memory lifecycle, no
1339
+ * prompt-boundary footer, and no prompt templates. Tolerated on failure the same way
1340
+ * `reloadSessionResources` tolerates a stuck reload: a degraded session still answers chat.
1341
+ */
1342
+ async loadSessionResources(resourceLoader) {
1343
+ try {
1344
+ await withTimeout(`[${this.channelId}] session resource load`, SESSION_RELOAD_TIMEOUT_MS, () => resourceLoader.reload());
1345
+ }
1346
+ catch (error) {
1347
+ log.logWarning(`[${this.channelId}] Session resources did not load`, errorMessage(error));
1348
+ }
1337
1349
  }
1338
1350
  /**
1339
1351
  * Resolve the initial thinking level using the same precedence as pi's SDK:
@@ -1343,7 +1355,7 @@ export class ChannelRunner {
1343
1355
  initializeThinkingLevel(agent, model, sessionManager) {
1344
1356
  initializeThinkingLevelCompat(agent, model, sessionManager, this.settingsManager.getDefaultThinkingLevel());
1345
1357
  }
1346
- createSessionRuntime(sessionManager, sessionStartEvent) {
1358
+ async createSessionRuntime(sessionManager, sessionStartEvent) {
1347
1359
  const tools = this.buildRuntimeTools();
1348
1360
  const agent = new Agent({
1349
1361
  initialState: {
@@ -1358,6 +1370,9 @@ export class ChannelRunner {
1358
1370
  });
1359
1371
  this.initializeThinkingLevel(agent, this.activeModel, sessionManager);
1360
1372
  const resourceLoader = this.createResourceLoader();
1373
+ // Must precede `new AgentSession`: the session snapshots the loader's extensions in its
1374
+ // constructor (see `loadSessionResources`).
1375
+ await this.loadSessionResources(resourceLoader);
1361
1376
  const sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
1362
1377
  const session = new AgentSession({
1363
1378
  agent,
@@ -1372,6 +1387,37 @@ export class ChannelRunner {
1372
1387
  this.sessionSettingsManager = sessionSettingsManager;
1373
1388
  return { agent, session, resourceLoader };
1374
1389
  }
1390
+ /**
1391
+ * Bind this runner to a task cycle's own session (spec 051, D3/INV-5).
1392
+ *
1393
+ * Task work must not accumulate in the channel's chat transcript: the one real channel on the
1394
+ * author's machine had grown to 7.4 MB and been compacted six times because chat and two daily
1395
+ * tasks shared it, so every compaction damaged all three at once. Swapping the bound session
1396
+ * per turn gives each cycle its own bounded context while leaving turn state, `/stop`, and
1397
+ * delivery exactly where they already are.
1398
+ */
1399
+ async bindTaskSession(taskId, cycleId) {
1400
+ await this.sessionReady;
1401
+ const path = taskSessionPath(this.channelDir, taskId, cycleId);
1402
+ await mkdir(dirname(path), { recursive: true });
1403
+ this.taskLoop = { taskId, cycleId };
1404
+ await this.sessionRuntime.switchSession(path);
1405
+ // A fresh task session starts with no memory bootstrap injected yet; the chat session's
1406
+ // own flag is per-binding, so reset it rather than inheriting the chat turn's state.
1407
+ this.firstTurnMemoryBootstrapPending = true;
1408
+ }
1409
+ /** Return to the channel's chat session after a task step. Safe to call when already bound. */
1410
+ async bindChatSession() {
1411
+ if (!this.taskLoop)
1412
+ return;
1413
+ this.taskLoop = undefined;
1414
+ await this.sessionRuntime.switchSession(join(this.channelDir, resolveActiveSessionFile(this.channelDir)));
1415
+ this.firstTurnMemoryBootstrapPending = true;
1416
+ }
1417
+ /** Which task loop this runner is currently bound to, if any. */
1418
+ getTaskLoop() {
1419
+ return this.taskLoop;
1420
+ }
1375
1421
  buildRuntimeTools() {
1376
1422
  const securityLoad = this.loadSecurityConfig();
1377
1423
  const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
@@ -1388,13 +1434,13 @@ export class ChannelRunner {
1388
1434
  channelDir: this.channelDir,
1389
1435
  channelId: this.channelId,
1390
1436
  getSubAgentDiscovery: () => this.subAgentDiscovery,
1391
- getMemoryRecallSettings: () => this.settingsManager.getMemoryRecallSettings(),
1392
1437
  getSubAgentModelReference: () => this.settingsManager.getSubAgentModelReference(),
1393
1438
  getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
1394
- memoryCandidateStore: this.memoryCandidateStore,
1395
1439
  securityConfig: securityLoad.config,
1396
1440
  toolsConfig: toolsLoad.config,
1397
1441
  mediaSender: this.mediaSender,
1442
+ taskLoop: this.taskLoop,
1443
+ getToolsUsed: () => this.runState.toolsUsed,
1398
1444
  });
1399
1445
  this.currentTools = tools;
1400
1446
  // Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
@@ -1442,6 +1488,11 @@ export class ChannelRunner {
1442
1488
  if (isRecord(event) && "reason" in event && event.reason === "new") {
1443
1489
  this.firstTurnMemoryBootstrapPending = true;
1444
1490
  }
1491
+ // Spec 050, D1: compaction rewrites the first-turn bootstrap into a summary; re-inject
1492
+ // the authoritative index on the next turn so memory does not decay with the transcript.
1493
+ if (isAutoCompactionEndEvent(event) && !event.aborted && !event.errorMessage) {
1494
+ this.firstTurnMemoryBootstrapPending = true;
1495
+ }
1445
1496
  if (!this.runState.ctx || !this.runState.logCtx || !this.runState.queue)
1446
1497
  return;
1447
1498
  // The SDK listener signature is `(event) => void`, so the promise below is fire-and-forget.
@@ -1478,6 +1529,11 @@ export class ChannelRunner {
1478
1529
  maxUnits: TASK_AGENDA_MAX_UNITS,
1479
1530
  });
1480
1531
  }
1532
+ /**
1533
+ * Spec 050, D1: assemble `<memory_bootstrap>` for the first turn of a session — workspace
1534
+ * MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered). The
1535
+ * journal subsection is added in P2.
1536
+ */
1481
1537
  async buildFirstTurnMemoryBootstrap() {
1482
1538
  const readOptionalFile = async (path) => {
1483
1539
  try {
@@ -1487,14 +1543,18 @@ export class ChannelRunner {
1487
1543
  return "";
1488
1544
  }
1489
1545
  };
1490
- const [channelMemory, workspaceMemory] = await Promise.all([
1491
- readOptionalFile(getChannelMemoryPath(this.channelDir)),
1546
+ const today = localDayKey();
1547
+ const [entries, workspaceMemory, journalToday] = await Promise.all([
1548
+ listMemoryEntries(this.channelDir).catch(() => []),
1492
1549
  readOptionalFile(join(this.workspaceDir, "MEMORY.md")),
1550
+ readJournalDay(this.channelDir, today).catch(() => ""),
1493
1551
  ]);
1494
- return buildFirstTurnMemoryBootstrapResult({
1495
- channelMemory,
1496
- workspaceMemory,
1497
- maxUnits: FIRST_TURN_BOOTSTRAP_MAX_UNITS,
1552
+ const index = buildChannelIndexForBootstrap(entries);
1553
+ const journalTail = clipJournalTailForBootstrap(journalToday);
1554
+ return renderMemoryBootstrap({
1555
+ workspaceMemory: clipWorkspaceMemoryForBootstrap(workspaceMemory),
1556
+ channelIndex: entries.length > 0 ? index.text : "",
1557
+ journal: journalTail ? { date: today, text: journalTail } : undefined,
1498
1558
  });
1499
1559
  }
1500
1560
  }
@@ -6,11 +6,12 @@ import { type FileStore } from "../file-store.js";
6
6
  * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
7
7
  * message. A background job instead returns immediately and the model can end its turn.
8
8
  *
9
- * Jobs live on the host, managed through shell commands (`nohup` to launch, `kill -0` to probe,
10
- * `kill` to cancel) with no in-process child handles. Records are mirrored to
11
- * `state/jobs/<channelId>/<id>.json` so they survive a restart: a `nohup` process outlives the
12
- * daemon, and losing the record while the process kept running meant orphaned work, leaked slots,
13
- * and unreachable output (spec 031, D6).
9
+ * Jobs live on the host, managed through shell commands (`setsid` to launch as its own process
10
+ * group with a startup handshake, a three-state identity probe, a confirmed kill) with no
11
+ * in-process child handles. Records
12
+ * are mirrored to `state/jobs/<channelId>/<id>.json` so they survive a restart: a detached
13
+ * process outlives the daemon, and losing the record while the process kept running meant orphaned
14
+ * work, leaked slots, and unreachable output (spec 031, D6).
14
15
  *
15
16
  * A finished job wakes its channel by itself. Making the model predict a completion time and
16
17
  * arrange its own callback was a judgement call it could not make correctly, so completion is a
@@ -38,6 +39,14 @@ export interface JobWakeContract {
38
39
  }
39
40
  interface JobRecord extends JobSnapshot {
40
41
  pid: number;
42
+ /** Process-group id of the launched job, as `ps` reported it right after spawn. `setsid` makes
43
+ * the job its own session/group leader, so this normally equals `pid` — the precondition for a
44
+ * safe negative-PGID kill. Absent on records written before this was captured. */
45
+ pgid?: number;
46
+ /** `ps -o lstart=` for `pid` at launch: the only OS-verifiable way to tell the still-running
47
+ * job apart from an unrelated process that later reused its pid. Absent on older records and
48
+ * whenever `ps` was unavailable at launch — callers must then treat identity as unprovable. */
49
+ pidStartedAt?: string;
41
50
  spillFile: string;
42
51
  exitFile: string;
43
52
  timeoutSeconds: number;
@@ -46,6 +55,12 @@ interface JobRecord extends JobSnapshot {
46
55
  finishedAt?: number;
47
56
  /** Set once the completion wake has been dispatched, so a restart cannot re-announce it. */
48
57
  notified?: boolean;
58
+ /**
59
+ * A cancel or timeout whose kill could not be *confirmed* yet: the job stays `running` and
60
+ * manageable, and every sweep re-attempts the kill until the process is proven gone, at which
61
+ * point this terminal status is applied. Internal only — never surfaced in a `JobSnapshot`.
62
+ */
63
+ pendingKill?: "cancelled" | "failed";
49
64
  wakeClaimDispatchId?: string;
50
65
  wakeConsumedAt?: number;
51
66
  }
@@ -86,6 +101,14 @@ export declare class ChannelJobManager {
86
101
  private readonly executor;
87
102
  private readonly jobs;
88
103
  private readonly wakeQueue;
104
+ /**
105
+ * Serializes every probe → decide → terminal-transition sequence for a single job. The sweeper,
106
+ * `list`/`poll`/`restore` (via `refresh`), `cancel`, and the persist-failure rollback all pass
107
+ * through it, so two callers can never race the same job to two terminal states (e.g. both see
108
+ * `pendingKill`, both `finish`, the second reading a now-cleared `pendingKill` and writing a
109
+ * bogus status). Inside the slot each op re-checks `record.status`.
110
+ */
111
+ private readonly reconcileQueue;
89
112
  private sweepTimer?;
90
113
  private garbageCollectionTimer?;
91
114
  private sweeping;
@@ -97,6 +120,8 @@ export declare class ChannelJobManager {
97
120
  /** Mirror a record to disk. Persistence is best-effort: it must never fail a job operation. */
98
121
  private persist;
99
122
  private forget;
123
+ /** Remove a job's scratch files (and optionally its persisted record). Every unlink is best-effort. */
124
+ private unlinkArtifacts;
100
125
  /**
101
126
  * Drop finished jobs whose retention window has passed, together with their spill files.
102
127
  * Called from the sweeper and from restore, so leftovers never outlive a daemon restart.
@@ -114,11 +139,20 @@ export declare class ChannelJobManager {
114
139
  /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
115
140
  runningTaskIds(): Set<string>;
116
141
  /**
117
- * Launch a command in the background and return its job id. The wrapper writes merged
118
- * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
119
- * `echo $!` hands back the nohup PID for later probing/cancellation.
142
+ * Launch a command in the background and return its snapshot. The wrapper (`buildLaunchScript`)
143
+ * runs a readiness handshake before the command executes: only after the inner shell proves it
144
+ * started — spill writable, `setsid`/`sh` execed — does the parent print `MODE`/`PID` and exit
145
+ * 0. A failed handshake, a non-zero launch, or an interrupted launch never creates a `running`
146
+ * record; a persist failure right after a successful launch terminates the process (see below).
120
147
  */
121
148
  start(command: string, label: string, timeoutSeconds: number, options?: JobStartOptions): Promise<JobSnapshot>;
149
+ /**
150
+ * Recover from a launch that rejected (an abort landed after the wrapper had already spawned the
151
+ * detached child, or the executor failed outright). The wrapper writes a metadata file *before*
152
+ * its readiness handshake, so even an interrupted launch usually leaves a recoverable pid;
153
+ * clean it up with no caller signal and return an error that is honest about what is known.
154
+ */
155
+ private recoverInterruptedLaunch;
122
156
  /**
123
157
  * Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
124
158
  * so their slots free up even when the model never polls, and stops itself once nothing is running.
@@ -127,10 +161,11 @@ export declare class ChannelJobManager {
127
161
  private stopSweeper;
128
162
  private sweep;
129
163
  /**
130
- * Probe every given job in one shell invocation, returning `id → EXIT:<code>|ALIVE|GONE`.
164
+ * Probe every given job in one shell invocation, returning
165
+ * `id → EXIT:<code> | ALIVE | GONE | DIFFERENT | UNKNOWN`.
131
166
  *
132
167
  * Each job contributes one branch that reads its exit-code file if present and otherwise checks
133
- * PID liveness — exactly what the single-job probe did, just batched.
168
+ * liveness (three-state when a start time was captured — see the inline comment).
134
169
  */
135
170
  private probeAll;
136
171
  /**
@@ -141,7 +176,19 @@ export declare class ChannelJobManager {
141
176
  * to say nothing.
142
177
  */
143
178
  private refresh;
144
- /** Turn one probe result into a status transition; an unrecognized result only ages the job. */
179
+ /**
180
+ * Probe one job and apply the result. The unlocked core of `refresh` — every caller must already
181
+ * hold the job's `reconcileQueue` slot (`refresh`, or `cancel`'s combined critical section).
182
+ */
183
+ private reconcileLocked;
184
+ /**
185
+ * The terminal status for a job a probe just showed as finished/gone. A cancel or timeout kill
186
+ * already in flight (`pendingKill`) wins over the raw probe result — a job the model asked to
187
+ * cancel lands `cancelled`, a timed-out one `failed`/124 — even if the process happened to exit
188
+ * on its own first. Clears `pendingKill`; call only immediately before `finish`.
189
+ */
190
+ private takePendingTerminal;
191
+ /** Turn one probe result into a status transition; an inconclusive result only ages the job. */
145
192
  private applyProbe;
146
193
  /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
147
194
  private finish;
@@ -153,7 +200,24 @@ export declare class ChannelJobManager {
153
200
  * version that persisted `notified` first, which could crash-lose the wake entirely).
154
201
  */
155
202
  private announce;
156
- private kill;
203
+ /**
204
+ * The shell command that terminates `record`'s process and prints one token describing what
205
+ * happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
206
+ * there is no pid we can safely signal.
207
+ *
208
+ * A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
209
+ * the command spawned dies with it). When a start time was captured it is checked first: a
210
+ * recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
211
+ * that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
212
+ * ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
213
+ */
214
+ private killCommand;
215
+ /**
216
+ * Run one kill attempt and classify it from the printed token plus the executor result — never
217
+ * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
218
+ * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
219
+ */
220
+ private runKill;
157
221
  list(signal?: AbortSignal): Promise<JobSnapshot[]>;
158
222
  beginWakeConsumption(id: string, taskId: string, dispatchId: string): Promise<boolean>;
159
223
  finishWakeConsumption(id: string, dispatchId: string): Promise<void>;
@@ -193,15 +257,6 @@ interface JobRuntimeConfig {
193
257
  * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
194
258
  */
195
259
  export declare function configureJobRuntime(config: JobRuntimeConfig): void;
196
- /**
197
- * Which of this channel's tasks a running background job will wake, without needing an `Executor`.
198
- *
199
- * Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
200
- * something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
201
- * startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
202
- * manager simply has no jobs, and the empty set is the right answer.
203
- */
204
- export declare function channelJobTaskIds(channelId: string): Set<string>;
205
260
  /**
206
261
  * Human-readable lines naming this channel's currently running background jobs, for the `/project
207
262
  * set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no