akm-cli 0.9.6 → 0.9.8-beta.1
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/CHANGELOG.md +408 -0
- package/dist/assets/hints/cli-hints-full.md +3 -3
- package/dist/assets/improve-strategies/catchup.json +40 -11
- package/dist/assets/improve-strategies/thorough.json +45 -7
- package/dist/assets/tasks/improve/akm-improve-frequent.yml +2 -2
- package/dist/commands/agent/contribute-cli.js +11 -0
- package/dist/commands/env/env.js +2 -21
- package/dist/commands/health/checks.js +0 -25
- package/dist/commands/health/improve-metrics.js +8 -34
- package/dist/commands/health/windows.js +0 -4
- package/dist/commands/health.js +1 -35
- package/dist/commands/improve/consolidate/eligibility.js +11 -5
- package/dist/commands/improve/extract.js +36 -32
- package/dist/commands/improve/improve-cli.js +1 -1
- package/dist/commands/improve/improve-strategies.js +0 -4
- package/dist/commands/improve/memory/memory-belief.js +15 -5
- package/dist/commands/improve/memory/memory-contradiction-detect.js +16 -25
- package/dist/commands/improve/memory/memory-improve.js +9 -20
- package/dist/commands/improve/preparation.js +53 -37
- package/dist/commands/improve/reflect.js +14 -18
- package/dist/commands/lint/base-linter.js +182 -19
- package/dist/commands/lint/index.js +21 -9
- package/dist/commands/migrate/config-extra-params.js +61 -0
- package/dist/commands/migrate/dead-residue.js +113 -0
- package/dist/commands/migrate/stale-txn.js +49 -0
- package/dist/commands/migrate-cli.js +42 -1
- package/dist/commands/proposal/proposal.js +1 -21
- package/dist/commands/proposal/repository.js +0 -4
- package/dist/commands/proposal/validators/proposal-quality-validators.js +0 -6
- package/dist/commands/read/curate.js +51 -18
- package/dist/commands/read/search-cli.js +24 -1
- package/dist/commands/read/show.js +2 -1
- package/dist/commands/sources/installed-stashes.js +5 -1
- package/dist/commands/sources/self-update.js +38 -1
- package/dist/commands/sources/sources-cli.js +17 -1
- package/dist/commands/tasks/tasks.js +0 -8
- package/dist/commands/url-checker.js +20 -28
- package/dist/core/adapter/adapters/agent-skills-adapter.js +2 -6
- package/dist/core/adapter/adapters/akm-adapter.js +2 -3
- package/dist/core/adapter/adapters/akm-lint.js +2 -20
- package/dist/core/adapter/adapters/akm-task-adapter.js +2 -6
- package/dist/core/adapter/adapters/akm-workflow-adapter.js +2 -6
- package/dist/core/adapter/adapters/dotenv-adapter.js +2 -22
- package/dist/core/adapter/adapters/generic-files-adapter.js +3 -9
- package/dist/core/adapter/adapters/llm-wiki-adapter.js +2 -6
- package/dist/core/adapter/adapters/okf-adapter.js +7 -18
- package/dist/core/adapter/adapters/shared.js +2 -0
- package/dist/core/adapter/adapters/tool-dir-shared.js +3 -9
- package/dist/core/adapter/adapters/website-snapshot-adapter.js +2 -6
- package/dist/core/adapter/validate-context.js +1 -3
- package/dist/core/asset/asset-placement.js +14 -5
- package/dist/core/asset/frontmatter.js +212 -0
- package/dist/core/asset/memory-archive.js +97 -0
- package/dist/core/common.js +66 -2
- package/dist/core/config/config-walker.js +6 -10
- package/dist/core/config/config.js +11 -8
- package/dist/core/config/engine-semantics.js +0 -2
- package/dist/core/extra-params.js +17 -13
- package/dist/core/improve-result.js +1 -3
- package/dist/core/json-schema.js +9 -11
- package/dist/core/state/migrations.js +52 -2
- package/dist/core/state-db.js +2 -1
- package/dist/execution/executable-identity.js +1 -3
- package/dist/execution/guarded-source.js +1 -6
- package/dist/indexer/bundle-identity-guard.js +6 -1
- package/dist/indexer/db/graph-db.js +139 -154
- package/dist/indexer/ensure-index.js +11 -19
- package/dist/indexer/graph/graph-boost.js +23 -34
- package/dist/indexer/graph/graph-extraction.js +12 -2
- package/dist/indexer/indexer.js +1 -1
- package/dist/indexer/lookup/adapter-concept-owner.js +12 -9
- package/dist/indexer/passes/memory-inference.js +7 -2
- package/dist/indexer/scan/drain-dir.js +2 -4
- package/dist/indexer/search/db-search.js +3 -3
- package/dist/indexer/search/fts-query.js +10 -15
- package/dist/indexer/search/search-source.js +0 -13
- package/dist/indexer/usage/usage-events.js +9 -1
- package/dist/indexer/walk/walker.js +11 -6
- package/dist/integrations/harnesses/claude/result-extractor.js +30 -15
- package/dist/integrations/harnesses/codex/result-extractor.js +43 -6
- package/dist/integrations/harnesses/copilot/result-extractor.js +39 -12
- package/dist/integrations/harnesses/gemini/result-extractor.js +40 -12
- package/dist/integrations/harnesses/index.js +0 -4
- package/dist/integrations/harnesses/openhands/result-extractor.js +51 -19
- package/dist/integrations/harnesses/pi/result-extractor.js +45 -12
- package/dist/integrations/lockfile.js +0 -14
- package/dist/integrations/session-logs/index.js +0 -81
- package/dist/llm/client.js +0 -12
- package/dist/llm/memory-infer.js +1 -3
- package/dist/llm/usage-telemetry.js +1 -3
- package/dist/registry/create-provider-registry.js +4 -0
- package/dist/registry/factory.js +4 -0
- package/dist/registry/resolve.js +23 -8
- package/dist/runtime.js +0 -12
- package/dist/scripts/akm-migrate-node.js +155 -251
- package/dist/scripts/akm-migrate.js +155 -251
- package/dist/setup/setup.js +6 -12
- package/dist/sources/providers/git-install.js +7 -2
- package/dist/sources/providers/tar-utils.js +1 -7
- package/dist/sources/snapshot-fetchers/content-extract.js +0 -17
- package/dist/sources/snapshot-fetchers/website-ingest.js +126 -0
- package/dist/storage/managed-db.js +20 -7
- package/dist/storage/repositories/events-repository.js +0 -81
- package/dist/storage/repositories/index-connection.js +45 -3
- package/dist/storage/repositories/index-entries-repository.js +0 -17
- package/dist/storage/repositories/index-fts-repository.js +24 -30
- package/dist/storage/repositories/index-utility-repository.js +0 -57
- package/dist/storage/repositories/index-vec-repository.js +25 -27
- package/dist/storage/repositories/task-history-repository.js +9 -3
- package/dist/tasks/backends/cron.js +49 -9
- package/dist/tasks/backends/launchd.js +8 -18
- package/dist/tasks/resolve-akm-bin.js +17 -2
- package/dist/tasks/run/task-history.js +21 -31
- package/dist/tasks/scheduler-invocation.js +8 -1
- package/dist/tasks/scheduler-sync.js +1 -6
- package/dist/tasks/source/bounded-document.js +1 -14
- package/dist/tasks/source/parse-task-source.js +23 -9
- package/dist/workflows/exec/child-workflow.js +1 -1
- package/dist/workflows/exec/native-executor.js +2 -2
- package/dist/workflows/exec/step-work.js +5 -17
- package/dist/workflows/exec/worktree.js +40 -6
- package/dist/workflows/freeze/task-bindings.js +2 -4
- package/dist/workflows/ir/compile.js +3 -14
- package/dist/workflows/ir/schema-v4.js +4 -6
- package/dist/workflows/ir/schema.js +2 -5
- package/dist/workflows/parser.js +23 -26
- package/dist/workflows/source-files.js +8 -13
- package/dist/workflows/source-ir/schema.js +1 -19
- package/docs/migration/v0.9.0-troubleshooting.md +12 -2
- package/docs/reference/cli.md +7 -1
- package/docs/reference/workflow-schema.md +24 -0
- package/package.json +2 -5
- package/dist/assets/improve-strategies/frequent.json +0 -15
- package/dist/assets/improve-strategies/memory-focus.json +0 -15
- package/dist/workflows/source-ir/compare.js +0 -17
package/dist/setup/setup.js
CHANGED
|
@@ -24,7 +24,7 @@ import { deriveBundleIds } from "../core/bundle-id.js";
|
|
|
24
24
|
import { bundleEntryToSourceEntry, DEFAULT_CONFIG, loadUserConfig, mutateConfigWithPrecommit, parseAndValidateConfigText, primaryBundlePath, validateCompleteConfig, } from "../core/config/config.js";
|
|
25
25
|
import { readConfigText } from "../core/config/config-io.js";
|
|
26
26
|
import { listTopLevelConfigKeys } from "../core/config/config-schema.js";
|
|
27
|
-
import { deepMergeConfig } from "../core/config/deep-merge.js";
|
|
27
|
+
import { deepMergeConfig, isPlainObject } from "../core/config/deep-merge.js";
|
|
28
28
|
import { ConfigError, UsageError } from "../core/errors.js";
|
|
29
29
|
import { getConfigPath, getDefaultStashDir, isTransientStashPath } from "../core/paths.js";
|
|
30
30
|
import { warn } from "../core/warn.js";
|
|
@@ -131,17 +131,11 @@ export function assertSetupConfigPreflight() {
|
|
|
131
131
|
`(e.g. \`mv ${configPath} ${configPath}.bak\`) and re-run \`akm setup\`.`);
|
|
132
132
|
}
|
|
133
133
|
}
|
|
134
|
-
function isPlainRecord(value) {
|
|
135
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
136
|
-
return false;
|
|
137
|
-
const prototype = Object.getPrototypeOf(value);
|
|
138
|
-
return prototype === Object.prototype || prototype === null;
|
|
139
|
-
}
|
|
140
134
|
function sameConfigValue(left, right) {
|
|
141
135
|
return isDeepStrictEqual(left, right);
|
|
142
136
|
}
|
|
143
137
|
function configArrayItemKey(value) {
|
|
144
|
-
if (!
|
|
138
|
+
if (!isPlainObject(value))
|
|
145
139
|
return `value:${JSON.stringify(value)}`;
|
|
146
140
|
if (typeof value.id === "string")
|
|
147
141
|
return `id:${value.id}`;
|
|
@@ -199,14 +193,14 @@ export function rebaseSetupChanges(original, desired, latest, pathParts = []) {
|
|
|
199
193
|
}
|
|
200
194
|
return result;
|
|
201
195
|
}
|
|
202
|
-
if (!
|
|
196
|
+
if (!isPlainObject(original) || !isPlainObject(desired)) {
|
|
203
197
|
if (!sameConfigValue(latest, original) && !sameConfigValue(latest, desired))
|
|
204
198
|
setupConflict(pathParts);
|
|
205
199
|
return desired;
|
|
206
200
|
}
|
|
207
|
-
if (latest !== undefined && !
|
|
201
|
+
if (latest !== undefined && !isPlainObject(latest))
|
|
208
202
|
setupConflict(pathParts);
|
|
209
|
-
const result =
|
|
203
|
+
const result = isPlainObject(latest) ? { ...latest } : {};
|
|
210
204
|
for (const key of new Set([...Object.keys(original), ...Object.keys(desired)])) {
|
|
211
205
|
if (!Object.hasOwn(desired, key)) {
|
|
212
206
|
if (Object.hasOwn(result, key) && !sameConfigValue(result[key], original[key]))
|
|
@@ -855,7 +849,7 @@ export async function runSetupFromConfig(opts) {
|
|
|
855
849
|
catch (e) {
|
|
856
850
|
throw new UsageError(`Invalid JSON in --config: ${e.message}`, "INVALID_FLAG_VALUE");
|
|
857
851
|
}
|
|
858
|
-
if (!
|
|
852
|
+
if (!isPlainObject(parsed)) {
|
|
859
853
|
throw new ConfigError("Setup config must contain a top-level object.", "INVALID_CONFIG_FILE");
|
|
860
854
|
}
|
|
861
855
|
const incoming = parsed;
|
|
@@ -48,8 +48,13 @@ export function inspectGitUpstream(repoDir) {
|
|
|
48
48
|
* commit SHA peels to itself.
|
|
49
49
|
*/
|
|
50
50
|
export function verifyClonedRevision(cloneDir, url, expectedRevision) {
|
|
51
|
-
if (!expectedRevision)
|
|
52
|
-
|
|
51
|
+
if (!expectedRevision) {
|
|
52
|
+
// `resolveGitArtifact` (registry/resolve.ts) throws when it cannot resolve
|
|
53
|
+
// a revision via `git ls-remote`, so a plain git install never reaches
|
|
54
|
+
// this call with `undefined` — treat it as a bug, not a silently-skipped
|
|
55
|
+
// check that would defeat the R-011 post-clone integrity verification.
|
|
56
|
+
throw new UsageError(`No revision was resolved from ${url}; refusing to install without a verifiable checkout.`);
|
|
57
|
+
}
|
|
53
58
|
const head = runGit(["-C", cloneDir, "rev-parse", "HEAD"]);
|
|
54
59
|
if (head.status !== 0 || !head.stdout.trim()) {
|
|
55
60
|
throw new UsageError(`Failed to read cloned HEAD at ${cloneDir}: ${head.stderr.trim() || "rev-parse failed"}`);
|
|
@@ -91,13 +91,7 @@ export function extractTarGzSecure(archivePath, destinationDir) {
|
|
|
91
91
|
scanExtractedFiles(destinationDir, destinationDir);
|
|
92
92
|
}
|
|
93
93
|
function scanExtractedFiles(dir, root) {
|
|
94
|
-
|
|
95
|
-
try {
|
|
96
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
97
|
-
}
|
|
98
|
-
catch {
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
94
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
101
95
|
for (const entry of entries) {
|
|
102
96
|
const fullPath = path.join(dir, entry.name);
|
|
103
97
|
// Reject only entries whose name is exactly the parent-traversal segment
|
|
@@ -609,20 +609,3 @@ export function htmlToMarkdownAndLinks(html, pageUrl) {
|
|
|
609
609
|
const markdown = root ? markdownFromRoot(root, html, pageUrl) : plainTextFallback(html);
|
|
610
610
|
return { markdown: finalizeMarkdown(markdown), links };
|
|
611
611
|
}
|
|
612
|
-
/**
|
|
613
|
-
* Collect links from the WHOLE document, not the extracted content region.
|
|
614
|
-
*
|
|
615
|
-
* Deliberate and load-bearing: nav/header/footer links are how a crawl
|
|
616
|
-
* discovers pages. Narrowing this to the content region would silently shrink
|
|
617
|
-
* every crawl to whatever the first page happens to link inline.
|
|
618
|
-
*/
|
|
619
|
-
export function extractDocumentLinks(html, pageUrl) {
|
|
620
|
-
let root;
|
|
621
|
-
try {
|
|
622
|
-
root = parse(scrubDangerousMarkup(html), { comment: false });
|
|
623
|
-
}
|
|
624
|
-
catch {
|
|
625
|
-
return [];
|
|
626
|
-
}
|
|
627
|
-
return collectLinksFromRoot(root, pageUrl);
|
|
628
|
-
}
|
|
@@ -23,6 +23,9 @@ const CACHE_STALE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
|
23
23
|
const QUEUE_EXPANSION_FACTOR = 5;
|
|
24
24
|
const MAX_PAGES_DEFAULT = 50;
|
|
25
25
|
const MAX_DEPTH_DEFAULT = 3;
|
|
26
|
+
/** Byte cap for the `llms.txt` manifest itself — a curated link list, never a large file. */
|
|
27
|
+
const LLMS_TXT_BYTE_CAP = 512 * 1024;
|
|
28
|
+
const LLMS_TXT_BODY_TIMEOUT_MS = 15_000;
|
|
26
29
|
/**
|
|
27
30
|
* Per-page body cap for website scraping. HTML pages this large are
|
|
28
31
|
* almost never useful as agent knowledge sources and a runaway server
|
|
@@ -531,6 +534,38 @@ async function crawlWebsite(startUrl, options) {
|
|
|
531
534
|
? createAllowAllRobotsPolicy()
|
|
532
535
|
: createRobotsPolicy((robotsUrl) => loadRobotsTxt(robotsUrl, { allowPrivateHosts: options.allowPrivateHosts, signal: crawlSignal }));
|
|
533
536
|
await assertStartUrlAllowedByRobots(robots, start, options.rawStartUrl);
|
|
537
|
+
// llms.txt fast path: an increasing number of doc sites publish a curated,
|
|
538
|
+
// deduplicated link list at `/llms.txt` specifically for tools like this
|
|
539
|
+
// one. When present, use it as the crawl frontier instead of discovering
|
|
540
|
+
// links by parsing HTML — each linked page still goes through the exact
|
|
541
|
+
// same robots-compliant, host-guarded `fetchWebsitePage` call below, so
|
|
542
|
+
// ingested pages stay individually addressable. Gated to origin-root start
|
|
543
|
+
// URLs only (mirrors `extractGithubRepository`'s repo-root restriction):
|
|
544
|
+
// adding a specific page must fetch that page, not silently pull in the
|
|
545
|
+
// whole site's manifest.
|
|
546
|
+
if (isOriginRootUrl(start)) {
|
|
547
|
+
const manifest = await fetchLlmsManifest(start, robots, {
|
|
548
|
+
allowPrivateHosts: options.allowPrivateHosts,
|
|
549
|
+
signal: crawlSignal,
|
|
550
|
+
});
|
|
551
|
+
if (manifest) {
|
|
552
|
+
warn("[akm] Using llms.txt manifest from %s", manifest.manifestUrl);
|
|
553
|
+
queue.length = 0;
|
|
554
|
+
for (const link of manifest.links) {
|
|
555
|
+
// A manifest can name arbitrary hosts; only same-origin links are
|
|
556
|
+
// honored by default, same as links discovered mid-crawl below.
|
|
557
|
+
if (link.origin !== allowedOrigin)
|
|
558
|
+
continue;
|
|
559
|
+
const candidate = normalizeCrawlUrl(link.toString());
|
|
560
|
+
if (!candidate)
|
|
561
|
+
continue;
|
|
562
|
+
// depth = maxDepth: fetch each manifest page individually, but don't
|
|
563
|
+
// treat it as a fresh BFS seed — the manifest is already the
|
|
564
|
+
// author-curated set of pages worth ingesting.
|
|
565
|
+
queue.push({ url: candidate, rawUrl: link.toString(), depth: options.maxDepth, deferrals: 0 });
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
534
569
|
// Counts actual `fetchWebsitePage` invocations (regardless of outcome) so
|
|
535
570
|
// Crawl-delay pacing skips the first fetch and never charges a delay slot
|
|
536
571
|
// to a URL that robots.txt skipped without ever being fetched (C-11).
|
|
@@ -870,6 +905,97 @@ function buildMarkdownSnapshot(page, slug, tags) {
|
|
|
870
905
|
"",
|
|
871
906
|
].join("\n");
|
|
872
907
|
}
|
|
908
|
+
/**
|
|
909
|
+
* True for a start URL that names an origin's root (no path, no query).
|
|
910
|
+
* Matches how `extractGithubRepository` restricts its own special-case match
|
|
911
|
+
* to repository-root URLs — the llms.txt probe must not fire for a
|
|
912
|
+
* user-supplied deep link, or `akm bundle add <site>/guides/foo` would
|
|
913
|
+
* silently ingest the whole site's manifest instead of the page requested.
|
|
914
|
+
*/
|
|
915
|
+
export function isOriginRootUrl(url) {
|
|
916
|
+
return url.pathname === "/" && !url.search;
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Parses the `llms.txt` link-list format: list items shaped like
|
|
920
|
+
* `- [title](path) - description` (the description, and its separator, are
|
|
921
|
+
* ignored — only the link target is needed). Any line that isn't a markdown
|
|
922
|
+
* link list item — headings, the leading `# Title`/`> summary` lines, prose —
|
|
923
|
+
* is simply not a link line and is skipped.
|
|
924
|
+
*/
|
|
925
|
+
export function parseLlmsTxtLinks(text, baseUrl) {
|
|
926
|
+
const links = [];
|
|
927
|
+
const seen = new Set();
|
|
928
|
+
for (const line of text.split(/\r?\n/)) {
|
|
929
|
+
const match = line.trim().match(/^-\s*\[[^\]]*\]\(([^)\s]+)\)/);
|
|
930
|
+
const href = match?.[1];
|
|
931
|
+
if (!href)
|
|
932
|
+
continue;
|
|
933
|
+
let resolved;
|
|
934
|
+
try {
|
|
935
|
+
resolved = new URL(href, baseUrl);
|
|
936
|
+
}
|
|
937
|
+
catch {
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
if (resolved.protocol !== "http:" && resolved.protocol !== "https:")
|
|
941
|
+
continue;
|
|
942
|
+
const key = resolved.toString();
|
|
943
|
+
if (seen.has(key))
|
|
944
|
+
continue;
|
|
945
|
+
seen.add(key);
|
|
946
|
+
links.push(resolved);
|
|
947
|
+
}
|
|
948
|
+
return links;
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* Probes `<origin>/llms.txt` and, if present, returns its parsed link list.
|
|
952
|
+
* Reuses `fetchWebsiteResponse` so the manifest fetch itself gets the exact
|
|
953
|
+
* same SSRF host guard, redirect handling, and (via `robots`) robots.txt
|
|
954
|
+
* compliance as any other page fetch — this is still a fetch against a
|
|
955
|
+
* user-supplied host, no different from the rest of the crawl.
|
|
956
|
+
*
|
|
957
|
+
* `llms-full.txt` (the single-file concatenation of every page) is
|
|
958
|
+
* deliberately NOT read here. Its `## <path>` separators are ambiguous — page
|
|
959
|
+
* content legitimately contains `##` headings too — so recovered page
|
|
960
|
+
* boundaries can't be trusted, whereas per-page fetches through the existing
|
|
961
|
+
* pipeline are cheap, bounded by this author-curated list, and produce
|
|
962
|
+
* cleanly addressable assets. See the issue's "alternatives considered".
|
|
963
|
+
*/
|
|
964
|
+
async function fetchLlmsManifest(start, robots, options) {
|
|
965
|
+
const manifestUrl = new URL("/llms.txt", start.origin).toString();
|
|
966
|
+
const decision = await resolveCrawlRobotsDecision(robots, manifestUrl);
|
|
967
|
+
if (!decision.allowed)
|
|
968
|
+
return null;
|
|
969
|
+
let fetched;
|
|
970
|
+
try {
|
|
971
|
+
fetched = await fetchWebsiteResponse(decision.fetchUrl, 0, {
|
|
972
|
+
allowPrivateHosts: options.allowPrivateHosts,
|
|
973
|
+
signal: options.signal,
|
|
974
|
+
robots,
|
|
975
|
+
});
|
|
976
|
+
}
|
|
977
|
+
catch {
|
|
978
|
+
return null;
|
|
979
|
+
}
|
|
980
|
+
if (!fetched.response.ok) {
|
|
981
|
+
await fetched.response.body?.cancel().catch(() => undefined);
|
|
982
|
+
return null;
|
|
983
|
+
}
|
|
984
|
+
let text;
|
|
985
|
+
try {
|
|
986
|
+
text = await readBodyWithByteCap(fetched.response, LLMS_TXT_BYTE_CAP, {
|
|
987
|
+
bodyTimeoutMs: LLMS_TXT_BODY_TIMEOUT_MS,
|
|
988
|
+
signal: options.signal,
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
catch {
|
|
992
|
+
return null;
|
|
993
|
+
}
|
|
994
|
+
const links = parseLlmsTxtLinks(text, fetched.finalUrl);
|
|
995
|
+
if (links.length === 0)
|
|
996
|
+
return null;
|
|
997
|
+
return { manifestUrl: fetched.finalUrl, links };
|
|
998
|
+
}
|
|
873
999
|
function normalizeCrawlUrl(rawUrl) {
|
|
874
1000
|
try {
|
|
875
1001
|
const parsed = new URL(rawUrl);
|
|
@@ -61,13 +61,19 @@ export function openManagedDatabase(spec) {
|
|
|
61
61
|
// Initializers may open a transaction (source update does so before index
|
|
62
62
|
// schema work). Never strand that transaction/handle when later setup
|
|
63
63
|
// fails; closing rolls it back and releases its writer lock.
|
|
64
|
-
|
|
65
|
-
|
|
64
|
+
//
|
|
65
|
+
// `db.inTransaction` is INSIDE the try: reading it on an already-closed
|
|
66
|
+
// handle throws "Database has closed", and it used to sit outside, so that
|
|
67
|
+
// throw escaped and replaced `error` — masking the real initializer failure
|
|
68
|
+
// this whole block exists to preserve. Every other step here was already
|
|
69
|
+
// guarded for exactly that reason; this one was not, and a concurrent
|
|
70
|
+
// close (WAL contention between two writers) reached it.
|
|
71
|
+
try {
|
|
72
|
+
if (db.inTransaction)
|
|
66
73
|
db.exec("ROLLBACK");
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// Closing remains the final rollback backstop.
|
|
71
77
|
}
|
|
72
78
|
try {
|
|
73
79
|
db.close();
|
|
@@ -99,6 +105,13 @@ export function withManagedDb(open, fn, opts) {
|
|
|
99
105
|
return fn(db);
|
|
100
106
|
}
|
|
101
107
|
finally {
|
|
102
|
-
|
|
108
|
+
try {
|
|
109
|
+
db.close();
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
// A close() throw here would REPLACE fn's in-flight exception — the same
|
|
113
|
+
// masking openManagedDatabase above was hardened against. The handle is
|
|
114
|
+
// being discarded either way; fn's error is the one that matters.
|
|
115
|
+
}
|
|
103
116
|
}
|
|
104
117
|
}
|
|
@@ -147,84 +147,3 @@ export function purgeOldEvents(db, retentionDays = 90) {
|
|
|
147
147
|
const changes = result.changes ?? 0;
|
|
148
148
|
return typeof changes === "bigint" ? Number(changes) : changes;
|
|
149
149
|
}
|
|
150
|
-
/**
|
|
151
|
-
* Import all events from an `events.jsonl` file into the `events` table.
|
|
152
|
-
*
|
|
153
|
-
* The old byte-offset `id` is NOT preserved — the database assigns new
|
|
154
|
-
* monotonic integer ids. Callers that persisted a byte-offset cursor must
|
|
155
|
-
* discard it after migration and use the returned `maxId` as the new cursor.
|
|
156
|
-
*
|
|
157
|
-
* **Idempotency**: each line is pre-checked against the `events` table using
|
|
158
|
-
* `(event_type, ts, ref, metadata_json)` as the duplicate key. Lines whose
|
|
159
|
-
* exact tuple is already present are skipped and reported as `skipped` in the
|
|
160
|
-
* return value. This makes the migration safe to re-run (the v0.7→v0.8
|
|
161
|
-
* migration guide recommends re-running the script as a recovery path; without
|
|
162
|
-
* this guard, every re-run would double-import the entire event log).
|
|
163
|
-
*
|
|
164
|
-
* Duplicate detection is per-import-tuple, not a table-wide UNIQUE constraint:
|
|
165
|
-
* the events table has no UNIQUE constraint at runtime so that
|
|
166
|
-
* `appendEvent` can write multiple events with the same ts (sub-millisecond
|
|
167
|
-
* bursts produce identical `(event_type, ts, ref)` triples in practice). The
|
|
168
|
-
* SELECT-first check is scoped to the import path only.
|
|
169
|
-
*
|
|
170
|
-
* The import is wrapped in a single transaction for atomicity.
|
|
171
|
-
*
|
|
172
|
-
* @param db - Open state.db connection.
|
|
173
|
-
* @param jsonlPath - Absolute path to the events.jsonl file to import.
|
|
174
|
-
* @returns Number of rows inserted, the max id assigned, and the
|
|
175
|
-
* count of rows skipped because an identical event already
|
|
176
|
-
* existed in the table.
|
|
177
|
-
*/
|
|
178
|
-
export async function importEventsJsonl(db, jsonlPath) {
|
|
179
|
-
const { readFileSync, existsSync } = await import("node:fs");
|
|
180
|
-
if (!existsSync(jsonlPath)) {
|
|
181
|
-
return { imported: 0, maxId: 0, skipped: 0 };
|
|
182
|
-
}
|
|
183
|
-
const text = readFileSync(jsonlPath, "utf8");
|
|
184
|
-
const lines = text.split("\n").filter((l) => l.trim().length > 0);
|
|
185
|
-
let imported = 0;
|
|
186
|
-
let maxId = 0;
|
|
187
|
-
let skipped = 0;
|
|
188
|
-
const insertStmt = db.prepare(`INSERT INTO events (event_type, ts, ref, metadata_json)
|
|
189
|
-
VALUES (?, ?, ?, ?)
|
|
190
|
-
RETURNING id`);
|
|
191
|
-
// Dedup pre-check: matches by the full tuple including metadata_json so an
|
|
192
|
-
// import is idempotent over identical rows but does not collide with two
|
|
193
|
-
// genuinely different events that happen to share (event_type, ts, ref).
|
|
194
|
-
//
|
|
195
|
-
// Uses IS for ref so two NULL refs compare equal (a plain `=` would treat
|
|
196
|
-
// NULL = NULL as NULL and the row would be re-inserted on every run).
|
|
197
|
-
const existsStmt = db.prepare(`SELECT 1 FROM events
|
|
198
|
-
WHERE event_type = ?
|
|
199
|
-
AND ts = ?
|
|
200
|
-
AND ref IS ?
|
|
201
|
-
AND metadata_json = ?
|
|
202
|
-
LIMIT 1`);
|
|
203
|
-
db.transaction(() => {
|
|
204
|
-
for (const line of lines) {
|
|
205
|
-
let parsed;
|
|
206
|
-
try {
|
|
207
|
-
parsed = JSON.parse(line);
|
|
208
|
-
}
|
|
209
|
-
catch {
|
|
210
|
-
continue; // skip malformed lines — same behaviour as readEvents()
|
|
211
|
-
}
|
|
212
|
-
const eventType = typeof parsed.eventType === "string" ? parsed.eventType : "unknown";
|
|
213
|
-
const ts = typeof parsed.ts === "string" ? parsed.ts : new Date().toISOString();
|
|
214
|
-
const ref = typeof parsed.ref === "string" ? parsed.ref : null;
|
|
215
|
-
const metadata = parsed.metadata !== undefined && typeof parsed.metadata === "object" ? JSON.stringify(parsed.metadata) : "{}";
|
|
216
|
-
const duplicate = existsStmt.get(eventType, ts, ref, metadata);
|
|
217
|
-
if (duplicate) {
|
|
218
|
-
skipped++;
|
|
219
|
-
continue;
|
|
220
|
-
}
|
|
221
|
-
const result = insertStmt.get(eventType, ts, ref, metadata);
|
|
222
|
-
if (result) {
|
|
223
|
-
imported++;
|
|
224
|
-
if (result.id > maxId)
|
|
225
|
-
maxId = result.id;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
})();
|
|
229
|
-
return { imported, maxId, skipped };
|
|
230
|
-
}
|
|
@@ -10,10 +10,12 @@
|
|
|
10
10
|
* import their opener from a sibling here instead of reaching up into the
|
|
11
11
|
* indexer — inverting the old storage→indexer arrow.
|
|
12
12
|
*/
|
|
13
|
+
import fs from "node:fs";
|
|
13
14
|
import { createRequire } from "node:module";
|
|
14
15
|
import { ConfigError } from "../../core/errors.js";
|
|
15
16
|
import { classifyPathAccess, describeInaccessiblePath } from "../../core/path-access.js";
|
|
16
17
|
import { getDbPath } from "../../core/paths.js";
|
|
18
|
+
import { warn } from "../../core/warn.js";
|
|
17
19
|
import { openDatabase } from "../database.js";
|
|
18
20
|
import { openManagedDatabase } from "../managed-db.js";
|
|
19
21
|
import { SQLITE_BUSY_TIMEOUT_MS } from "../sqlite-pragmas.js";
|
|
@@ -21,9 +23,23 @@ import { openSqliteReadSnapshot } from "../sqlite-read-snapshot.js";
|
|
|
21
23
|
import { isCanonicalIndexGeneration } from "./index-entry-schema.js";
|
|
22
24
|
import { ensureSchema } from "./index-schema.js";
|
|
23
25
|
import { loadVecExtension, warnIfVecMissing } from "./index-vec-repository.js";
|
|
26
|
+
/**
|
|
27
|
+
* Whether `error` is SQLite reporting on-disk corruption (`SQLITE_CORRUPT`,
|
|
28
|
+
* "database disk image is malformed") rather than a permission, lock, or
|
|
29
|
+
* schema problem. Matched on both `code` (bun:sqlite, better-sqlite3) and
|
|
30
|
+
* message text, since driver error shapes are not perfectly uniform.
|
|
31
|
+
*/
|
|
32
|
+
function isCorruptionError(error) {
|
|
33
|
+
const code = error?.code;
|
|
34
|
+
if (code === "SQLITE_CORRUPT")
|
|
35
|
+
return true;
|
|
36
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
37
|
+
return message.includes("database disk image is malformed") || message.includes("SQLITE_CORRUPT");
|
|
38
|
+
}
|
|
24
39
|
export function openIndexDatabase(dbPath, options) {
|
|
25
|
-
|
|
26
|
-
|
|
40
|
+
const resolvedPath = dbPath ?? getDbPath();
|
|
41
|
+
const spec = {
|
|
42
|
+
path: resolvedPath,
|
|
27
43
|
init: (db) => {
|
|
28
44
|
// Try to load sqlite-vec extension
|
|
29
45
|
loadVecExtension(db);
|
|
@@ -41,7 +57,33 @@ export function openIndexDatabase(dbPath, options) {
|
|
|
41
57
|
// Warn once at init if using JS fallback with many entries
|
|
42
58
|
warnIfVecMissing(db, { once: true });
|
|
43
59
|
},
|
|
44
|
-
}
|
|
60
|
+
};
|
|
61
|
+
try {
|
|
62
|
+
return openManagedDatabase(spec);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
// index.db is a derived cache, fully regenerable from the stash on disk
|
|
66
|
+
// (see src/core/state-db.ts's "Why a separate database from index.db"
|
|
67
|
+
// note) — so real on-disk corruption is recovered by deleting the file
|
|
68
|
+
// and rebuilding, not by surfacing a raw SQLITE_CORRUPT to the caller or
|
|
69
|
+
// quietly falling through to an unreadable index. This mirrors the
|
|
70
|
+
// existing stale-version-marker rebuild below, one layer further down
|
|
71
|
+
// (that path opens fine and rewrites tables in place; corruption prevents
|
|
72
|
+
// even opening, so the file itself has to go first).
|
|
73
|
+
if (!isCorruptionError(error))
|
|
74
|
+
throw error;
|
|
75
|
+
warn(`Index database is corrupt at ${resolvedPath} — rebuilding.`);
|
|
76
|
+
for (const suffix of ["", "-wal", "-shm"]) {
|
|
77
|
+
try {
|
|
78
|
+
fs.rmSync(`${resolvedPath}${suffix}`, { force: true });
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Best-effort cleanup; the retried open below still fails loudly if
|
|
82
|
+
// the file could not actually be removed.
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return openManagedDatabase(spec);
|
|
86
|
+
}
|
|
45
87
|
}
|
|
46
88
|
/**
|
|
47
89
|
* Read the operator-configured embedding dimension from the on-disk config.
|
|
@@ -683,23 +683,6 @@ export function getEntryFilePathById(db, id) {
|
|
|
683
683
|
const row = db.prepare("SELECT file_path FROM entries WHERE id = ?").get(id);
|
|
684
684
|
return row?.file_path;
|
|
685
685
|
}
|
|
686
|
-
/**
|
|
687
|
-
* Fetch every `(file_path, document_json)` row whose path is under a source
|
|
688
|
-
* root. The path containment filter is applied in JS so SQLite LIKE wildcard
|
|
689
|
-
* characters in filesystem paths cannot widen ownership.
|
|
690
|
-
*
|
|
691
|
-
* Lifted verbatim (WS5) from the inline query in commands/graph.ts'
|
|
692
|
-
* `buildRefByPath`. The full result set is materialised with `.all()` before
|
|
693
|
-
* return so callers can iterate it after the connection closes (WS5
|
|
694
|
-
* connection-lifetime rule). JSON parsing stays with the caller, unchanged.
|
|
695
|
-
*/
|
|
696
|
-
export function getEntryRefRowsForStashRoot(db, stashRoot) {
|
|
697
|
-
const root = path.resolve(stashRoot);
|
|
698
|
-
return db.prepare("SELECT file_path, document_json FROM entries").all().filter((row) => {
|
|
699
|
-
const file = path.resolve(row.file_path);
|
|
700
|
-
return file === root || file.startsWith(`${root}${path.sep}`);
|
|
701
|
-
});
|
|
702
|
-
}
|
|
703
686
|
// ── Indexer-phase helpers (moved from indexer.ts) ────────────────────────────
|
|
704
687
|
/**
|
|
705
688
|
* Return distinct zero-result search queries from the `usage_events` table
|
|
@@ -91,38 +91,32 @@ function runFtsQuery(db, ftsQuery, lexicalMatch, limit, entryType, excludeTypes)
|
|
|
91
91
|
ORDER BY bm25Score, e.id ASC
|
|
92
92
|
LIMIT ?
|
|
93
93
|
`;
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
entry = JSON.parse(row.documentJson);
|
|
102
|
-
}
|
|
103
|
-
catch {
|
|
104
|
-
warn(`[db] searchFts: skipping entry id=${row.id} — corrupt document_json`);
|
|
105
|
-
continue;
|
|
106
|
-
}
|
|
107
|
-
results.push({
|
|
108
|
-
id: row.id,
|
|
109
|
-
filePath: row.filePath,
|
|
110
|
-
entry,
|
|
111
|
-
searchText: row.searchText,
|
|
112
|
-
bm25Score: row.bm25Score,
|
|
113
|
-
itemRef: row.itemRef,
|
|
114
|
-
bundleId: row.bundleId,
|
|
115
|
-
conceptId: row.conceptId,
|
|
116
|
-
adapterId: row.adapterId,
|
|
117
|
-
lexicalMatch,
|
|
118
|
-
});
|
|
94
|
+
const rows = db.prepare(sql).all(...params);
|
|
95
|
+
// Guard against corrupt JSON — skip the row rather than crashing
|
|
96
|
+
const results = [];
|
|
97
|
+
for (const row of rows) {
|
|
98
|
+
let entry;
|
|
99
|
+
try {
|
|
100
|
+
entry = JSON.parse(row.documentJson);
|
|
119
101
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
102
|
+
catch {
|
|
103
|
+
warn(`[db] searchFts: skipping entry id=${row.id} — corrupt document_json`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
results.push({
|
|
107
|
+
id: row.id,
|
|
108
|
+
filePath: row.filePath,
|
|
109
|
+
entry,
|
|
110
|
+
searchText: row.searchText,
|
|
111
|
+
bm25Score: row.bm25Score,
|
|
112
|
+
itemRef: row.itemRef,
|
|
113
|
+
bundleId: row.bundleId,
|
|
114
|
+
conceptId: row.conceptId,
|
|
115
|
+
adapterId: row.adapterId,
|
|
116
|
+
lexicalMatch,
|
|
117
|
+
});
|
|
125
118
|
}
|
|
119
|
+
return results;
|
|
126
120
|
}
|
|
127
121
|
/**
|
|
128
122
|
* Explicitly rebuild the complete FTS5 projection from canonical entries.
|
|
@@ -263,63 +263,6 @@ function getSourceScopedRetrievalCounts(indexDb, stateDb, refs, options) {
|
|
|
263
263
|
}
|
|
264
264
|
return result;
|
|
265
265
|
}
|
|
266
|
-
/**
|
|
267
|
-
* Apply a MemRL reward signal to a batch of entries via exponential moving
|
|
268
|
-
* average (EMA): next = clamp(current + lr * (reward - current), 0, 1).
|
|
269
|
-
*
|
|
270
|
-
* Wrapped in a single transaction so all bumps succeed or fail together.
|
|
271
|
-
* The indexer (`akm index`) will overwrite these values at next reindex run;
|
|
272
|
-
* bumps are intentionally temporary hints between index runs, not permanent
|
|
273
|
-
* overrides.
|
|
274
|
-
*
|
|
275
|
-
* When `scopeKey` is provided, also writes a scoped bump to
|
|
276
|
-
* `utility_scores_scoped` so per-project usage signals accumulate alongside
|
|
277
|
-
* the global ones. The global table is always updated regardless.
|
|
278
|
-
*/
|
|
279
|
-
export function bumpUtilityScoresBatch(db, entryIds, reward, lr = 0.1, scopeKey) {
|
|
280
|
-
if (entryIds.length === 0)
|
|
281
|
-
return;
|
|
282
|
-
db.transaction(() => {
|
|
283
|
-
const { global: scoreMap } = getUtilityScoresByIds(db, entryIds);
|
|
284
|
-
const now = new Date().toISOString();
|
|
285
|
-
const nowMs = Date.now();
|
|
286
|
-
const stmt = db.prepare(`INSERT INTO utility_scores (entry_id, utility, show_count, search_count, select_rate, last_used_at, updated_at)
|
|
287
|
-
VALUES (?, ?, 0, 0, 0, ?, ?)
|
|
288
|
-
ON CONFLICT(entry_id) DO UPDATE SET
|
|
289
|
-
utility = excluded.utility,
|
|
290
|
-
updated_at = excluded.updated_at`);
|
|
291
|
-
// Prepare scoped upsert once outside the loop when scopeKey is present.
|
|
292
|
-
const scopedStmt = scopeKey
|
|
293
|
-
? db.prepare(`INSERT INTO utility_scores_scoped (entry_id, scope_key, utility, last_used_at)
|
|
294
|
-
VALUES (?, ?, ?, ?)
|
|
295
|
-
ON CONFLICT(entry_id, scope_key) DO UPDATE SET
|
|
296
|
-
utility = excluded.utility,
|
|
297
|
-
last_used_at = excluded.last_used_at`)
|
|
298
|
-
: null;
|
|
299
|
-
for (const entryId of entryIds) {
|
|
300
|
-
const existing = scoreMap.get(entryId);
|
|
301
|
-
const current = existing?.utility ?? 0;
|
|
302
|
-
const next = Math.max(0, Math.min(1, current + lr * (reward - current)));
|
|
303
|
-
stmt.run(entryId, next, now, now);
|
|
304
|
-
if (scopedStmt && scopeKey) {
|
|
305
|
-
// Retrieve the current scoped utility so we can apply the same EMA.
|
|
306
|
-
const scopedCurrent = getScopedUtility(db, entryId, scopeKey);
|
|
307
|
-
const scopedNext = Math.max(0, Math.min(1, scopedCurrent + lr * (reward - scopedCurrent)));
|
|
308
|
-
scopedStmt.run(entryId, scopeKey, scopedNext, nowMs);
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
})();
|
|
312
|
-
}
|
|
313
|
-
/**
|
|
314
|
-
* Return the current utility value for a single (entry_id, scope_key) pair.
|
|
315
|
-
* Returns 0 when no row exists yet.
|
|
316
|
-
*/
|
|
317
|
-
function getScopedUtility(db, entryId, scopeKey) {
|
|
318
|
-
const row = db
|
|
319
|
-
.prepare("SELECT utility FROM utility_scores_scoped WHERE entry_id = ? AND scope_key = ?")
|
|
320
|
-
.get(entryId, scopeKey);
|
|
321
|
-
return row?.utility ?? 0;
|
|
322
|
-
}
|
|
323
266
|
/**
|
|
324
267
|
* Apply accumulated feedback counts to the utility score of an entry, persisting
|
|
325
268
|
* the result. The bounded-step EMA policy itself (MemRL, F-5 / #386,
|