@delfini/drift-engine 0.2.0 → 0.3.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,172 +1,76 @@
1
1
  # @delfini/drift-engine
2
2
 
3
- Pure-logic drift analysis core shared by `@delfini/action` (CI surface, `apps/action`) and `@delfini/cli` (Skill surface, `packages/cli`). No I/O, no LLM client, no credentials, no `fetch`. Runtime deps: `zod` + `picomatch` (both pure CPU — no I/O, no network, no env).
3
+ The pure-logic analysis core behind [Delfini](https://github.com/Legends-of-Tech/delfini) the tool that detects when a code change has made your documentation wrong and proposes the fix.
4
4
 
5
- The package exists so both surfaces consume the same prompt assembly, schema, and reconciliation logic algorithm parity between the Action and the Skill holds **by construction** (FR139, NFR44). A finding surfaced locally by the Skill is the same finding the Action will surface on the eventual PR.
5
+ This package is the brain, with none of the plumbing. Given a diff and a set of documents, it builds the analysis prompt, defines the schema the model must answer in, and reconciles the model's output back to exact line numbers. It is shared by both Delfini surfaces — the **Skill** (local, `@delfini/cli`) and the **Action** (CI) — so the analysis is identical wherever it runs. A finding surfaced locally is the same finding the Action would surface on the eventual PR.
6
+
7
+ ## What it does
8
+
9
+ A drift analysis is three pure steps, and this package owns all three:
10
+
11
+ 1. **`buildPrompt`** — assemble the LLM prompt from a diff, the in-scope docs, and PR metadata. Every doc line is prefixed with its number so the model can cite exact ranges.
12
+ 2. **`analysisSchema`** — the schema the model's JSON output must satisfy: structured findings of three kinds — `drift` (replace these lines), `additive` (insert this content), and `clarification` (uncertain — surface for a human).
13
+ 3. **`validateAndReconcile`** — validate the model's JSON and verify each finding's quoted text actually matches the doc at the cited lines. Mismatches (model hallucinations) are discarded before they reach the caller.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install @delfini/drift-engine
19
+ ```
6
20
 
7
21
  ## Public API
8
22
 
9
23
  ```ts
10
24
  import {
11
- buildPrompt,
12
- validateAndReconcile,
13
- estimatePromptTokens,
14
- analysisSchema,
25
+ buildPrompt, // (input, template, options?) => string
26
+ validateAndReconcile, // (rawJson, docs) => AnalysisResult
27
+ estimatePromptTokens, // (prompt) => number
28
+ analysisSchema, // Zod schema for the model's output
29
+ // doc-scope matching:
30
+ normalizeDocScope,
31
+ validateDocScopeEntry,
32
+ classifyEntry,
33
+ isFileInDocScope,
34
+ // types:
15
35
  type AnalysisInput,
16
36
  type AnalysisResult,
17
37
  type DocFile,
18
38
  type Contradiction,
19
39
  type Addition,
20
- type ClarifyingQuestion,
21
- type PRMetadata,
22
- type Severity,
23
40
  } from '@delfini/drift-engine'
24
41
  ```
25
42
 
26
- Internal helpers (`dedupeOverlappingContradictions`, `filterActionableContradictions`, `reconcileLineNumbers`, `reconcileAdditiveAnchors`, `ContradictionSchema`, `AdditionSchema`, `locateQuote`, `locateAnchorHeading`, etc.) are **not** re-exported. Callers compose only through the surface above.
43
+ Both the Action and the CLI follow the same flow: gather inputs (diff + docs + PR metadata) `buildPrompt` → send to an LLM → `validateAndReconcile` on the JSON → render the result. Internal helpers are not re-exported; callers compose only through the surface above.
27
44
 
28
- ## Relevance gating (opt-in)
45
+ ## Relevance retrieval (optional)
29
46
 
30
- `buildPrompt(input, template, options?)` accepts an optional third argument:
47
+ `buildPrompt(input, template, options?)` accepts an optional third argument to keep large prompts focused:
31
48
 
32
49
  ```ts
33
- interface BuildPromptOptions {
34
- relevanceThreshold?: number
35
- }
50
+ buildPrompt(input, template, { relevanceThreshold: 5 })
36
51
  ```
37
52
 
38
- When `relevanceThreshold` is a positive integer, docs whose relevance score is below the threshold are dropped before the prompt is rendered. Scoring breakdown:
39
-
40
- | Tier | Signal | Score |
41
- |---|---|---|
42
- | 1 | The doc itself appears in the diff (`diff --git a/<doc> ...`) | +20 |
43
- | 2 | A code-file path from the diff appears in the doc body | +10 per file |
44
- | 3 | An identifier from the diff appears in the doc body | +3 per identifier, capped at +30 |
45
- | 4 | A heading whose terms overlap with diff identifiers | +5 per heading |
46
-
47
- Default behaviour (`options` omitted, or `relevanceThreshold` is `undefined`, `0`, or non-finite) is observably no-op — the prompt-snapshot gate (NFR44 gate A) enforces byte-equality with the legacy output.
48
-
49
- **Recommended starting threshold:** `5` — keeps any doc with at least one Tier-2 hit or the doc-itself-in-diff signal.
50
-
51
- ## NFR44 release gates
52
-
53
- The extraction is observably no-op for the Action's public behaviour. Two release gates guard that invariant on every PR:
53
+ Each doc section is scored against the diff and sections below the threshold are dropped before rendering:
54
54
 
55
- | Gate | Lives at | Catches | Misses (caught by the other gate) |
56
- |---|---|---|---|
57
- | **A snapshot parity** | `packages/drift-engine/__tests__/prompt-snapshot.test.ts` | Any change to `prompt.md` text, `prompt-builder.ts` rendering, `prefixDocLines`, or `renderDocsBlock` that perturbs the rendered prompt | Schema / reconcile / orchestrator regressions — none flow through `buildPrompt` |
58
- | **B Action pipeline** | `apps/action/src/__tests__/pipeline.test.ts` | Any change to `reconcile.ts`, `schema.ts`, orchestrator wiring, or the round-trip from LLM JSON → rendered PR comment / check verdict / intake payload | Pure prompt-text drift that the LLM-mocked fixtures don't surface |
59
-
60
- Both gates must be green for a drift-engine PR to merge. Gate A catches regressions **before** the LLM ever runs; gate B catches everything downstream of the LLM.
61
-
62
- ## When to update the snapshot
63
-
64
- Update `__tests__/fixtures/canonical-prompt.snapshot.md` **only** when the prompt change is intentional. Examples that require an update:
65
-
66
- - Editing the text of any section of `src/prompt.md`.
67
- - Adding, removing, or renaming a placeholder in `src/prompt.md` plus the corresponding substitution in `src/prompt-builder.ts`.
68
- - Changing how `prefixDocLines` formats line-number prefixes (e.g. `${n}: ` → `${n}| `).
69
- - Changing how `renderDocsBlock` iterates documents.
70
-
71
- Examples that should **not** require a snapshot update:
72
-
73
- - Edits to `reconcile.ts`, `schema.ts`, `prompt-budget.ts`, or `types.ts` — none of these flow through `buildPrompt`.
74
- - Edits to `src/index.ts` re-exports.
75
- - Tooling / config changes (`package.json`, `tsconfig.json`, ESLint rules).
76
-
77
- A fixture-only change (editing `canonical-input.json` without touching the prompt) implies the snapshot no longer matches and the test fails. Always update fixture + snapshot together.
78
-
79
- ## How to update the snapshot
80
-
81
- The snapshot is regenerated by hand to keep human-reviewer eyes on every byte of drift:
82
-
83
- ```bash
84
- cd packages/drift-engine
85
-
86
- # One-shot regeneration via a temporary node script. Inline so nothing checked
87
- # into the repo can ever auto-update the snapshot.
88
- node --import tsx -e "
89
- import { readFileSync, writeFileSync } from 'node:fs'
90
- import { fileURLToPath } from 'node:url'
91
- import { buildPrompt } from './src/prompt-builder.ts'
92
-
93
- const input = JSON.parse(readFileSync('./__tests__/fixtures/canonical-input.json', 'utf8'))
94
- const template = readFileSync('./src/prompt.md', 'utf8')
95
- writeFileSync('./__tests__/fixtures/canonical-prompt.snapshot.md', buildPrompt(input, template))
96
- "
97
-
98
- # Verify the test now passes
99
- pnpm test prompt-snapshot.test
100
- ```
101
-
102
- In the PR description, include:
103
-
104
- 1. **Which prompt change drove the snapshot update** — name the section of `prompt.md` or the rendering helper that changed.
105
- 2. **Confirmation that NFR44 gate B is unaffected** — `pnpm --filter @delfini/action test` still passes (gate B usually does — the rewrite is at the prompt-text level, not the reconcile-shape level).
106
- 3. **Explicit reviewer sign-off on the snapshot diff** — at least one reviewer confirms every byte of drift is intentional.
107
-
108
- ## What NOT to do
109
-
110
- - **Do not `it.skip` the snapshot test** to make a PR go green. If the test fires, either the change is intentional (update the snapshot per above) or unintentional (revert the source change).
111
- - **Do not auto-update the snapshot via tooling** without reviewer eyes on the diff. The manual `node --import tsx` workflow above is intentional friction.
112
- - **Do not use Vitest's `toMatchSnapshot` / `toMatchInlineSnapshot`** — both auto-create on first run and auto-update on `--update-snapshots`, defeating the human-review-required semantics. The test uses `readFileSync` + a literal-string comparison so the snapshot is a real, reviewable file in the PR diff.
113
- - **Do not change `core.autocrlf` / `.gitattributes`** to "fix" a Windows checkout that's producing CRLF snapshots. The repo's `.gitattributes` pins `packages/drift-engine/src/prompt.md`, `__tests__/fixtures/*.snapshot.md`, and `__tests__/fixtures/*.json` to `eol=lf`; renormalise with `git add --renormalize <path>` if a checkout drifted.
114
-
115
- ## NFR49(b) Parity-Gate Policy
116
-
117
- PRD v6.7 added the token-efficient retrieval stage (FR150–FR153) — section-granularity doc retrieval (`selectRelevantSections`), deterministic diff pre-filtering (`filterDiff`), ranked-fill prompt budget (`rankedFillSections` + `buildPromptWithDrops`), and the working-tree-at-branch-HEAD doc-read invariant. The stage changes `buildPrompt` output **when enabled**, so it would trip the NFR44 release gates without discipline. The policy that keeps the gates green during roll-out:
118
-
119
- ### Three allowed paths — and one forbidden
120
-
121
- - **Path A — opt-in / default-off (V1 default).** Every retrieval knob ships behind a `BuildPromptOptions` field with an explicit no-op fast-path (`relevanceThreshold` and `promptTokenBudget` both default to undefined / `<= 0` / non-finite → keep everything, identical output). The default `buildPrompt(input, template)` call path produces **byte-identical** output vs. the pre-v6.7 baseline. All three NFR44 release gates (A drift-engine snapshot, B Action pipeline, C bundled-CLI parity) pass with **no re-snapshot**. This is the V1-expected path and the path the FR150–FR152 stories landed on.
122
- - **Path B — deliberate, reviewed re-snapshot.** When a `prompt.md` wording change or a default-on activation is genuinely required, the PR re-snapshots `canonical-prompt.snapshot.md` (gate A) and the bundled-CLI parity fixture (gate C) in lockstep. The PR description names the change explicitly with a sentence such as: *"intentional `prompt.md` re-snapshot under NFR49(b) Path B — &lt;short rationale&gt;."* Reviewers read the snapshot diff as part of code review; sign-off is required.
123
- - **Path C — silent regen — FORBIDDEN.** Running `pnpm test -u` to make a failing snapshot diff disappear without explicit PR acknowledgement is a process violation. If the snapshot is moving and you cannot justify why, the source change is not yet ready.
124
-
125
- ### PR-description templates
126
-
127
- Copy the right paragraph into the PR body:
128
-
129
- **Path A:**
130
-
131
- > **NFR49(b) parity statement (Path A — no prompt wording change / opt-in default-off).** The retrieval / filter / budget logic this PR adds is gated behind a `BuildPromptOptions` knob whose default (undefined / `<= 0` / non-finite) keeps every section and every diff hunk. `buildPrompt(input, template)` emits byte-identical output vs. the pre-PR baseline. All three NFR44 release gates (A drift-engine snapshot, B Action pipeline, C bundled-CLI parity) stay green with no re-snapshot.
132
-
133
- **Path B:**
134
-
135
- > **NFR49(b) parity statement (Path B — deliberate re-snapshot).** This PR sharpens `packages/drift-engine/src/prompt.md` (commit `<sha>`, lines `<range>`). The NFR44 gate A snapshot (`__tests__/prompt-snapshot.test.ts`'s `canonical-prompt.snapshot.md`) and the bundled-CLI parity gate C's expected output are deliberately re-snapped in lockstep. Rationale: `<one-sentence rationale>`. Reviewer sign-off on the snapshot diff: `<reviewer>`.
136
-
137
- ### Release-time recall
138
-
139
- Per-commit recall is asserted via the **retention gate** in `__tests__/token-efficiency.test.ts` (LLM-free): for each labelled fixture in `__tests__/fixtures/token-efficiency/` and `__tests__/fixtures/residual-drift/`, the section identified by `expected.json`'s `groundTruthDocPath` + `groundTruthSection` MUST survive `selectRelevantSections` + `rankedFillSections`. A regression that drops it fails CI.
140
-
141
- Behavioural LLM recall — does the model actually flag the drift in the assembled prompt? — is verified **at release** on `apps/action`'s NFR40 eval set, inherited by construction via the shared `buildPrompt`. **No LLM call runs in the drift-engine / CLI unit suite** (design-spec NG6 — model-quality testing lives in the Action's eval harness). The `__tests__/token-efficiency.test.ts` suite is sub-second and dispatches no subagent.
142
-
143
- ### `scripts/measure-tokens.ts` — local iteration tool
144
-
145
- For local before/after token measurement without re-running the whole vitest suite, use the `tsx` script:
146
-
147
- ```bash
148
- # All fixtures in the corpus
149
- node --import tsx packages/drift-engine/scripts/measure-tokens.ts
150
-
151
- # A single fixture
152
- node --import tsx packages/drift-engine/scripts/measure-tokens.ts \
153
- packages/drift-engine/__tests__/fixtures/token-efficiency/case-01-doc-heavy/analysis-input.json
154
- ```
55
+ | Signal | Points |
56
+ |---|---|
57
+ | The doc itself appears in the diff | +20 |
58
+ | A code-file path from the diff appears in the section | +10 per file |
59
+ | An identifier from the diff appears in the section | +3 each, capped at +30 |
60
+ | A heading overlaps a diff identifier | +5 per heading |
155
61
 
156
- Output is one line per case: `<case-slug>: tokens off=<N1> on=<N2> ratio=<r.rr> Δ=<Δ%>`. The script uses the same `estimatePromptTokens(buildPrompt(...))` math as the CI gate in `token-efficiency.test.ts`, so the live number and the CI number agree by construction. The script is not wired into CI, has no assertions, and is not surfaced as a npm script — it is purely a developer-iteration aid. Errors (missing fixture, malformed JSON) print to stderr and exit non-zero.
62
+ A threshold of `5` keeps any section with a single file-path or heading match a safe default that typically cuts prompt size ~40% on doc-heavy inputs with no measurable recall loss. Omit `options` (or pass `0`) to keep every section.
157
63
 
158
- ### Source pointers
64
+ ## Runtime constraints
159
65
 
160
- - **PRD v6.7 NFR49** in `_bmad-output/planning-artifacts/prd.md` §"NFR49" normative target + parity-gate policy.
161
- - **Architecture ADR (2026-06-03)** in `_bmad-output/planning-artifacts/architecture.md` §"Token-Efficient Drift-Analysis Retrieval" — design rationale.
162
- - **Story P3.7.5** in `_bmad-output/implementation-artifacts/skill-p3-7-5-token-efficiency-measurement-parity-gate.md` — the harness story that ratified this policy.
66
+ The package is intentionally pure so it can run unchanged in CI and on a developer's laptop:
163
67
 
164
- ## Runtime constraints (lint-enforced)
68
+ - **No I/O** — never reads files, never touches the network.
69
+ - **No LLM client** — never imports an Anthropic, OpenAI, or LangChain SDK. It builds the prompt and validates the response; *calling* the model is the caller's job.
70
+ - **No environment reads** — pure functions of explicit arguments. Same input → byte-identical output, every time.
165
71
 
166
- The package's `eslint.config.js` rules forbid imports that would compromise its pure-logic posture:
72
+ Runtime dependencies are exactly two, both pure CPU: [`zod`](https://www.npmjs.com/package/zod) (schema validation) and [`picomatch`](https://www.npmjs.com/package/picomatch) (glob matching).
167
73
 
168
- - **No I/O** — no `fs`, `child_process`, `http`, `https`, `node:fs`, etc.
169
- - **No LLM client** — no `@anthropic-ai/sdk`, `openai`, `@langchain/*`.
170
- - **No env-var reads** — no `process.env`. Pure functions of explicit arguments.
74
+ ## License
171
75
 
172
- Runtime deps: `zod` + `picomatch` (both pure CPU — no I/O, no network, no env). DevDeps: `vitest`, `@types/node`, `typescript`. Adding anything else is a regression.
76
+ [Apache-2.0](https://github.com/Legends-of-Tech/delfini/blob/main/LICENSE)
@@ -1,5 +1,5 @@
1
1
  /** Why a path or hunk was dropped. */
2
- export type DropReason = 'lockfile' | 'generated' | 'vendored' | 'fixture' | 'whitespace-only' | 'import-only';
2
+ export type DropReason = 'lockfile' | 'generated' | 'vendored' | 'fixture' | 'whitespace-only' | 'import-only' | 'ignored';
3
3
  export interface DroppedPath {
4
4
  path: string;
5
5
  reason: DropReason;
@@ -17,6 +17,25 @@ export interface FilterDiffResult {
17
17
  /** Individual hunks dropped from otherwise-kept files. */
18
18
  droppedHunks: DroppedHunk[];
19
19
  }
20
+ /** Options controlling which filtering passes `filterDiff` applies. */
21
+ export interface FilterDiffOptions {
22
+ /**
23
+ * Apply the built-in noise classifiers (lockfile/generated/vendored/fixture
24
+ * path-level + whitespace-only/import-only hunk-level). Defaults to `true`
25
+ * so the legacy single-arg call `filterDiff(diff)` is byte-identical to the
26
+ * pre-options behaviour (the `enableDiffPreFilter` consumer path). Pass
27
+ * `false` to run an ignore-only pass that leaves all non-ignored files
28
+ * verbatim.
29
+ */
30
+ builtins?: boolean;
31
+ /**
32
+ * User `ignore_code_scope` entries (repo-relative; picomatch@4 dialect via
33
+ * the shared `isFileInDocScope` predicate). A changed file matching any
34
+ * entry is dropped whole with reason `'ignored'`, classified BEFORE the
35
+ * built-ins. Empty / omitted → no ignore dropping (observably no-op).
36
+ */
37
+ ignorePaths?: string[];
38
+ }
20
39
  /**
21
40
  * Filter a unified-diff string deterministically.
22
41
  *
@@ -28,6 +47,11 @@ export interface FilterDiffResult {
28
47
  * not lose surrounding context.
29
48
  *
30
49
  * Identical input → identical output (NFR46 reproducibility carries forward).
50
+ *
51
+ * `options.builtins` (default `true`) gates the built-in noise classifiers;
52
+ * `options.ignorePaths` adds user `ignore_code_scope` dropping on top. With
53
+ * the default options (`{ builtins: true, ignorePaths: [] }`) the output is
54
+ * byte-identical to the legacy single-arg `filterDiff(diff)`.
31
55
  */
32
- export declare function filterDiff(diff: string): FilterDiffResult;
56
+ export declare function filterDiff(diff: string, options?: FilterDiffOptions): FilterDiffResult;
33
57
  //# sourceMappingURL=diff-filter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"diff-filter.d.ts","sourceRoot":"","sources":["../src/diff-filter.ts"],"names":[],"mappings":"AAsBA,sCAAsC;AACtC,MAAM,MAAM,UAAU,GAClB,UAAU,GACV,WAAW,GACX,UAAU,GACV,SAAS,GACT,iBAAiB,GACjB,aAAa,CAAA;AAEjB,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,UAAU,CAAA;CACnB;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,UAAU,CAAA;CACnB;AAED,MAAM,WAAW,gBAAgB;IAC/B,+DAA+D;IAC/D,QAAQ,EAAE,MAAM,CAAA;IAChB,uCAAuC;IACvC,YAAY,EAAE,WAAW,EAAE,CAAA;IAC3B,0DAA0D;IAC1D,YAAY,EAAE,WAAW,EAAE,CAAA;CAC5B;AAID;;;;;;;;;;;GAWG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,CA0DzD"}
1
+ {"version":3,"file":"diff-filter.d.ts","sourceRoot":"","sources":["../src/diff-filter.ts"],"names":[],"mappings":"AAgCA,sCAAsC;AACtC,MAAM,MAAM,UAAU,GAClB,UAAU,GACV,WAAW,GACX,UAAU,GACV,SAAS,GACT,iBAAiB,GACjB,aAAa,GAGb,SAAS,CAAA;AAEb,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,UAAU,CAAA;CACnB;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,UAAU,CAAA;CACnB;AAED,MAAM,WAAW,gBAAgB;IAC/B,+DAA+D;IAC/D,QAAQ,EAAE,MAAM,CAAA;IAChB,uCAAuC;IACvC,YAAY,EAAE,WAAW,EAAE,CAAA;IAC3B,0DAA0D;IAC1D,YAAY,EAAE,WAAW,EAAE,CAAA;CAC5B;AAED,uEAAuE;AACvE,MAAM,WAAW,iBAAiB;IAChC;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;CACvB;AAID;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB,GAAG,gBAAgB,CAgF1F"}
@@ -8,8 +8,16 @@
8
8
  // Pure-logic — no I/O, no clock, no randomness, no new runtime dep. ESLint
9
9
  // `no-restricted-imports` on packages/drift-engine/src/**/*.ts forbids fs /
10
10
  // child_process / http / https / @anthropic-ai/sdk / openai / @langchain/* /
11
- // process.env. Path classification uses hand-written predicates NO
12
- // `picomatch` (Story Dev Notes §"Path classification predicates").
11
+ // process.env. The BUILT-IN noise classifiers (lockfile/generated/vendored/
12
+ // fixture) use hand-written predicates — NO `picomatch` (Story Dev Notes
13
+ // §"Path classification predicates").
14
+ //
15
+ // ignore_code_scope (user-configurable ignore paths) is the ONE place this
16
+ // module reaches for picomatch — via the shared `isFileInDocScope` predicate
17
+ // (sibling module, same package, no new external dep). User globs MUST use the
18
+ // same picomatch@4 dialect as the CLI config + the Action array-filter so a
19
+ // file the Skill ignores is the file the Action ignores (ADR-2026-06-01
20
+ // dialect parity). The hand-written built-ins above are unrelated and stay.
13
21
  //
14
22
  // Exposed via `index.ts` (unlike the P3.7.1 relevance internals, which run
15
23
  // INSIDE `buildPrompt`). The gate for this filter lives at the CONSUMER —
@@ -19,6 +27,7 @@
19
27
  // `@delfini/drift-engine/src/...` imports). The default consumer path never
20
28
  // invokes this module, so `buildPrompt` output stays byte-identical and the
21
29
  // NFR44 snapshot gate stays green (NFR49(b) parity discipline).
30
+ import { isFileInDocScope } from './doc-scope.js';
22
31
  // -- Public entry point ------------------------------------------------------
23
32
  /**
24
33
  * Filter a unified-diff string deterministically.
@@ -31,8 +40,16 @@
31
40
  * not lose surrounding context.
32
41
  *
33
42
  * Identical input → identical output (NFR46 reproducibility carries forward).
43
+ *
44
+ * `options.builtins` (default `true`) gates the built-in noise classifiers;
45
+ * `options.ignorePaths` adds user `ignore_code_scope` dropping on top. With
46
+ * the default options (`{ builtins: true, ignorePaths: [] }`) the output is
47
+ * byte-identical to the legacy single-arg `filterDiff(diff)`.
34
48
  */
35
- export function filterDiff(diff) {
49
+ export function filterDiff(diff, options = {}) {
50
+ const builtins = options.builtins ?? true;
51
+ const ignorePaths = options.ignorePaths ?? [];
52
+ const hasIgnore = ignorePaths.length > 0;
36
53
  const droppedPaths = [];
37
54
  const droppedHunks = [];
38
55
  const files = parseDiffIntoFiles(diff);
@@ -41,6 +58,22 @@ export function filterDiff(diff) {
41
58
  keptParts.push(files.preamble);
42
59
  }
43
60
  for (const file of files.files) {
61
+ // ignore_code_scope wins over everything — the dev explicitly told Delfini
62
+ // this code path is out of bounds for drift, so it is dropped whole and
63
+ // reported as 'ignored' regardless of whether the built-ins would also have
64
+ // matched it. Shared picomatch@4 predicate → parity with the CLI config and
65
+ // the Action's array-filter.
66
+ if (hasIgnore && isFileInDocScope(file.path, ignorePaths)) {
67
+ droppedPaths.push({ path: file.path, reason: 'ignored' });
68
+ continue;
69
+ }
70
+ // Built-ins off (ignore-only pass): a non-ignored file passes through
71
+ // verbatim — no path-level or hunk-level noise dropping. Byte-fidelity via
72
+ // the original slice.
73
+ if (!builtins) {
74
+ keptParts.push(file.rawSlice);
75
+ continue;
76
+ }
44
77
  // Path-level drops — classified first, in priority order. Lockfiles win
45
78
  // over generated/vendored/fixture since the canonical lockfile names
46
79
  // never overlap those patterns in practice.
package/dist/index.d.ts CHANGED
@@ -6,6 +6,6 @@ export { normalizeDocScope, validateDocScopeEntry, classifyEntry, isFileInDocSco
6
6
  export { filterDiff } from './diff-filter.js';
7
7
  export { rankedFillSections } from './relevance.js';
8
8
  export type { AnalysisInput, AnalysisResult, DocFile, Contradiction, Addition, ClarifyingQuestion, PRMetadata, Severity, BuildPromptOptions, } from './types.js';
9
- export type { DropReason, DroppedPath, DroppedHunk, FilterDiffResult, } from './diff-filter.js';
9
+ export type { DropReason, DroppedPath, DroppedHunk, FilterDiffResult, FilterDiffOptions, } from './diff-filter.js';
10
10
  export type { DocSection, DroppedSection, RankedFillCandidate, RankedFillResult, } from './relevance.js';
11
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA0BA,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAI5C,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACrB,aAAa,EACb,gBAAgB,GACjB,MAAM,gBAAgB,CAAA;AAOvB,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAS7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AAEnD,YAAY,EACV,aAAa,EACb,cAAc,EACd,OAAO,EACP,aAAa,EACb,QAAQ,EACR,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,kBAAkB,GACnB,MAAM,YAAY,CAAA;AAEnB,YAAY,EACV,UAAU,EACV,WAAW,EACX,WAAW,EACX,gBAAgB,GACjB,MAAM,kBAAkB,CAAA;AAEzB,YAAY,EACV,UAAU,EACV,cAAc,EACd,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,gBAAgB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA0BA,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAI5C,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACrB,aAAa,EACb,gBAAgB,GACjB,MAAM,gBAAgB,CAAA;AAOvB,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAS7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AAEnD,YAAY,EACV,aAAa,EACb,cAAc,EACd,OAAO,EACP,aAAa,EACb,QAAQ,EACR,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,kBAAkB,GACnB,MAAM,YAAY,CAAA;AAEnB,YAAY,EACV,UAAU,EACV,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,kBAAkB,CAAA;AAEzB,YAAY,EACV,UAAU,EACV,cAAc,EACd,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,gBAAgB,CAAA"}
package/package.json CHANGED
@@ -1,8 +1,13 @@
1
1
  {
2
2
  "name": "@delfini/drift-engine",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Legends-of-Tech/delfini.git",
9
+ "directory": "packages/drift-engine"
10
+ },
6
11
  "publishConfig": {
7
12
  "access": "public"
8
13
  },