@oyasmi/pipiclaw 0.9.2-beta.6 → 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
@@ -3,7 +3,6 @@ import { dirname, join } from "node:path";
3
3
  import { getChannelDirName } from "../channel/channel-paths.js";
4
4
  import * as log from "../log.js";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
- import { parseLocalTime } from "../shared/local-time.js";
7
6
  import { createSerialQueue } from "../shared/serial-queue.js";
8
7
  import { errorMessage } from "../shared/text-utils.js";
9
8
  const stateUpdateQueue = createSerialQueue();
@@ -23,13 +22,11 @@ export function getMemoryMaintenanceStatePath(appHomeDir, channelId) {
23
22
  }
24
23
  /**
25
24
  * Where a pre-escaping runtime put the same channel's state. Only differs for ids containing
26
- * `/`, and only matters until the next write moves the state to its canonical path — but the
27
- * state carries maintenance cadence and transcript cursors, so dropping it would silently
28
- * re-run structural maintenance and re-scan the transcript for every affected group.
25
+ * `/`, and only matters until the next write moves the state to its canonical path.
29
26
  *
30
- * RETIRE AT v0.9.3, same rationale as the header comment in `../runtime/task-migration.js`:
31
- * by the stable cut, every still-running group channel with a `/` in its id will have had its
32
- * state folded onto the canonical path at least once, so this fallback read finds nothing.
27
+ * RETIRE AT v0.9.3, same rationale as the header comment in `../runtime/task-migration.js`: by
28
+ * the stable cut, every still-running group channel with a `/` in its id will have had its state
29
+ * folded onto the canonical path at least once, so this fallback read finds nothing.
33
30
  */
34
31
  function legacyStatePath(appHomeDir, channelId) {
35
32
  return getChannelDirName(channelId) === channelId
@@ -37,13 +34,7 @@ function legacyStatePath(appHomeDir, channelId) {
37
34
  : join(getMemoryMaintenanceStateDir(appHomeDir), `${channelId}.json`);
38
35
  }
39
36
  function createDefaultState(channelId) {
40
- return {
41
- channelId,
42
- dirty: false,
43
- turnsSinceSessionRefresh: 0,
44
- toolCallsSinceSessionRefresh: 0,
45
- failureBackoffUntil: null,
46
- };
37
+ return { channelId, dirty: false, failureBackoffUntil: null };
47
38
  }
48
39
  function normalizeOptionalString(value) {
49
40
  return typeof value === "string" && value.trim().length > 0 ? value : undefined;
@@ -54,16 +45,6 @@ function normalizeOptionalNullableString(value) {
54
45
  }
55
46
  return normalizeOptionalString(value);
56
47
  }
57
- function normalizeCounter(value) {
58
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
59
- }
60
- function laterTimestamp(a, b) {
61
- if (!a)
62
- return b;
63
- if (!b)
64
- return a;
65
- return (parseLocalTime(a) ?? -Infinity) >= (parseLocalTime(b) ?? -Infinity) ? a : b;
66
- }
67
48
  function normalizeState(channelId, value) {
68
49
  if (!value || typeof value !== "object" || Array.isArray(value)) {
69
50
  return createDefaultState(channelId);
@@ -74,19 +55,11 @@ function normalizeState(channelId, value) {
74
55
  dirty: typeof record.dirty === "boolean" ? record.dirty : false,
75
56
  lastActivityAt: normalizeOptionalString(record.lastActivityAt),
76
57
  eligibleAfter: normalizeOptionalString(record.eligibleAfter),
77
- lastSessionRefreshAt: normalizeOptionalString(record.lastSessionRefreshAt),
78
- // Legacy states carried separate consolidation/growth-review fields; fold them
79
- // into the merged checkpoint so cadence and cursor survive the migration.
80
- lastCheckpointAt: normalizeOptionalString(record.lastCheckpointAt) ??
81
- laterTimestamp(normalizeOptionalString(record.lastDurableConsolidationAt), normalizeOptionalString(record.lastGrowthReviewAt)),
82
- lastStructuralMaintenanceAt: normalizeOptionalString(record.lastStructuralMaintenanceAt),
83
- turnsSinceSessionRefresh: normalizeCounter(record.turnsSinceSessionRefresh),
84
- toolCallsSinceSessionRefresh: normalizeCounter(record.toolCallsSinceSessionRefresh),
85
- lastSessionEntryId: normalizeOptionalString(record.lastSessionEntryId),
86
- lastSessionRefreshedEntryId: normalizeOptionalString(record.lastSessionRefreshedEntryId),
87
- lastCheckpointEntryId: normalizeOptionalString(record.lastCheckpointEntryId) ??
88
- normalizeOptionalString(record.lastConsolidatedEntryId) ??
89
- normalizeOptionalString(record.lastReviewedEntryId),
58
+ // v1 states carried the checkpoint job's fields under a different name; fold them into
59
+ // the reflect cadence/cursor so an upgrade does not re-run reflect on the channel's whole
60
+ // history nor lose its due time.
61
+ lastReflectAt: normalizeOptionalString(record.lastReflectAt) ?? normalizeOptionalString(record.lastCheckpointAt),
62
+ lastReflectedEntryId: normalizeOptionalString(record.lastReflectedEntryId) ?? normalizeOptionalString(record.lastCheckpointEntryId),
90
63
  failureBackoffUntil: normalizeOptionalNullableString(record.failureBackoffUntil) ?? null,
91
64
  };
92
65
  }
@@ -138,24 +111,10 @@ export async function updateMemoryMaintenanceState(appHomeDir, channelId, update
138
111
  });
139
112
  }
