@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.2

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 (178) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +3 -1
  3. package/dist/agent/channel-runner.d.ts +59 -2
  4. package/dist/agent/channel-runner.js +177 -76
  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 +19 -0
  40. package/dist/memory/render.js +35 -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/memory/transcript.js +12 -5
  54. package/dist/playbooks/agent-delegation.md +37 -9
  55. package/dist/playbooks/background-jobs.md +1 -1
  56. package/dist/playbooks/event-scheduling.md +6 -2
  57. package/dist/playbooks/memory-and-learning.md +36 -12
  58. package/dist/playbooks/outbound-media.md +1 -1
  59. package/dist/playbooks/runtime-orientation.md +9 -8
  60. package/dist/playbooks/task-loop.md +110 -0
  61. package/dist/runtime/bootstrap.d.ts +3 -3
  62. package/dist/runtime/bootstrap.js +66 -41
  63. package/dist/runtime/events.d.ts +9 -0
  64. package/dist/runtime/events.js +43 -4
  65. package/dist/runtime/task-commands.d.ts +14 -15
  66. package/dist/runtime/task-commands.js +249 -485
  67. package/dist/runtime/task-driver.d.ts +41 -29
  68. package/dist/runtime/task-driver.js +170 -317
  69. package/dist/runtime/task-migration.d.ts +34 -30
  70. package/dist/runtime/task-migration.js +229 -183
  71. package/dist/runtime/task-wake.d.ts +6 -3
  72. package/dist/runtime/task-wake.js +26 -19
  73. package/dist/settings.d.ts +0 -29
  74. package/dist/settings.js +12 -35
  75. package/dist/shared/markdown-sections.d.ts +0 -1
  76. package/dist/shared/markdown-sections.js +0 -3
  77. package/dist/subagents/discovery.d.ts +2 -2
  78. package/dist/subagents/discovery.js +21 -10
  79. package/dist/subagents/external/progress-tail.js +6 -1
  80. package/dist/subagents/external/run.js +1 -0
  81. package/dist/subagents/runs.d.ts +19 -2
  82. package/dist/subagents/runs.js +73 -4
  83. package/dist/subagents/tool.d.ts +10 -8
  84. package/dist/subagents/tool.js +55 -94
  85. package/dist/tasks/brief.d.ts +17 -0
  86. package/dist/tasks/brief.js +57 -0
  87. package/dist/tasks/budget.d.ts +26 -0
  88. package/dist/tasks/budget.js +59 -0
  89. package/dist/tasks/cycle.d.ts +48 -0
  90. package/dist/tasks/cycle.js +94 -0
  91. package/dist/tasks/frontmatter.d.ts +73 -0
  92. package/dist/tasks/frontmatter.js +175 -0
  93. package/dist/tasks/ledger.d.ts +66 -106
  94. package/dist/tasks/ledger.js +90 -546
  95. package/dist/tasks/log.d.ts +88 -0
  96. package/dist/tasks/log.js +97 -0
  97. package/dist/tasks/rounds.d.ts +41 -0
  98. package/dist/tasks/rounds.js +53 -0
  99. package/dist/tasks/session-path.d.ts +9 -0
  100. package/dist/tasks/session-path.js +16 -0
  101. package/dist/tasks/steer.d.ts +8 -0
  102. package/dist/tasks/steer.js +79 -0
  103. package/dist/tasks/store.d.ts +60 -35
  104. package/dist/tasks/store.js +166 -107
  105. package/dist/tasks/ticket.d.ts +102 -0
  106. package/dist/tasks/ticket.js +209 -0
  107. package/dist/tasks/verification.d.ts +47 -0
  108. package/dist/tasks/verification.js +60 -1
  109. package/dist/tools/index.d.ts +13 -4
  110. package/dist/tools/index.js +5 -10
  111. package/dist/tools/memory-manage.d.ts +6 -16
  112. package/dist/tools/memory-manage.js +108 -129
  113. package/dist/tools/presentation.js +2 -1
  114. package/dist/tools/registry.d.ts +11 -2
  115. package/dist/tools/registry.js +17 -6
  116. package/dist/tools/subagent-manage.d.ts +0 -9
  117. package/dist/tools/subagent-manage.js +8 -17
  118. package/dist/tools/task-manage/create.js +2 -2
  119. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  120. package/dist/tools/task-manage/lifecycle.js +136 -188
  121. package/dist/tools/task-manage/log-view.d.ts +8 -0
  122. package/dist/tools/task-manage/log-view.js +24 -0
  123. package/dist/tools/task-manage/schema.d.ts +38 -14
  124. package/dist/tools/task-manage/schema.js +46 -27
  125. package/dist/tools/task-manage/shared.d.ts +35 -31
  126. package/dist/tools/task-manage/shared.js +130 -141
  127. package/dist/tools/task-manage/step-end.d.ts +11 -0
  128. package/dist/tools/task-manage/step-end.js +134 -0
  129. package/dist/tools/task-manage/types.d.ts +23 -32
  130. package/dist/tools/task-manage.d.ts +4 -3
  131. package/dist/tools/task-manage.js +30 -15
  132. package/dist/tools/tool-details.d.ts +1 -1
  133. package/dist/tui/app.js +0 -2
  134. package/examples/sub-agents/README.md +54 -38
  135. package/examples/sub-agents/builder-hard.md +21 -12
  136. package/examples/sub-agents/builder.md +24 -16
  137. package/examples/sub-agents/explorer.md +17 -15
  138. package/examples/sub-agents/git-committer.md +8 -6
  139. package/examples/sub-agents/planner.md +17 -16
  140. package/examples/sub-agents/reviewer.md +11 -9
  141. package/examples/sub-agents/verifier.md +22 -16
  142. package/examples/sub-agents/worker.md +22 -6
  143. package/package.json +1 -1
  144. package/dist/agent/effect-ledger.d.ts +0 -32
  145. package/dist/agent/effect-ledger.js +0 -89
  146. package/dist/memory/bootstrap.d.ts +0 -17
  147. package/dist/memory/bootstrap.js +0 -120
  148. package/dist/memory/candidates.d.ts +0 -26
  149. package/dist/memory/candidates.js +0 -202
  150. package/dist/memory/consolidation.d.ts +0 -54
  151. package/dist/memory/consolidation.js +0 -292
  152. package/dist/memory/extraction.d.ts +0 -54
  153. package/dist/memory/extraction.js +0 -240
  154. package/dist/memory/files.d.ts +0 -71
  155. package/dist/memory/files.js +0 -419
  156. package/dist/memory/maintenance-jobs.d.ts +0 -41
  157. package/dist/memory/maintenance-jobs.js +0 -265
  158. package/dist/memory/metadata.d.ts +0 -57
  159. package/dist/memory/metadata.js +0 -142
  160. package/dist/memory/probation.d.ts +0 -17
  161. package/dist/memory/probation.js +0 -44
  162. package/dist/memory/promotion.d.ts +0 -38
  163. package/dist/memory/promotion.js +0 -36
  164. package/dist/memory/recall.d.ts +0 -59
  165. package/dist/memory/recall.js +0 -746
  166. package/dist/memory/session.d.ts +0 -24
  167. package/dist/memory/session.js +0 -273
  168. package/dist/playbooks/task-driving.md +0 -92
  169. package/dist/playbooks/task-planning.md +0 -58
  170. package/dist/tasks/control.d.ts +0 -56
  171. package/dist/tasks/control.js +0 -169
  172. package/dist/tasks/transitions.d.ts +0 -16
  173. package/dist/tasks/transitions.js +0 -48
  174. package/dist/tools/task-manage/verification.d.ts +0 -19
  175. package/dist/tools/task-manage/verification.js +0 -91
  176. package/examples/sub-agents/documenter.md +0 -50
  177. package/examples/sub-agents/log-sifter.md +0 -47
  178. package/examples/sub-agents/scout.md +0 -34
