ds4-context-engine 0.1.2 → 0.2.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,7 +16,7 @@ bounded active context with provenance
16
16
  Pi provider
17
17
  ```
18
18
 
19
- > **Project status:** M0–M13 are implemented. The Pi adapter and standalone `ds4-context-core` package are version `0.1.2`; the adapter targets Pi `0.84.3`.
19
+ > **Project status:** M0–M20 are implemented on `main`. Prerelease `0.2.0-beta.2` includes M14–M20: quality measurement, structural/hybrid retrieval, cross-session project memory, learned-ranking shadow evaluation, the runtime adapter kit, and opt-in local KV reuse. Stable `0.1.2` remains available; all lines target Pi `0.84.3`.
20
20
 
21
21
  ## Why DS4
22
22
 
@@ -27,13 +27,19 @@ It provides:
27
27
  - deterministic token budgeting with soft and hard input limits;
28
28
  - preservation of the current request, recent turns and atomic tool call/result groups;
29
29
  - exact and FTS5 historical retrieval with source provenance;
30
- - trust-gated project indexing, Git-aware invalidation and bounded source snippets;
30
+ - opt-in hybrid semantic retrieval with a deterministic local embedding and lexical fallback;
31
+ - trust-gated structural project indexing, Git-aware invalidation and bounded source snippets;
31
32
  - hierarchical, validated, non-destructive compaction summaries;
32
33
  - persistent pins and append-only durable memory stored canonically in Pi JSONL;
34
+ - opt-in checkpointed project-memory replay across exact trusted Pi project sessions;
33
35
  - content-addressed storage and bounded references for large tool results;
34
36
  - privacy classifications, secret redaction and provider-specific allow rules;
35
37
  - model-specific calibration and adaptive context allocation;
36
38
  - optional verified continuation for eligible OpenAI Responses profiles;
39
+ - opt-in metadata-only context-quality metrics and deterministic replay comparisons;
40
+ - checksummed metadata-only learned ranking with shadow mode, canonical classified feedback and static fallback;
41
+ - a versioned runtime adapter contract, reusable conformance kit and non-Pi callback/JSONL reference adapter;
42
+ - opt-in exact-prefix local KV reuse for capable local runtime adapters, with volatile handles and full-replay fallback;
37
43
  - an inspectable Context Manifest explaining included and excluded material;
38
44
  - fail-open recovery to Pi's native context path for operational failures.
39
45
 
@@ -74,12 +80,20 @@ pi -e git:github.com/Alucard24/ds4-context-engine
74
80
 
75
81
  ### From npm
76
82
 
77
- Install the public npm package with:
83
+ Install the latest stable public npm package with:
78
84
 
79
85
  ```bash
80
86
  pi install npm:ds4-context-engine
81
87
  ```
82
88
 
89
+ Install the opt-in 0.2 prerelease from the `beta` dist-tag with:
90
+
91
+ ```bash
92
+ pi install npm:ds4-context-engine@beta
93
+ ```
94
+
95
+ All prerelease packages (`ds4-context-engine`, `ds4-context-core`, and `ds4-context-reference-adapter`) use the same exact version.
96
+
83
97
  ### Local checkout
84
98
 
85
99
  ```bash
@@ -106,6 +120,7 @@ After loading the extension, inspect its state:
106
120
 
107
121
  ```text
108
122
  /context status
123
+ /context adapter
109
124
  /context tokens
110
125
  /context health
111
126
  ```
@@ -149,6 +164,7 @@ Project configuration and project source indexing are disabled when Pi reports t
149
164
  | Command | Purpose |
150
165
  | --- | --- |
151
166
  | `/context` or `/context status` | Runtime, session, planner and subsystem status |
167
+ | `/context adapter` | Runtime contract and per-capability negotiation diagnostics |
152
168
  | `/context tokens` | Token budget and active-context composition |
153
169
  | `/context manifest` | Latest Context Manifest |
154
170
  | `/context explain` | Human-readable planning explanation |
@@ -159,6 +175,8 @@ Project configuration and project source indexing are disabled when Pi reports t
159
175
  | `/context project` | Project index and retrieval status |
160
176
  | `/context privacy` | Classification and provider-policy status |
161
177
  | `/context model` | Active model profile and calibration |
178
+ | `/context quality` | Metadata-only context-quality scores and sample counts |
179
+ | `/context ranking` | Learned model, promotion gate, aggregate shadow comparison and feedback counts |
162
180
  | `/context continuation` | Native continuation decisions and counters |
163
181
  | `/context artifacts` | Artifact storage and integrity status |
164
182
  | `/context compaction` | Last compaction status |
@@ -179,10 +197,22 @@ Project configuration and project source indexing are disabled when Pi reports t
179
197
  /context memory supersede MEMORY_ID [--source ID,ID] <new claim>
180
198
  /context memory invalidate MEMORY_ID [reason]
181
199
  /context memory expire MEMORY_ID [reason]
