mirror of
https://github.com/mksglu/context-mode.git
synced 2026-11-23 13:11:14 +08:00
fix(store): one forward-slash label for path sources on every OS (D-PATH-LABEL-1)
ctx_index labelled path sources with the OS separator, so ctx_search source:"data/x.html" found nothing on Windows. Path labels now use forward slashes; ctx_search and ctx_purge accept either slash form; schema v6 renames stored backslash path labels in place. The bench counts a failed quality check as a miss and searches with the label ctx_index returned. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
33775e3e51
commit
bbee5c28db
15 files changed
+189
-30
No files matched your search
@@ -2,7 +2,7 @@
|
||||
// whether code blocks of the source come back whole, and for the HTML page whether the expected answer string is in the hits.
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { BENCH, bytes, read, fences, queriesWithHits, pct, kb, rng3 } from "../suite/lib.mjs";
|
||||
import { BENCH, bytes, read, fences, queriesWithHits, pct, kb, rng3, indexedLabel, savedCell } from "../suite/lib.mjs";
|
||||
|
||||
const scen = JSON.parse(readFileSync(path.join(BENCH, "fixtures", "scenarios.json"), "utf8"));
|
||||
const v1 = JSON.parse(readFileSync(path.join(BENCH, "fixtures", "v1-baseline.json"), "utf8"));
|
||||
@@ -40,7 +40,9 @@ export default {
|
||||
const raw = s.html ? read(s.fixture) : text;
|
||||
const queries = s.qa.map((x) => x.q);
|
||||
const ix = await client.call("ctx_index", s.html ? { path: "data/" + s.fixture } : { content: text, source: s.source });
|
||||
const se = await client.call("ctx_search", { queries, source: s.html ? "data/" + s.fixture : s.source });
|
||||
// The search uses the label ctx_index returned (D-PATH-LABEL-1), not a label the harness spelled itself.
|
||||
const label = s.html ? indexedLabel(ix.text) ?? "data/" + s.fixture : s.source;
|
||||
const se = await client.call("ctx_search", { queries, source: label });
|
||||
if (ix.error || se.error || ix.isError || se.isError) return { error: ix.error ?? se.error ?? (ix.isError ? ix.text : se.text) };
|
||||
const blocks = fences(s.html ? raw : text);
|
||||
const whole = blocks.filter((b) => se.text.includes(b)).length;
|
||||
@@ -69,7 +71,7 @@ export default {
|
||||
for (const r of rows) {
|
||||
const m = r.metrics;
|
||||
const ans = m.answers_expected ? `${m.answers_found.median}/${m.answers_expected.median}` : "n/a";
|
||||
out.push(`| [${r.title}](${r.link}) | ${kb(m.raw_bytes.median)} | ${pct(m.raw_bytes.median, m.v1_bytes?.median)} | ${kb(m.ctx_bytes.median)} | ${pct(m.raw_bytes.median, m.ctx_bytes.median)} | ${m.queries_hit.median}/${m.queries.median} | ${m.blocks_whole.median}/${m.blocks_in_source.median} | ${ans} | ${rng3({ median: m.index_ms.median + m.search_ms.median, min: m.index_ms.min + m.search_ms.min, max: m.index_ms.max + m.search_ms.max })} |`);
|
||||
out.push(`| [${r.title}](${r.link}) | ${kb(m.raw_bytes.median)} | ${pct(m.raw_bytes.median, m.v1_bytes?.median)} | ${kb(m.ctx_bytes.median)} | ${savedCell(r, m.raw_bytes.median, m.ctx_bytes.median)} | ${m.queries_hit.median}/${m.queries.median} | ${m.blocks_whole.median}/${m.blocks_in_source.median} | ${ans} | ${rng3({ median: m.index_ms.median + m.search_ms.median, min: m.index_ms.min + m.search_ms.min, max: m.index_ms.max + m.search_ms.max })} |`);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
|
||||
+9
-4
@@ -12,7 +12,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { devVersionLabel } from "../scripts/release/dev-version.mjs";
|
||||
import { BENCH, REPO, DATA, sandbox, startServer, stats, sha256, tokens } from "./suite/lib.mjs";
|
||||
import { BENCH, REPO, DATA, sandbox, startServer, stats, sha256, tokens, qualityMisses } from "./suite/lib.mjs";
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const opt = (name, d) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : d; };
|
||||
@@ -67,7 +67,7 @@ for (const g of groups) {
|
||||
const link = `../${g.dir}/README.md#${s.id}`;
|
||||
results.push({ group: g.dir, id: s.id, title: s.title, link, inputs: s.inputs ?? [], synthetic: !!s.synthetic, v1_scenario: s.v1 ?? null, command: s.command, ok: err ? false : ok, note, error: err, metrics });
|
||||
if (err) errors++;
|
||||
console.log(`${err ? "ERROR" : ok ? "ok " : "WARN "} ${s.id}${err ? " " + err : note ? " (" + note + ")" : ""}`);
|
||||
console.log(`${err ? "ERROR" : ok ? "ok " : "MISS "} ${s.id}${err ? " " + err : note ? " (" + note + ")" : ""}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ for (const r of results) for (const f of r.inputs) if (!manifest[f]) { const p =
|
||||
|
||||
const runMs = Math.round(performance.now() - T0);
|
||||
const out = {
|
||||
schema: 1, date, runs: RUNS, run_ms: runMs, token_method: "bytes / 4, an estimate (no tokenizer is vendored)",
|
||||
schema: 1, quality_misses: qualityMisses(results).map((r) => r.id), date, runs: RUNS, run_ms: runMs, token_method: "bytes / 4, an estimate (no tokenizer is vendored)",
|
||||
context_mode: { version: devVersionLabel(pkg.version, commit), commit, dirty }, env, fixtures: manifest, results,
|
||||
};
|
||||
|
||||
@@ -110,5 +110,10 @@ if (WRITE) {
|
||||
writeFileSync(path.join(BENCH, g.dir, "README.md"), l.join("\n"));
|
||||
}
|
||||
}
|
||||
console.log(`done in ${runMs} ms, ${results.length} scenarios, ${errors} error(s)`);
|
||||
const misses = qualityMisses(results);
|
||||
if (misses.length) {
|
||||
console.log(`\nQUALITY MISS in ${misses.length} scenario(s); these rows show no saving:`);
|
||||
for (const r of misses) console.log(` - ${r.id}${r.note ? ": " + r.note : ""}`);
|
||||
}
|
||||
console.log(`done in ${runMs} ms, ${results.length} scenarios, ${errors} error(s), ${misses.length} quality miss(es)`);
|
||||
process.exit(errors ? 1 : 0);
|
||||
@@ -168,3 +168,16 @@ export function hostPayload(id, cwd, command, text) {
|
||||
default: throw new Error("unknown shape " + shape);
|
||||
}
|
||||
}
|
||||
|
||||
// D-PATH-LABEL-1: a scenario whose own quality check failed (ok false, no error) is a quality miss: it is listed in the
|
||||
// summary and its table row shows "miss" where a saving would stand, so a failed row never reads as a saving.
|
||||
export const qualityMisses = (results) => results.filter((r) => !r.error && r.ok === false);
|
||||
export const savedCell = (row, raw, x) => (row.ok === false ? "miss" : pct(raw, x));
|
||||
// The source label ctx_index returned, from its reply line "Indexed N source(s), M chunk(s) from <label>." (no regex).
|
||||
export function indexedLabel(text) {
|
||||
const line = String(text).split("\n")[0];
|
||||
const at = line.indexOf(" from ");
|
||||
if (at < 0) return null;
|
||||
const rest = line.slice(at + 6);
|
||||
return rest.endsWith(".") ? rest.slice(0, -1) : rest;
|
||||
}
|
||||
@@ -124,3 +124,4 @@ Split: this file holds the deviation rows without a date (format: id, files, dec
|
||||
| D-EXEC-BARE-1 | src/core/tools/execute.ts (finish: `bare`), tests/prd9-sandbox.test.mjs (2 new tests, 1 changed), tests/0017-v1-retention.test.mjs (OK cases), e2e/cases/GP4-execute.e2e.mjs (project-cwd-temp-dir-cleanup), goldens e2e/golden/GP1/no-clientinfo-agent-from-flag.json, GP4/code-point-safe-truncation-cut.json, GP4/deleted-cwd-no-ansi.json, GP4/env-via-spawn-env-no-node-options-leak.json, GP4/host-rpc-timeout-governs-no-default.json, GP4/output-cut-is-code-point-safe.json, GP4/project-cwd-temp-dir-cleanup.json, GP4/recreate-preload-temp-file.json, GP4/surrogate-safe-truncation.json, GP7/adapter-root-path-containment.json, GP7/workspace-folder-remote-wsl.json, GP7/worktree-containment-consistent.json | Root cause of bench group A (14 v1 rows): v2 ctx_execute returned exactly 16-17 B more than v1 on every row (react docs 277 vs 261, HN snapshot 315 vs 299, github issues 1156 vs 1139). The cause was the head line `exit 0 · <N> B` that D-M2-T10-6 added to every reply (git log -S summaryLine: 0db963c3). v1 (227230d8 src/server.ts) returned the bare stdout on exit 0. When exit is 0, no echo is asked and the whole output is in the reply, the head line states nothing the reply does not hold (exit 0, whole output, N is the reply length), so the reply is now the output itself. The head stays where it informs: non-zero exit, empty output (`exit 0 · 0 B`), `summary:true`, and every reply where the output is kept in the store. Nothing is cut or lost. Bench A before/after/v1 (B): 277/261/261, 265/249/249, 202/186/186, 315/299/299, 365/349/349, 735/719/719, 1156/1139/1139, 353/337/337, 363/347/347, 421/405/405, 758/742/742, 171/155/155, 123/107/107, 238/222/222: every row v2 = v1. The 4 v2-only rows drop 16 B too (834 to 818, 451 to 435, 489 to 473, 153 to 137). Exec ms unchanged (about 55 ms median, no extra work on the path). Goldens changed only to the new text (head line removed from exit-0 whole-output replies): the 12 files in the Files column. |
|
||||
| D-EXEC-PREVIEW-1 | src/core/contracts/constants.ts (`EXEC_PREVIEW_BYTES` 4096), src/core/tools/execute.ts (finish), tests/prd9-sandbox.test.mjs (new test) | A ctx_execute output that does not fit OUTPUT_CAP was indexed and the reply carried 14-16 KB of selected chunks (bench group D: 14.6, 15.7, 16.4, 15.1 KB for 78-651 KB of output). The ~14 KB was only what is left of OUTPUT_CAP (16384) after the head and `more:` line (D-M2-T10-6, D-M2-6); no number backed it. The model reaches the rest with the `ctx_search({queries:[...], source:"ctx_execute:..."})` line the reply ends with, and the replace path already sets its own smaller sizes (D-M7-SV-1..3, REPLACE_RETURN_BYTES 96). New budget for output over OUTPUT_CAP and no intent: EXEC_PREVIEW_BYTES = 4096 for head + whole chunks + `more:` line. Whole chunks only, the full output stays indexed, the pointer line stays. An intent still gets the full OUTPUT_CAP budget when the output fits OUTPUT_CAP. Bench D before/after (reply B, saved%): 120 KB log 14610 to 2319 (82% to 97%), 1 MB log 15671 to 3380 (98% to 99%), GitHub JSON 16353 to 4060 (93% to 98%), git log 15133 to 2842 (92% to 99%); markers found 3/3 in all four (before and after); exec ms 90/125/195/342 before, 56/101/73/77 after (less text to select and send; median of 3). Not measured: values under 4096 (chunks can be up to MAX_CHUNK_BYTES 4096, so a smaller budget can select no whole chunk). |
|
||||
| D-README-NO-SCOPE-1 | README.md (the "## Scope" section removed), tests/0014-repo-hygiene.test.mjs (README parts test: no "## Scope", "## Limitations" or "## Known" section, no OPEN-ITEMS pointer) | Owner, 2026-11-01, on the README Scope section: "bu kisma gerek yok ne icin var anlamadim". He said the same of the Limitations section before. The README keeps no section for scope, limits or open work; the fact that `ctx_execute` code runs as the user stays in section 7 (Security model). Open work stays in docs/v2/OPEN-ITEMS.md. |
|
||||
| D-PATH-LABEL-1 | src/core/store/fts.ts (pathLabel, storedLabel, resolveSourceLabel), src/core/store/schema.ts (DDL_V6), src/core/contracts/constants.ts (SCHEMA_VERSION 6), src/core/tools/index.ts (pathItems, itemsOf), src/core/tools/purge.ts, bench/suite/lib.mjs (qualityMisses, savedCell, indexedLabel), bench/run.mjs, bench/b-retrieval/index.mjs, tests/prd8-index-search.test.mjs (3 tests, one Windows only), tests/prd12-stats-purge.test.mjs, tests/0002-store.test.mjs (v6 migration), tests/0012-m2-bench.test.mjs, tests/0018-contracts.test.mjs | Windows retest 2026-11-01 (Codex 0.166, Claude Desktop, next.23): ctx_index({path:"data/sqlite-fts5-docs.html"}) stored and returned the label "data\\sqlite-fts5-docs.html" (node:path join and relative use the OS separator); ctx_search with source:"data/sqlite-fts5-docs.html" gave "No hits ... across 0 source(s)" because the filter is `label = :source` (3/3 questions fail in 3 fresh runs; nested/notes.md gave 0 hits, nested\\notes.md gave 1). Root cause: the label is a name the agent types back, but it was built with the OS separator and compared by exact text. Now a path label has one form on every OS: forward slashes, relative to the project (`pathLabel`). The `source` argument of ctx_search and ctx_purge takes either slash form: the argument as typed if a row has it, else its forward-slash form (`storedLabel`). Schema version 6 renames existing backslash path labels in place (`UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path'`): no source or chunk row is deleted or rewritten, content and url labels are not touched, so data stored on Windows before the fix stays findable. The harness (bench/b-retrieval) now searches with the label ctx_index returned. A scenario whose own check fails (WARN, answers < expected) is a quality miss: bench/run.mjs prints `MISS`, a QUALITY MISS list and a count in the last line, writes `quality_misses` into the results JSON, and the table row shows `miss` where a saving would stand (before, the row printed WARN, exited 0 and showed a saving). Loss: a non-Windows path with a literal backslash in a file name is now labelled with a slash (rare; the file is still found by path). | New behaviour on all OSes for path labels; macOS and Linux labels are unchanged (no backslash). Windows-only test runs on the windows-latest CI job. |
|
||||
+1
-1
@@ -7,7 +7,7 @@ Each tool rejects an unknown input field with `UNKNOWN_FIELD`.
|
||||
|---|---|---|---|
|
||||
| `ctx_execute` | `language`, `code`, `file?`, `intent?`, `timeoutMs?`, `background?`, `summary?` | Runs code or a shell command in a sandbox; returns only what it prints, up to `OUTPUT_CAP` (16,384 B). Default and max timeout: `EXEC_TIMEOUT_MS` (600,000 ms) | `src/core/tools/execute.ts` |
|
||||
| `ctx_batch` | `commands[]`, `queries[]` | Runs the commands, indexes the output, and searches it in one call | `src/core/tools/batch.ts` |
|
||||
| `ctx_index` | `path?`, `content?`, `url?`, `source?` | Indexes a file, a folder, a text or a URL into the project database | `src/core/tools/index.ts` |
|
||||
| `ctx_index` | `path?`, `content?`, `url?`, `source?` | Indexes a file, a folder, a text or a URL into the project database. A path source is labelled relative to the project with forward slashes on every OS (`nested/notes.md`); `ctx_search` and `ctx_purge` take `source` in either slash form | `src/core/tools/index.ts` |
|
||||
| `ctx_search` | `queries[]`, `scope?` (`session`, `worktree`, `project`; default `worktree`), `source?`, `offset?`, `sort?` (`relevance`, `timeline`), `after?` | Searches the index; returns the matching parts only, `SEARCH_REPLY_HITS` (5) per reply; a `More:` line pages on with `offset` | `src/core/tools/search.ts` |
|
||||
| `ctx_resume` | `session?`, `seq?` | Returns the state block (at most `RESUME_CAP`, 2,048 B), or one full row by `seq` | `src/core/tools/resume.ts` |
|
||||
| `ctx_stats` | none | Shows how much output stayed out of context, per session, project and all time | `src/core/tools/stats.ts` |
|
||||
|
||||
@@ -106,7 +106,7 @@ export const MS_PER_DAY = 86400000; // DEVIATIONS D-M1-3: day-to-ms factor for t
|
||||
|
||||
// Store (impl/02 §0; DEVIATIONS D-M1-3: impl/00 names NODE_MIN and INDEX_WRITE_CHUNK cover the rest)
|
||||
export const PROJECT_KEY_HEX_LEN = 16; // impl/00 A5: first 16 hex chars of sha256(git common dir realpath)
|
||||
export const SCHEMA_VERSION = 5; // ADR-0002 decision 2: PRAGMA user_version; 2 = cost dedup index (D-M5-arch-2); 3 = chunks title + porter (D-SEARCH-3); 4 = trigram table + vocab (D-SEARCH-4); 5 = line_units (r3-ledger)
|
||||
export const SCHEMA_VERSION = 6; // ADR-0002 decision 2: PRAGMA user_version; 2 = cost dedup index (D-M5-arch-2); 3 = chunks title + porter (D-SEARCH-3); 4 = trigram table + vocab (D-SEARCH-4); 5 = line_units (r3-ledger); 6 = path labels with forward slashes (D-PATH-LABEL-1)
|
||||
export const RETENTION_IDLE_DAYS = 30; // impl/02 A-S1: row-level, age since last access
|
||||
export const RETENTION_SIZE_CAP_BYTES = 524288000; // impl/02 A-S2 (Q7b): 500 MB per project
|
||||
export const PROJECT_DEAD_IDLE_DAYS = 14; // DECISIONS-r9 V22 (#1024): project-level sweep, dead owner
|
||||
|
||||
+27
-4
@@ -638,19 +638,42 @@ export function parseSourceHandle(s: string): number | null {
|
||||
return n > 0 && sourceHandle(n) === s ? n : null;
|
||||
}
|
||||
|
||||
// D-PATH-LABEL-1: the one label form of a path source on every OS: forward slashes. A backslash is a separator
|
||||
// only on Windows, but the label is a name the agent types back, so it has one spelling everywhere.
|
||||
export function pathLabel(p: string): string {
|
||||
return p.includes("\\") ? p.split("\\").join("/") : p;
|
||||
}
|
||||
|
||||
function labelStored(db: DbHandle, label: string): boolean {
|
||||
return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label) !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* D-PATH-LABEL-1: the stored label a `source` argument names by its spelling: the argument itself when a row has
|
||||
* it, else its forward-slash form (a backslash path from a Windows agent), else the argument as given.
|
||||
* ctx_purge uses this alone; ctx_search adds the id and "#" suffix forms in resolveSourceLabel.
|
||||
*/
|
||||
export function storedLabel(db: DbHandle, source: string): string {
|
||||
if (labelStored(db, source)) return source;
|
||||
const canon = pathLabel(source);
|
||||
return canon !== source && labelStored(db, canon) ? canon : source;
|
||||
}
|
||||
|
||||
// D-CR3-HANDLE-1: the label a `source` argument names, in this order: a short id of a stored row, a full
|
||||
// label, a label without its "#<call id>" suffix (the newest such source). No match -> the argument as given.
|
||||
// label (either slash form, D-PATH-LABEL-1), a label without its "#<call id>" suffix (the newest such source).
|
||||
// No match -> the argument as given.
|
||||
export function resolveSourceLabel(db: DbHandle, source: string): string {
|
||||
const id = parseSourceHandle(source);
|
||||
if (id !== null) {
|
||||
const row = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id) as { label: string } | undefined;
|
||||
if (row !== undefined) return row.label;
|
||||
}
|
||||
if (stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(source) !== undefined) return source;
|
||||
const prefix = source + LABEL_SUFFIX_SEP;
|
||||
const named = storedLabel(db, source);
|
||||
if (labelStored(db, named)) return named;
|
||||
const prefix = named + LABEL_SUFFIX_SEP;
|
||||
const rows = stmt(db.raw, "SELECT label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix) as Array<{ label: string }>;
|
||||
for (const r of rows) {
|
||||
if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === source.length) return r.label;
|
||||
if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named.length) return r.label;
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
@@ -132,6 +132,13 @@ CREATE VIRTUAL TABLE line_units USING fts5(
|
||||
);
|
||||
`;
|
||||
|
||||
// Version 6 (D-PATH-LABEL-1): a path source label has one spelling, forward slashes. Windows wrote "data\\x.html"
|
||||
// before; those rows are renamed in place (no row or chunk is touched), so every stored source stays findable.
|
||||
// content and url labels keep their text.
|
||||
export const DDL_V6: string = `
|
||||
UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
|
||||
`;
|
||||
|
||||
// Ascending by version; step N brings the DB from N-1 to N.
|
||||
const MIGRATIONS: ReadonlyArray<{ version: number; sql: string }> = [
|
||||
{ version: 1, sql: DDL },
|
||||
@@ -139,6 +146,7 @@ const MIGRATIONS: ReadonlyArray<{ version: number; sql: string }> = [
|
||||
{ version: 3, sql: DDL_V3 },
|
||||
{ version: 4, sql: DDL_V4 },
|
||||
{ version: 5, sql: DDL_V5 },
|
||||
{ version: 6, sql: DDL_V6 },
|
||||
];
|
||||
|
||||
export function applyMigrations(db: DatabaseSync, fromVersion: number): void {
|
||||
|
||||
@@ -14,7 +14,7 @@ import { capBytes } from "../sandbox/cap.ts";
|
||||
import { safeFetch } from "../sandbox/fetch.ts";
|
||||
import { unknownField } from "./search.ts";
|
||||
import { closeDb, openDb } from "../store/db.ts";
|
||||
import { sourceHandle } from "../store/fts.ts";
|
||||
import { pathLabel, sourceHandle } from "../store/fts.ts";
|
||||
import { indexText, storeText, type ChunkKind } from "../index/text.ts";
|
||||
import { hasMdStructure } from "../index/chunk.ts";
|
||||
import { htmlToReadable } from "../index/html-text.ts";
|
||||
@@ -84,12 +84,12 @@ function pathItems(input: CtxIndexInput & { path: string }, project: ProjectCont
|
||||
if (statSync(abs).isDirectory()) {
|
||||
return walkDir(abs, project.containmentRoot).map((f) => ({
|
||||
sourceKind: "path",
|
||||
label: join(base, f.relPath),
|
||||
label: pathLabel(join(base, f.relPath)),
|
||||
kind: kindOfPath(f.relPath),
|
||||
read: () => readUtf8(f.absPath),
|
||||
}));
|
||||
}
|
||||
return [{ sourceKind: "path", label: base === "" ? input.path : base, kind: kindOfPath(abs), read: () => readUtf8(abs) }];
|
||||
return [{ sourceKind: "path", label: pathLabel(base === "" ? input.path : base), kind: kindOfPath(abs), read: () => readUtf8(abs) }];
|
||||
}
|
||||
|
||||
async function itemsOf(input: CtxIndexInput, ctx: ToolContext): Promise<{ items: Item[]; from: string }> {
|
||||
@@ -102,7 +102,7 @@ async function itemsOf(input: CtxIndexInput, ctx: ToolContext): Promise<{ items:
|
||||
}
|
||||
if (input.path !== undefined) {
|
||||
const items = pathItems({ ...input, path: input.path }, ctx.project);
|
||||
return { items, from: items.length === 1 ? items[0].label : input.path };
|
||||
return { items, from: items.length === 1 ? items[0].label : pathLabel(input.path) };
|
||||
}
|
||||
// url: safeFetch owns proxy env and the per-hop SSRF check; its CtxError is the reply (P1, one path).
|
||||
// 00 §5.2 step 3 / Q8: the handler runs under cancel and EXEC_TIMEOUT_MS, so a server that never
|
||||
|
||||
@@ -12,9 +12,9 @@ import {
|
||||
SQLITE_BUSY_CODE,
|
||||
SQLITE_PRIMARY_CODE_MASK,
|
||||
} from "../contracts/constants.ts";
|
||||
import type { CtxPurgeInput, ToolContext, ToolReply } from "../contracts/types.ts";
|
||||
import type { CtxPurgeInput, DbHandle, ToolContext, ToolReply } from "../contracts/types.ts";
|
||||
import { closeDb, openDb, withWrite } from "../store/db.ts";
|
||||
import { deleteChunkRows } from "../store/fts.ts";
|
||||
import { deleteChunkRows, storedLabel } from "../store/fts.ts";
|
||||
import { unknownField } from "./search.ts";
|
||||
|
||||
export type { CtxPurgeInput } from "../contracts/types.ts";
|
||||
@@ -46,10 +46,12 @@ function changes(raw: DatabaseSync, sql: string, ...args: string[]): number {
|
||||
}
|
||||
|
||||
// Steps 3-5: the rows deleted for one scope, summed across the tables it touches.
|
||||
function purgeScope(raw: DatabaseSync, scope: PurgeScope, input: CtxPurgeInput): number {
|
||||
function purgeScope(db: DbHandle, scope: PurgeScope, input: CtxPurgeInput): number {
|
||||
const raw = db.raw;
|
||||
if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session as string);
|
||||
if (scope === "source") {
|
||||
const label = input.source as string;
|
||||
// D-PATH-LABEL-1: a path label is named by either slash form.
|
||||
const label = storedLabel(db, input.source as string);
|
||||
return deleteChunkRows(raw, { label }) + changes(raw, "DELETE FROM sources WHERE label = ?", label);
|
||||
}
|
||||
const chunks = deleteChunkRows(raw, "all");
|
||||
@@ -71,7 +73,7 @@ async function handler(input: CtxPurgeInput, ctx: ToolContext): Promise<ToolRepl
|
||||
const db = await openDb(ctx.project);
|
||||
try {
|
||||
// Steps 2 and 6: one BEGIN IMMEDIATE; withWrite commits or rolls back.
|
||||
const rows = withWrite(db, (h) => purgeScope(h.raw, scope, input));
|
||||
const rows = withWrite(db, (h) => purgeScope(h, scope, input));
|
||||
return reply(PURGE_SUMMARY(rows, scope), false); // steps 7-8
|
||||
} finally {
|
||||
closeDb(db);
|
||||
|
||||
@@ -388,7 +388,7 @@ describe("ADR-0002: schema", { concurrency: CONC }, () => {
|
||||
|
||||
test("SCHEMA_VERSION equals the constants.ts SCHEMA_VERSION", () => {
|
||||
assert.equal(SCHEMA_VERSION, C.SCHEMA_VERSION);
|
||||
assert.equal(SCHEMA_VERSION, 5); // D-M5-arch-2: v2 adds the cost dedup index; D-SEARCH-3: v3 chunks title + porter; D-SEARCH-4: v4 trigram; r3-ledger: v5 line_units
|
||||
assert.equal(SCHEMA_VERSION, 6); // D-PATH-LABEL-1: v6 path labels use forward slashes; D-M5-arch-2: v2 adds the cost dedup index; D-SEARCH-3: v3 chunks title + porter; D-SEARCH-4: v4 trigram; r3-ledger: v5 line_units
|
||||
});
|
||||
|
||||
test("v2 (D-M5-arch-2): a fresh DB has the partial unique index events(session_id, turn) WHERE kind = 'cost'", () => {
|
||||
@@ -411,7 +411,7 @@ describe("ADR-0002: schema", { concurrency: CONC }, () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("v2 (D-M5-arch-2): a version-1 DB migrates to the current version (2, 3, 4, then 5) without losing rows", () => {
|
||||
test("v2 (D-M5-arch-2): a version-1 DB migrates to the current version (2, 3, 4, 5, then 6) without losing rows", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cm-schema-"));
|
||||
try {
|
||||
const db = freshDb(dir);
|
||||
@@ -419,7 +419,7 @@ describe("ADR-0002: schema", { concurrency: CONC }, () => {
|
||||
db.exec("PRAGMA user_version = 1");
|
||||
db.exec("INSERT INTO events(session_id, worktree, agent, kind, turn, created_at, accessed_at) VALUES ('s','w','claude-code','prompt',1,0,0)");
|
||||
applyMigrations(db, 1);
|
||||
assert.equal(db.prepare("PRAGMA user_version").get().user_version, 5);
|
||||
assert.equal(db.prepare("PRAGMA user_version").get().user_version, SCHEMA_VERSION);
|
||||
assert.equal(db.prepare("SELECT COUNT(*) AS n FROM events").get().n, 1);
|
||||
assert.ok(db.prepare("SELECT 1 FROM sqlite_master WHERE name = 'idx_events_cost_session_turn'").get());
|
||||
db.close();
|
||||
@@ -547,7 +547,7 @@ describe("ADR-0002: schema", { concurrency: CONC }, () => {
|
||||
ins.run(1, 0, "connection pooling");
|
||||
ins.run(1, 1, "Привет café");
|
||||
applyMigrations(v2, 2);
|
||||
assert.equal(v2.prepare("PRAGMA user_version").get().user_version, 5);
|
||||
assert.equal(v2.prepare("PRAGMA user_version").get().user_version, SCHEMA_VERSION);
|
||||
assert.equal(v2.prepare("SELECT COUNT(*) AS n FROM chunks").get().n, 2);
|
||||
assert.deepEqual(v2.prepare("SELECT ord, title FROM chunks WHERE chunks MATCH 'connecting'").all().map((r) => ({ ...r })), [{ ord: 0, title: "" }]);
|
||||
assert.equal(v2.prepare("SELECT COUNT(*) AS n FROM chunks WHERE chunks MATCH 'cafe'").get().n, 1);
|
||||
@@ -570,7 +570,7 @@ describe("ADR-0002: schema", { concurrency: CONC }, () => {
|
||||
ins.run(1, 0, "see T-CMP here", "");
|
||||
ins.run(1, 1, "other", "Guide > src/core/fts.ts");
|
||||
applyMigrations(db, 3);
|
||||
assert.equal(db.prepare("PRAGMA user_version").get().user_version, 5);
|
||||
assert.equal(db.prepare("PRAGMA user_version").get().user_version, SCHEMA_VERSION);
|
||||
assert.equal(db.prepare("SELECT COUNT(*) AS n FROM chunks").get().n, 2);
|
||||
const rid = (m) => db.prepare("SELECT rowid AS r FROM chunks_tri WHERE chunks_tri MATCH ?").all(m).map((r) => r.r);
|
||||
const want = (o) => db.prepare("SELECT rowid AS r FROM chunks WHERE ord = ?").get(o).r;
|
||||
@@ -581,6 +581,34 @@ describe("ADR-0002: schema", { concurrency: CONC }, () => {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// D-PATH-LABEL-1: a version-5 DB with backslash path labels (written on Windows before the fix) keeps every row and
|
||||
// reads them under the forward-slash label; content and url labels are not touched.
|
||||
test("v6 (D-PATH-LABEL-1): a version-5 DB migrates path labels to forward slashes and loses no source or chunk", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cm-schema-"));
|
||||
try {
|
||||
const db = freshDb(dir);
|
||||
applyMigrations(db, 0);
|
||||
db.exec("PRAGMA user_version = 5");
|
||||
const src = db.prepare("INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts) VALUES ('s','w','claude-code',?,?,1,1,1,'t',1)");
|
||||
src.run("path", "data\\sqlite-fts5-docs.html");
|
||||
src.run("path", "data\\sqlite-fts5-docs.html (raw)");
|
||||
src.run("path", "plain.md");
|
||||
src.run("content", "keep\\this");
|
||||
src.run("url", "https://example.com/a");
|
||||
const ins = db.prepare("INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, 's', 'w', 'claude-code', 0, 'migrated body', '')");
|
||||
for (const id of [1, 2, 3, 4, 5]) ins.run(id);
|
||||
applyMigrations(db, 5);
|
||||
assert.equal(db.prepare("PRAGMA user_version").get().user_version, SCHEMA_VERSION);
|
||||
assert.deepEqual(db.prepare("SELECT label FROM sources ORDER BY id").all().map((r) => r.label), [
|
||||
"data/sqlite-fts5-docs.html", "data/sqlite-fts5-docs.html (raw)", "plain.md", "keep\\this", "https://example.com/a",
|
||||
]);
|
||||
assert.equal(db.prepare("SELECT COUNT(*) AS n FROM chunks").get().n, 5);
|
||||
db.close();
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("ADR-0002: sha256 helper", { concurrency: CONC }, () => {
|
||||
@@ -761,8 +789,8 @@ describe("ADR-0002: cost row dedup", { concurrency: CONC }, () => {
|
||||
};
|
||||
}
|
||||
|
||||
test("[M5] SCHEMA_VERSION is 5 after the Usage/cost dedup migration (2), the search title + porter migration (3, D-SEARCH-3), the trigram table (4, D-SEARCH-4) and line units (5, r3-ledger)", () => {
|
||||
assert.equal(SCHEMA_VERSION, 5);
|
||||
test("[M5] SCHEMA_VERSION is 6 after the Usage/cost dedup migration (2), the search title + porter migration (3, D-SEARCH-3), the trigram table (4, D-SEARCH-4) and line units (5, r3-ledger) and path labels (6, D-PATH-LABEL-1)", () => {
|
||||
assert.equal(SCHEMA_VERSION, 6);
|
||||
});
|
||||
|
||||
test("[M5] cost-dedup/usage-events-idempotent-per-turn: 3 step-finish events in one turn journal once", async (t) => {
|
||||
|
||||
@@ -142,6 +142,18 @@ describe("ADR-0012 / bench suite (bench/run.mjs)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// D-PATH-LABEL-1: a failed quality check is a miss, never a saving; the harness searches with the label ctx_index returned.
|
||||
test("quality miss: a row with ok false is listed as a miss and shows no saving; the returned index label is read whole", async () => {
|
||||
const { qualityMisses, savedCell, indexedLabel } = await import("../bench/suite/lib.mjs");
|
||||
const rows = [{ id: "a", ok: true }, { id: "b", ok: false, note: "answer string missing for 3 query(ies)" }, { id: "c", ok: false, error: "boom" }];
|
||||
assert.deepEqual(qualityMisses(rows).map((r) => r.id), ["b"]);
|
||||
assert.equal(savedCell(rows[1], 1000, 100), "miss");
|
||||
assert.equal(savedCell(rows[0], 1000, 100), "90%");
|
||||
assert.equal(indexedLabel("Indexed 1 source(s), 95 chunk(s) from data\\sqlite-fts5-docs.html.\nRaw HTML kept as x"), "data\\sqlite-fts5-docs.html");
|
||||
assert.equal(indexedLabel("Indexed 1 source(s), 95 chunk(s) from data/sqlite-fts5-docs.html."), "data/sqlite-fts5-docs.html");
|
||||
assert.equal(indexedLabel("no label here"), null);
|
||||
});
|
||||
|
||||
test("a one-scenario run works and a bad --runs is refused", () => {
|
||||
const bad = spawnSync(process.execPath, [path.join(BENCH, "run.mjs"), "--runs", "0", "--no-write"], { encoding: "utf8" });
|
||||
assert.equal(bad.status, 2);
|
||||
|
||||
@@ -59,7 +59,7 @@ describe("ADR-0018: contracts (concurrent)", { concurrency: CONC }, () => {
|
||||
DATA_ROOT: "~/.context-mode", LIVE_MODEL: "claude-sonnet-5", LIVE_EFFORT: "low", LIVE_BUDGET_USD: 0.25,
|
||||
LIVE_SKIP_LIMIT: 3, RRF_K: 60, SEARCH_P95_MS: 30, HOOK_TIMEOUT_MS: 5000,
|
||||
// store additions (impl/02 §0, DEVIATIONS D-M1-3)
|
||||
PROJECT_KEY_HEX_LEN: 16, SCHEMA_VERSION: 5, // r3-ledger: v5 = line_units; D-M5-arch-2: v2 = cost dedup index; D-SEARCH-3: v3 = chunks title + porter; D-SEARCH-4: v4 = trigram table
|
||||
PROJECT_KEY_HEX_LEN: 16, SCHEMA_VERSION: 6, // D-PATH-LABEL-1: v6 = path labels with forward slashes; r3-ledger: v5 = line_units; D-M5-arch-2: v2 = cost dedup index; D-SEARCH-3: v3 = chunks title + porter; D-SEARCH-4: v4 = trigram table
|
||||
RETENTION_IDLE_DAYS: 30, RETENTION_SIZE_CAP_BYTES: 524288000,
|
||||
PROJECT_DEAD_IDLE_DAYS: 14, MS_PER_DAY: 86400000,
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@ import { OUTPUT_CAP, STATS_COLUMNS, STATS_NO_DATA, STATS_SUMMARY, STATS_UNKNOWN_
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { ctxPurge } from "../src/core/tools/purge.ts";
|
||||
import { ctxIndex } from "../src/core/tools/index.ts";
|
||||
import { ctxSearch } from "../src/core/tools/search.ts";
|
||||
|
||||
// Concurrent.
|
||||
describe("PRD-v2 sections 8 and 12: stats and purge (concurrent)", { concurrency: CONC }, () => {
|
||||
@@ -285,6 +286,17 @@ describe("PRD-v2 sections 8 and 12: stats and purge (concurrent)", { concurrency
|
||||
assert.deepEqual(after, { events: before.events, sources: before.sources - 1, chunks: before.chunks - goneChunks });
|
||||
}));
|
||||
|
||||
test("D-PATH-LABEL-1: purge/source takes the backslash form of a path label", () => withRoot(async (root) => {
|
||||
const ctx = ctxFor(root);
|
||||
mkdirSync(join(root, "nested"));
|
||||
writeFileSync(join(root, "nested", "notes.md"), "# N\n\npurgezedtoken\n");
|
||||
await ctxIndex.handler({ path: "nested/notes.md" }, ctx);
|
||||
const out = await ctxPurge.handler({ source: "nested\\notes.md" }, ctx);
|
||||
assert.equal(out.isError, false);
|
||||
assert.notEqual(out.text, PURGE_SUMMARY(0, "source"), "the backslash form reached the row: " + out.text);
|
||||
assert.deepEqual((await ctxSearch.handler({ queries: ["purgezedtoken"] }, ctx)).text.includes("nested/notes.md"), false);
|
||||
}));
|
||||
|
||||
test("[M4] purge/source-unknown: an unknown source deletes zero rows", () => withRoot(async (root) => {
|
||||
const ctx = ctxFor(root);
|
||||
await ctxIndex.handler({ content: "gamma", source: "kept" }, ctx);
|
||||
|
||||
@@ -1568,6 +1568,59 @@ describe("PRD-v2 section 8: stage 1 (concurrent)", { concurrency: CONC }, () =>
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
// D-PATH-LABEL-1: a path source has one label form on every OS: forward slashes, relative to the project.
|
||||
// The `source` argument of ctx_search takes either slash form; the label shown to the agent is the canonical one.
|
||||
test("D-PATH-LABEL-1: a file label uses forward slashes; ctx_search source takes the forward or the backslash form", async () => {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "cm-plabel-")));
|
||||
try {
|
||||
const ctx = ctxFor(root);
|
||||
mkdirSync(join(root, "nested"));
|
||||
writeFileSync(join(root, "nested", "notes.md"), "# N\n\nlabelzedtoken in nested notes\n");
|
||||
writeFileSync(join(root, "other.md"), "# O\n\nlabelzedtoken in other file\n");
|
||||
const ix = await ctxIndex.handler({ path: "nested/notes.md" }, ctx);
|
||||
await ctxIndex.handler({ path: "other.md" }, ctx);
|
||||
assert.ok(ix.text.includes("from nested/notes.md."), ix.text);
|
||||
assert.equal(ix.text.includes("\\"), false, "no backslash in the reply: " + ix.text);
|
||||
for (const source of ["nested/notes.md", "nested\\notes.md"]) {
|
||||
const out = await ctxSearch.handler({ queries: ["labelzedtoken"], source }, ctx);
|
||||
assert.ok(out.text.includes("nested/notes.md #0") && !out.text.includes("other file"), source + ": " + out.text);
|
||||
}
|
||||
const all = await ctxSearch.handler({ queries: ["labelzedtoken"] }, ctx);
|
||||
assert.ok(all.text.includes("nested notes") && all.text.includes("other file"), all.text);
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test("D-PATH-LABEL-1: a folder index labels each file with forward slashes", async () => {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "cm-plabel2-")));
|
||||
try {
|
||||
const ctx = ctxFor(root);
|
||||
mkdirSync(join(root, "docs", "deep"), { recursive: true });
|
||||
writeFileSync(join(root, "docs", "deep", "a.md"), "# A\n\nfoldzedtoken deep file\n");
|
||||
const ix = await ctxIndex.handler({ path: "docs" }, ctx);
|
||||
assert.equal(ix.isError, false, ix.text);
|
||||
const out = await ctxSearch.handler({ queries: ["foldzedtoken"], source: "docs\\deep\\a.md" }, ctx);
|
||||
assert.ok(out.text.includes("docs/deep/a.md #0"), out.text);
|
||||
assert.equal(out.text.includes("\\"), false, out.text);
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
// The same case with the real Windows separator: it runs on the windows-latest CI job (the path is built by node:path there).
|
||||
test("D-PATH-LABEL-1: Windows only: an absolute and a backslash path index under the forward-slash label", { skip: process.platform !== "win32" }, async () => {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "cm-plabel3-")));
|
||||
try {
|
||||
const ctx = ctxFor(root);
|
||||
mkdirSync(join(root, "nested"));
|
||||
writeFileSync(join(root, "nested", "notes.md"), "# N\n\nwinzedtoken in nested notes\n");
|
||||
const a = await ctxIndex.handler({ path: join(root, "nested", "notes.md") }, ctx);
|
||||
const b = await ctxIndex.handler({ path: "nested\\notes.md" }, ctx);
|
||||
for (const ix of [a, b]) assert.ok(ix.text.includes("from nested/notes.md."), ix.text);
|
||||
for (const source of ["nested/notes.md", "nested\\notes.md"]) {
|
||||
const out = await ctxSearch.handler({ queries: ["winzedtoken"], source }, ctx);
|
||||
assert.ok(out.text.includes("nested/notes.md #0"), source + ": " + out.text);
|
||||
}
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
// #717 / #736: the ran code and commands are echoed so the user can audit them.
|
||||
test("[W1-core] #717: ctx_execute summary:true echoes the language and the code before stdout", async () => {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "cm-echo-")));
|
||||
|
||||
Reference in new issue
Block a user