@@ -6,56 +6,29 @@ import { discoverWorkspaceChannelIds } from "../channel/channel-index.js";
6
6
  import { dedupeChannelIdsByDirectory, isChannelId } from "../channel/channel-paths.js";
7
7
  import * as log from "../log.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
- import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
10
- import { runMemoryCheckpointJob, runSessionRefreshJob, runStructuralMaintenanceJob } from "./maintenance-jobs.js";
9
+ import { shouldRunReflect } from "./maintenance-gates.js";
11
10
  import { getMemoryMaintenanceStateDir, readMemoryMaintenanceState } from "./maintenance-state.js";
11
+ import { runReflectJob } from "./reflect-job.js";
12
12
  const DEFAULT_TICK_INTERVAL_MS = 60_000;
13
13
  /**
14
14
  * Cheap due-time predicate, evaluated before `getRuntimeContext` (transcript access, model
15
15
  * resolution, settings reload) is paid for.
16
16
  *
17
- * Reuses the real gates with optimistic material (transcript-derived checks always pass), so the
18
- * only work here is one state-file read plus timestamp arithmetic. A gate's material checks are
19
- * purely additive restrictions on top of the cheap checks (interval/backoff/idle/dirty), so
17
+ * Reuses the real gate with optimistic material (transcript-derived checks always pass), so the
18
+ * only work here is one state-file read plus timestamp arithmetic. The gate's material check is a
19
+ * purely additive restriction on top of the cheap checks (interval/backoff/idle/dirty), so
20
20
  * optimistic material can only ever make this predicate *more* permissive than the real job would
21
- * be — it never wrongly skips a channel that a job would actually run for.
21
+ * be — it never wrongly skips a channel the job would actually run for.
22
22
  */