200
+ /context memory sources
201
+ /context memory exclude SESSION_ID [reason]
202
+ /context memory include SESSION_ID
182
203
  ```
183
204
 
184
205
  Valid privacy classifications are `normal`, `internal`, `sensitive` and `local-only`.
185
206
 
207
+ Learned-ranking feedback and local training are explicit:
208
+
209
+ ```text
210
+ /context ranking feedback useful|irrelevant CANDIDATE_ID [--classification LEVEL]
211
+ /context ranking train
212
+ ```
213
+
214
+ See [`docs/LEARNED_RANKING.md`](docs/LEARNED_RANKING.md).
215
+
186
216
  ## Configuration reference
187
217
 
188
218
  The following example shows the main configuration groups. Omitted values use the defaults in [`packages/core/src/config/config.ts`](packages/core/src/config/config.ts).
@@ -208,7 +238,19 @@ The following example shows the main configuration groups. Omitted values use th
208
238
  "exact": true,
209
239
  "fts": true,
210
240
  "semantic": false,
211
- "maxResults": 12
241
+ "maxResults": 12,
242
+ "embedding": {
243
+ "mode": "local",
244
+ "provider": "ds4-local",
245
+ "model": "feature-hash-v1",
246
+ "dimensions": 256,
247
+ "remoteProfiles": [],
248
+ "maxSources": 50000,
249
+ "candidatePool": 80,
250
+ "batchSize": 64,
251
+ "queryCacheSize": 64,
252
+ "timeoutMs": 2000
253
+ }
212
254
  },
213
255
  "project": {
214
256
  "enabled": true,
@@ -221,6 +263,8 @@ The following example shows the main configuration groups. Omitted values use th
221
263
  },
222
264
  "memory": {
223
265
  "enabled": true,
266
+ "crossSession": false,
267
+ "maxProjectSessions": 250,
224
268
  "maxPinChars": 4000,
225
269
  "maxClaimChars": 2000,
226
270
  "maxResults": 12
@@ -271,13 +315,27 @@ The following example shows the main configuration groups. Omitted values use th
271
315
  "maxStateAgeMs": 1800000,
272
316
  "retryManagedReplay": true
273
317
  },
318
+ "quality": {
319
+ "enabled": false,
320
+ "maxSamples": 1000
321
+ },
322
+ "ranking": {
323
+ "mode": "off",
324
+ "modelPath": "ds4-context/ranking-model.json",
325
+ "minimumTrainingSamples": 20,
326
+ "maxTrainingSamples": 10000,
327
+ "maxLatencyMs": 10
328
+ },
274
329
  "diagnostics": {
275
330
  "storeContextManifest": true,
276
331
  "storeFullRenderedContext": false,
277
332
  "logLevel": "info"
278
333
  },
279
334
  "storage": {
280
- "databasePath": "ds4-context/context.db"
335
+ "databasePath": "ds4-context/context.db",
336
+ "busyTimeoutMs": 5000,
337
+ "writeRetryTimeoutMs": 30000,
338
+ "projectIndexLeaseMs": 120000
281
339
  }
282
340
  }
283
341
  ```
@@ -302,7 +360,9 @@ Native continuation is also disabled by default. Enabling it requires both expli
302
360
 
303
361
  Eligible OpenAI Responses requests then set `store: true`. Review the provider's retention policy before enabling this option. DS4 keeps response handles only in volatile memory, verifies exact managed prefixes before reuse and retries once with a full managed replay when recognized continuation state is stale.
304
362
 
305
- See [`docs/PRIVACY.md`](docs/PRIVACY.md) and [`docs/NATIVE_CONTINUATION.md`](docs/NATIVE_CONTINUATION.md).
363
+ Local KV reuse is separately disabled by default through `localKvReuse.enabled`. It also requires a local runtime adapter with a versioned `local-kv-reuse` capability and a volatile runtime port. Pi exposes no such handles and remains unsupported even if configuration is enabled.
364
+
365
+ See [`docs/PRIVACY.md`](docs/PRIVACY.md), [`docs/NATIVE_CONTINUATION.md`](docs/NATIVE_CONTINUATION.md), and [`docs/LOCAL_KV_REUSE.md`](docs/LOCAL_KV_REUSE.md).
306
366
 
307
367
  ## Storage and recovery
308
368
 
@@ -311,10 +371,11 @@ By default, derived state is stored below Pi's agent directory:
311
371
  ```text
312
372
  ~/.pi/agent/ds4-context/
313
373
  ├── context.db
374
+ ├── ranking-model.json
314
375
  └── artifacts/
315
376
  ```
316
377
 
317
- The database contains rebuildable indexes, summary metadata, manifests, project projections and calibration data. Canonical memory and pin mutations remain append-only entries in Pi JSONL. Project files remain canonical for project knowledge. Complete tool results remain in Pi JSONL while the artifact store keeps verified, content-addressed copies for bounded retrieval.
378
+ The database contains rebuildable indexes, summary metadata, manifests, project projections and calibration data. The optional checksummed learned-ranking model is also derived local state; its classified metadata-only labels remain canonical Pi custom entries. All Pi sessions share this WAL database: writes use bounded busy-aware transaction replay, and a renewable project lease prevents multiple Pi processes from indexing the same project concurrently. `busyTimeoutMs` controls each SQLite lock wait, while `writeRetryTimeoutMs` bounds the total replay window. Canonical memory and pin mutations remain append-only entries in Pi JSONL. Project files remain canonical for project knowledge. Complete tool results remain in Pi JSONL while the artifact store keeps verified, content-addressed copies for bounded retrieval.
318
379
 
