@agfpd/iapeer-memory 0.2.7 → 0.2.9

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.
@@ -39,6 +39,13 @@ import {
39
39
  getTaxonomy,
40
40
  isLocaleId,
41
41
  resolveAgentName,
42
+ resolveZone,
43
+ splitFrontmatter,
44
+ parseNoteTags,
45
+ parseDictionaryTags,
46
+ tagGateProblems,
47
+ tagsDictionarySourceRel,
48
+ type TaxonomyPreset,
42
49
  } from "@agfpd/iapeer-memory-core";
43
50
  import { memoryPaths, type MemoryPaths } from "../paths.js";
44
51
  import { DEFAULT_HEARTBEAT_STALE_MS } from "./verify.js";
@@ -113,15 +120,6 @@ export type PostWriteResult = {
113
120
  output: string | null;
114
121
  };
115
122
 
116
- export function reminderText(inboxFolder: string): string {
117
- return (
118
- "[iapeer-memory] New note in your agent memory. Check the guide's " +
119
- "canon-vs-memory filter: does any part of it belong to the team's shared " +
120
- `knowledge? If yes — also drop a draft into ${inboxFolder}/ and mention ` +
121
- "this note inline as [[Title]] in the draft body; the Index will link them."
122
- );
123
- }
124
-
125
123
  export function runPostWrite(
126
124
  eventJson: string,
127
125
  env: Record<string, string | undefined> = process.env,
@@ -182,26 +180,194 @@ export function runPostWrite(
182
180
  stamp: true,
183
181
  });
184
182
 
185
- // Reminder: ONLY on a claude Write (new note) in the author's OWN memory
186
- // folder an Edit-loop must not spam the context (reference semantics).
187
- // The codex branch NEVER emits: hookSpecificOutput.additionalContext is a
188
- // claude protocol codex support is unverified (upstream issue #19385
189
- // ASKS for it, which reads as «not there»; fact-checked stance, not a gap).
190
- const ownMemoryDir =
191
- path.join(vault, taxonomy.folders.agentMemory, agent) + path.sep;
192
- const output =
193
- tool === "Write" && files[0]!.startsWith(ownMemoryDir)
194
- ? JSON.stringify({
195
- hookSpecificOutput: {
196
- hookEventName: "PostToolUse",
197
- additionalContext: reminderText(taxonomy.folders.inbox),
198
- },
199
- })
200
- : null;
201
-
183
+ // TAG GATE (lean §3): validate the canon note's tags against the dictionary
184
+ // and teach the author to fix any problem (unknown tag / no tag). The guard
185
+ // stays SILENT on a clean write (§2.3) — output is non-null ONLY on a
186
+ // problem. RUNTIME-AGNOSTIC: codex supports PostToolUse `additionalContext`
187
+ // too (official codex hooks docs the earlier «claude-only» was wrong), so
188
+ // the SAME schema reaches both runtimes. `files` already covers claude
189
+ // Write/Edit and codex apply_patch (multi-file).
190
+ const problems = collectTagProblems(files, vault, taxonomy);
191
+ const output = problems.length
192
+ ? JSON.stringify({
193
+ hookSpecificOutput: {
194
+ hookEventName: "PostToolUse",
195
+ additionalContext: tagTeaching(problems),
196
+ },
197
+ })
198
+ : null;
202
199
  return { stamped: true, output };
203
200
  }
204
201
 
