@fabersep/memory 0.0.0-stage → 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,272 @@
1
- # Temporary Holding Version
1
+ # FaberSEP Memory (`@fabersep/memory`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE)
4
+
5
+ > Layer 0 of the FaberSEP engineering context stack (`@fabersep/memory` -> `@fabersep/spec` -> `@fabersep/atlas`).
6
+
7
+ **Prefix-cache-first, Git-backed Markdown memory for AI coding agents.**
8
+
9
+ Zero databases. Zero native addons. Zero runtime dependencies. Just plain Markdown files in Git, a deterministic compiled index that keeps your prompt cache warm, a human-approved `pre-memory` inbox so agents never pollute your rules, and a 3-tool MCP server (`memory_search`, `memory_get`, `memory_propose`).
10
+
11
+ ---
12
+
13
+ ## How It Works (The 2-Minute Mental Model)
14
+
15
+ If you are new to agent memory systems, here is everything you need to know:
16
+
17
+ 1. **Git is the single source of truth.** Every active memory entry is a small Markdown file committed to Git (`HEAD`). Uncommitted files are never silently trusted.
18
+ 2. **Three progressive layers (L0 -> L1 -> L2) keep context small and prompt-cache friendly:**
19
+ - **L0 (`MEMORY.md`):** A short, deterministic table of contents compiled from your active `team` and `personal` entries (hard cap: 1,500 tokens). No timestamps, no pending counts, no machine paths — so your LLM prompt cache stays warm turn after turn.
20
+ - **L1 (`memory_search`):** When an agent needs details, it searches your memory with a built-in pure-JS BM25 search tool and gets compact summaries back.
21
+ - **L2 (`memory_get`):** The agent fetches the full Markdown body only for the exact entry it needs.
22
+ 3. **Agents propose; humans approve (`pre-memory`).** Active memory is read-only for agents. When an agent learns a new rule or lesson, it calls `memory_propose`, which stages a proposal in `pre-memory`. You review and approve it in one batch — keeping your memory accurate and noise-free.
23
+ 4. **Three scopes:**
24
+ - **`personal`** — Your own rules, lessons, and preferences (solo local Git repo, e.g. `~/.faber/memory`).
25
+ - **`team`** — Shared engineering rules in a private team Git repo.
26
+ - **`project`** — Optional repo-specific memory in `<repo>/.faber/memory/`.
27
+
28
+ ---
29
+
30
+ ## Prerequisites
31
+
32
+ - **Node.js 20 or newer** (`node -v` to check)
33
+ - **Git** (`git --version` to check)
34
+
35
+ You do **not** need to install anything globally to try it — `npx @fabersep/memory` runs the CLI directly.
36
+ *(If you prefer shorter commands, you can install it globally once with `npm install -g @fabersep/memory` and use `faber-memory` instead of `npx @fabersep/memory`.)*
37
+
38
+ ---
39
+
40
+ ## Step-by-Step Quickstart (Solo / Personal Setup)
41
+
42
+ Follow these 5 steps in order. Each step is safe and reversible.
43
+
44
+ ### Step 1: Create your personal memory folder
45
+
46
+ Run:
47
+
48
+ ```bash
49
+ npx @fabersep/memory setup ~/.faber/memory
50
+ ```
51
+
52
+ **What this does:**
53
+ - Creates `~/.faber/memory` (you can pick any folder path you like) and initializes a local Git repository on branch `main`.
54
+ - Saves your configuration in `~/.faber/memory-state/config.json`.
55
+
56
+ ### Step 2: Connect your AI coding agent
57
+
58
+ First, run a **dry-run** to preview the exact file changes without modifying anything:
59
+
60
+ ```bash
61
+ npx @fabersep/memory init
62
+ ```
63
+
64
+ You will see a unified diff showing which instruction file and MCP config will be updated for the agents detected on your machine (`claude-code`, `antigravity`, `cursor`).
65
+
66
+ When the diff looks good, apply it:
67
+
68
+ ```bash
69
+ npx @fabersep/memory init --apply
70
+ ```
71
+
72
+ **What this does:**
73
+ - Compiles your L0 index first to `~/.faber/memory-state/MEMORY.md`.
74
+ - Creates a `.bak` backup of every file it touches.
75
+ - Adds a clearly marked `<!-- faber-memory:start --> ... <!-- faber-memory:end -->` block and registers the `faber-memory` MCP server (`npx -y @fabersep/memory serve`).
76
+
77
+ > **Tip:** Want to target only specific engines? Pass `--engine`:
78
+ > ```bash
79
+ > npx @fabersep/memory init --engine claude-code,antigravity --apply
80
+ > ```
81
+ > Want to revert the wiring cleanly at any time?
82
+ > ```bash
83
+ > npx @fabersep/memory init --undo
84
+ > ```
85
+
86
+ #### Supported Engines & What `init --apply` Wires
87
+
88
+ | Engine | Instruction File | MCP Config | Notes |
89
+ | :--- | :--- | :--- | :--- |
90
+ | **Claude Code** | `~/.claude/CLAUDE.md` (`@path` include) | `~/.claude.json` | Native `@path` L0 include + MCP tools |
91
+ | **Antigravity** | `~/.gemini/GEMINI.md` (read-at-start rule) | `~/.gemini/config/mcp_config.json` | Reads L0 at start + MCP tools |
92
+ | **Claude Desktop** | — | `claude_desktop_config.json` | MCP tools (`--engine claude-desktop`) |
93
+ | **Cursor** | — (GAP) | `~/.cursor/mcp.json` | MCP-only |
94
+ | **Codex** | — (GAP) | — | MCP-only (manual config) |
95
+
96
+ ### Step 3: Import your existing memory files (optional, zero LLM)
97
+
98
+ Already have Markdown notes, Claude auto-memory files, an `AGENTS.md`, or Cursor rules? You can import them deterministically without spending any LLM tokens.
99
+
100
+ Pick the command that matches your source:
101
+
102
+ ```bash
103
+ # 1. Any folder of Markdown (.md) files
104
+ npx @fabersep/memory import --from markdown-dir ./path/to/your/memory
105
+
106
+ # 2. Existing Claude Code auto-memory folder
107
+ npx @fabersep/memory import --from claude-memory ~/.claude/projects/<your-project>/memory
108
+
109
+ # 3. A single AGENTS.md or CLAUDE.md (split each # / ## heading into its own entry)
110
+ npx @fabersep/memory import --from agents-md ./AGENTS.md --split-headings
111
+
112
+ # 4. Existing Cursor rules
113
+ npx @fabersep/memory import --from cursor-rules ./.cursor/rules
114
+ ```
115
+
116
+ **What this does:**
117
+ - Scans your files, infers frontmatter (`id`, `type`, `summary`), checks for near-duplicates and hygiene issues (like hardcoded machine paths or secrets), and stages valid items into **`pre-memory`**.
118
+ - Nothing becomes active until you approve it in Step 4. *(In solo mode, if you trust the whole folder and want to skip manual review, you can add `--approve`.)*
119
+ - If you imported from `claude-memory`, the CLI also prints how to disable Claude's built-in auto-memory (`"autoMemoryEnabled": false` in `~/.claude/settings.json`) so future notes go through `pre-memory`.
120
+
121
+ ### Step 4: Review and approve staged proposals
122
+
123
+ Review everything waiting in `pre-memory`:
124
+
125
+ ```bash
126
+ npx @fabersep/memory review
127
+ ```
128
+
129
+ For each proposal, you will see its `scope`, `type`, `summary`, and full `body`, and choose:
130
+ - `a` — **approve** (queued for a single batch commit at the end)
131
+ - `e` — **edit** the body before approving
132
+ - `r` — **reject** and delete the proposal
133
+ - `s` — **skip** for now
134
+
135
+ Once you finish the list, all approved proposals are written to your memory repo, committed in **one Git commit**, and your L0 `MEMORY.md` is recompiled automatically.
136
+
137
+ *(Shortcuts: `npx @fabersep/memory review --approve-all`, `npx @fabersep/memory approve <id1> <id2>`, or `npx @fabersep/memory reject <id>`.)*
138
+
139
+ ### Step 5: Verify everything is healthy
140
+
141
+ Check your current setup and pending queue:
142
+
143
+ ```bash
144
+ npx @fabersep/memory status
145
+ ```
146
+
147
+ Run the strict validation check (schema, duplicates, 1,500-token L0 budget, and hygiene rules):
148
+
149
+ ```bash
150
+ npx @fabersep/memory compile --check
151
+ ```
152
+
153
+ If both succeed, restart (or start a new session in) your AI coding agent — it now has access to your compiled L0 memory and the 3 `faber-memory` MCP tools.
154
+
155
+ ---
156
+
157
+ ## Team Mode Setup (Shared Private Git Repo)
158
+
159
+ If you want to share rules across a team (or across multiple machines via a private Git repo):
160
+
161
+ ```bash
162
+ # Clone and register your private team memory repo
163
+ npx @fabersep/memory setup --team git@github.com:your-org/team-memory.git
164
+
165
+ # Pull the latest team changes and recompile L0
166
+ npx @fabersep/memory sync
167
+ ```
168
+
169
+ When you approve a `team` proposal via `review` or `approve`:
170
+ - **`--submit-mode auto` (default):** Pushes directly to the team repo's default branch via a clean temporary worktree. If branch protection rejects the push, it automatically falls back to creating a branch and opening a PR.
171
+ - **`--submit-mode pr`:** Always submits via a Pull Request (`npx @fabersep/memory config set-submit-mode pr`).
172
+
173
+ ---
174
+
175
+ ## Everyday Workflow
176
+
177
+ Once set up, daily use is simple:
178
+
179
+ 1. **During a session:** Your agent loads the compact L0 index, searches deeper with `memory_search` + `memory_get`, and proposes new lessons via `memory_propose`.
180
+ 2. **Whenever you have a minute:** Run `npx @fabersep/memory status` to see pending proposals, then `npx @fabersep/memory review` to approve or reject them in one batch.
181
+ 3. **In team mode:** Run `npx @fabersep/memory sync` whenever you want to pull teammates' updates.
182
+
183
+ ### Writing a Memory File by Hand
184
+
185
+ Memory files are standard Markdown with a small YAML frontmatter block:
186
+
187
+ ```markdown
188
+ ---
189
+ id: no-broad-process-kill
190
+ type: rule
191
+ scope: personal
192
+ summary: Never run pkill or killall by broad pattern; stop only your own PID or task.
193
+ tags: [safety, shell]
194
+ ---
195
+
196
+ Never kill processes by broad name patterns like `pkill node` or `killall python`.
197
+ Always stop only the specific PID or background task you started.
198
+ ```
199
+
200
+ Valid `type` values: `rule`, `decision`, `lesson`, `preference`, `reference`.
201
+ After editing or adding a file manually in your memory repo, commit it with Git and run `npx @fabersep/memory compile`.
202
+
203
+ ---
204
+
205
+ ## Installing Globally or Running from Source
206
+
207
+ **Global npm install** (gives you the `faber-memory` command directly):
208
+
209
+ ```bash
210
+ npm install -g @fabersep/memory
211
+ faber-memory --help
212
+ ```
213
+
214
+ **From GitHub source** (for contributing or local development):
215
+
216
+ ```bash
217
+ git clone https://github.com/fabersep/memory.git
218
+ cd memory
219
+ npm install
220
+ npm test
221
+ npm link
222
+ ```
223
+
224
+ ---
225
+
226
+ ## CLI Command Reference
227
+
228
+ | Command | Description |
229
+ | :--- | :--- |
230
+ | `setup [path]` | Initialize a local solo (personal) memory Git repo. |
231
+ | `setup --team <git-url> [--path <dir>] [--submit-mode auto\|pr]` | Clone and configure a shared team memory repo. |
232
+ | `config` | Print current `~/.faber/memory-state/config.json`. |
233
+ | `config set-path <personal\|team> <new-path>` | Move a configured memory root while keeping its UUID. |
234
+ | `config set-submit-mode <auto\|pr>` | Change team approval mode (`auto` push with PR fallback, or always `pr`). |
235
+ | `init [--apply \| --undo] [--engine ...] [--project-hint]` | Preview, apply (with `.bak` backups), or undo user-level agent wiring. |
236
+ | `compile [--check] [--repo <dir>]` | Compile L0 `MEMORY.md`, or validate schema/budget/hygiene in CI (`--check`). |
237
+ | `sync [--timeout <ms>]` | Fast-forward pull remote updates and recompile L0. |
238
+ | `status` | Show compiled L0 status, configured roots, warnings, and pending/stale proposals. |
239
+ | `review [--approve-all]` | Interactively approve, edit, reject, or skip pending `pre-memory` proposals. |
240
+ | `approve <id...> [--mode auto\|pr]` | Approve one or more proposals by ID in a single batch commit. |
241
+ | `reject <id>` | Reject and delete a pending proposal. |
242
+ | `import --from <type> <path> [--split-headings] [--approve]` | Deterministically import existing memory into `pre-memory`. |
243
+ | `serve` | Run the 3-tool stdio MCP server (used by your AI agent's MCP config). |
244
+
245
+ ---
246
+
247
+ ## MCP Tools
248
+
249
+ The MCP server exposes exactly **3 lean tools** (~350 tokens total tool schema):
250
+
251
+ | Tool | Purpose |
252
+ | :--- | :--- |
253
+ | `memory_search` | Pure-JS BM25 full-text search across active `team`, `personal`, and `project` scopes (returns compact L1 summaries). Automatically reindexes on Git `HEAD` change. |
254
+ | `memory_get` | Fetch the full L2 Markdown body of a specific entry by ID. |
255
+ | `memory_propose` | Stage a new entry or update into `pre-memory` for human review (never writes directly to active memory). |
256
+
257
+ ---
258
+
259
+ ## Documentation & Specs
260
+
261
+ This repository follows the [FaberSEP Spec](https://github.com/fabersep/spec) standard:
262
+
263
+ - [Master PRD](docs/master-prd.md)
264
+ - [Architecture](docs/architecture.md)
265
+ - [Core Memory PRD](docs/features/01-core-memory/prd.md)
266
+ - [BDD Acceptance Criteria (55 scenarios)](docs/features/01-core-memory/acceptance_criteria.md)
267
+
268
+ ---
269
+
270
+ ## License
271
+
272
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,26 @@
1
+ import { MemoryEntry, Proposal, Scope, SearchResultItem, EntryType } from './types.js';
2
+ export declare function tokenize(text: string): string[];
3
+ export declare class BM25Index {
4
+ private docs;
5
+ private docFreq;
6
+ private avgDocLen;
7
+ private readonly k1;
8
+ private readonly b;
9
+ rebuild(entries: MemoryEntry[], pendingProposals?: Proposal[]): void;
10
+ private addDoc;
11
+ search(query: string, options?: {
12
+ scope?: Scope;
13
+ type?: EntryType;
14
+ includePending?: boolean;
15
+ limit?: number;
16
+ }): SearchResultItem[];
17
+ }
18
+ export interface NearDuplicateMatch {
19
+ id: string;
20
+ scope: Scope;
21
+ summary: string;
22
+ pending: boolean;
23
+ similarity: number;
24
+ }
25
+ export declare function computeSimilarity(textA: string, textB: string): number;
26
+ export declare function findNearDuplicates(candidateSummary: string, candidateBody: string, activeEntries: MemoryEntry[], pendingProposals: Proposal[], threshold: number): NearDuplicateMatch[];
@@ -0,0 +1,183 @@
1
+ export function tokenize(text) {
2
+ return text
3
+ .toLowerCase()
4
+ .split(/[^a-z0-9]+/)
5
+ .filter((t) => t.length >= 2);
6
+ }
7
+ const SCOPE_ORDER = {
8
+ team: 0,
9
+ personal: 1,
10
+ project: 2,
11
+ };
12
+ export class BM25Index {
13
+ docs = [];
14
+ docFreq = new Map();
15
+ avgDocLen = 1;
16
+ k1 = 1.5;
17
+ b = 0.75;
18
+ rebuild(entries, pendingProposals = []) {
19
+ this.docs = [];
20
+ this.docFreq.clear();
21
+ for (const e of entries) {
22
+ if (e.status !== 'active')
23
+ continue;
24
+ // Weight id, summary, and tags higher by repeating them in the token bag
25
+ const weightedText = `${e.id} ${e.id} ${e.summary} ${e.summary} ${e.tags.join(' ')} ${e.body}`;
26
+ const tokens = tokenize(weightedText);
27
+ this.addDoc({
28
+ key: `${e.scope}:${e.id}`,
29
+ id: e.id,
30
+ scope: e.scope,
31
+ type: e.type,
32
+ summary: e.summary,
33
+ tags: e.tags,
34
+ pending: false,
35
+ shadowed: e.shadowed,
36
+ shadowWarning: e.shadowWarning,
37
+ tokens,
38
+ });
39
+ }
40
+ for (const p of pendingProposals) {
41
+ const weightedText = `${p.entryId} ${p.entryId} ${p.summary} ${p.summary} ${(p.tags || []).join(' ')} ${p.body}`;
42
+ const tokens = tokenize(weightedText);
43
+ this.addDoc({
44
+ key: `pending:${p.id}`,
45
+ id: p.id,
46
+ scope: p.scope,
47
+ type: p.type,
48
+ summary: p.summary,
49
+ tags: p.tags || [],
50
+ pending: true,
51
+ proposalId: p.id,
52
+ tokens,
53
+ });
54
+ }
55
+ const totalLen = this.docs.reduce((acc, d) => acc + d.length, 0);
56
+ this.avgDocLen = this.docs.length > 0 ? totalLen / this.docs.length : 1;
57
+ }
58
+ addDoc(input) {
59
+ const termFreqs = new Map();
60
+ for (const t of input.tokens) {
61
+ termFreqs.set(t, (termFreqs.get(t) || 0) + 1);
62
+ }
63
+ for (const term of termFreqs.keys()) {
64
+ this.docFreq.set(term, (this.docFreq.get(term) || 0) + 1);
65
+ }
66
+ this.docs.push({
67
+ ...input,
68
+ termFreqs,
69
+ length: input.tokens.length || 1,
70
+ });
71
+ }
72
+ search(query, options = {}) {
73
+ const includePending = Boolean(options.includePending);
74
+ const limit = options.limit || 50;
75
+ const candidates = this.docs.filter((d) => {
76
+ if (!includePending && d.pending)
77
+ return false;
78
+ if (options.scope && d.scope !== options.scope)
79
+ return false;
80
+ if (options.type && d.type !== options.type)
81
+ return false;
82
+ return true;
83
+ });
84
+ const queryTokens = tokenize(query || '');
85
+ if (queryTokens.length === 0) {
86
+ return candidates
87
+ .sort((a, b) => {
88
+ if (a.pending !== b.pending)
89
+ return a.pending ? 1 : -1;
90
+ if (SCOPE_ORDER[a.scope] !== SCOPE_ORDER[b.scope]) {
91
+ return SCOPE_ORDER[a.scope] - SCOPE_ORDER[b.scope];
92
+ }
93
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
94
+ })
95
+ .slice(0, limit)
96
+ .map(toSearchResult);
97
+ }
98
+ const N = Math.max(this.docs.length, 1);
99
+ const scored = [];
100
+ for (const doc of candidates) {
101
+ let score = 0;
102
+ for (const term of queryTokens) {
103
+ const tf = doc.termFreqs.get(term) || 0;
104
+ if (tf === 0)
105
+ continue;
106
+ const df = this.docFreq.get(term) || 0;
107
+ const idf = Math.log(1 + (N - df + 0.5) / (df + 0.5));
108
+ const denom = tf + this.k1 * (1 - this.b + this.b * (doc.length / this.avgDocLen));
109
+ score += idf * ((tf * (this.k1 + 1)) / denom);
110
+ }
111
+ if (score > 0) {
112
+ scored.push({ doc, score });
113
+ }
114
+ }
115
+ scored.sort((a, b) => b.score - a.score || (a.doc.id < b.doc.id ? -1 : 1));
116
+ return scored.slice(0, limit).map((s) => toSearchResult(s.doc));
117
+ }
118
+ }
119
+ function toSearchResult(doc) {
120
+ const item = {
121
+ id: doc.id,
122
+ scope: doc.scope,
123
+ type: doc.type,
124
+ summary: doc.summary,
125
+ tags: doc.tags,
126
+ };
127
+ if (doc.pending) {
128
+ item.pending = true;
129
+ item.proposal_id = doc.proposalId;
130
+ }
131
+ if (doc.shadowed) {
132
+ item.shadowed = true;
133
+ item.shadow_warning = doc.shadowWarning;
134
+ }
135
+ return item;
136
+ }
137
+ export function computeSimilarity(textA, textB) {
138
+ const tokensA = new Set(tokenize(textA));
139
+ const tokensB = new Set(tokenize(textB));
140
+ if (tokensA.size === 0 || tokensB.size === 0)
141
+ return 0;
142
+ let intersection = 0;
143
+ for (const t of tokensA) {
144
+ if (tokensB.has(t))
145
+ intersection++;
146
+ }
147
+ const union = tokensA.size + tokensB.size - intersection;
148
+ const jaccard = union > 0 ? intersection / union : 0;
149
+ const overlap = intersection / Math.min(tokensA.size, tokensB.size);
150
+ return 0.6 * jaccard + 0.4 * overlap;
151
+ }
152
+ export function findNearDuplicates(candidateSummary, candidateBody, activeEntries, pendingProposals, threshold) {
153
+ const candidateText = `${candidateSummary} ${candidateBody}`;
154
+ const matches = [];
155
+ for (const e of activeEntries) {
156
+ if (e.status !== 'active')
157
+ continue;
158
+ const sim = computeSimilarity(candidateText, `${e.summary} ${e.body}`);
159
+ if (sim >= threshold) {
160
+ matches.push({
161
+ id: e.id,
162
+ scope: e.scope,
163
+ summary: e.summary,
164
+ pending: false,
165
+ similarity: Number(sim.toFixed(3)),
166
+ });
167
+ }
168
+ }
169
+ for (const p of pendingProposals) {
170
+ const sim = computeSimilarity(candidateText, `${p.summary} ${p.body}`);
171
+ if (sim >= threshold) {
172
+ matches.push({
173
+ id: p.id,
174
+ scope: p.scope,
175
+ summary: p.summary,
176
+ pending: true,
177
+ similarity: Number(sim.toFixed(3)),
178
+ });
179
+ }
180
+ }
181
+ matches.sort((a, b) => b.similarity - a.similarity);
182
+ return matches;
183
+ }