319
380
  To validate or rebuild derived state:
320
381
 
@@ -323,32 +384,36 @@ To validate or rebuild derived state:
323
384
  /context rebuild-index
324
385
  ```
325
386
 
326
- Deleting DS4's database must not alter a Pi session or project, although derived indexes and calibration data will be regenerated.
387
+ Deleting DS4's database must not alter a Pi session or project, although derived indexes and calibration data will be regenerated. When `memory.crossSession` is enabled for a trusted project, DS4 discovers bounded sibling Pi JSONL files by exact canonical header identity, incrementally replays their explicit project mutations, and excludes missing or unverifiable sources.
327
388
 
328
389
  ## Development
329
390
 
330
391
  ```bash
331
392
  npm ci
332
393
  npm run build:core
394
+ npm run build:adapters
333
395
  npm run typecheck
334
396
  npm test
335
397
  npm run check
398
+ npm run quality:compare
336
399
  npm run pack:check
337
400
  npm pack --dry-run
338
401
  npm pack --dry-run --workspace ds4-context-core
402
+ npm pack --dry-run --workspace ds4-context-reference-adapter
339
403
  ```
340
404
 
341
- The test suite covers configuration, migrations, canonical JSONL projection, planning, atomic tool groups, retrieval, compaction, project knowledge, artifacts, memory, privacy, model awareness, continuation, the portable-core dependency boundary and Pi extension lifecycle behavior. The package check also builds both tarballs, installs them in a clean temporary consumer and starts the packaged extension with isolated Pi RPC state.
405
+ The test suite covers configuration, migrations, canonical JSONL projection, planning, atomic tool groups, retrieval, compaction, project knowledge, artifacts, memory, privacy, model awareness, continuation, local-KV eligibility/replay, runtime-adapter conformance, the portable-core dependency boundary and Pi extension lifecycle behavior. The package check builds all three tarballs, installs them in a clean temporary consumer, reruns compiled reference-adapter conformance and starts the packaged Pi extension with isolated RPC state.
342
406
 
343
407
  ### Portable core
344
408
 
345
- `ds4-context-core` is a compiled ESM package with no Pi dependency. It owns runtime-neutral policy, storage and projections; agent adapters translate native sessions and lifecycle hooks at the boundary. The root `ds4-context-engine` package is the Pi adapter and depends one-way on the core workspace.
409
+ `ds4-context-core` is a compiled ESM package with no runtime SDK dependency. It owns runtime-neutral policy, storage, adapter contracts and projections; agent adapters translate native sessions and lifecycle hooks at the boundary. The root `ds4-context-engine` package is the Pi adapter. `ds4-context-reference-adapter` is a separately compiled non-Pi callback/JSONL implementation. Both depend one-way and exactly on matching core.
346
410
 
347
411
  ### Repository layout
348
412
 
349
413
  ```text
350
- packages/core/src portable policy, planning, compaction, retrieval and storage
351
- src/pi-adapter Pi JSONL projection, summary completion and provider integration
414
+ packages/core/src portable policy, adapter kit, planning, retrieval and storage
415
+ packages/reference-adapter/src non-Pi callback/JSONL reference runtime boundary
416
+ src/pi-adapter Pi JSONL projection, summary completion and provider integration
352
417
  src/extension Pi hooks, commands and fail-open orchestration
353
418
  tests core contract, unit, integration, golden and benchmark coverage
354
419
  scripts package and release-readiness checks
@@ -359,10 +424,13 @@ scripts package and release-readiness checks
359
424
 
360
425
  - [Architecture](docs/ARCHITECTURE.md)
361
426
  - [Context planner](docs/CONTEXT_PLANNER.md)
427
+ - [Context quality](docs/CONTEXT_QUALITY.md)
428
+ - [Learned ranking](docs/LEARNED_RANKING.md)
362
429
  - [Context Manifest](docs/CONTEXT_MANIFEST.md)
363
430
  - [Compaction](docs/COMPACTION.md)
364
431
  - [Summary graph](docs/SUMMARY_GRAPH.md)
365
432
  - [Historical retrieval](docs/RETRIEVAL.md)
433
+ - [Hybrid semantic retrieval](docs/HYBRID_RETRIEVAL.md)
366
434
  - [Project knowledge](docs/PROJECT_KNOWLEDGE.md)
367
435
  - [Artifacts](docs/ARTIFACTS.md)
368
436
  - [Memory and pins](docs/MEMORY_AND_PINS.md)
@@ -370,6 +438,8 @@ scripts package and release-readiness checks
370
438
  - [Model awareness](docs/MODEL_AWARENESS.md)
371
439
  - [Native continuation](docs/NATIVE_CONTINUATION.md)
372
440
  - [Portable core](docs/PORTABLE_CORE.md)