202
+ /**
203
+ * Tag-gate problems across the just-written CANON files (lean §3). Reads the
204
+ * dictionary from the vault; FAIL-OPEN — an unreadable/empty dictionary (e.g.
205
+ * an evicted iCloud placeholder) yields no problems rather than rejecting
206
+ * every tag. Operative/inbox zones are not gated (canon only).
207
+ */
208
+ export function collectTagProblems(
209
+ files: string[],
210
+ vault: string,
211
+ taxonomy: TaxonomyPreset,
212
+ ): string[] {
213
+ const dictRel = tagsDictionarySourceRel(taxonomy);
214
+ let allow: Set<string> | null = null;
215
+ try {
216
+ const dict = fs.readFileSync(path.join(vault, dictRel), "utf-8");
217
+ if (dict.trim()) allow = new Set(parseDictionaryTags(dict));
218
+ } catch {
219
+ // fail-open
220
+ }
221
+ if (!allow) return [];
222
+ const out: string[] = [];
223
+ for (const f of files) {
224
+ if (resolveZone(f, vault, taxonomy) !== "permanent") continue;
225
+ let fm: string;
226
+ try {
227
+ fm = splitFrontmatter(fs.readFileSync(f, "utf-8"))[0];
228
+ } catch {
229
+ continue;
230
+ }
231
+ const problems = tagGateProblems(parseNoteTags(fm), allow, {
232
+ requireAtLeastOne: true,
233
+ dictionaryRel: dictRel,
234
+ });
235
+ for (const p of problems) out.push(`${path.basename(f)}: ${p}`);
236
+ }
237
+ return out;
238
+ }
239
+
240
+ export function tagTeaching(problems: string[]): string {
241
+ return (
242
+ "[iapeer-memory] tag check — fix so this canon note indexes cleanly:\n" +
243
+ problems.map((p) => `- ${p}`).join("\n")
244
+ );
245
+ }
246
+
247
+ // ── dedup hint (lean §3a) ──────────────────────────────────────────────────────
248
+
249
+ /** Short fail-open budget for the dedup RPC — a slow/down memoryd must never
250
+ * hang a write-hook (same posture as the embedding circuit-breaker). */
251
+ export const DEDUP_TIMEOUT_MS = 1500;
252
+
253
+ type DedupResponse = {
254
+ enabled: boolean;
255
+ matches: Array<{ path: string; title: string; similarity: number }>;
256
+ };
257
+
258
+ /** POST the note body to memoryd's loopback /dedup RPC through the egress hub
259
+ * (loopback allowance — П6 topology). Fail-open: any error (timeout,
260
+ * connection refused, bad JSON) → null → the caller stays silent. */
261
+ async function dedupFetch(
262
+ egress: Egress,
263
+ env: Record<string, string | undefined>,
264
+ content: string,
265
+ ): Promise<DedupResponse | null> {
266
+ const port = env.IAPEER_MEMORY_MCP_PORT || "8766";
267
+ const thr = env.IAPEER_MEMORY_DEDUP_THRESHOLD;
268
+ const body: { content: string; threshold?: number } = { content };
269
+ if (thr && !Number.isNaN(Number(thr))) body.threshold = Number(thr);
270
+ const controller = new AbortController();
271
+ const timer = setTimeout(() => controller.abort(), DEDUP_TIMEOUT_MS);
272
+ try {
273
+ const res = await egress.fetch(`http://127.0.0.1:${port}/dedup`, {
274
+ method: "POST",
275
+ headers: { "Content-Type": "application/json" },
276
+ body: JSON.stringify(body),
277
+ signal: controller.signal,
278
+ });
279
+ if (!res.ok) return null;
280
+ return (await res.json()) as DedupResponse;
281
+ } catch {
282
+ return null; // fail-open
283
+ } finally {
284
+ clearTimeout(timer);
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Dedup hint lines for a just-written CANON note (lean §3a). Re-parses the
290
+ * event independently of `runPostWrite` (keeps that sync contract intact).
291
+ * Claude-only (Write/Edit → additionalContext); canon-zone only; queries
292
+ * memoryd by the note BODY. Embeddings-off → memoryd returns enabled:false →
293
+ * no hint (silent).
294
+ */
295
+ export async function collectDedupHints(
296
+ eventJson: string,
297
+ egress: Egress,
298
+ env: Record<string, string | undefined> = process.env,
299
+ ): Promise<string[]> {
300
+ let event: {
301
+ tool_name?: string;
302
+ cwd?: string;
303
+ tool_input?: { file_path?: string };
304
+ tool_response?: unknown;
305
+ };
306
+ try {
307
+ event = JSON.parse(eventJson) as typeof event;
308
+ } catch {
309
+ return [];
310
+ }
311
+ const tool = event.tool_name ?? "";
312
+ if (!POST_WRITE_TOOLS.has(tool)) return [];
313
+ const vault = env.IAPEER_MEMORY_VAULT_PATH ?? "";
314
+ if (!vault) return [];
315
+ const localeRaw = env.IAPEER_MEMORY_LOCALE || "en";
316
+ if (!isLocaleId(localeRaw)) return [];
317
+ const taxonomy = getTaxonomy(localeRaw);
318
+ // Candidate files: claude Write/Edit carry one file_path; codex apply_patch
319
+ // carries a patch over possibly many (RUNTIME-AGNOSTIC — codex receives the
320
+ // additionalContext hint via the same channel).
321
+ const candidates =
322
+ tool === "apply_patch" ? applyPatchPaths(event) : [event.tool_input?.file_path ?? ""];
323
+ const vaultPrefix = vault.endsWith(path.sep) ? vault : vault + path.sep;
324
+ const files = candidates.filter(
325
+ (p) => p.endsWith(".md") && p.startsWith(vaultPrefix) && fs.existsSync(p),
326
+ );
327
+ const hints: string[] = [];
328
+ for (const file of files) {
329
+ if (resolveZone(file, vault, taxonomy) !== "permanent") continue; // canon only (§3a)
330
+ let body: string;
331
+ try {
332
+ body = splitFrontmatter(fs.readFileSync(file, "utf-8"))[1];
333
+ } catch {
334
+ continue;
335
+ }
336
+ if (!body.trim()) continue;
337
+ const result = await dedupFetch(egress, env, body);
338
+ if (!result?.enabled || !result.matches?.length) continue;
339
+ for (const m of result.matches) {
340
+ if (path.basename(m.path) === path.basename(file)) continue; // self-guard (belt + braces)
341
+ hints.push(`[[${m.title}]] (${Math.round(m.similarity * 100)}%)`);
342
+ }
343
+ }
344
+ return hints;
345
+ }
346
+
347
+ /** Combine the sync tag-teaching output with async dedup hints into one
348
+ * additionalContext blob (or null when both are empty). */
349
+ export function mergeHookOutput(tagOutput: string | null, dedupHints: string[]): string | null {
350
+ let ctx = "";
351
+ if (tagOutput) {
352
+ try {
353
+ ctx = (JSON.parse(tagOutput).hookSpecificOutput?.additionalContext as string) ?? "";
354
+ } catch {
355
+ ctx = "";
356
+ }
357
+ }
358
+ if (dedupHints.length) {
359
+ const dedupText =
360
+ "[iapeer-memory] possible duplicate(s) of this canon note — verify, then extend " +
361
+ "the existing note or keep only new material:\n" +
362
+ dedupHints.map((h) => `- ${h}`).join("\n");
363
+ ctx = ctx ? `${ctx}\n\n${dedupText}` : dedupText;
364
+ }
365
+ if (!ctx) return null;
366
+ return JSON.stringify({
367
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: ctx },
368
+ });
369
+ }
370
+
205
371
  // ── session-start ────────────────────────────────────────────────────────────
206
372
 
207
373
  export type SessionStartResult = {
@@ -298,8 +464,11 @@ export async function cmdHook(argv: string[], egress: Egress): Promise<number> {
298
464
  try {
299
465
  switch (event) {
300
466
  case "post-write": {
301
- const result = runPostWrite(await Bun.stdin.text());
302
- if (result.output) console.log(result.output);
467
+ const text = await Bun.stdin.text();
468
+ const result = runPostWrite(text); // sync: stamp + tag gate
469
+ const dedupHints = await collectDedupHints(text, egress); // async, fail-open §3a
470
+ const output = mergeHookOutput(result.output, dedupHints);
471
+ if (output) console.log(output);
303
472
  return 0;
304
473
  }
305
474
  case "session-start": {
@@ -51,11 +51,13 @@ import {
51
51
  } from "../templates/index.js";
52
52
  import { packageVersion } from "../version.js";
53
53
  import {
54
+ DREAM_TARGET,
54
55
  dreamTimerMessage,
55
56
  patchWakePolicyEphemeral,
56
57
  registerTimer,
57
58
  registerWatcher,
58
59
  sweepTimerMessage,
60
+ writeDreamGateScript,
59
61
  writeLauncherScript,
60
62
  writeStaleCheckScript,
61
63
  } from "../watcher.js";
@@ -402,8 +404,15 @@ export async function cmdInit(argv: string[], egress: Egress): Promise<number> {
402
404
  message: sweepTimerMessage({ checkScriptPath: paths.checkScriptPath }),
403
405
  iapeerBin: flags.iapeerBin,
404
406
  });
407
+ writeDreamGateScript({
408
+ dreamGateScriptPath: paths.dreamGateScriptPath,
409
+ binaryPath: paths.binaryPath,
410
+ });
405
411
  const dream = registerTimer(egress, {
406
- message: dreamTimerMessage(),
412
+ message: dreamTimerMessage({
413
+ cron: process.env.IAPEER_MEMORY_DREAM_CRON,
414
+ dreamGateScriptPath: paths.dreamGateScriptPath,
415
+ }),
407
416
  iapeerBin: flags.iapeerBin,
408
417
  });
409
418
  const timersSandboxed = sweep.suppressed && dream.suppressed;
@@ -412,7 +421,7 @@ export async function cmdInit(argv: string[], egress: Egress): Promise<number> {
412
421
  timersSandboxed
413
422
  ? "skipped (test sandbox — sends suppressed)"
414
423
  : sweep.ok && dream.ok
415
- ? `sweep (@every 1h, check ${paths.checkScriptPath}) + dream-tick (weekly)target index`
424
+ ? `sweep (@every 1h, check ${paths.checkScriptPath}) + dream-tick (weekly, gated, ${DREAM_TARGET})`
416
425
  : `sweep: ${sweep.ok ? "sent" : sweep.detail}; dream: ${dream.ok ? "sent" : dream.detail}`,
417
426
  Boolean(timersSandboxed) || (sweep.ok && dream.ok),
418
427
  );
@@ -125,7 +125,10 @@ function renderFragment(argv: string[]): number {
125
125
  logs: paths.logsDir,
126
126
  },
127
127
  authorIndexPath: indexFile,
128
- tagsDictionaryPath: agent === indexAgent ? paths.tagsMirrorPath : undefined,
128
+ // lean §3: the compact projection goes to EVERY peer (memoryd renders the
129
+ // projection file; a missing file is skipped gracefully by buildLayers).
130
+ tagsProjectionPath: paths.tagsProjectionPath,
131
+ tagsTitle: config.taxonomy.systemFiles.tagsDictionary,
129
132
  };
130
133
  const written = renderPeerFragment({ peerCwd, env });
131
134
  console.log(`render fragment: ${written}`);
@@ -51,10 +51,12 @@ import { mcpPort } from "./provision-peer.js";
51
51
  import { guideText, materialiseTemplates } from "../templates/index.js";
52
52
  import { packageVersion } from "../version.js";
53
53
  import {
54
+ DREAM_TARGET,
54
55
  dreamTimerMessage,
55
56
  registerTimer,
56
57
  registerWatcher,
57
58
  sweepTimerMessage,
59
+ writeDreamGateScript,
58
60
  writeLauncherScript,
59
61
  writeStaleCheckScript,
60
62
  } from "../watcher.js";
@@ -245,18 +247,27 @@ export function cmdUpdate(argv: string[], egress: Egress): number {
245
247
  } catch {
246
248
  // unprovisioned env — registrations below still re-target
247
249
  }
250
+ writeDreamGateScript({
251
+ dreamGateScriptPath: paths.dreamGateScriptPath,
252
+ binaryPath: paths.binaryPath,
253
+ });
248
254
  const w = registerWatcher(egress, { launcherPath: paths.launcherPath });
249
255
  const s = registerTimer(egress, {
250
256
  message: sweepTimerMessage({ checkScriptPath: paths.checkScriptPath }),
251
257
  });
252
- const d = registerTimer(egress, { message: dreamTimerMessage() });
258
+ const d = registerTimer(egress, {
259
+ message: dreamTimerMessage({
260
+ cron: process.env.IAPEER_MEMORY_DREAM_CRON,
261
+ dreamGateScriptPath: paths.dreamGateScriptPath,
262
+ }),
263
+ });
253
264
  const sandboxed = w.suppressed && s.suppressed && d.suppressed;
254
265
  step(
255
266
  "triggers",
256
267
  sandboxed
257
268
  ? "skipped (test sandbox — sends suppressed)"
258
269
  : w.ok && s.ok && d.ok
259
- ? `re-sent: event→scriber, sweep+dream→index (same id = replace); confirm: verify`
270
+ ? `re-sent: event→scriber, sweep→index, dream→${DREAM_TARGET} (gated; same id = replace); confirm: verify`
260
271
  : `event: ${w.ok ? "sent" : w.detail}; sweep: ${s.ok ? "sent" : s.detail}; dream: ${d.ok ? "sent" : d.detail}`,
261
272
  Boolean(sandboxed) || (w.ok && s.ok && d.ok),
262
273
  );
@@ -35,6 +35,7 @@ import { checkFleetSurfaces, sweepProvision } from "../surfaces/sweep.js";
35
35
  import { mcpPort } from "./provision-peer.js";
36
36
  import { packageVersion } from "../version.js";
37
37
  import {
38
+ DREAM_TARGET,
38
39
  dreamTimerMessage,
39
40
  DEFAULT_EVENT_TARGET,
40
41
  DREAM_TRIGGER_ID,
@@ -43,6 +44,7 @@ import {
43
44
  registerWatcher,
44
45
  sweepTimerMessage,
45
46
  SWEEP_TRIGGER_ID,
47
+ writeDreamGateScript,
46
48
  writeLauncherScript,
47
49
  writeStaleCheckScript,
48
50
  WATCHER_TRIGGER_ID,
@@ -385,9 +387,24 @@ export function runVerify(egress: Egress, opts: VerifyOptions = {}): CheckResult
385
387
  id: DREAM_TRIGGER_ID,
386
388
  role: "time",
387
389
  expect: (t) =>
388
- t.target !== "index" ? `target is ${t.target ?? "?"}, expected index` : null,
389
- repairSend: () =>
390
- registerTimer(egress, { message: dreamTimerMessage(), iapeerBin: opts.iapeerBin }),
390
+ t.target !== DREAM_TARGET
391
+ ? `target is ${t.target ?? "?"}, expected ${DREAM_TARGET}`
392
+ : (t as { check?: string }).check !== paths.dreamGateScriptPath
393
+ ? `check is ${(t as { check?: string }).check ?? "?"}, expected ${paths.dreamGateScriptPath}`
394
+ : null,
395
+ repairSend: () => {
396
+ writeDreamGateScript({
397
+ dreamGateScriptPath: paths.dreamGateScriptPath,
398
+ binaryPath: paths.binaryPath,
399
+ });
400
+ return registerTimer(egress, {
401
+ message: dreamTimerMessage({
402
+ cron: process.env.IAPEER_MEMORY_DREAM_CRON,
403
+ dreamGateScriptPath: paths.dreamGateScriptPath,
404
+ }),
405
+ iapeerBin: opts.iapeerBin,
406
+ });
407
+ },
391
408
  },
392
409
  ];
393
410
  for (const c of checks) {
package/src/fleet.ts CHANGED
@@ -80,7 +80,7 @@ export function readFleetMap(fleetMapPath: string): FleetPeer[] | null {
80
80
  }
81
81
 
82
82
  /** Live-registry query — the ONE place `iapeer list --json` is parsed.
83
- * Shared by writeFleetMap (the persisted map) and dream-paths (the
83
+ * Shared by writeFleetMap (the persisted map) and dream-collect (the
84
84
  * tick-time resolution; freshness fact: birth does NOT touch fleet.json
85
85
  * and the SessionStart kick is heartbeat-gated, so the LIVE registry is
86
86
  * the only source that sees a newborn before the next update). */
package/src/paths.ts CHANGED
@@ -32,6 +32,8 @@ export type MemoryPaths = {
32
32
  heartbeatPath: string;
33
33
  hashStatePath: string;
34
34
  tagsMirrorPath: string;
35
+ /** Compact tags-dictionary projection, injected to all peers (lean §3). */
36
+ tagsProjectionPath: string;
35
37
  /** Roles manifest (written by init, read by verify/render): role → peerCwd/template. */
36
38
  rolesManifestPath: string;
37
39
  /** Rendered author indexes (`<agent>-vault-index.md` + `-full` variant). */
@@ -56,6 +58,9 @@ export type MemoryPaths = {
56
58
  launcherPath: string;
57
59
  /** Sweep check-script — gates the fail-open inbox sweep (ADR-015). */
58
60
  checkScriptPath: string;
61
+ /** Dream-tick gate check-script — the notifier `check` for the weekly timer
62
+ * (shells the registry-free `dream-collect --gate`; a dead week wakes no one). */
63
+ dreamGateScriptPath: string;
59
64
  /** Fleet map (personality → cwd) — written by init/update/verify --repair
60
65
  * from `iapeer list --json`, consumed by memoryd's fragment renderer
61
66
  * (docs/05; дыра 10.06: без карты пиры не получали paths-блок и индекс). */
@@ -89,6 +94,7 @@ export function memoryPaths(
89
94
  heartbeatPath: path.join(stateDir, "memoryd.heartbeat"),
90
95
  hashStatePath: path.join(stateDir, "memoryd.hashes.json"),
91
96
  tagsMirrorPath: path.join(cacheDir, "tags-dictionary.md"),
97
+ tagsProjectionPath: path.join(cacheDir, "tags-projection.md"),
92
98
  rolesManifestPath: path.join(stateDir, "roles.json"),
93
99
  indexesDir: path.join(stateDir, "indexes"),
94
100
  pidPath: path.join(stateDir, "memoryd.pid"),
@@ -99,6 +105,7 @@ export function memoryPaths(
99
105
  hooksDir: path.join(path.dirname(configFile), "hooks"),
100
106
  launcherPath: path.join(path.dirname(configFile), "memoryd-launcher.sh"),
101
107
  checkScriptPath: path.join(path.dirname(configFile), "inbox-stale-check.sh"),
108
+ dreamGateScriptPath: path.join(path.dirname(configFile), "dream-tick-gate.sh"),
102
109
  fleetMapPath: path.join(stateDir, "fleet.json"),
103
110
  };
104
111
  }
package/src/provision.ts CHANGED
@@ -176,6 +176,29 @@ export function defaultConfigContent(opts: ConfigContentOptions): string {
176
176
  "# Curator personalities exempt from needs_review stamping (ADR-006).",
177
177
  "# IAPEER_MEMORY_CURATOR_SET=index,scriber,dreamweaver",
178
178
  "",
179
+ "# Lean §3: per-tag boundary budget in the injected dictionary projection",
180
+ "# (×whole fleet — keep tight). Boundary text over this many chars is clipped.",
181
+ "# IAPEER_MEMORY_TAGS_BOUNDARY_MAXLEN=160",
182
+ "",
183
+ "# Lean §3a: dedup hint on canon writes — raw cosine similarity threshold",
184
+ "# above which an existing canon note is surfaced as a possible duplicate.",
185
+ "# Needs embeddings (semantic); with embeddings off the hint is silent.",
186
+ "# IAPEER_MEMORY_DEDUP_THRESHOLD=0.82",
187
+ "",
188
+ "# Weekly dream-tick (deterministic pre-filter → DreamWeaver). Schedule is",
189
+ "# 5-field cron; the window is days BY TIME (not since-last-tick).",
190
+ "# IAPEER_MEMORY_DREAM_CRON=0 4 * * 1",
191
+ "# IAPEER_MEMORY_DREAM_WINDOW_DAYS=7",
192
+ "# description longer than this many chars → a reformulation candidate.",
193
+ "# IAPEER_MEMORY_DREAM_DESC_MAXLEN=250",
194
+ "# >threshold new notes in a folder → its own subagent; smaller folders are",
195
+ "# grouped up to the cap (sum of per-folder weights).",
196
+ "# IAPEER_MEMORY_DREAM_BATCH_THRESHOLD=20",
197
+ "# IAPEER_MEMORY_DREAM_GROUP_CAP=20",
198
+ "# Per-folder cap on transcripts handed to phase D (most recent N by mtime;",
199
+ "# bounds an ephemeral worker's hundreds of sessions). 0 = uncapped.",
200
+ "# IAPEER_MEMORY_DREAM_TRANSCRIPT_CAP=20",
201
+ "",
179
202
  ].join("\n");
180
203
  }
181
204
 
@@ -51,17 +51,12 @@ different world.
51
51
  scriber thread stalled: place the stale drafts UNVETTED by the usual
52
52
  rules; \`needs_review: true\` already travels with each file. The
53
53
  Scriber re-vets them with the next PERMANENT_BATCH once alive.
54
- - **DREAM_TICK** (notifier timer, weekly) — run \`iapeer-memory
55
- dream-paths\` (read-only; the LIVE registry at tick time) and fan out
56
- DreamWeaver over the folders of its output (including your own),
57
- strictly one folder per task, sequentially. DreamWeaver takes tasks ONLY
58
- from you (the one exception: a folder's owner may task it on their own
59
- folder). Task: \`{agent, path, mode, transcripts_window_days,
60
- transcripts}\` — copy \`transcripts\` from the verb's output AS IS
61
- (globs + the codex cwdFilter; path forms are the code's zone, not
62
- yours). A verb error = report to the owner, never guess the fleet. On
63
- the consolidation report: archive what it deprecated, act on its
64
- \`attention\` blocks yourself.
54
+ - **DreamWeaver consolidation report** (weekly) — DreamWeaver now
55
+ orchestrates the tick (a deterministic pre-filter finds the work, it
56
+ fans out subagents); you are OFF the entry and only FINALISE. On its
57
+ report: archive each note it deprecated (move to the archive subfolder),
58
+ build the links section for each new merged note via vault_search, and
59
+ act on its \`attention\` items yourself.
65
60
  - **Direct IAP** from agents or the human — structure questions; never
66
61
  run searches for others (they have their own vault tools).
67
62
 
@@ -114,8 +109,8 @@ it under the usual three conditions.
114
109
  Never write note content (authors own it); never answer other agents'
115
110
  search requests; never dispatch the Scriber (events reach it directly —
116
111
  it reports to you); never detect events yourself (memoryd detects, the
117
- notifier delivers); never let DreamWeaver take tasks from anyone but you
118
- (save the owner-on-own-folder exception).
112
+ notifier delivers); never orchestrate the dream-tick (DreamWeaver owns it
113
+ end to end now — you only finalise on its report).
119
114
  `;
120
115
 
121
116
  export const SCRIBER_DOCTRINE_EN = `---
@@ -233,47 +228,78 @@ locale: en
233
228
  ---
234
229
  # DreamWeaver — sleep-cycle memory consolidation
235
230
 
236
- You are DreamWeaver: an ephemeral worker peer, the weekly hygiene
237
- instrument for agent memory. Vault root on this host: \`{{VAULT_PATH}}\`
238
- (never guess it). Tasks arrive as IAP messages: weekly fan-out
239
- from the Index (one task per subfolder, including the Index's own), or
240
- on-demand from a folder's OWNER for their own folder only. One task = one
241
- clean window = ONE outbound message (the final consolidation report to the
242
- task sender). Discipline: touch ONLY the folder named in the task.
243
-
244
- Task: \`{agent, path, mode, transcripts_window_days, transcripts}\`.
245
-
246
- ## The four phases
247
-
248
- - **A Dedup.** Read the folder's notes; group the ones about one topic
249
- (LLM judgement). For each group of 2+: write ONE merging note (meaningful
250
- filename in the vault language, \`subtype\` + \`description\` + body with
251
- inline \`[[old note A]]\`, \`[[old note B]]\` mentions) and flip each old
252
- note's \`status\` to the outdated token.
253
- - **B Compress descriptions.** \`description\` longer than ~250 chars
254
- tighten to 1–2 sentences (~150 chars). Never touch the body in this
255
- phase.
256
- - **C Local fact verification.** Find file paths and env-variable
257
- mentions in bodies; read the targets; on a clear mismatch (file gone,
258
- function renamed) write an updated note and flip the old one to the
259
- outdated token. LOCAL checks only.
260
- - **D Transcript scan.** Read the session transcripts for the window
261
- (\`transcripts_window_days\`) per the task's \`transcripts\`: each entry
262
- is a glob; for \`runtime: codex\` the store is HOST-WIDE take ONLY the
263
- sessions whose \`session_meta.cwd\` equals the entry's \`cwdFilter\`
264
- (foreign cwds are foreign memory). No entries / empty glob skip the
265
- phase. Find user phrases that formulate a rule with 2+ explicit
266
- confirmations in different sessions; check against existing feedback
267
- notes; write new notes with quotes for what's missing.
268
-
269
- ## Hard limits
270
-
271
- - No hard deletes only the outdated status token; archiving and links
272
- are the Index's pass (it acts on your report), not yours.
273
- - Never touch canon folders; no vault MCP tools; no web fact-checking
274
- (that's the distill skill's domain, not yours).
275
- - Your edits are stamped \`last_edited_by: dreamweaver\`; the \`author\`
276
- constant is parsed from the subfolder path, so writing into a foreign
277
- subfolder ON TASK keeps the owner's attribution intact that is by
278
- design.
231
+ You are DreamWeaver: an ephemeral worker peer that ORCHESTRATES the weekly
232
+ agent-memory hygiene tick. Vault root on this host: \`{{VAULT_PATH}}\`
233
+ (never guess it a stale copy elsewhere on disk is a different world). A
234
+ deterministic pre-filter has already found the work; you turn its output
235
+ into subagent tasks, then report once. The notifier delivers DREAM_TICK to
236
+ you, weekly, only on a week that has work (a gate skips dead weeks)
237
+ nobody else tasks you.
238
+
239
+ ## Running the tick
240
+
241
+ 1. Run \`iapeer-memory dream-collect\` (Bash, read-only). It returns JSON:
242
+ \`{vault, windowDays, tasks[], skipped[]}\`. Each task is
243
+ \`{kind, folders[]}\`; each folder carries \`{agent, path,
244
+ newNotes:[{path, flags}], transcripts:[{runtime, files}]}\`. A
245
+ \`folder\` task is one busy folder for one subagent; a \`grouped\` task
246
+ is several small folders for one subagent. The pre-filter already
247
+ dropped inactive folders, so you spawn ONLY where there is real work.
248
+ 2. A verb error line = report it to the human owner and stop; never guess
249
+ the fleet. Empty \`tasks\` = a clean week finish with \`iapeer
250
+ self-done\` (the non-waking finish), no report.
251
+ 3. Fan out one subagent per task, using your runtime's own subagent
252
+ mechanism (whatever it is called there). Run tasks concurrently when
253
+ your runtime allows, otherwise in sequence.
254
+ 4. Collect the subagents' results into ONE consolidation report to the
255
+ Index: the notes they deprecated (for archival), the new merged notes
256
+ (for linking), and any attention items. The Index finalises — archival
257
+ and the links section are its pass, not yours.
258
+
259
+ Your window is one clean cycle = ONE outbound message (the report to the
260
+ Index, or \`self-done\` on an empty week).
261
+
262
+ ## The subagent's task
263
+
264
+ Each subagent sees ONLY the task you write — make it self-sufficient. Copy,
265
+ verbatim from the verb's output, the folder path(s), the \`newNotes\` with
266
+ their flags, the \`transcripts\` files, and the vault root. State the
267
+ objective, the four judgement phases, the boundaries, and the report shape
268
+ below. The subagent JUDGES the supplied material; it never re-discovers
269
+ (the script already did the finding, so a subagent that re-scans the folder
270
+ wastes the whole point).
271
+
272
+ - **A Dedup.** Group the supplied \`newNotes\` that cover one topic. Read
273
+ sibling notes in the folder for CONTEXT — including ones outside the
274
+ window — so a fresh note merges with an older twin; edit ONLY in-window
275
+ notes (the rest are already settled). For each group of 2+: write one
276
+ merging note (meaningful filename in the vault language, \`subtype\` +
277
+ \`description\` + body with inline \`[[old note]]\` mentions) and flip
278
+ each merged note's \`status\` to the outdated token.
279
+ - **B — Compress descriptions.** For a note flagged \`long-desc\`: tighten
280
+ \`description\` to 1–2 sentences (~150 chars), leaving the body untouched.
281
+ - **C — Verify flagged references.** For a note flagged \`broken-ref\`: the
282
+ script already located the suspect path/env mention — read the target,
283
+ and on a clear mismatch (file gone, var unset, function renamed) write an
284
+ updated note and flip the old one to outdated. Local checks only.
285
+ - **D — Extract rules from transcripts.** Read the supplied
286
+ \`transcripts.files\` (concrete paths — no globbing). Find user phrases
287
+ that state a rule with 2+ explicit confirmations across sessions; check
288
+ against existing feedback notes; write what is missing, with quotes. No
289
+ files → skip the phase.
290
+
291
+ Boundaries for every subagent: touch only the folder(s) named in the task,
292
+ and only in-window notes; stay out of canon folders; no hard deletes (only
293
+ the outdated status token, because archiving and links are the Index's
294
+ pass); no vault MCP tools and no web fact-checking (that is the distill
295
+ skill's domain). Edits are stamped \`last_edited_by: dreamweaver\` and the
296
+ \`author\` constant is parsed from the subfolder path, so writing into an
297
+ owner's folder ON TASK keeps their attribution intact — by design.
298
+
299
+ ## What you never do
300
+
301
+ You never discover work yourself (the pre-filter does) and never write a
302
+ note's substance (its author owns that). You act through subagents and
303
+ report to the Index; you do not archive or set links — that is the Index's
304
+ finalising pass.
279
305
  `;