agent-recall-core 3.4.46 → 3.4.48

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 (102) hide show
  1. package/dist/helpers/handoff.d.ts.map +1 -1
  2. package/dist/helpers/handoff.js +17 -9
  3. package/dist/helpers/handoff.js.map +1 -1
  4. package/dist/helpers/journal-files.d.ts +24 -1
  5. package/dist/helpers/journal-files.d.ts.map +1 -1
  6. package/dist/helpers/journal-files.js +29 -10
  7. package/dist/helpers/journal-files.js.map +1 -1
  8. package/dist/helpers/journal-filter.d.ts +25 -0
  9. package/dist/helpers/journal-filter.d.ts.map +1 -1
  10. package/dist/helpers/journal-filter.js +12 -1
  11. package/dist/helpers/journal-filter.js.map +1 -1
  12. package/dist/index.d.ts +18 -9
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +45 -6
  15. package/dist/index.js.map +1 -1
  16. package/dist/retrieval/candidates.d.ts +339 -0
  17. package/dist/retrieval/candidates.d.ts.map +1 -0
  18. package/dist/retrieval/candidates.js +473 -0
  19. package/dist/retrieval/candidates.js.map +1 -0
  20. package/dist/retrieval/contradiction.d.ts +284 -0
  21. package/dist/retrieval/contradiction.d.ts.map +1 -0
  22. package/dist/retrieval/contradiction.js +343 -0
  23. package/dist/retrieval/contradiction.js.map +1 -0
  24. package/dist/retrieval/query-memory.d.ts +464 -0
  25. package/dist/retrieval/query-memory.d.ts.map +1 -0
  26. package/dist/retrieval/query-memory.js +1189 -0
  27. package/dist/retrieval/query-memory.js.map +1 -0
  28. package/dist/retrieval/scope.d.ts +75 -0
  29. package/dist/retrieval/scope.d.ts.map +1 -0
  30. package/dist/retrieval/scope.js +91 -0
  31. package/dist/retrieval/scope.js.map +1 -0
  32. package/dist/storage/corrections.d.ts +163 -2
  33. package/dist/storage/corrections.d.ts.map +1 -1
  34. package/dist/storage/corrections.js +147 -3
  35. package/dist/storage/corrections.js.map +1 -1
  36. package/dist/storage/lifecycle-telemetry.d.ts +20 -5
  37. package/dist/storage/lifecycle-telemetry.d.ts.map +1 -1
  38. package/dist/storage/lifecycle-telemetry.js +16 -5
  39. package/dist/storage/lifecycle-telemetry.js.map +1 -1
  40. package/dist/storage/session.d.ts +28 -1
  41. package/dist/storage/session.d.ts.map +1 -1
  42. package/dist/storage/session.js +41 -8
  43. package/dist/storage/session.js.map +1 -1
  44. package/dist/supabase/recall-backend.d.ts +26 -2
  45. package/dist/supabase/recall-backend.d.ts.map +1 -1
  46. package/dist/supabase/recall-backend.js +233 -27
  47. package/dist/supabase/recall-backend.js.map +1 -1
  48. package/dist/supabase/sync.d.ts +41 -0
  49. package/dist/supabase/sync.d.ts.map +1 -1
  50. package/dist/supabase/sync.js +46 -0
  51. package/dist/supabase/sync.js.map +1 -1
  52. package/dist/tools-logic/check.d.ts.map +1 -1
  53. package/dist/tools-logic/check.js +62 -36
  54. package/dist/tools-logic/check.js.map +1 -1
  55. package/dist/tools-logic/drill-down.d.ts +24 -0
  56. package/dist/tools-logic/drill-down.d.ts.map +1 -1
  57. package/dist/tools-logic/drill-down.js +36 -0
  58. package/dist/tools-logic/drill-down.js.map +1 -1
  59. package/dist/tools-logic/journal-cold-start.d.ts.map +1 -1
  60. package/dist/tools-logic/journal-cold-start.js +48 -9
  61. package/dist/tools-logic/journal-cold-start.js.map +1 -1
  62. package/dist/tools-logic/journal-list.d.ts +42 -0
  63. package/dist/tools-logic/journal-list.d.ts.map +1 -1
  64. package/dist/tools-logic/journal-list.js +60 -10
  65. package/dist/tools-logic/journal-list.js.map +1 -1
  66. package/dist/tools-logic/journal-read.d.ts.map +1 -1
  67. package/dist/tools-logic/journal-read.js +22 -13
  68. package/dist/tools-logic/journal-read.js.map +1 -1
  69. package/dist/tools-logic/journal-search.d.ts +58 -0
  70. package/dist/tools-logic/journal-search.d.ts.map +1 -1
  71. package/dist/tools-logic/journal-search.js +123 -92
  72. package/dist/tools-logic/journal-search.js.map +1 -1
  73. package/dist/tools-logic/palace-search.d.ts.map +1 -1
  74. package/dist/tools-logic/palace-search.js +30 -11
  75. package/dist/tools-logic/palace-search.js.map +1 -1
  76. package/dist/tools-logic/palace-walk.d.ts +10 -0
  77. package/dist/tools-logic/palace-walk.d.ts.map +1 -1
  78. package/dist/tools-logic/palace-walk.js +25 -16
  79. package/dist/tools-logic/palace-walk.js.map +1 -1
  80. package/dist/tools-logic/recall-insight.d.ts +20 -0
  81. package/dist/tools-logic/recall-insight.d.ts.map +1 -1
  82. package/dist/tools-logic/recall-insight.js +12 -1
  83. package/dist/tools-logic/recall-insight.js.map +1 -1
  84. package/dist/tools-logic/session-end.d.ts.map +1 -1
  85. package/dist/tools-logic/session-end.js +23 -7
  86. package/dist/tools-logic/session-end.js.map +1 -1
  87. package/dist/tools-logic/session-start.d.ts +85 -0
  88. package/dist/tools-logic/session-start.d.ts.map +1 -1
  89. package/dist/tools-logic/session-start.js +245 -108
  90. package/dist/tools-logic/session-start.js.map +1 -1
  91. package/dist/tools-logic/smart-recall.d.ts +87 -62
  92. package/dist/tools-logic/smart-recall.d.ts.map +1 -1
  93. package/dist/tools-logic/smart-recall.js +183 -508
  94. package/dist/tools-logic/smart-recall.js.map +1 -1
  95. package/dist/tools-logic/supersession.d.ts +63 -2
  96. package/dist/tools-logic/supersession.d.ts.map +1 -1
  97. package/dist/tools-logic/supersession.js +153 -48
  98. package/dist/tools-logic/supersession.js.map +1 -1
  99. package/dist/types.d.ts +12 -1
  100. package/dist/types.d.ts.map +1 -1
  101. package/dist/types.js +1 -1
  102. package/package.json +1 -1