441
+ - [Runtime adapter kit](docs/RUNTIME_ADAPTER_KIT.md)
442
+ - [Local KV reuse](docs/LOCAL_KV_REUSE.md)
373
443
  - [Storage](docs/STORAGE.md)
374
444
  - [Roadmap 0.2.0](docs/ROADMAP_0.2.0.md)
375
445
  - [Release process](docs/RELEASING.md)
@@ -378,9 +448,9 @@ scripts package and release-readiness checks
378
448
 
379
449
  ## Roadmap
380
450
 
381
- The original M0–M13 roadmap is complete. `ds4-context-core` now contains the compiled Pi-independent implementation, while runtime-specific behavior remains in the Pi adapter.
451
+ The original M0–M13 roadmap is complete. `ds4-context-core` contains the compiled runtime-neutral implementation. M14 context-quality metrics, M15 rich symbol indexing, M16 hybrid semantic retrieval, M17 cross-session project memory, M18 learned-ranking shadow evaluation, M19's runtime adapter/conformance kit, and M20 opt-in local KV eligibility/replay are implemented on `main`. Learned active ranking remains promotion-gated, Pi reports local KV as unsupported, and static ranking/native completion stay authoritative on every failure.
382
452
 
383
- The planned [0.2.0 roadmap](docs/ROADMAP_0.2.0.md) covers context-quality metrics, richer symbol indexing, hybrid semantic retrieval, cross-session project memory, optional learned ranking, a runtime adapter kit with one reference adapter, and optional local KV reuse. Sensitive or transport-specific behavior remains opt-in, and the 0.1 lexical planner stays available as the deterministic fallback.
453
+ The [0.2.0 roadmap](docs/ROADMAP_0.2.0.md) now proceeds to release-candidate hardening. Sensitive or transport-specific behavior remains opt-in, and the 0.1 lexical planner stays available as the deterministic fallback.
384
454
 
385
455
  ## Contributing
386
456
 
@@ -9,7 +9,12 @@ Pi session_start
9
9
  -> validate Pi JSONL v3 header
10
10
  -> full index or checkpointed append sync
11
11
  -> replay versioned memory/pin custom-entry mutations into transactional projections
12
+ -> when opted in and trusted, checkpoint/replay explicit project mutations from exact-identity sibling Pi sessions
12
13
  -> if trusted, canonicalize project root and incrementally index bounded text files
14
+ -> parse TypeScript/JavaScript/Python/Go declaration boundaries through the runtime-neutral parser interface
15
+ -> fall back deterministically to bounded text windows when adapters, syntax, or language support are unavailable
16
+ -> persist only rebuildable symbol/signature/parent/import/reference projections
17
+ -> when semantic retrieval is opted in, refresh source-hash/model-keyed vectors through the runtime embedding port
13
18
  -> snapshot Git root/branch/HEAD/dirty paths
14
19
 
15
20
  Pi context hook
@@ -30,16 +35,22 @@ Pi context hook
30
35
  -> select a contiguous, model-adaptive recent tail
31
36
  -> derive current-task identifiers, files, errors, phrases and keywords
32
37
  -> query exact matches and FTS5 over canonical indexed entries
38
+ -> optionally add bounded cosine-ranked history candidates and deterministic lexical/vector rank fusion
33
39
  -> reject active-context duplicates and all alternate-branch candidates
34
40
  -> rank, deduplicate, quote and budget historical evidence groups
35
- -> query exact path/symbol/phrase and project FTS5 candidates
36
- -> live-validate candidate SHA-256 and reindex changed files
41
+ -> query exact literal path and qualified/simple declaration indexes ahead of phrase and project FTS5 candidates
42
+ -> optionally add bounded project vectors while retaining exact path/symbol priority
43
+ -> live-validate candidate SHA-256 and reindex only changed-file projections
37
44
  -> rank, overlap-deduplicate, quote and budget project source groups
38
45
  -> omit prohibited history/project/pin/memory supplements with metadata-only privacy reasons
39
46
  -> fit active Pi summaries in the remaining budget
40
47
  -> validate hard limit, current request, and tool call/results
41
48
  -> return selected messages or fail open to the already privacy-sanitized native context
42
49
  -> persist metadata-only Context Manifest, privacy counters, and prompt hash
50
+ -> when opted in, queue the completed metadata-only manifest for deferred quality measurement
51
+
52
+ Pi agent_settled / shutdown
53
+ -> materialize and persist bounded content-free quality counts without changing the plan
43
54
 
44
55
  before_provider_request
45
56
  -> recheck provider-specific serialized system/messages/tools/content
@@ -55,6 +66,15 @@ optional OpenAI Responses provider wrapper
55
66
  -> retry a rejected stale handle once through the complete managed replay before exposing stream events
56
67
  -> record metadata-only mode/item counts/retry/invalidation diagnostics; never record the provider handle
57
68
 