140
113
  function mergeMemoryActivity(pending, event) {
141
- const next = pending ?? {
142
- lastActivityAt: event.timestamp,
143
- toolCalls: 0,
144
- turns: 0,
145
- dirty: false,
146
- };
114
+ const next = pending ?? { lastActivityAt: event.timestamp, dirty: false };
147
115
  next.lastActivityAt = event.timestamp;
148
116
  next.eligibleAfter = event.eligibleAfter ?? next.eligibleAfter;
149
- next.latestSessionEntryId = event.latestSessionEntryId ?? next.latestSessionEntryId;
150
- if (event.kind === "tool-call") {
151
- next.dirty = true;
152
- next.toolCalls += 1;
153
- }
154
- if (event.kind === "assistant-turn-completed") {
155
- next.dirty = true;
156
- next.turns += 1;
157
- }
158
- if (event.kind === "boundary") {
117
+ if (event.kind === "tool-call" || event.kind === "assistant-turn-completed" || event.kind === "boundary") {
159
118
  next.dirty = true;
160
119
  }
161
120
  return next;
@@ -166,10 +125,7 @@ function applyPendingActivityToState(state, channelId, pending) {
166
125
  channelId,
167
126
  lastActivityAt: pending.lastActivityAt,
168
127
  eligibleAfter: pending.eligibleAfter ?? state.eligibleAfter,
169
- lastSessionEntryId: pending.latestSessionEntryId ?? state.lastSessionEntryId,
170
128
  dirty: state.dirty || pending.dirty,
171
- toolCallsSinceSessionRefresh: state.toolCallsSinceSessionRefresh + pending.toolCalls,
172
- turnsSinceSessionRefresh: state.turnsSinceSessionRefresh + pending.turns,
173
129
  };
174
130
  }
175
131
  /** Apply a single activity event. The buffered path folds a whole burst through the same core. */
@@ -244,9 +200,6 @@ function mergeBack(failed, current) {
244
200
  // `current` is the newer batch, so it wins on every last-write-wins field.
245
201
  lastActivityAt: current.lastActivityAt,
246
202
  eligibleAfter: current.eligibleAfter ?? failed.eligibleAfter,
247
- latestSessionEntryId: current.latestSessionEntryId ?? failed.latestSessionEntryId,
248
- toolCalls: failed.toolCalls + current.toolCalls,
249
- turns: failed.turns + current.turns,
250
203
  dirty: failed.dirty || current.dirty,
251
204
  };
252
205
  }
@@ -1,37 +1,17 @@
1
1
  /**
2
- * Cadence and threshold constants for the background memory maintenance
3
- * pipeline (spec 035 D1/D2).
2
+ * Cadence and threshold constants for the background reflect pass (spec 050, D7/D9).
4
3
  *
5
- * These were `settings.json` keys until 0.8.10. They are algorithm parameters,
6
- * not product intent: a user can decide *whether* background maintenance runs
7
- * (`memoryMaintenance.enabled` is still a setting), but has no basis for
8
- * deciding whether the checkpoint interval should be 20 minutes or 25.
4
+ * These were `settings.json` keys until 0.8.10, then split across three jobs' worth of
5
+ * constants; spec 050 collapses the pipeline to one job and these to one small set. A user can
6
+ * decide *whether* background maintenance runs (`memoryMaintenance.enabled` is still a setting),
7
+ * but has no basis for deciding whether the reflect interval should be 20 minutes or 25.
9
8
  */