@@ -1,18 +1,68 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
1
  import { resolveProject } from "../storage/project.js";
4
- import { listJournalFiles, extractTitle, extractMomentum } from "../helpers/journal-files.js";
2
+ import { extractTitle, extractMomentum } from "../helpers/journal-files.js";
3
+ import { listCandidateStubs } from "../retrieval/candidates.js";
4
+ /** Title shown for a quarantined (rescue-sourced) entry — never the real, attacker-influenced title/momentum. */
5
+ export const QUARANTINE_TITLE = "[quarantined — rescue-sourced entry]";
6
+ /**
7
+ * Identity-trust (P0 trust-class closure, 2026-08-30, wave/pipe-p0-trustclass;
8
+ * REVISED by the independent-review FIX 1 pass, same date):
9
+ *
10
+ * ORIGINAL fix (this wave's first pass) routed through `readTierCandidates`,
11
+ * which DROPS the whole rescue-tagged row before returning. Independent
12
+ * review flagged this as an over-reach: `candidate.date` here is the
13
+ * journal-live tier's FILENAME date, itself derived from `listJournalFiles`'s
14
+ * own `dateMatch` guard at rescue-write time — i.e. system-clock-derived at
15
+ * the moment `distillOneSession` wrote the card
16
+ * (`storage/working-memory.ts`'s `writeSessionCard` call), NOT a value an
17
+ * attacker's prompt content can influence. Only `title`/`momentum` (parsed
18
+ * from the file's raw BODY) are the actual injection vector. Dropping the
19
+ * whole row therefore hid the entry's EXISTENCE for no security reason —
20
+ * and because `limit` was applied AFTER the drop, `journal_list(limit=N)`
21
+ * silently backfilled the quota from further back in time, misrepresenting
22
+ * recency/continuity with no signal to the caller that anything was hidden.
23
+ *
24
+ * THE FIX: use `listCandidateStubs` (packages/core/src/retrieval/
25
+ * candidates.ts) instead of `readTierCandidates` — it preserves EVERY
26
+ * candidate's existence (date/file) but strips `content` for any row whose
27
+ * underlying candidate is untrusted. A quarantined row here renders with
28
+ * `QUARANTINE_TITLE` and an empty momentum, AT its real date, in its real
29
+ * chronological position — never dropped, never given a fabricated
30
+ * title/momentum. `limit` is applied to the FULL rendered list (quarantined
31
+ * rows included, in position), so the window never silently backfills past
32
+ * a hidden entry.
33
+ *
34
+ * Error-path note (Worker Done-Definition #1): a journal-live-tier candidate's
35
+ * `date` can never be malformed/unparseable here — `listJournalFiles` (the
36
+ * live-tier reader `listCandidateStubs("journal", ...)` delegates to)
37
+ * requires a leading `^\d{4}-\d{2}-\d{2}` filename match before a file is
38
+ * even considered a candidate at all (see helpers/journal-files.ts), so
39
+ * every candidate this function ever sees already carries a well-formed
40
+ * date string by construction — no additional validation/fallback is needed
41
+ * here for that path. (journalList never opts into rollup/raw-archive
42
+ * candidates, whose date semantics differ — see candidates.ts's own header —
43
+ * so this guarantee is not weakened by a future opt-in without a
44
+ * corresponding review of this comment.)
45
+ */
5
46
  export async function journalList(input) {
6
47
  const slug = await resolveProject(input.project);
7
- let entries = listJournalFiles(slug);
48
+ const stubs = listCandidateStubs("journal", slug);
8
49
  const limit = input.limit ?? 10;
9
- if (limit > 0) {
10
- entries = entries.slice(0, limit);
11
- }
12
- const result = entries.map((e) => {
13
- const content = fs.readFileSync(path.join(e.dir, e.file), "utf-8");
14
- return { date: e.date, title: extractTitle(content), momentum: extractMomentum(content) };
50
+ const entries = stubs.map((s) => {
51
+ if (!s.trusted) {
52
+ return { date: s.date, title: QUARANTINE_TITLE, momentum: "" };
53
+ }
54
+ const content = s.content ?? "";
55
+ return {
56
+ date: s.date,
57
+ title: extractTitle(content),
58
+ momentum: extractMomentum(content),
59
+ };
15
60
  });
61
+ // Slice the FULL rendered list (quarantined rows included, in their real
62
+ // chronological position) — never slice the raw candidate/stub array
63
+ // before rendering. This is what closes the "silent backfill" bug: the
64
+ // limit window's boundary is decided over the SAME set a caller sees.
65
+ const result = limit > 0 ? entries.slice(0, limit) : entries;
16
66
  return { project: slug, entries: result };
17
67
  }
18
68
  //# sourceMappingURL=journal-list.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"journal-list.js","sourceRoot":"","sources":["../../src/tools-logic/journal-list.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAY9F,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,KAAuB;IACvD,MAAM,IAAI,GAAG,MAAM,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjD,IAAI,OA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CAAC;CAChB;AAED,wBAAsB,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAuCrF"}
1
+ {"version":3,"file":"journal-read.d.ts","sourceRoot":"","sources":["../../src/tools-logic/journal-read.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wBAAsB,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAgDrF"}
@@ -1,34 +1,43 @@
1
1
  import * as fs from "node:fs";
2
- import * as path from "node:path";
3
2
  import { resolveProject } from "../storage/project.js";
4
- import { listJournalFiles, readJournalFile } from "../helpers/journal-files.js";
3
+ import { readJournalFile } from "../helpers/journal-files.js";
5
4
  import { extractSection } from "../helpers/sections.js";
5
+ import { readTierCandidates } from "../retrieval/candidates.js";
6
6
  export async function journalRead(input) {
7
7
  const slug = await resolveProject(input.project);
8
8
  let targetDate = input.date ?? "latest";
9
9
  if (targetDate === "latest") {
10
- const allEntries = listJournalFiles(slug, true);
11
- if (allEntries.length === 0) {
10
+ // Identity-trust (P0 trust-class closure, 2026-08-30, wave/pipe-p0-trustclass,
11
+ // gap #1): was a hand-rolled listJournalFiles()+mtime scan with its OWN
12
+ // raw fs.readFileSync, bypassing readJournalFile's choke entirely — a
13
+ // rescue-tagged card could win "latest" and surface unfiltered. Routed
14
+ // through readTierCandidates (already trust-tagged + safe-by-default:
15
+ // drops untrusted candidates before returning), matching includeRollupArchive
16
+ // to the original's `listJournalFiles(slug, true)` includeArchive=true scope.
17
+ const candidates = readTierCandidates("journal", slug, { includeRollupArchive: true });
18
+ if (candidates.length === 0) {
12
19
  return { content: "", date: "", project: slug, error: `No journal entries found for project '${slug}'` };
13
20
  }
14
- // Among files with the most recent date, pick the file with the highest mtime
15
- const latestDate = allEntries[0].date;
16
- const recentEntries = allEntries.filter(e => e.date === latestDate);
17
- let bestEntry = recentEntries[0];
21
+ // Among candidates with the most recent date, pick the one with the
22
+ // highest mtime (candidates are NOT guaranteed globally date-sorted:
23
+ // the live half and the rollup-archive half are each sorted
24
+ // independently, then concatenated — see candidates.ts's own header).
25
+ const latestDate = candidates.reduce((max, c) => (c.date > max ? c.date : max), candidates[0].date);
26
+ const recentCandidates = candidates.filter(c => c.date === latestDate);
27
+ let bestCandidate = recentCandidates[0];
18
28
  let bestMtime = 0;
19
- for (const entry of recentEntries) {
29
+ for (const cand of recentCandidates) {
20
30
  try {
21
- const stat = fs.statSync(path.join(entry.dir, entry.file));
31
+ const stat = fs.statSync(cand.sourcePath);
22
32
  if (stat.mtimeMs > bestMtime) {
23
33
  bestMtime = stat.mtimeMs;
24
- bestEntry = entry;
34
+ bestCandidate = cand;
25
35
  }
26
36
  }
27
37
  catch { /* skip unreadable files */ }
28
38
  }
29
- const raw = fs.readFileSync(path.join(bestEntry.dir, bestEntry.file), "utf-8");
30
39
  const section = input.section ?? "all";
31
- const extracted = extractSection(raw, section) || "";
40
+ const extracted = extractSection(bestCandidate.content, section) || "";
32
41
  const content = extracted.length > 20000 ? extracted.slice(0, 20000) + "\n\n...(truncated)" : extracted;
33
42
  return { content, date: latestDate, project: slug };
34
43
  }
@@ -1 +1 @@
1
- {"version":3,"file":"journal-read.js","sourceRoot":"","sources":["../../src/tools-logic/journal-read.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EA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AO,EAAE,IAAI,EAAE,KAAK,EAAE,8BAA8B,UAAU,gBAAgB,IAAI,GAAG,EAAE,CAAC;IAClI,CAAC;IAED,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC;IACvC,MAAM,GAAG,GAAG,cAAc,CAAC,WAAW,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;IACvD,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,oBAAoB,CAAC,CAAC,CAAC,GAAG,CAAC;IACtF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACtD,CAAC"}
@@ -8,6 +8,15 @@ export interface JournalSearchInput {
8
8
  * Accepts ISO date string ("2026-05-01") or relative duration ("7d", "30d").
9
9
  * Palace and insight results are unaffected. */
10
10
  since?: string;
11
+ /** SCOPE stage (Wave 3b, retrieval/scope.ts) — threaded through to
12
+ * queryMemory() for forward-compat with future consumers of this seam.
13
+ * Currently a NO-OP for the journal tier: readTierCandidates("journal",
14
+ * project, ...) only ever reads `project`'s own tree, so every journal
15
+ * candidate is trivially "of project" — there is nothing cross-project
16
+ * to filter (see query-memory.ts's `SCOPE_ATTRIBUTED_TIERS`). Kept as an
17
+ * accepted parameter so a future genuinely cross-project journal-like
18
+ * tier does not require another signature change here. */
19
+ scope?: string;
11
20
  }
12
21
  /**
13
22
  * Parse a `since` value into a Date cutoff.
@@ -16,10 +25,59 @@ export interface JournalSearchInput {
16
25
  export declare function parseSinceDate(since: string): Date;
17
26
  export interface JournalSearchResult {
18
27
  results: Array<{
28
+ /**
29
+ * RESOLVABLE-ANNOTATION fix (pre-ship red-team fix, STEP 4c, 2026-09-01,
30
+ * wave/pipe-w5fix — correctness red-team). Additive: this result's own
31
+ * stable identity (`QueryMemoryItem.id`, the SAME id `smart_recall`'s
32
+ * `SmartRecallResultItem.id` exposes for the equivalent underlying
33
+ * item), so `supersededBy`/`conflictsWith` below can be cross-referenced
34
+ * against a SIBLING entry's `id` in this SAME array — mirroring
35
+ * `SmartRecallResultItem`'s existing `id` field. Before this fix,
36
+ * `JournalSearchResult.results` carried no `id` of its own at all, so an
37
+ * agent reading `journal_search`'s JSON output had a `supersededBy`
38
+ * value with nothing in the SAME payload to resolve it against (it was
39
+ * only meaningful against `queryMemory()`'s internal, unexposed item
40
+ * set) — this is `E10`'s "annotation is resolvable via id" requirement.
41
+ */
42
+ id: string;
19
43
  date: string;
20
44
  section: string;
21
45
  excerpt: string;
22
46
  line: number;
47
+ /**
48
+ * CONTRADICTION stage (Wave 5a, `retrieval/contradiction.ts`) — set ONLY
49
+ * when this result was detected as the STALE side of a same-tier
50
+ * version-token conflict with a sibling that could be confidently
51
+ * ordered as more current. Holds the CURRENT sibling's `id` — as of the
52
+ * STEP 4c fix above, that id is now this SAME array's own `id` field for
53
+ * the corresponding entry (when that sibling survives this call's own
54
+ * `section` filter / `limit` truncation — see below). Additive — absent
55
+ * when no conflict was detected. W5a salvage (2026-08-31, HIGH-3): this
56
+ * field was computed by `queryMemory()`'s journal tier all along but
57
+ * silently dropped by this function's own field-list map below (the
58
+ * same gap `smart-recall.ts`'s `localRecallSearch` had) — now threaded
59
+ * through. NOTE: since `journalSearch()` still applies its own `section`
60
+ * filter and `limit` slice AFTER this map, a `supersededBy`/
61
+ * `conflictsWith` id CAN still point at a sibling that this call's OWN
62
+ * filtered/truncated `results` array no longer contains — this is an
63
+ * accepted, additive-metadata limitation (see STEP 3 of the W5a salvage
64
+ * report), not a broken contract: the id is still meaningful against the
65
+ * underlying `queryMemory()` candidate set, and — as of STEP 4c —
66
+ * resolvable within THIS array whenever both sides of the pair survive
67
+ * the same filter/truncation (unlike before, when there was no `id`
68
+ * field on this shape to resolve against even in that common case).
69
+ * ANNOTATE-ONLY (STEP 4a): a `supersededBy` result's rank/order in this
70
+ * array is never changed by the contradiction stage itself (see
71
+ * query-memory.ts's `applyContradictionStage`) — journalSearch's own
72
+ * independent date-descending sort below is unaffected either way.
73
+ */
74
+ supersededBy?: string;
75
+ /** CONTRADICTION stage (Wave 5a) — the `id`s of every sibling this
76
+ * result's text grammar-conflicts with, regardless of whether a stale
77
+ * direction could be resolved. See `supersededBy`'s doc comment for
78
+ * the same truncation/section-filter caveat, and for the STEP 4c
79
+ * resolvable-via-`id` fix. */
80
+ conflictsWith?: string[];
23
81
  }>;
24
82
  palace_searched: boolean;
25
83
  _note?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"journal-search.d.ts","sourceRoot":"","sources":["../../src/tools-logic/journal-search.ts"],"names":[],"mappings":"AAQA,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;qDAEiD;IACjD,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAQlD;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACjF,eAAe,EAAE,OAAO,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAgCD,wBAAsB,aAAa,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CA4G3F"}
1
+ {"version":3,"file":"journal-search.d.ts","sourceRoot":"","sources":["../../src/tools-logic/journal-search.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;qDAEiD;IACjD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;;;;;+DAO2D;IAC3D,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAQlD;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,KAAK,CAAC;QACb;;;;;;;;;;;;;WAaG;QACH,EAAE,EAAE,MAAM,CAAC;QACX,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb;;;;;;;;;;;;;;;;;;;;;;;;;;WA0BG;QACH,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB;;;;uCAI+B;QAC/B,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;KAC1B,CAAC,CAAC;IACH,eAAe,EAAE,OAAO,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAgCD,wBAAsB,aAAa,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAmJ3F"}
@@ -1,10 +1,8 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
1
  import { resolveProject } from "../storage/project.js";
4
- import { journalDirs, palaceDir } from "../storage/paths.js";
5
- import { ensurePalaceInitialized, listRooms } from "../palace/rooms.js";
2
+ import { ensurePalaceInitialized } from "../palace/rooms.js";
6
3
  import { tokenizeWords } from "../helpers/tokenize.js";
7
- import { isRescueSourcedContent } from "../helpers/journal-filter.js";
4
+ import { readTierCandidates } from "../retrieval/candidates.js";
5
+ import { queryMemory, stableId } from "../retrieval/query-memory.js";
8
6
  /**
9
7
  * Parse a `since` value into a Date cutoff.
10
8
  * Supports "Nd" (N days ago) and ISO date strings.
@@ -49,98 +47,131 @@ function firstMatchIndex(line, keywords) {
49
47
  }
50
48
  export async function journalSearch(input) {
51
49
  const slug = await resolveProject(input.project);
52
- // Include archive so recall reaches rollup-archived entries (P0-2).
53
- // F4 (2026-07-31): journalDirs(slug, true) no longer descends into
54
- // journal/archive/raw/ (the unstructured hook-archive verbatim tier) — see
55
- // journalDirs' doc comment in storage/paths.ts. That noisy, collision-prone
56
- // path is replaced by smartRecall's explicit, confidence-gated "archive"
57
- // source (tools-logic/smart-recall.ts). journalSearch here only ever sees
58
- // curated journal entries + rollup summaries.
59
- const dirs = journalDirs(slug, true);
60
- const keywords = queryKeywords(input.query);
50
+ const keywords = queryKeywords(input.query); // still needed below for the include_palace branch's own local scan
61
51
  const limit = input.limit ?? 25;
62
- const sinceCutoff = input.since ? parseSinceDate(input.since) : null;
63
- const results = [];
64
- for (const dir of dirs) {
65
- if (!fs.existsSync(dir))
66
- continue;
67
- const files = fs.readdirSync(dir).filter((f) => f.endsWith(".md"));
68
- for (const file of files) {
69
- // since-filter: skip files whose date is before the cutoff
70
- if (sinceCutoff) {
71
- const dateMatch = file.match(/^(\d{4}-\d{2}-\d{2})/);
72
- if (dateMatch) {
73
- const fileDate = new Date(dateMatch[1]);
74
- if (fileDate < sinceCutoff)
75
- continue;
76
- }
77
- }
78
- const filePath = path.join(dir, file);
79
- const content = fs.readFileSync(filePath, "utf-8");
80
- // Identity-trust (CRITICAL-1 followup, 2026-08-20): quarantine a
81
- // working-memory-rescue card at the shared choke point
82
- // (journal-filter.ts's isRescueSourcedContent) — this is the surface
83
- // an MCP-connected agent actually calls for "recall/search/find
84
- // previous context" (directly via `ar search`, and indirectly as
85
- // smart_recall's journal source, see smart-recall.ts), and the exact
86
- // one the red-team CRITICAL-2 exploit found returning a hijacked
87
- // card's content verbatim, unmarked, with no way for the caller to
88
- // even represent an "untrusted" signal on this result shape.
89
- if (isRescueSourcedContent(content))
90
- continue;
91
- const lines = content.split("\n");
92
- let currentSection = "top";
93
- for (let i = 0; i < lines.length; i++) {
94
- const line = lines[i];
95
- if (line.startsWith("## ")) {
96
- currentSection = line.slice(3).trim().toLowerCase().replace(/\s+/g, "_");
97
- }
98
- if (input.section && currentSection !== input.section.toLowerCase())
99
- continue;
100
- if (lineMatchesQuery(line, keywords)) {
101
- if (results.length >= limit)
102
- break;
103
- const dateMatch = file.match(/^(\d{4}-\d{2}-\d{2})/);
104
- const date = dateMatch ? dateMatch[1] : file;
105
- const matchIdx = firstMatchIndex(line, keywords);
106
- const start = Math.max(0, matchIdx - 100);
107
- const end = Math.min(line.length, matchIdx + 150);
108
- let excerpt = line.slice(start, end).trim();
109
- if (start > 0)
110
- excerpt = "..." + excerpt;
111
- if (end < line.length)
112
- excerpt = excerpt + "...";
113
- results.push({ date, section: currentSection, excerpt, line: i + 1 });
114
- }
115
- }
116
- }
52
+ // Primary journal scan — migrated onto the shared pipeline (Wave 3b,
53
+ // 2026-08-30, reports/2026-08-30-pipe-w3b-migrate-report.md STEP 1):
54
+ // fetch + trust-filter + per-line scoring now all come from queryMemory()'s
55
+ // journal tier (identical excerpt-window/tokenization logic, ported
56
+ // verbatim into scoreJournalTier — see query-memory.ts) instead of this
57
+ // function's own fs scan plus an inline call to the rescue-tag choke
58
+ // predicate (helpers/journal-filter.ts).
59
+ //
60
+ // perTierLimit is requested effectively UNBOUNDED
61
+ // (Number.MAX_SAFE_INTEGER) rather than this function's own `limit`,
62
+ // because queryMemory()'s journal-tier scorer has no `section` concept —
63
+ // the section filter below must see every match in the corpus before
64
+ // truncating, not just the first `limit` unfiltered ones (requesting a
65
+ // pipeline-level cap here would silently under-fill a section-scoped
66
+ // result set that has plenty of matches beyond that cap). This mirrors
67
+ // the ORIGINAL implementation's own shape: it scanned every file/line in
68
+ // the corpus unconditionally too, refusing only to keep PUSHING past
69
+ // `limit` — see this function's own equivalence notes in the Wave 3b
70
+ // report for the one case where truncation ORDER now differs
71
+ // (characterized, not silent — see below).
72
+ const queryResult = await queryMemory({
73
+ query: input.query,
74
+ project: slug,
75
+ tiers: ["journal"],
76
+ scope: input.scope,
77
+ since: input.since,
78
+ journal: { includeRollupArchive: true, perTierLimit: Number.MAX_SAFE_INTEGER },
79
+ });
80
+ let results = queryResult.items.map((it) => {
81
+ const date = it.date ?? "";
82
+ // `it.title` is always exactly "${date} / ${section}" — scoreJournalTier's
83
+ // own construction (query-memory.ts). Strip the fixed "${date} / "
84
+ // prefix to recover the raw section value, rather than adding a
85
+ // redundant field to the shared QueryMemoryItem shape only this one
86
+ // surface would consume.
87
+ const section = it.title.slice(date.length + 3);
88
+ return {
89
+ // STEP 4c (2026-09-01): expose queryMemory()'s own stable id — see
90
+ // JournalSearchResult["results"]["id"]'s own doc comment for why.
91
+ id: it.id,
92
+ date, section, excerpt: it.excerpt, line: it.line ?? 0,
93
+ // W5a salvage (HIGH-3, 2026-08-31): thread the CONTRADICTION stage's
94
+ // annotation through — see JournalSearchResult["results"]'s own doc
95
+ // comment for the section-filter/limit truncation caveat this
96
+ // surface (unlike smart_recall) carries for these two fields.
97
+ ...(it.supersededBy ? { supersededBy: it.supersededBy } : {}),
98
+ ...(it.conflictsWith && it.conflictsWith.length > 0 ? { conflictsWith: it.conflictsWith } : {}),
99
+ };
100
+ });
101
+ if (input.section) {
102
+ const wanted = input.section.toLowerCase();
103
+ results = results.filter((r) => r.section === wanted);
117
104
  }
105
+ // Sort-before-truncate (matches the characterized recency-favoring
106
+ // improvement already documented for the smart_recall migration,
107
+ // query-memory.ts's CHALLENGE (c)-2): when total matches are within
108
+ // `limit` this reproduces the ORIGINAL's own final sort byte-for-byte
109
+ // (same matches, same order); when matches exceed `limit`, this keeps
110
+ // the truly newest `limit` — not an arbitrary filesystem-enumeration-order
111
+ // subset (the ORIGINAL's actual truncation behavior — its `limit` cutoff
112
+ // fired DURING an unsorted raw-readdir traversal, before its own final
113
+ // date-sort ever ran). See the Wave 3b report for the full equivalence
114
+ // scoping. This is an intermediate sort — the join with include_palace
115
+ // results below is re-sorted once more, at the very end, matching the
116
+ // ORIGINAL's single final sort over the combined set.
117
+ //
118
+ // W5a salvage STEP 3 note (2026-08-31; updated STEP 4a, 2026-09-01): this
119
+ // date-descending sort was ALREADY independent of the CONTRADICTION
120
+ // stage's own re-sort (query-memory.ts's `applyContradictionStage` used to
121
+ // re-sort by penalized score) — a stale item is, by construction, the
122
+ // OLDER-dated one (direction is resolved by date for journal — see
123
+ // contradiction.ts's DIRECTION rule), so it already sorted to the bottom
124
+ // here regardless. As of STEP 4a, `applyContradictionStage` no longer
125
+ // re-sorts at all (ANNOTATE-ONLY) — this sort's independence from it is
126
+ // now simply a non-issue rather than a redundancy to note. The VALUE this
127
+ // stage adds to journalSearch is the now-VISIBLE, now-resolvable-via-`id`
128
+ // (STEP 4c) `supersededBy`/`conflictsWith` annotation (see the map above),
129
+ // not a reorder this surface never needed in the first place — do not
130
+ // attempt to force the reorder to matter here by changing this sort's key.
131
+ results.sort((a, b) => b.date.localeCompare(a.date));
132
+ results = results.slice(0, limit);
118
133
  if (input.include_palace) {
119
134
  try {
120
135
  ensurePalaceInitialized(slug);
121
- const pd = palaceDir(slug);
122
- const rooms = listRooms(slug);
123
- for (const room of rooms) {
124
- const roomPath = path.join(pd, "rooms", room.slug);
125
- if (!fs.existsSync(roomPath))
126
- continue;
127
- const files = fs.readdirSync(roomPath).filter((f) => f.endsWith(".md"));
128
- for (const file of files) {
129
- const filePath = path.join(roomPath, file);
130
- const content = fs.readFileSync(filePath, "utf-8");
131
- const lines = content.split("\n");
132
- for (let i = 0; i < lines.length; i++) {
133
- if (lineMatchesQuery(lines[i], keywords)) {
134
- const matchIdx = firstMatchIndex(lines[i], keywords);
135
- const start = Math.max(0, matchIdx - 40);
136
- const end = Math.min(lines[i].length, matchIdx + 80);
137
- let excerpt = lines[i].slice(start, end).trim();
138
- if (start > 0)
139
- excerpt = "..." + excerpt;
140
- if (end < lines[i].length)
141
- excerpt = excerpt + "...";
142
- results.push({ date: `palace:${room.slug}`, section: file.replace(".md", ""), excerpt, line: i + 1 });
143
- }
136
+ // Identity-trust (P0 trust-class closure, 2026-08-30, wave/pipe-p0-trustclass,
137
+ // gap #4): was a raw fs.readdirSync+readFileSync glob over every room's
138
+ // `.md` files with ZERO rescue-tag check. Routed through
139
+ // readTierCandidates("palace-room", ...) — already trust-tagged +
140
+ // safe-by-default (the SAME canonical trust-filter the primary journal
141
+ // scan above now inherits via queryMemory()'s journal tier — Wave 3b,
142
+ // 2026-08-30 — rather than each branch calling the choke predicate on
143
+ // its own).
144
+ const candidates = readTierCandidates("palace-room", slug);
145
+ for (const c of candidates) {
146
+ const lines = c.content.split("\n");
147
+ for (let i = 0; i < lines.length; i++) {
148
+ if (lineMatchesQuery(lines[i], keywords)) {
149
+ const matchIdx = firstMatchIndex(lines[i], keywords);
150
+ const start = Math.max(0, matchIdx - 40);
151
+ const end = Math.min(lines[i].length, matchIdx + 80);
152
+ let excerpt = lines[i].slice(start, end).trim();
153
+ if (start > 0)
154
+ excerpt = "..." + excerpt;
155
+ if (end < lines[i].length)
156
+ excerpt = excerpt + "...";
157
+ // STEP 4c (2026-09-01): this branch never produces a
158
+ // QueryMemoryItem (it bypasses queryMemory() entirely — its own
159
+ // local candidate scan, see this branch's header comment above),
160
+ // so there is no pre-existing `.id` to thread through. Mint one
161
+ // with the SAME stableId() helper queryMemory() itself uses, so
162
+ // every row in `results` carries a real id, not just the
163
+ // primary journal-tier ones. These rows never carry
164
+ // `supersededBy`/`conflictsWith` (the CONTRADICTION stage only
165
+ // runs inside queryMemory(), which this branch does not call),
166
+ // so the id here only needs to be unique for cross-row identity,
167
+ // not resolvable against an annotation.
168
+ results.push({
169
+ id: stableId("palace", `${c.room}/${c.file}/${i}`),
170
+ date: `palace:${c.room}`,
171
+ section: c.file.replace(".md", ""),
172
+ excerpt,
173
+ line: i + 1,
174
+ });
144
175
  }
145
176
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["../../src/tools-logic/palace-search.ts"],"names":[],"mappings":"AAQA,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,KAAK,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,qGAAqG;QACrG,aAAa,EAAE,MAAM,CAAC;KACvB,CAAC,CAAC;IACH,aAAa,EAAE,MAAM,CAAC;CACvB;AAyBD,wBAAsB,YAAY,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAwKxF"}
1
+ {"version":3,"file":"palace-search.d.ts","sourceRoot":"","sources":["../../src/tools-logic/palace-search.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,KAAK,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,qGAAqG;QACrG,aAAa,EAAE,MAAM,CAAC;KACvB,CAAC,CAAC;IACH,aAAa,EAAE,MAAM,CAAC;CACvB;AAyBD,wBAAsB,YAAY,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CA4LxF"}
@@ -1,10 +1,8 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
1
  import { resolveProject } from "../storage/project.js";
4
- import { palaceDir } from "../storage/paths.js";
5
2
  import { ensurePalaceInitialized, listRooms, recordAccess } from "../palace/rooms.js";
6
3
  import { stem, expandQuery } from "../helpers/normalize.js";
7
4
  import { tokenizeWords } from "../helpers/tokenize.js";
5
+ import { readTierCandidates } from "../retrieval/candidates.js";
8
6
  /**
9
7
  * Parse YAML frontmatter tags from markdown content.
10
8
  * Looks for `tags: [...]` line between `---` markers.
@@ -31,7 +29,6 @@ export async function palaceSearch(input) {
31
29
  const slug = await resolveProject(input.project);
32
30
  ensurePalaceInitialized(slug);
33
31
  const rooms = listRooms(slug);
34
- const pd = palaceDir(slug);
35
32
  // v3.3.14: use keyword overlap instead of exact substring match.
36
33
  // Old approach: lines[i].toLowerCase().includes(fullQuery) required the entire
37
34
  // query to appear as one continuous substring — too strict, missed relevant entries.
@@ -64,14 +61,36 @@ export async function palaceSearch(input) {
64
61
  const queryWords = expandQuery(filteredRawQueryWords);
65
62
  const results = [];
66
63
  const targetRooms = input.room ? rooms.filter((r) => r.slug === input.room) : rooms;
67
- for (const roomMeta of targetRooms) {
68
- const roomPath = path.join(pd, "rooms", roomMeta.slug);
69
- if (!fs.existsSync(roomPath))
64
+ // Wave 3a (P0 palace-room KNOWN-GAP closure, 2026-08-30): fetch every
65
+ // room's candidate files ONCE through the shared, trust-safe FETCH stage
66
+ // (readTierCandidates) instead of this surface's own raw
67
+ // fs.readdirSync+readFileSync glob. readTierCandidates drops
68
+ // rescue-tagged content before returning (safe by default), so a
69
+ // hijacked working-memory-rescue card can no longer impersonate a
70
+ // genuine room entry in search results. This swap ONLY changes WHERE
71
+ // `content`/`file` come from — 100% of the scoring pipeline below
72
+ // (tokenize/stem/expandQuery, project-variant stripping, tag bonus, IDF,
73
+ // per-line reporting) is untouched, and result ordering is preserved:
74
+ // readTierCandidates enumerates rooms via the SAME listRooms() order and
75
+ // each room's files via the SAME fs.readdirSync() call the old code used,
76
+ // so grouping the flattened output back by `room` (below) reproduces the
77
+ // exact per-room, per-file iteration order the old raw scan had.
78
+ const candidates = readTierCandidates("palace-room", slug, { room: input.room });
79
+ const candidatesByRoom = new Map();
80
+ for (const c of candidates) {
81
+ if (!c.room)
70
82
  continue;
71
- const files = fs.readdirSync(roomPath).filter((f) => f.endsWith(".md"));
72
- for (const file of files) {
73
- const filePath = path.join(roomPath, file);
74
- const content = fs.readFileSync(filePath, "utf-8");
83
+ const list = candidatesByRoom.get(c.room);
84
+ if (list)
85
+ list.push(c);
86
+ else
87
+ candidatesByRoom.set(c.room, [c]);
88
+ }
89
+ for (const roomMeta of targetRooms) {
90
+ const roomCandidates = candidatesByRoom.get(roomMeta.slug) ?? [];
91
+ for (const candidate of roomCandidates) {
92
+ const file = candidate.file;
93
+ const content = candidate.content;
75
94
  const lines = content.split("\n");
76
95
  // Parse YAML frontmatter tags for bonus scoring
77
96
  const fileTags = parseFrontmatterTags(content);