69
+ optional local runtime KV port (non-Pi adapters)
70
+ -> require opt-in configuration plus a negotiated versioned local-KV capability
71
+ -> apply current privacy policy before runtime-specific prefix/options extraction
72
+ -> hash exact prefix bytes, provider/model/revision, options, privacy policy, runtime revision and capability version
73
+ -> let the runtime port map only the fingerprint to its volatile native handle
74
+ -> replay the complete sanitized payload after miss, stale rejection, unavailable state or runtime restart
75
+ -> report aggregate hits/misses/saved-prefill/replay latency separately from context occupancy
76
+ -> never place handles, prefixes or payloads in canonical history, manifests, SQLite or diagnostics
77
+
58
78
  assistant message_end
59
79
  -> attach uncached input plus cache read/write usage to the pending manifest
60
80
  -> append one exact provider/model calibration sample
@@ -109,10 +129,10 @@ session_tree / shutdown
109
129
  -> immutable graph nodes, ordered edges, roots, levels and current-branch active path
110
130
 
111
131
  /context retrieved
112
- -> query terms, candidate counts, branch blocks, budget decisions and injected excerpts
132
+ -> query terms, lexical/vector/fused counts, embedding profile/freshness/fallback, branch blocks, budgets and excerpts
113
133
 
114
134
  /context project
115
- -> trust, Git revision, file/snippet/stale counts, retrieval decisions and local excerpts
135
+ -> trust, Git revision, file/snippet/stale/vector counts, retrieval decisions and local excerpts
116
136
 
117
137
  /context pins | pin | unpin
118
138
  -> inspect or append immutable session/branch/project pin mutations
@@ -141,16 +161,18 @@ session_tree / shutdown
141
161
  Dependency direction is one-way:
142
162
 
143
163
  ```text
144
- Pi native types and lifecycle
145
- ↓
146
- ds4-context-engine (src/pi-adapter + src/extension)
147
- ↓
148
- ds4-context-core (packages/core)
164
+ Pi native types and lifecycle callback/JSONL runtime
165
+ ↓ ↓
166
+ ds4-context-engine ds4-context-reference-adapter
167
+ └──────────────────────┬───────────────────────┘
168
+ ↓
169
+ ds4-context-core (packages/core)
149
170
  ```
150
171
 
151
172
  `ds4-context-core` is compiled ESM and has no dependency on Pi. Its workspace contains:
152
173
 
153
- - `packages/core/src/core`: portable model profiles, robust calibration, adaptive category limits, budgets and token-estimation policy;
174
+ - `packages/core/src/adapter`: versioned runtime contract, canonical tool-group validation, isolated capability negotiation, exact local-KV eligibility/replay orchestration and framework-neutral conformance runner;
175
+ - `packages/core/src/core`: portable canonical messages, model profiles, robust calibration, adaptive category limits, budgets and token-estimation policy;
154
176
  - `packages/core/src/continuation`: hashed-prefix continuation decisions without provider transport or response APIs;
155
177
  - `packages/core/src/config`: runtime-neutral configuration model and filesystem loader;
156
178
  - `packages/core/src/planner`: atomic grouping, deterministic ranking, fitting, validation and privacy-aware plans;
@@ -158,21 +180,25 @@ ds4-context-core (packages/core)
158
180
  - `packages/core/src/memory`: mutation projections, conservative contradiction/key detection, scope selection, prompt boundaries, ranking and diagnostics;
159
181
  - `packages/core/src/artifacts`: atomic content-addressed files, deterministic condensation, redaction, branch-safe literal search, reconciliation and garbage collection;
160
182
  - `packages/core/src/compaction`: structured summary contract, hierarchical graph model, validation, lifecycle metadata and source hashing;
161
- - `packages/core/src/retrieval`: task descriptors, safe FTS queries, deterministic ranking, evidence quoting, deduplication and token fitting;
183
+ - `packages/core/src/retrieval`: task descriptors, safe FTS queries, runtime-neutral embedding port, semantic index orchestration, deterministic rank fusion, evidence quoting, quality comparison, deduplication and token fitting;
162
184
  - `packages/core/src/project`: trust-gated file discovery, hashing, Git state, symbol/chunk extraction, invalidation, retrieval and source quoting;
163
- - `packages/core/src/persistence`: rebuildable session/project/memory/pin SQLite state, repositories, FTS5, event replay and transactional migrations;
185
+ - `packages/core/src/quality`: versioned replay fixtures/contracts, deterministic metrics, static/candidate comparison and metadata-only aggregation;
186
+ - `packages/core/src/ranking`: bounded metadata-only features, classified label contracts, deterministic local training, checksummed model artifacts, aggregate shadow comparison and promotion-gated inference;
187
+ - `packages/core/src/persistence`: rebuildable session/project/vector/memory/pin/quality SQLite state, repositories, FTS5, event replay and transactional migrations;
164
188
  - `packages/core/src/manifest` and `packages/core/src/shared`: runtime-neutral projections, provenance, hashing, stable serialization and logging.
165
189
 
190
+ The `packages/reference-adapter` workspace is the non-Pi reference adapter: it reads bounded append-only canonical JSONL, injects completion through a host callback, enforces privacy at that callback boundary, rebuilds disposable snapshots and explicitly disables unsupported native features. A local host can inject a handle-free `LocalKvRuntimePort`; the port alone retains native handles and transport while core receives only exact prefix bytes transiently for hashing.
191
+
166
192
  The root `ds4-context-engine` package is the Pi adapter:
167
193
 
168
- - `src/pi-adapter`: byte-safe Pi JSONL reading, provenance mapping, custom mutation projection, active label discovery, checkpoints, runtime snapshots, Pi model completion for summaries and the narrow Pi-AI OpenAI Responses transport wrapper;
194
+ - `src/pi-adapter`: byte-safe Pi JSONL reading, provenance mapping, memory/pin and learned-ranking label projection, active label discovery, checkpoints, runtime snapshots, Pi model completion for summaries and the narrow Pi-AI OpenAI Responses transport wrapper;
169
195
  - `src/extension`: Pi hooks, lifecycle, command presentation and fail-open/fail-closed orchestration.
170
196
 
171
- The adapter may import core exports. Core source must never import `@earendil-works/pi-ai`, `@earendil-works/pi-coding-agent`, `src/pi-adapter` or `src/extension`; an automated boundary test enforces this rule.
197
+ Adapters may import core exports. Core source must never import `@earendil-works/pi-ai`, `@earendil-works/pi-coding-agent`, `src/pi-adapter`, `src/extension` or a reference-adapter source path; an automated boundary test enforces this rule. Runtime SDK dependencies belong only to their adapter package.
172
198
 
173
199
  ## Canonical and derived state
174
200
 
175
- The Pi session JSONL remains canonical for conversation/tool state, inline classification markers, and append-only classified memory/pin custom mutations; live files remain canonical for project knowledge. Native continuation keeps only volatile request/response-item hashes plus the minimum response handle and creates no continuation table or custom entry. SQLite and content-addressed object files store only rebuildable indexes, summary nodes/edges, metadata-only manifests, project file/snippet projections, artifact copies/references, materialized memory/pins, and calibration data. Each aggregate's active text is the Pi compaction summary; non-active nodes created by the same operation are embedded in its details, while older ancestors remain in earlier entries. Deleting the database must never damage or alter a Pi session or project. Reopening a source session replays its memory/pin mutations. Ephemeral sessions keep manifests and graph nodes in memory, disable durable memory/pins/artifacts, and may share the project index because files—not session JSONL—are its durable source.
201
+ The Pi session JSONL remains canonical for conversation/tool state, inline classification markers, append-only classified memory/pin mutations and metadata-only learned-ranking feedback/replay labels; live files remain canonical for project knowledge. Native continuation keeps only volatile request/response-item hashes plus the minimum response handle and creates no continuation table or custom entry. SQLite and content-addressed object files store only rebuildable indexes, source-hash/model-keyed vectors, summary nodes/edges, metadata-only manifests, project file/snippet projections, artifact copies/references, materialized memory/pins, calibration data, and bounded metadata-only quality samples. The checksummed learned-ranking model is a separate disposable local artifact reconstructed from canonical labels; it contains bounded weights and aggregate gate metadata, never raw text. Each aggregate's active text is the Pi compaction summary; non-active nodes created by the same operation are embedded in its details, while older ancestors remain in earlier entries. Deleting the database must never damage or alter a Pi session or project. Reopening a source session replays its memory/pin mutations. Ephemeral sessions keep manifests and graph nodes in memory, disable durable memory/pins/artifacts, and may share the project index because files—not session JSONL—are its durable source.
176
202
 
177
203
  ## Lifecycle
178
204
 
@@ -195,6 +221,6 @@ Database settings:
195
221
 
196
222
  ## Failure policy
197
223
 
198
- Configuration, database, session/project indexing, memory/pin replay, artifact offload/search, retrieval, planning, observer, native continuation, and diagnostics failures are caught at the extension boundary. Session index failures retain the previous transactional snapshot. Historical and project FTS errors degrade to exact matches; project subsystem failure contributes no snippets without disabling session management. Expected planning hazards produce an explicit fallback manifest and discard synthetic evidence.
224
+ Configuration, database, session/project indexing, memory/pin replay, artifact offload/search, retrieval, planning, observer, native continuation, quality measurement, and diagnostics failures are caught at the extension boundary. Session index failures retain the previous transactional snapshot. Cross-session source failures exclude only the unverifiable source and retain explicit diagnostics; they do not disable current-session memory. Historical and project FTS errors degrade to exact matches; embedding consent/privacy/model/timeout/corruption/provider failures degrade to lexical results; project subsystem failure contributes no snippets without disabling session management. Expected planning hazards produce an explicit fallback manifest and discard synthetic evidence.
199
225
 
200
226
  Privacy is the exception to ordinary fail-open behavior. Once enabled, planner failures return the sanitized native array, preparation failures replace message content with structural placeholders, and provider-payload sanitizer failures return an empty object so the remote request fails rather than receiving unchecked content. Pi 0.84.3 runs provider-payload handlers in extension load order, so DS4 should be loaded last when other extensions can rewrite provider payloads.