23
- async function mightAnyMaintenanceJobBeDue(input) {
23
+ async function mightReflectBeDue(input) {
24
24
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
25
- const sessionRefresh = shouldRunSessionRefresh({
25
+ return shouldRunReflect({
26
26
  now: input.now,
27
27
  state,
28
- sessionMemory: input.settings.sessionMemory,
29
28
  maintenance: input.settings.memoryMaintenance,
30
29
  channelActive: false,
31
- hasNewSessionEntry: () => true,
32
- hasMeaningfulMaterial: () => true,
33
- });
34
- if (sessionRefresh.allowed)
35
- return true;
36
- const checkpoint = shouldRunMemoryCheckpoint({
37
- now: input.now,
38
- state,
39
- maintenance: input.settings.memoryMaintenance,
40
- channelActive: false,
41
- material: () => ({ hasNewEntry: true, hasMeaningfulExchange: true, batchSize: Number.MAX_SAFE_INTEGER }),
42
- });
43
- if (checkpoint.allowed)
44
- return true;
45
- const structural = await shouldRunStructuralMaintenance({
46
- now: input.now,
47
- state,
48
- maintenance: input.settings.memoryMaintenance,
49
- channelActive: false,
50
- material: async () => ({
51
- memoryCleanupNeeded: true,
52
- historyFoldingNeeded: true,
53
- hasMemoryContent: true,
54
- hasHistoryContent: true,
55
- expiredEntryCount: 1,
56
- }),
57
- });
58
- return structural.allowed;
30
+ material: () => ({ hasNewEntry: true, hasMeaningfulExchange: true }),
31
+ }).allowed;
59
32
  }
60
33
  /**
61
34
  * Channels with a maintenance state file — the ones nobody has spoken to since this process
@@ -141,7 +114,7 @@ export class MemoryMaintenanceScheduler {
141
114
  const channelId = channelIds[index];
142
115
  if (channelId &&
143
116
  !this.options.isChannelActive(channelId) &&
144
- (await mightAnyMaintenanceJobBeDue({
117
+ (await mightReflectBeDue({
145
118
  appHomeDir: this.options.appHomeDir,
146
119
  channelId,
147
120
  settings,
@@ -167,10 +140,11 @@ export class MemoryMaintenanceScheduler {
167
140
  if (!context) {
168
141
  return;
169
142
  }
170
- const common = {
143
+ await runReflectJob({
171
144
  appHomeDir: this.options.appHomeDir,
172
145
  channelId,
173
146
  channelDir: context.channelDir,
147
+ workspaceDir: context.workspaceDir,
174
148
  channelActive: this.options.isChannelActive(channelId),
175
149
  now,
176
150
  settings: context.settings,
@@ -178,15 +152,6 @@ export class MemoryMaintenanceScheduler {
178
152
  resolveApiKey: context.resolveApiKey,
179
153
  messages: context.messages,
180
154
  sessionEntries: context.sessionEntries,
181
- };
182
- const session = await runSessionRefreshJob(common);
183
- if (session.ran) {
184
- return;
185
- }
186
- const checkpoint = await runMemoryCheckpointJob(common);
187
- if (checkpoint.ran) {
188
- return;
189
- }
190
- await runStructuralMaintenanceJob(common);
155
+ });
191
156
  }
192
157
  }
@@ -0,0 +1,35 @@
1
+ import type { MemoryEntry } from "./store.js";
2
+ /**
3
+ * Age-bucketed recency boost (≤1 day / ≤7 days / ≤30 days / older), scaled by `weights`. Kept
4
+ * here (not `session-search.ts`) so both cold-storage callers share one scoring primitive; each
5
+ * caller supplies its own weights since the two scoring systems live on different magnitudes.
6
+ */
7
+ export declare function recencyBoostByAge(timestamp: string | undefined, weights: {
8
+ day: number;
9
+ week: number;
10
+ month: number;
11
+ }): number;
12
+ export declare function tokenizeRecallText(text: string): string[];
13
+ export declare const NEAR_DUPLICATE_JACCARD = 0.6;
14
+ export declare function descriptionSimilarity(a: string, b: string): number;
15
+ /** Entries whose description is a near-duplicate of `description`, strongest match first. */
16
+ export declare function findNearDuplicateEntries(description: string, entries: MemoryEntry[]): MemoryEntry[];
17
+ export interface MemorySearchHit {
18
+ kind: "memory" | "journal" | "workspace";
19
+ /** entry name, journal date, or workspace section heading */
20
+ label: string;
21
+ date?: string;
22
+ line: string;
23
+ }
24
+ export interface MemorySearchInput {
25
+ query: string;
26
+ entries: MemoryEntry[];
27
+ /** `{ date, content }` per journal file, newest first. */
28
+ journal?: Array<{
29
+ date: string;
30
+ content: string;
31
+ }>;
32
+ workspaceMemory?: string;
33
+ limit?: number;
34
+ }
35
+ export declare function searchMemory(input: MemorySearchInput): MemorySearchHit[];
@@ -0,0 +1,297 @@
1
+ import { parseLocalTime } from "../shared/local-time.js";
2
+ import { splitH2Sections } from "../shared/markdown-sections.js";
3
+ import { HAN_REGEX } from "../shared/text-utils.js";
4
+ import { COMMON_CHINESE_WORDS } from "./chinese-words.js";
5
+ /**
6
+ * Age-bucketed recency boost (≤1 day / ≤7 days / ≤30 days / older), scaled by `weights`. Kept
7
+ * here (not `session-search.ts`) so both cold-storage callers share one scoring primitive; each
8
+ * caller supplies its own weights since the two scoring systems live on different magnitudes.
9
+ */
10
+ export function recencyBoostByAge(timestamp, weights) {
11
+ if (!timestamp)
12
+ return 0;
13
+ const timestampMs = parseLocalTime(timestamp);
14
+ if (timestampMs === undefined)
15
+ return 0;
16
+ const ageMs = Date.now() - timestampMs;
17
+ const dayMs = 24 * 60 * 60 * 1000;
18
+ if (ageMs <= dayMs)
19
+ return weights.day;
20
+ if (ageMs <= 7 * dayMs)
21
+ return weights.week;
22
+ if (ageMs <= 30 * dayMs)
23
+ return weights.month;
24
+ return 0;
25
+ }
26
+ /**
27
+ * Spec 050, D3/D4: the lexical tokenizer, moved here from the retired `recall.ts`. It now serves
28
+ * exactly two callers — `memory_search` and `memory_save`'s deterministic near-duplicate guard.
29
+ * Per-turn recall scoring, intent seeding, and the usage-count boost are gone.
30
+ */
31
+ const TOKEN_PART_REGEX = /[\p{Script=Han}]+|[\p{L}\p{N}_./-]+/gu;
32
+ const ASCII_SPLIT_REGEX = /[._/-]+/g;
33
+ const MAX_HAN_WORD_LENGTH = Array.from(COMMON_CHINESE_WORDS).reduce((max, word) => Math.max(max, word.length), 2);
34
+ const LATIN_STOP_WORDS = new Set([
35
+ "a",
36
+ "an",
37
+ "and",
38
+ "are",
39
+ "as",
40
+ "at",
41
+ "be",
42
+ "been",
43
+ "being",
44
+ "by",
45
+ "can",
46
+ "could",
47
+ "did",
48
+ "do",
49
+ "does",
50
+ "doing",
51
+ "for",
52
+ "from",
53
+ "had",
54
+ "has",
55
+ "have",
56
+ "here",
57
+ "how",
58
+ "i",
59
+ "in",
60
+ "is",
61
+ "it",
62
+ "its",
63
+ "me",
64
+ "my",
65
+ "of",
66
+ "on",
67
+ "or",
68
+ "our",
69
+ "please",
70
+ "should",
71
+ "that",
72
+ "the",
73
+ "their",
74
+ "them",
75
+ "there",
76
+ "these",
77
+ "they",
78
+ "this",
79
+ "to",
80
+ "was",
81
+ "we",
82
+ "were",
83
+ "what",
84
+ "when",
85
+ "where",
86
+ "which",
87
+ "who",
88
+ "why",
89
+ "with",
90
+ "would",
91
+ "you",
92
+ "your",
93
+ ]);
94
+ const CHINESE_STOP_CHARS = new Set([
95
+ "的",
96
+ "了",
97
+ "在",
98
+ "是",
99
+ "有",
100
+ "不",
101
+ "和",
102
+ "与",
103
+ "个",
104
+ "把",
105
+ "被",
106
+ "从",
107
+ "对",
108
+ "而",
109
+ "给",
110
+ "将",
111
+ "就",
112
+ "让",
113
+ "向",
114
+ "也",
115
+ "以",
116
+ "因",
117
+ "又",
118
+ "于",
119
+ "则",
120
+ "之",
121
+ "这",
122
+ "那",
123
+ "其",
124
+ "它",
125
+ "他",
126
+ "她",
127
+ "们",
128
+ "都",
129
+ "要",
130
+ "会",
131
+ "能",
132
+ "很",
133
+ "得",
134
+ "地",
135
+ "着",
136
+ "过",
137
+ "吗",
138
+ "呢",
139
+ "吧",
140
+ "啊",
141
+ "哦",
142
+ "嗯",
143
+ "呀",
144
+ ]);
145
+ function containsHanText(text) {
146
+ return HAN_REGEX.test(text);
147
+ }
148
+ function tokenizeHanPart(part) {
149
+ const chars = Array.from(part);
150
+ const covered = new Uint8Array(chars.length);
151
+ const tokens = [];
152
+ for (let index = 0; index < chars.length; index++) {
153
+ const maxLength = Math.min(MAX_HAN_WORD_LENGTH, chars.length - index);
154
+ for (let size = maxLength; size >= 2; size--) {
155
+ const candidate = chars.slice(index, index + size).join("");
156
+ if (COMMON_CHINESE_WORDS.has(candidate)) {
157
+ tokens.push(candidate);
158
+ for (let c = index; c < index + size; c++) {
159
+ covered[c] = 1;
160
+ }
161
+ break;
162
+ }
163
+ }
164
+ }
165
+ for (let index = 0; index <= chars.length - 2; index++) {
166
+ if (covered[index] || covered[index + 1]) {
167
+ continue;
168
+ }
169
+ tokens.push(chars.slice(index, index + 2).join(""));
170
+ }
171
+ for (let index = 0; index < chars.length; index++) {
172
+ if (!covered[index] && !CHINESE_STOP_CHARS.has(chars[index])) {
173
+ tokens.push(chars[index]);
174
+ }
175
+ }
176
+ // Trigrams across the whole run — they survive greedy dictionary shredding of domain compounds
177
+ // and match verbatim on both the query and the stored side.
178
+ for (let index = 0; index + 3 <= chars.length; index++) {
179
+ tokens.push(chars.slice(index, index + 3).join(""));
180
+ }
181
+ return Array.from(new Set(tokens));
182
+ }
183
+ function tokenizeAsciiPart(part) {
184
+ const tokens = [];
185
+ const normalized = part.toLowerCase();
186
+ if (normalized.length >= 2 && !LATIN_STOP_WORDS.has(normalized)) {
187
+ tokens.push(normalized);
188
+ }
189
+ for (const segment of normalized.split(ASCII_SPLIT_REGEX).filter(Boolean)) {
190
+ if (segment.length >= 2 && !LATIN_STOP_WORDS.has(segment)) {
191
+ tokens.push(segment);
192
+ }
193
+ }
194
+ return tokens;
195
+ }
196
+ export function tokenizeRecallText(text) {
197
+ const parts = text.toLowerCase().match(TOKEN_PART_REGEX) ?? [];
198
+ const tokens = [];
199
+ for (const part of parts) {
200
+ if (containsHanText(part)) {
201
+ tokens.push(...tokenizeHanPart(part));
202
+ }
203
+ else {
204
+ tokens.push(...tokenizeAsciiPart(part));
205
+ }
206
+ }
207
+ return Array.from(new Set(tokens));
208
+ }
209
+ // -------------------------------------------------------------------------------------------------
210
+ // Near-duplicate detection for memory_save (spec 050, D3)
211
+ // -------------------------------------------------------------------------------------------------
212
+ export const NEAR_DUPLICATE_JACCARD = 0.6;
213
+ function normalizeForEquality(text) {
214
+ return text.normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
215
+ }
216
+ export function descriptionSimilarity(a, b) {
217
+ if (normalizeForEquality(a) === normalizeForEquality(b)) {
218
+ return 1;
219
+ }
220
+ const setA = new Set(tokenizeRecallText(a));
221
+ const setB = new Set(tokenizeRecallText(b));
222
+ if (setA.size === 0 || setB.size === 0) {
223
+ return 0;
224
+ }
225
+ let intersection = 0;
226
+ for (const token of setA) {
227
+ if (setB.has(token)) {
228
+ intersection++;
229
+ }
230
+ }
231
+ return intersection / (setA.size + setB.size - intersection);
232
+ }
233
+ /** Entries whose description is a near-duplicate of `description`, strongest match first. */
234
+ export function findNearDuplicateEntries(description, entries) {
235
+ return entries
236
+ .map((entry) => ({ entry, score: descriptionSimilarity(description, entry.description) }))
237
+ .filter(({ score }) => score >= NEAR_DUPLICATE_JACCARD)
238
+ .sort((a, b) => b.score - a.score)
239
+ .map(({ entry }) => entry);
240
+ }
241
+ function scoreText(queryTokens, text) {
242
+ const textTokens = new Set(tokenizeRecallText(text));
243
+ let score = 0;
244
+ for (const token of queryTokens) {
245
+ if (textTokens.has(token)) {
246
+ score++;
247
+ }
248
+ }
249
+ const lower = text.toLowerCase();
250
+ for (const token of queryTokens) {
251
+ if (token.length >= 3 && lower.includes(token)) {
252
+ score += 0.5;
253
+ }
254
+ }
255
+ const firstLine = text
256
+ .split("\n")
257
+ .find((l) => l.trim().length > 0)
258
+ ?.trim() ?? text.trim();
259
+ return { score, line: firstLine.length > 200 ? `${firstLine.slice(0, 197)}…` : firstLine };
260
+ }
261
+ export function searchMemory(input) {
262
+ const queryTokens = new Set(tokenizeRecallText(input.query));
263
+ if (queryTokens.size === 0) {
264
+ return [];
265
+ }
266
+ const hits = [];
267
+ for (const entry of input.entries) {
268
+ const { score, line } = scoreText(queryTokens, `${entry.description}\n${entry.body}`);
269
+ if (score > 0) {
270
+ hits.push({ kind: "memory", label: entry.name, date: entry.updated, line, score });
271
+ }
272
+ }
273
+ for (const day of input.journal ?? []) {
274
+ for (const rawLine of day.content.split("\n")) {
275
+ const line = rawLine.replace(/^[-*]\s*/, "").trim();
276
+ if (!line || line.startsWith("#")) {
277
+ continue;
278
+ }
279
+ const { score } = scoreText(queryTokens, line);
280
+ if (score > 0) {
281
+ hits.push({ kind: "journal", label: day.date, date: day.date, line, score });
282
+ }
283
+ }
284
+ }
285
+ if (input.workspaceMemory) {
286
+ for (const section of splitH2Sections(input.workspaceMemory)) {
287
+ const { score, line } = scoreText(queryTokens, section.content);
288
+ if (score > 0) {
289
+ hits.push({ kind: "workspace", label: section.heading, line, score });
290
+ }
291
+ }
292
+ }
293
+ return hits
294
+ .sort((a, b) => b.score - a.score || (b.date ?? "").localeCompare(a.date ?? ""))
295
+ .slice(0, input.limit ?? 12)
296
+ .map(({ score: _score, ...hit }) => hit);
297
+ }
@@ -1,7 +1,7 @@
1
1
  import { relative } from "node:path";
2
2
  import { parseLocalTime } from "../shared/local-time.js";
3
3
  import { clipText } from "../shared/text-utils.js";
4
- import { recencyBoostByAge, tokenizeRecallText } from "./recall.js";
4
+ import { recencyBoostByAge, tokenizeRecallText } from "./search.js";
5
5
  import { buildSessionCorpus } from "./session-corpus.js";
6
6
  import { runSidecarTask } from "./sidecar-worker.js";
7
7
  const SESSION_SEARCH_SUMMARY_SYSTEM_PROMPT = `You summarize current-channel transcript search hits for Pipiclaw.
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Spec 050, D2/D3: one memory is one Markdown file under a channel's `memory/` directory,
3
+ * with frontmatter as the single source of metadata truth. The `MEMORY.md` index is a
4
+ * generated artifact rebuilt from those files after every write — never hand-authored, never
5
+ * a second store. Files may be edited directly with any editor; the next read reflects the
6
+ * change and the index is regenerated.
7
+ */
8
+ export type MemoryType = "user" | "feedback" | "project" | "reference";
9
+ export type MemorySource = "user" | "agent" | "migrated";
10
+ /** Group order in the generated index; also the fallback ordering used by the budget tiering. */
11
+ export declare const MEMORY_TYPE_ORDER: readonly MemoryType[];
12
+ export interface MemoryEntry {
13
+ /** File name without `.md`. Authoritative even when frontmatter `name` disagrees. */
14
+ name: string;
15
+ /** One self-contained line — exactly what the index shows. */
16
+ description: string;
17
+ type: MemoryType;
18
+ source: MemorySource;
19
+ /** Local calendar dates (`YYYY-MM-DD`). */
20
+ created: string;
21
+ updated: string;
22
+ /** Present only for probationary entries (spec 050, D6); cleared on touch/update. */
23
+ expires?: string;
24
+ /** Optional long form; empty for the common one-line memory. */
25
+ body: string;
26
+ /** Frontmatter was missing or incomplete and defaults were filled in. Reported by `/memory status`. */
27
+ malformed: boolean;
28
+ }
29
+ export interface MemoryTombstoneRecord {
30
+ /** The entry name at deletion time; may be absent for records carried over from v1. */
31
+ name?: string;
32
+ contentHash: string;
33
+ deletedAt: string;
34
+ reason: string;
35
+ }
36
+ export declare function getChannelMemoryDir(channelDir: string): string;
37
+ export declare function getChannelMemoryIndexPath(channelDir: string): string;
38
+ export declare function getMemoryEntryPath(channelDir: string, name: string): string;
39
+ export declare function isValidMemoryName(name: string): boolean;
40
+ /** Slugify free text into a memory name; falls back to `m-<hash6>` when nothing usable remains. */
41
+ export declare function slugifyMemoryName(text: string): string;
42
+ /** Return a name not already taken by `existing`, appending `-2`, `-3`, … when needed. */
43
+ export declare function dedupeMemoryName(name: string, existing: Iterable<string>): string;
44
+ /** Parse one memory file. `name` (from the file name) always wins over frontmatter `name`. */
45
+ export declare function parseMemoryFile(name: string, raw: string, fallbackDate: string): MemoryEntry;
46
+ export declare function serializeMemoryEntry(entry: MemoryEntry): string;
47
+ /** Test seam: drop the parse cache so a fixture rewritten in place is re-read. */
48
+ export declare function clearMemoryStoreCache(): void;
49
+ export declare function listMemoryEntries(channelDir: string): Promise<MemoryEntry[]>;
50
+ export declare function readMemoryEntry(channelDir: string, name: string): Promise<MemoryEntry | undefined>;
51
+ export declare function renderMemoryIndex(entries: MemoryEntry[]): string;
52
+ export declare function renderIndexLine(entry: MemoryEntry): string;
53
+ export declare function rebuildMemoryIndex(channelDir: string): Promise<MemoryEntry[]>;
54
+ export declare function readMemoryTombstoneRecords(channelDir: string): Promise<MemoryTombstoneRecord[]>;
55
+ export declare function appendMemoryTombstoneRecord(channelDir: string, record: MemoryTombstoneRecord): Promise<void>;
56
+ export declare function isDescriptionTombstoned(channelDir: string, description: string): Promise<boolean>;
57
+ /**
58
+ * Mechanical store mutations. Policy — per-pass caps, confidence bars, user-source protection —
59
+ * lives in the reflect pass (spec 050, D7), never here.
60
+ */
61
+ export type MemoryStoreOp = {
62
+ op: "add";
63
+ description: string;
64
+ source: MemorySource;
65
+ name?: string;
66
+ type?: MemoryType;
67
+ details?: string;
68
+ /** A date string starts probation; omitted or `null` means permanent. */
69
+ expires?: string | null;
70
+ } | {
71
+ op: "update";
72
+ name: string;
73
+ description?: string;
74
+ type?: MemoryType;
75
+ details?: string;
76
+ /** `null` clears probation (promote); a string resets it; omitted leaves it. */
77
+ expires?: string | null;
78
+ } | {
79
+ op: "delete";
80
+ name: string;
81
+ reason?: string;
82
+ } | {
83
+ op: "touch";
84
+ names: string[];
85
+ };
86
+ export interface ApplyMemoryOpsResult {
87
+ added: string[];
88
+ updated: string[];
89
+ deleted: string[];
90
+ touched: string[];
91
+ skippedTombstone: number;
92
+ skippedSecret: number;
93
+ missingTarget: number;
94
+ renamed: Array<{
95
+ requested: string;
96
+ used: string;
97
+ }>;
98
+ }
99
+ export declare function applyMemoryOps(channelDir: string, ops: MemoryStoreOp[], options?: {
100
+ today?: string;
101
+ }): Promise<ApplyMemoryOpsResult>;
102
+ /**
103
+ * Spec 050, D6/D8: a probationary entry nobody touched before `expires` is removed —
104
+ * deterministically, before the reflect pass even runs, so a cleanup prompt never spends
105
+ * tokens on an entry about to disappear. No tombstone: probation lapsing means "not needed
106
+ * right now", not "must never be learned again" (037, D8's rationale, carried over unchanged).
107
+ */
108
+ export declare function expireProbationaryEntries(channelDir: string, today?: string): Promise<string[]>;