10
9
  export interface MemoryMaintenanceTuning {
11
10
  /** How long a channel must be quiet before background LLM work is allowed. */
12
11
  minIdleMinutesBeforeLlmWork: number;
13
- sessionRefreshIntervalMinutes: number;
14
- /** Idle cadence of the merged memory checkpoint (durable extraction) job. */
15
- checkpointIntervalMinutes: number;
16
- /** Confidence bar a candidate must clear before it is written to MEMORY.md. */
17
- minMemoryAutoWriteConfidence: number;
18
- structuralMaintenanceIntervalHours: number;
12
+ /** Idle cadence of the reflect pass. */
13
+ reflectIntervalMinutes: number;
19
14
  maxConcurrentChannels: number;
20
15
  failureBackoffMinutes: number;
21
- /** Reject a MEMORY.md cleanup whose result shrinks below this ratio of the original. */
22
- cleanupShrinkGuardMinRatio: number;
23
- /** Only apply the shrink guard when the original exceeds this length (chars). */
24
- cleanupShrinkGuardMinChars: number;
25
16
  }
26
17
  export declare function getMemoryMaintenanceTuning(env?: NodeJS.ProcessEnv): MemoryMaintenanceTuning;
27
- /**
28
- * How much conversation must accumulate before a scheduled `SESSION.md` refresh
29
- * is allowed (`maintenance-gates.ts` reads these). Constants like the tuning
30
- * above, and lowered by the same test hook so a single-message E2E turn can
31
- * trip the gate instead of waiting for a natural multi-turn exchange.
32
- */
33
- export interface SessionRefreshCadence {
34
- minTurnsBetweenUpdate: number;
35
- minToolCallsBetweenUpdate: number;
36
- }
37
- export declare function getSessionRefreshCadence(env?: NodeJS.ProcessEnv): SessionRefreshCadence;
@@ -1,46 +1,29 @@
1
1
  /**
2
- * Cadence and threshold constants for the background memory maintenance
3
- * pipeline (spec 035 D1/D2).
2
+ * Cadence and threshold constants for the background reflect pass (spec 050, D7/D9).
4
3
  *
5
- * These were `settings.json` keys until 0.8.10. They are algorithm parameters,
6
- * not product intent: a user can decide *whether* background maintenance runs
7
- * (`memoryMaintenance.enabled` is still a setting), but has no basis for
8
- * deciding whether the checkpoint interval should be 20 minutes or 25.
4
+ * These were `settings.json` keys until 0.8.10, then split across three jobs' worth of
5
+ * constants; spec 050 collapses the pipeline to one job and these to one small set. A user can
6
+ * decide *whether* background maintenance runs (`memoryMaintenance.enabled` is still a setting),
7
+ * but has no basis for deciding whether the reflect interval should be 20 minutes or 25.
9
8
  */
10
9
  const PRODUCTION_TUNING = {
11
10
  minIdleMinutesBeforeLlmWork: 10,
12
- sessionRefreshIntervalMinutes: 10,
13
- checkpointIntervalMinutes: 20,
14
- minMemoryAutoWriteConfidence: 0.85,
15
- structuralMaintenanceIntervalHours: 6,
11
+ reflectIntervalMinutes: 20,
16
12
  maxConcurrentChannels: 1,
17
13
  failureBackoffMinutes: 30,
18
- cleanupShrinkGuardMinRatio: 0.4,
19
- cleanupShrinkGuardMinChars: 2_000,
20
14
  };
21
15
  /**
22
- * Test-only escape hatch. E2E and behavior-eval runs assert that `SESSION.md`
23
- * refreshes within tens of seconds, which the production idle/interval gates
24
- * make impossible. Set by `test/support/setup.ts`; deliberately undocumented in
25
- * `docs/configuration.md` — it is a test hook, not a supported knob.
16
+ * Test-only escape hatch. E2E and behavior-eval runs assert that reflect fires within tens of
17
+ * seconds, which the production idle/interval gates make impossible. Set by
18
+ * `test/support/setup.ts`; deliberately undocumented in `docs/configuration.md` — it is a test
19
+ * hook, not a supported knob.
26
20
  */