@@ -20,13 +20,14 @@ A Context Manifest explains the context visible at DS4's Pi `context` hook witho
20
20
  - artifact IDs, SHA-256, bytes, MIME, classification, exact source entry/tool IDs, error state, and before/after token estimates;
21
21
  - provider destination and allow-set names, selected classification counts, blocked/excluded/redacted counts, final provider-check count, and enforcement stage;
22
22
  - planner mode/version, original and selected counts, group counts, internal budgets, duration, and fallback reason;
23
+ - learned-ranking mode/status, feature/model versions, candidate count, aggregate disagreement/rank shift, duration, and generic static-fallback reason;
23
24
  - planner and policy versions;
24
25
  - deterministic SHA-256 over system prompt, active tools, and messages;
25
26
  - Pi's reported context usage when available;
26
27
  - finalized uncached input, cache-read, cache-write, total provider input, and cache shares when available;
27
28
  - optional native-continuation eligibility, storage-consent state, request mode, full/sent/omitted input-item counts, state age, generic fallback/invalidation reason, and managed-replay retry outcome.
28
29
 
29
- The manifest does **not** contain system instructions, message text, classified spans, pin content, memory claims, project snippets, artifact content/excerpts, tool arguments/results, image data, provider payloads, provider response/conversation IDs, API keys, or headers.
30
+ The manifest does **not** contain system instructions, message text, classified spans, pin content, memory claims, project snippets, artifact content/excerpts, learned-ranking feature vectors/labels/candidate IDs/model weights, local-KV prefixes/fingerprints/handles, tool arguments/results, image data, provider payloads, provider response/conversation IDs, API keys, or headers. Local-KV hit/miss/prefill counters are volatile adapter diagnostics and are not copied into Pi manifests.
30
31
 
31
32
  ## Provenance mapping
32
33
 
@@ -62,6 +63,7 @@ Use:
62
63
  /context pins
63
64
  /context memory
64
65
  /context privacy
66
+ /context ranking
65
67
  /context continuation
66
68
  /context artifacts
67
69
  ```
@@ -76,6 +76,14 @@ With privacy disabled, DS4 returns Pi's original `AgentMessage[]` when:
76
76
 
77
77
  Expected fallbacks are recorded in the Context Manifest. With privacy enabled, the fallback baseline is the sanitized native array—not raw Pi messages—and an unexpected privacy failure replaces content/payload fields instead of sending unchecked data. Observer mode disables planning but still enforces enabled privacy policy and records manifests/usage calibration.
78
78
 
79
+ ## Quality measurement
80
+
81
+ M14 can queue the finalized manifest after planning when `quality.enabled` is true; materialization runs after `agent_settled`, outside provider planning latency. It records only counts, ratios, normalized reason codes, budget utilization and separate timing; it does not inspect or persist message/evidence text and cannot alter the active selection. Live samples remain unlabeled for evidence recall. The versioned synthetic replay corpus supplies expected source IDs for deterministic baseline/candidate comparisons. Any quality failure is isolated and the 0.1 plan remains active. See [`CONTEXT_QUALITY.md`](CONTEXT_QUALITY.md).
82
+
83
+ ## Learned ranking
84
+
85
+ M18 can evaluate bounded metadata-only features after privacy exclusion and before supplemental candidates enter category fitting. `shadow` keeps every static score/order authoritative and records aggregate disagreement only. `active` is accepted only for a compatible checksummed model carrying an eligible held-out promotion report. Privacy exclusions, mandatory pins/current turns, atomic groups and hard budgets cannot be overridden. See [`LEARNED_RANKING.md`](LEARNED_RANKING.md).
86
+
79
87
  ## Current limits
80
88
 
81
- The planner does not call a model inside the `context` hook. Model calibration uses only finalized provider usage and deterministic local statistics. Historical/project retrieval and memory ranking are lexical; semantic reranking is intentionally disabled even if configured. Project symbol extraction is heuristic, artifact search is literal, and memory/pin creation is manual-first. Automatic memory extraction remains disabled; M10 supplies policy enforcement but not an automatic classifier or confirmation workflow. Provider-payload coverage targets Pi 0.84.3's supported serializers, and DS4 must load after any extension allowed to replace payloads when strict final ordering is required.
89
+ The planner does not call a model inside the `context` hook. Model calibration uses only finalized provider usage and deterministic local statistics. Historical/project retrieval can opt into derived semantic candidates; learned supplemental reranking remains off by default and active mode is promotion-gated. Project symbol extraction is heuristic, artifact search is literal, and memory/pin creation is manual-first. Automatic memory extraction remains disabled; M10 supplies policy enforcement but not an automatic classifier or confirmation workflow. Provider-payload coverage targets Pi 0.84.3's supported serializers, and DS4 must load after any extension allowed to replace payloads when strict final ordering is required.
@@ -0,0 +1,91 @@
1
+ # Context Quality Metrics
2
+
3
+ M14 adds an opt-in, metadata-only quality layer around the deterministic 0.1 planner. The context hook only queues the completed metadata-only manifest; metric materialization and storage run after `agent_settled` (or during shutdown flush), outside provider planning latency. Measurement never changes selection, ranking, privacy enforcement, provider payloads, or Pi JSONL.
4
+
5
+ ## Configuration
6
+
7
+ Quality sampling is disabled by default:
8
+
9
+ ```json
10
+ {
11
+ "quality": {
12
+ "enabled": true,
13
+ "maxSamples": 1000
14
+ }
15
+ }
16
+ ```
17
+
18
+ `maxSamples` must be between 1 and 100,000. Retention is bounded in SQLite. Disabling the feature returns before sample scheduling. Enabling it adds only a bounded metadata-reference queue operation to the context path; the more expensive metric pass is deferred.
19
+
20
+ ## Metrics
21
+
22
+ `context-quality-v1` records deterministic counts and ratios for:
23
+
24
+ - expected evidence recall;
25
+ - irrelevant selected-token ratio;
26
+ - duplicate evidence references;
27
+ - provenance coverage;
28
+ - current-request retention;
29
+ - atomic-group validity;
30
+ - overflow and planner-fallback rates;
31
+ - selected/dropped source-kind counts;
32
+ - category budget utilization;
33
+ - normalized selection/drop reason counts.
34
+
35
+ The primary score is versioned with the metric contract:
36
+
37
+ ```text
38
+ 35% evidence recall
39
+ 20% relevant-token share
40
+ 15% provenance coverage
41
+ 15% current-request retention
42
+ 10% atomic-group validity
43
+ 5% no-overflow/no-fallback reliability
44
+ ```
45
+
46
+ A ratio with no applicable denominator is reported as `null` and contributes a neutral value once an aggregate contains labeled evidence. An aggregate with no labeled evidence reports a zero primary score rather than claiming success. Live requests do not have human expected-evidence labels, so their evidence recall remains explicitly unlabeled rather than being assigned a tautological success. Versioned replay fixtures supply expected source IDs and produce labeled recall.
47
+
48
+ Planning duration is stored and reported separately. It is excluded from deterministic aggregates and golden output because wall-clock time is not byte-stable.
49
+
50
+ ## Privacy and storage
51
+
52
+ `context_quality_samples` is a disposable SQLite v11 projection. A stored sample contains only:
53
+
54
+ - schema, metric, corpus, planner and profile versions;
55
+ - aggregate source-kind, token, budget and decision counts;
56
+ - outcome labels;
57
+ - normalized timing values.
58
+
59
+ It does **not** contain prompts, messages, summaries, memory claims, artifact text, project paths, evidence text, provider payloads, provider response IDs, or raw evidence source IDs. Live source IDs are hashed only while constructing the volatile metric input; only resulting counts are persisted.
60
+
61
+ Malformed, incomplete, unknown-version, or structurally inconsistent rows are ignored during aggregation. Quality write/read failures are caught independently and cannot replace or block the 0.1 context plan.
62
+
63
+ Deleting SQLite discards samples without affecting canonical state. Replaying the same versioned local corpus reconstructs byte-identical non-timing aggregates.
64
+
65
+ ## Replay corpus and comparisons
66
+
67
+ [`quality/corpus-v1.json`](../quality/corpus-v1.json) contains synthetic, sanitized metadata fixtures with task descriptors, expected evidence source IDs, atomic groups, token costs, and planner budgets. It contains no captured user or project text.
68
+
69
+ Run the 0.1 static-ranking baseline against the task-weighted 0.2 candidate interface:
70
+
71
+ ```bash
72
+ npm run quality:compare
73
+ ```
74
+
75
+ The final stdout line is stable JSON. Add `-- --timing` to report wall-clock duration separately on stderr. The task-weighted candidate remains evaluation-only. M18 adds a separate sanitized learned-ranking promotion fixture contract that enforces quality, exact-recall, privacy, atomicity, overflow, latency and determinism gates before active ordering is eligible; see [`LEARNED_RANKING.md`](LEARNED_RANKING.md).
76
+
77
+ ## Diagnostics
78
+
79
+ ```text
80
+ /context quality
81
+ ```
82
+
83
+ The command reports sample counts, labeled coverage, aggregate scores, rates, category utilization, normalized reasons, and separate mean/p95 planning duration. It never renders source content.
84
+
85
+ ## Verification
86
+
87
+ - `tests/unit/context-quality.test.ts` covers every metric, weighted aggregation, deterministic replay, and live-sample redaction.
88
+ - `tests/integration/context-quality-repository.test.ts` covers delete/rebuild equivalence, bounded retention, and corrupt-row isolation.
89
+ - `tests/golden/context-quality-comparison.test.ts` locks byte-stable non-timing comparison output.
90
+ - `tests/integration/extension.test.ts` covers opt-in runtime recording and `/context quality`.
91
+ - `tests/benchmarks/context-quality.bench.ts` measures disabled/enabled context-path scheduling separately from deferred 1,000-item materialization. On the development host, a 1,000-message planner measured `2.5680 ms` p99 with metrics disabled and `2.5929 ms` with enabled scheduling (about `0.97%` overhead); the deferred 1,000-item pass measured `11.6510 ms` p99. These are observational, not portable guarantees.