27
21
  const FAST_MAINTENANCE_TUNING = {
28
22
  ...PRODUCTION_TUNING,
29
23
  minIdleMinutesBeforeLlmWork: 0,
30
- sessionRefreshIntervalMinutes: 0,
24
+ reflectIntervalMinutes: 0,
31
25
  failureBackoffMinutes: 1,
32
26
  };
33
27
  export function getMemoryMaintenanceTuning(env = process.env) {
34
28
  return env.PIPICLAW_TEST_FAST_MAINTENANCE === "1" ? FAST_MAINTENANCE_TUNING : PRODUCTION_TUNING;
35
29
  }
36
- const PRODUCTION_SESSION_REFRESH = {
37
- minTurnsBetweenUpdate: 2,
38
- minToolCallsBetweenUpdate: 4,
39
- };
40
- const FAST_SESSION_REFRESH = {
41
- minTurnsBetweenUpdate: 1,
42
- minToolCallsBetweenUpdate: 1,
43
- };
44
- export function getSessionRefreshCadence(env = process.env) {
45
- return env.PIPICLAW_TEST_FAST_MAINTENANCE === "1" ? FAST_SESSION_REFRESH : PRODUCTION_SESSION_REFRESH;
46
- }
@@ -0,0 +1,15 @@
1
+ export interface MigrationResult {
2
+ migrated: boolean;
3
+ reason?: string;
4
+ entries: number;
5
+ journalDays: number;
6
+ ongoingWorkItems: number;
7
+ tombstones: number;
8
+ }
9
+ export declare function getMigrationMarkerPath(channelDir: string): string;
10
+ export declare function isChannelMigratedToV2(channelDir: string): boolean;
11
+ export declare function migrateChannelMemoryToV2(channelDir: string, options?: {
12
+ today?: string;
13
+ }): Promise<MigrationResult>;
14
+ /** Reverse a migration: restore `.memory-v1/` originals, drop the v2 artifacts. */
15
+ export declare function rollbackChannelMemoryV2(channelDir: string): Promise<void>;
@@ -0,0 +1,364 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { readOptionalTextFile } from "../shared/fs-utils.js";
6
+ import { localDayKey, parseLocalTime } from "../shared/local-time.js";
7
+ import { dedupeMemoryName, getChannelMemoryDir, getChannelMemoryIndexPath, getMemoryEntryPath, rebuildMemoryIndex, serializeMemoryEntry, slugifyMemoryName, } from "./store.js";
8
+ import { hashMemoryContent } from "./tombstones.js";
9
+ /**
10
+ * Spec 050 §5: one-shot, deterministic, no-LLM, idempotent, reversible migration from the v1
11
+ * layout (5 files + entries.json) to the v2 layout (`memory/*.md` + `journal/` + generated
12
+ * index). Original files are moved to `.memory-v1/`, never deleted. Runs per channel at daemon
13
+ * / TUI startup, before the runner is created. The workspace directory is never migrated.
14
+ */
15
+ const MARKER = ".migrated-v2";
16
+ const V1_DIR = ".memory-v1";
17
+ export function getMigrationMarkerPath(channelDir) {
18
+ return join(getChannelMemoryDir(channelDir), MARKER);
19
+ }
20
+ export function isChannelMigratedToV2(channelDir) {
21
+ return existsSync(getMigrationMarkerPath(channelDir));
22
+ }
23
+ function hasV1Layout(channelDir) {
24
+ return (existsSync(join(channelDir, "MEMORY.md")) ||
25
+ existsSync(join(channelDir, "HISTORY.md")) ||
26
+ existsSync(join(channelDir, "SESSION.md")) ||
27
+ existsSync(join(channelDir, ".memory")));
28
+ }
29
+ const ID_COMMENT = /\s*<!--\s*id:(m-[a-z0-9]+)\s*-->\s*$/i;
30
+ function parseV1MemoryBullets(raw) {
31
+ const lines = raw.replace(/\r/g, "").split("\n");
32
+ const bullets = [];
33
+ let section = "";
34
+ let updateTimestamp;
35
+ for (const line of lines) {
36
+ const h2 = /^##\s+(.+)$/.exec(line);
37
+ if (h2) {
38
+ section = h2[1].trim();
39
+ const update = /^Update\s+(.+)$/.exec(section);
40
+ updateTimestamp = update ? update[1].trim() : undefined;
41
+ continue;
42
+ }
43
+ if (!section) {
44
+ continue;
45
+ }
46
+ const zeroIndentBullet = /^-\s+(.+)$/.exec(line);
47
+ const indentedBullet = /^\s+[-*]\s+(.+)$/.exec(line);
48
+ if (zeroIndentBullet) {
49
+ const idMatch = ID_COMMENT.exec(zeroIndentBullet[1]);
50
+ const content = zeroIndentBullet[1].replace(ID_COMMENT, "").trim();
51
+ if (content) {
52
+ bullets.push({
53
+ section,
54
+ content,
55
+ details: [],
56
+ explicitId: idMatch?.[1],
57
+ updateTimestamp,
58
+ });
59
+ }
60
+ }
61
+ else if (indentedBullet && bullets.length > 0) {
62
+ // F1: a nested bullet is a continuation of its parent, not its own memory.
63
+ bullets[bullets.length - 1].details.push(indentedBullet[1].trim());
64
+ }
65
+ }
66
+ return bullets;
67
+ }
68
+ async function loadV1Metadata(channelDir) {
69
+ const byId = new Map();
70
+ const byContentHash = new Map();
71
+ const raw = await readOptionalTextFile(join(channelDir, ".memory", "entries.json"));
72
+ if (!raw) {
73
+ return { byId, byContentHash };
74
+ }
75
+ try {
76
+ const parsed = JSON.parse(raw);
77
+ for (const [id, record] of Object.entries(parsed.entries ?? {})) {
78
+ byId.set(id, record);
79
+ if (record.contentHash) {
80
+ byContentHash.set(record.contentHash, record);
81
+ }
82
+ }
83
+ }
84
+ catch {
85
+ /* corrupt entries.json — proceed with empty metadata */
86
+ }
87
+ return { byId, byContentHash };
88
+ }
89
+ function syntheticV1Id(section, content) {
90
+ return `m-${createHash("sha1").update(`${section}\x00${content}`).digest("hex").slice(0, 8)}`;
91
+ }
92
+ // -------------------------------------------------------------------------------------------------
93
+ // type / source mapping (spec 050, D2 table)
94
+ // -------------------------------------------------------------------------------------------------
95
+ const POINTER_PATTERN = /(~\/|https?:\/\/|\/home\/|[\w-]+\.md\b|路径|目录|repo)/i;
96
+ function mapType(section, kind, content) {
97
+ const heading = section.toLowerCase();
98
+ if (kind === "lesson") {
99
+ return "feedback";
100
+ }
101
+ if (kind === "preference" || heading.includes("preference")) {
102
+ return heading.includes("identity") || heading.includes("participant") ? "user" : "feedback";
103
+ }
104
+ if (heading.includes("identity") || heading.includes("participant")) {
105
+ return "user";
106
+ }
107
+ // A pointer-shaped fact (a path, URL, CLI location, repo) is `reference` even when it was
108
+ // filed under Constraints in v1.
109
+ if ((kind === "fact" || kind === undefined) && POINTER_PATTERN.test(content)) {
110
+ return "reference";
111
+ }
112
+ if (kind === "decision" || kind === "constraint" || heading.includes("decision") || heading.includes("constraint")) {
113
+ return "project";
114
+ }
115
+ return POINTER_PATTERN.test(content) ? "reference" : "project";
116
+ }
117
+ function mapSource(sourceType) {
118
+ return sourceType === "user" ? "user" : "migrated";
119
+ }
120
+ function toDateKey(value, fallback) {
121
+ if (!value) {
122
+ return fallback;
123
+ }
124
+ const ms = parseLocalTime(value);
125
+ return ms === undefined ? fallback : localDayKey(new Date(ms));
126
+ }
127
+ // -------------------------------------------------------------------------------------------------
128
+ // journal assembly
129
+ // -------------------------------------------------------------------------------------------------
130
+ function timeOfDay(timestamp) {
131
+ const ms = parseLocalTime(timestamp);
132
+ if (ms === undefined) {
133
+ return "";
134
+ }
135
+ const d = new Date(ms);
136
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
137
+ }
138
+ /** `## <ts>` blocks in a v1 HISTORY.md, plus the single folded block. */
139
+ function parseV1History(raw) {
140
+ const days = new Map();
141
+ let folded;
142
+ const blocks = raw.replace(/\r/g, "").split(/\n(?=## )/);
143
+ for (const block of blocks) {
144
+ const headingMatch = /^##\s+(.+)$/m.exec(block);
145
+ if (!headingMatch) {
146
+ continue;
147
+ }
148
+ const heading = headingMatch[1].trim();
149
+ const body = block.slice(block.indexOf("\n") + 1).trim();
150
+ const foldedMatch = /^Folded History Through\s+(.+)$/.exec(heading);
151
+ if (foldedMatch) {
152
+ folded = { date: toDateKey(foldedMatch[1], localDayKey()), text: body };
153
+ continue;
154
+ }
155
+ const date = toDateKey(heading, "");
156
+ if (!date || !body) {
157
+ continue;
158
+ }
159
+ const time = timeOfDay(heading);
160
+ const bullets = body
161
+ .split("\n")
162
+ .map((line) => line.replace(/^[-*]\s*/, "").trim())
163
+ .filter(Boolean)
164
+ .map((line) => (time ? `- ${time} ${line}` : `- ${line}`));
165
+ days.set(date, [...(days.get(date) ?? []), ...bullets]);
166
+ }
167
+ return { days, folded };
168
+ }
169
+ const SESSION_MIGRATED_SECTIONS = ["Decisions", "Constraints", "Errors & Corrections"];
170
+ function parseSessionMigratedBullets(raw) {
171
+ const lines = raw.replace(/\r/g, "").split("\n");
172
+ const out = [];
173
+ let capturing = false;
174
+ for (const line of lines) {
175
+ const h1 = /^#\s+(.+)$/.exec(line);
176
+ if (h1) {
177
+ capturing = SESSION_MIGRATED_SECTIONS.includes(h1[1].trim());
178
+ continue;
179
+ }
180
+ if (!capturing) {
181
+ continue;
182
+ }
183
+ const bullet = /^[-*]\s+(.+)$/.exec(line.trim());
184
+ if (bullet?.[1] && !bullet[1].startsWith("<!--")) {
185
+ out.push(`- ${bullet[1].trim()}`);
186
+ }
187
+ }
188
+ return out;
189
+ }
190
+ async function writeJournalFile(channelDir, date, sections) {
191
+ const nonEmpty = sections.filter((s) => s.bullets.length > 0);
192
+ if (nonEmpty.length === 0) {
193
+ return;
194
+ }
195
+ const blocks = [`# ${date}`];
196
+ for (const section of nonEmpty) {
197
+ if (section.heading) {
198
+ blocks.push(`## ${section.heading}`);
199
+ }
200
+ blocks.push(section.bullets.join("\n"));
201
+ }
202
+ await mkdir(join(channelDir, "journal"), { recursive: true });
203
+ await writeFile(join(channelDir, "journal", `${date}.md`), `${blocks.join("\n\n")}\n`, "utf-8");
204
+ }
205
+ // -------------------------------------------------------------------------------------------------
206
+ // migration
207
+ // -------------------------------------------------------------------------------------------------
208
+ async function moveToV1Archive(channelDir, relPath) {
209
+ const source = join(channelDir, relPath);
210
+ if (!existsSync(source)) {
211
+ return;
212
+ }
213
+ const target = join(channelDir, V1_DIR, relPath);
214
+ await mkdir(join(target, ".."), { recursive: true });
215
+ await rename(source, target);
216
+ }
217
+ export async function migrateChannelMemoryToV2(channelDir, options = {}) {
218
+ const today = options.today ?? localDayKey();
219
+ const empty = {
220
+ migrated: false,
221
+ entries: 0,
222
+ journalDays: 0,
223
+ ongoingWorkItems: 0,
224
+ tombstones: 0,
225
+ };
226
+ if (isChannelMigratedToV2(channelDir)) {
227
+ return { ...empty, reason: "already-migrated" };
228
+ }
229
+ if (!hasV1Layout(channelDir)) {
230
+ // A fresh channel is already v2 — drop the marker so the retired v1 writers stay disabled
231
+ // here too, and the startup pass does not re-scan it every launch.
232
+ await mkdir(getChannelMemoryDir(channelDir), { recursive: true });
233
+ await writeFile(getMigrationMarkerPath(channelDir), `${JSON.stringify({ migratedAt: today, fresh: true })}\n`, "utf-8");
234
+ return { ...empty, reason: "nothing-to-migrate" };
235
+ }
236
+ const metadata = await loadV1Metadata(channelDir);
237
+ const memoryRaw = await readOptionalTextFile(join(channelDir, "MEMORY.md"));
238
+ const historyRaw = await readOptionalTextFile(join(channelDir, "HISTORY.md"));
239
+ const sessionRaw = await readOptionalTextFile(join(channelDir, "SESSION.md"));
240
+ const bullets = parseV1MemoryBullets(memoryRaw);
241
+ const memoryDir = getChannelMemoryDir(channelDir);
242
+ await mkdir(memoryDir, { recursive: true });
243
+ const usedNames = new Set();
244
+ const ongoingWork = [];
245
+ let entryCount = 0;
246
+ for (const bullet of bullets) {
247
+ if (/ongoing work|open (loop|question)/i.test(bullet.section)) {
248
+ ongoingWork.push(`- ${bullet.content}`);
249
+ continue;
250
+ }
251
+ const record = (bullet.explicitId ? metadata.byId.get(bullet.explicitId) : undefined) ??
252
+ metadata.byId.get(syntheticV1Id(bullet.section, bullet.content)) ??
253
+ metadata.byContentHash.get(hashMemoryContent(bullet.content));
254
+ const asciiWords = bullet.content
255
+ .toLowerCase()
256
+ .replace(/[^a-z0-9\s]/g, " ")
257
+ .split(/\s+/)
258
+ .filter((word) => word.length > 1)
259
+ .slice(0, 6);
260
+ // A one-word slug ("ai", "user") is too generic to be a handle; hash instead.
261
+ const base = asciiWords.length >= 2
262
+ ? slugifyMemoryName(asciiWords.join(" "))
263
+ : `m-${createHash("sha1").update(bullet.content).digest("hex").slice(0, 6)}`;
264
+ const name = dedupeMemoryName(base, usedNames);
265
+ usedNames.add(name);
266
+ const created = toDateKey(bullet.updateTimestamp ?? record?.createdAt, today);
267
+ const entry = {
268
+ name,
269
+ description: bullet.content.replace(/\s+/g, " ").trim(),
270
+ type: mapType(bullet.section, record?.kind, bullet.content),
271
+ source: mapSource(record?.sourceType),
272
+ created,
273
+ updated: created,
274
+ expires: record?.probationUntil ? toDateKey(record.probationUntil, today) : undefined,
275
+ body: bullet.details.join("\n"),
276
+ malformed: false,
277
+ };
278
+ await writeFile(getMemoryEntryPath(channelDir, name), serializeMemoryEntry(entry), "utf-8");
279
+ entryCount++;
280
+ }
281
+ // tombstones: v1 `.memory/tombstones.jsonl` → `memory/.tombstones.jsonl` (contentHash kept)
282
+ let tombstoneCount = 0;
283
+ const tombRaw = await readOptionalTextFile(join(channelDir, ".memory", "tombstones.jsonl"));
284
+ if (tombRaw) {
285
+ const lines = tombRaw
286
+ .split("\n")
287
+ .filter(Boolean)
288
+ .flatMap((line) => {
289
+ try {
290
+ const v = JSON.parse(line);
291
+ if (!v.contentHash) {
292
+ return [];
293
+ }
294
+ tombstoneCount++;
295
+ return [
296
+ JSON.stringify({
297
+ contentHash: v.contentHash,
298
+ deletedAt: v.deletedAt ?? today,
299
+ reason: v.reason ?? "migrated",
300
+ }),
301
+ ];
302
+ }
303
+ catch {
304
+ return [];
305
+ }
306
+ });
307
+ if (lines.length > 0) {
308
+ await writeFile(join(memoryDir, ".tombstones.jsonl"), `${lines.join("\n")}\n`, "utf-8");
309
+ }
310
+ }
311
+ // journal: HISTORY blocks → per-day; folded block → one file; SESSION + Ongoing Work → today
312
+ const { days, folded } = parseV1History(historyRaw);
313
+ for (const [date, bulletsForDay] of days) {
314
+ await writeJournalFile(channelDir, date, [{ bullets: bulletsForDay }]);
315
+ }
316
+ if (folded) {
317
+ await mkdir(join(channelDir, "journal"), { recursive: true });
318
+ await writeFile(join(channelDir, "journal", `folded-through-${folded.date}.md`), `# Folded history through ${folded.date}\n\n${folded.text}\n`, "utf-8");
319
+ }
320
+ const sessionBullets = parseSessionMigratedBullets(sessionRaw);
321
+ await writeJournalFile(channelDir, today, [
322
+ { heading: "迁移自 SESSION.md", bullets: sessionBullets },
323
+ { heading: "迁移自 MEMORY.md 的进行中事项", bullets: ongoingWork },
324
+ ]);
325
+ // archive v1 originals (never deleted)
326
+ for (const rel of [
327
+ "MEMORY.md",
328
+ "HISTORY.md",
329
+ "HISTORY.archive.md",
330
+ "HISTORY.archive.md.1",
331
+ "SESSION.md",
332
+ "SESSION.invalid-response.txt",
333
+ ".memory",
334
+ ".memory-backups",
335
+ ]) {
336
+ await moveToV1Archive(channelDir, rel);
337
+ }
338
+ await rebuildMemoryIndex(channelDir);
339
+ const result = {
340
+ migrated: true,
341
+ entries: entryCount,
342
+ journalDays: days.size + (folded ? 1 : 0) + (sessionBullets.length + ongoingWork.length > 0 ? 1 : 0),
343
+ ongoingWorkItems: ongoingWork.length,
344
+ tombstones: tombstoneCount,
345
+ };
346
+ await writeFile(getMigrationMarkerPath(channelDir), `${JSON.stringify({ migratedAt: today, ...result })}\n`, "utf-8");
347
+ return result;
348
+ }
349
+ /** Reverse a migration: restore `.memory-v1/` originals, drop the v2 artifacts. */
350
+ export async function rollbackChannelMemoryV2(channelDir) {
351
+ // Drop the v2 artifacts first — the generated index shares the name `MEMORY.md` with the
352
+ // archived v1 original, so it must go before the restore, not after.
353
+ await rm(getChannelMemoryDir(channelDir), { recursive: true, force: true });
354
+ await rm(join(channelDir, "journal"), { recursive: true, force: true });
355
+ await rm(getChannelMemoryIndexPath(channelDir), { force: true });
356
+ const archive = join(channelDir, V1_DIR);
357
+ if (existsSync(archive)) {
358
+ for (const name of await readdir(archive)) {
359
+ await rm(join(channelDir, name), { recursive: true, force: true });
360
+ await rename(join(archive, name), join(channelDir, name));
361
+ }
362
+ await rm(archive, { recursive: true, force: true });
363
+ }
364
+ }
@@ -0,0 +1,43 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { Api, Model } from "@earendil-works/pi-ai";
3
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
4
+ import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
5
+ import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
6
+ import { type MaintenanceJobKind } from "./maintenance-gates.js";
7
+ import { runReflect } from "./reflect.js";
8
+ /**
9
+ * Spec 050, D7/D9: the scheduler's idle-tick entry point into the reflect pass. Boundary
10
+ * triggers (compaction, `/new`, shutdown) bypass this job entirely and call `reflect.js`
11
+ * directly from `lifecycle.ts`, the same split `maintenance-jobs.ts` used to have between the
12
+ * idle checkpoint job and `MemoryLifecycle`'s preflight consolidation.
13
+ */
14
+ export interface ReflectJobInput {
15
+ appHomeDir: string;
16
+ channelId: string;
17
+ channelDir: string;
18
+ workspaceDir: string;
19
+ channelActive: boolean;
20
+ now?: Date;
21
+ settings: {
22
+ memoryMaintenance: PipiclawMemoryMaintenanceSettings;
23
+ };
24
+ model: Model<Api>;
25
+ resolveApiKey: (model: Model<Api>) => Promise<string>;
26
+ /** Transcript accessors: only called once the gate has decided the job may actually run. */
27
+ messages: () => AgentMessage[];
28
+ sessionEntries: () => SessionEntry[];
29
+ queue?: ChannelMemoryQueue;
30
+ }
31
+ export interface ReflectJobResult {
32
+ jobKind: MaintenanceJobKind;
33
+ ran: boolean;
34
+ skipped: boolean;
35
+ skipReason?: string;
36
+ error?: string;
37
+ }
38
+ export declare function runReflectJob(input: ReflectJobInput): Promise<ReflectJobResult>;
39
+ /** Shared by the idle job and `lifecycle.ts`'s boundary calls, so both write the same shape. */
40
+ export declare function reviewLogEntryFor(result: Awaited<ReturnType<typeof runReflect>>): {
41
+ actions?: unknown[];
42
+ skipped?: unknown[];
43
+ };