akm-cli 0.9.0-beta.5 → 0.9.0-beta.51
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 +711 -0
- package/README.md +12 -4
- package/dist/akm +38 -0
- package/dist/akm-migrate-storage +38 -0
- package/dist/assets/profiles/default.json +9 -4
- package/dist/assets/profiles/frequent.json +1 -1
- package/dist/assets/profiles/memory-focus.json +1 -1
- package/dist/assets/profiles/quick.json +1 -1
- package/dist/assets/profiles/synthesize.json +15 -0
- package/dist/assets/profiles/thorough.json +1 -1
- package/dist/assets/prompts/consolidate-system.md +23 -0
- package/dist/assets/prompts/contradiction-judge.md +33 -0
- package/dist/assets/prompts/distill-knowledge-system.md +22 -0
- package/dist/assets/prompts/distill-lesson-system.md +36 -0
- package/dist/assets/prompts/extract-session.md +6 -2
- package/dist/assets/prompts/graph-extract-system.md +1 -0
- package/dist/assets/prompts/graph-extract-user-prompt.md +1 -1
- package/dist/assets/prompts/memory-infer-system.md +1 -0
- package/dist/assets/prompts/memory-infer-user.md +5 -0
- package/dist/assets/prompts/metadata-enhance-system.md +1 -0
- package/dist/assets/prompts/procedural-system.md +44 -0
- package/dist/assets/prompts/recombine-system.md +40 -0
- package/dist/assets/prompts/staleness-detect-system.md +6 -0
- package/dist/assets/prompts/validate-summary-judge.md +1 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/agent.md +38 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/command.md +38 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/fact.md +39 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/knowledge.md +40 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/lesson.md +43 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/memory.md +38 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/script.md +43 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/skill.md +40 -0
- package/dist/assets/stash-skeleton/facts/conventions/assets/workflow.md +43 -0
- package/dist/assets/templates/html/health.html +281 -111
- package/dist/assets/wiki/ingest-workflow-template.md +38 -10
- package/dist/cli/parse-args.js +46 -1
- package/dist/cli/shared.js +28 -0
- package/dist/cli.js +27 -11
- package/dist/commands/agent/agent-dispatch.js +2 -2
- package/dist/commands/agent/agent-support.js +0 -7
- package/dist/commands/agent/contribute-cli.js +17 -4
- package/dist/commands/config-cli.js +18 -2
- package/dist/commands/env/child-env.js +47 -0
- package/dist/commands/env/env-cli.js +33 -26
- package/dist/commands/env/secret-cli.js +36 -22
- package/dist/commands/feedback-cli.js +15 -6
- package/dist/commands/graph/graph-cli.js +5 -13
- package/dist/commands/graph/graph.js +76 -72
- package/dist/commands/health/checks.js +49 -1
- package/dist/commands/health/html-report.js +422 -80
- package/dist/commands/health.js +386 -9
- package/dist/commands/improve/calibration.js +161 -0
- package/dist/commands/improve/consolidate/chunking.js +141 -0
- package/dist/commands/improve/consolidate/eligibility.js +81 -0
- package/dist/commands/improve/consolidate/merge.js +145 -0
- package/dist/commands/improve/consolidate/sanitize.js +231 -0
- package/dist/commands/{lint.js → improve/consolidate/types.js} +1 -1
- package/dist/commands/improve/consolidate.js +635 -660
- package/dist/commands/improve/dedup.js +482 -0
- package/dist/commands/improve/distill.js +159 -69
- package/dist/commands/improve/eligibility.js +434 -0
- package/dist/commands/improve/encoding-salience.js +205 -0
- package/dist/commands/improve/extract-cli.js +124 -2
- package/dist/commands/improve/extract-prompt.js +39 -2
- package/dist/commands/improve/extract-watch.js +140 -0
- package/dist/commands/improve/extract.js +389 -40
- package/dist/commands/improve/feedback-valence.js +54 -0
- package/dist/commands/improve/homeostatic.js +467 -0
- package/dist/commands/improve/improve-auto-accept.js +138 -7
- package/dist/commands/improve/improve-cli.js +36 -61
- package/dist/commands/improve/improve-profiles.js +14 -0
- package/dist/commands/improve/improve-result-file.js +14 -25
- package/dist/commands/improve/improve-session.js +58 -0
- package/dist/commands/improve/improve.js +485 -2498
- package/dist/commands/improve/locks.js +154 -0
- package/dist/commands/improve/loop-stages.js +1083 -0
- package/dist/commands/improve/memory/memory-contradiction-detect.js +23 -28
- package/dist/commands/improve/outcome-loop.js +256 -0
- package/dist/commands/improve/preparation.js +1966 -0
- package/dist/commands/improve/proactive-maintenance.js +115 -0
- package/dist/commands/improve/procedural.js +418 -0
- package/dist/commands/improve/recombine.js +850 -0
- package/dist/commands/improve/reflect-noise.js +0 -0
- package/dist/commands/improve/reflect.js +183 -40
- package/dist/commands/improve/salience.js +438 -0
- package/dist/commands/improve/triage.js +93 -0
- package/dist/commands/lint/agent-linter.js +19 -24
- package/dist/commands/lint/base-linter.js +173 -60
- package/dist/commands/lint/command-linter.js +19 -24
- package/dist/commands/lint/env-key-rules.js +38 -1
- package/dist/commands/lint/fact-linter.js +39 -0
- package/dist/commands/lint/index.js +31 -13
- package/dist/commands/lint/memory-linter.js +1 -1
- package/dist/commands/lint/registry.js +7 -2
- package/dist/commands/lint/task-linter.js +3 -3
- package/dist/commands/lint/workflow-linter.js +26 -1
- package/dist/commands/proposal/drain-policies.js +5 -0
- package/dist/commands/proposal/drain.js +43 -50
- package/dist/commands/proposal/proposal-cli.js +21 -31
- package/dist/commands/proposal/proposal.js +5 -0
- package/dist/commands/proposal/propose.js +7 -2
- package/dist/commands/proposal/validators/proposal-quality-validators.js +9 -8
- package/dist/commands/proposal/validators/proposals.js +189 -63
- package/dist/commands/read/curate.js +414 -94
- package/dist/commands/read/knowledge.js +6 -3
- package/dist/commands/read/search-cli.js +9 -4
- package/dist/commands/read/search.js +10 -6
- package/dist/commands/read/show.js +86 -7
- package/dist/commands/sources/init.js +49 -17
- package/dist/commands/sources/installed-stashes.js +11 -3
- package/dist/commands/sources/schema-repair.js +43 -45
- package/dist/commands/sources/self-update.js +2 -2
- package/dist/commands/sources/source-add.js +7 -3
- package/dist/commands/sources/stash-cli.js +28 -40
- package/dist/commands/sources/stash-skeleton.js +23 -8
- package/dist/commands/tasks/tasks-cli.js +19 -27
- package/dist/commands/tasks/tasks.js +39 -11
- package/dist/commands/wiki-cli.js +21 -35
- package/dist/core/asset/asset-registry.js +3 -1
- package/dist/core/asset/asset-spec.js +18 -2
- package/dist/core/asset/frontmatter.js +166 -167
- package/dist/core/asset/markdown.js +8 -0
- package/dist/core/authoring-rules.js +92 -0
- package/dist/core/common.js +0 -5
- package/dist/core/config/config-migration.js +12 -11
- package/dist/core/config/config-schema.js +340 -56
- package/dist/core/config/config-types.js +3 -3
- package/dist/core/config/config.js +28 -7
- package/dist/core/events.js +3 -7
- package/dist/core/improve-types.js +11 -8
- package/dist/core/logs-db.js +10 -66
- package/dist/core/parse.js +36 -16
- package/dist/core/paths.js +3 -0
- package/dist/core/standards/resolve-standards-context.js +87 -0
- package/dist/core/standards/resolve-stash-standards.js +99 -0
- package/dist/core/standards/resolve-type-conventions.js +66 -0
- package/dist/core/state/migrations.js +714 -0
- package/dist/core/state-db.js +525 -474
- package/dist/indexer/db/db.js +439 -247
- package/dist/indexer/db/graph-db.js +129 -86
- package/dist/indexer/ensure-index.js +152 -17
- package/dist/indexer/graph/graph-boost.js +51 -41
- package/dist/indexer/graph/graph-extraction.js +218 -4
- package/dist/indexer/index-writer-lock.js +99 -0
- package/dist/indexer/indexer.js +123 -221
- package/dist/indexer/passes/dir-staleness.js +114 -0
- package/dist/indexer/passes/memory-inference.js +13 -5
- package/dist/indexer/passes/staleness-detect.js +2 -5
- package/dist/indexer/search/db-search.js +19 -6
- package/dist/indexer/search/ranking-contributors.js +22 -0
- package/dist/indexer/search/ranking.js +4 -0
- package/dist/indexer/search/search-source.js +17 -18
- package/dist/indexer/search/semantic-status.js +4 -0
- package/dist/indexer/walk/matchers.js +9 -0
- package/dist/integrations/agent/config.js +6 -53
- package/dist/integrations/agent/index.js +2 -18
- package/dist/integrations/agent/prompts.js +75 -9
- package/dist/integrations/agent/runner-dispatch.js +59 -0
- package/dist/integrations/harnesses/claude/session-log.js +11 -1
- package/dist/integrations/harnesses/index.js +2 -3
- package/dist/integrations/harnesses/opencode/session-log.js +173 -3
- package/dist/integrations/harnesses/opencode-sdk/index.js +2 -2
- package/dist/integrations/harnesses/opencode-sdk/sdk-runner.js +0 -2
- package/dist/integrations/session-logs/index.js +16 -0
- package/dist/llm/client.js +45 -15
- package/dist/llm/embedder.js +42 -3
- package/dist/llm/embedders/deterministic.js +66 -0
- package/dist/llm/embedders/local.js +66 -2
- package/dist/llm/feature-gate.js +8 -4
- package/dist/llm/graph-extract.js +67 -44
- package/dist/llm/memory-infer-impl.js +138 -0
- package/dist/llm/memory-infer.js +1 -127
- package/dist/llm/metadata-enhance.js +44 -31
- package/dist/llm/structured-call.js +49 -0
- package/dist/migrate-storage-node.mjs +8 -0
- package/dist/output/context.js +5 -5
- package/dist/output/renderers.js +74 -2
- package/dist/output/shapes/curate.js +14 -2
- package/dist/output/shapes/passthrough.js +0 -1
- package/dist/output/text/helpers.js +16 -1
- package/dist/registry/providers/skills-sh.js +21 -147
- package/dist/registry/providers/static-index.js +15 -157
- package/dist/registry/resolve.js +22 -9
- package/dist/runtime.js +25 -1
- package/dist/scripts/migrate-storage.js +2617 -1961
- package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +759 -510
- package/dist/setup/setup.js +29 -8
- package/dist/sources/include.js +6 -2
- package/dist/sources/providers/filesystem.js +0 -1
- package/dist/sources/providers/git-install.js +210 -0
- package/dist/sources/providers/git-provider.js +234 -0
- package/dist/sources/providers/git-stash.js +248 -0
- package/dist/sources/providers/git.js +10 -661
- package/dist/sources/providers/npm.js +2 -6
- package/dist/sources/providers/provider-utils.js +13 -7
- package/dist/sources/providers/sync-from-ref.js +9 -1
- package/dist/sources/providers/tar-utils.js +16 -8
- package/dist/sources/providers/website.js +9 -5
- package/dist/sources/website-ingest.js +187 -29
- package/dist/sources/wiki-fetchers/registry.js +53 -0
- package/dist/sources/wiki-fetchers/youtube.js +239 -0
- package/dist/storage/database.js +45 -10
- package/dist/storage/managed-db.js +82 -0
- package/dist/storage/repositories/registry-cache.js +92 -0
- package/dist/storage/sqlite-pragmas.js +146 -0
- package/dist/tasks/backends/cron.js +1 -1
- package/dist/tasks/backends/launchd.js +1 -1
- package/dist/tasks/backends/schtasks.js +1 -1
- package/dist/tasks/{resolveAkmBin.js → resolve-akm-bin.js} +2 -2
- package/dist/tasks/runner.js +5 -13
- package/dist/text-import-hook.mjs +0 -0
- package/dist/wiki/wiki.js +37 -0
- package/dist/workflows/db.js +3 -4
- package/dist/workflows/runtime/runs.js +1 -117
- package/dist/workflows/runtime/workflow-asset-loader.js +125 -0
- package/dist/workflows/validate-summary.js +2 -7
- package/docs/data-and-telemetry.md +3 -2
- package/docs/migration/release-notes/0.9.0.md +39 -0
- package/package.json +13 -11
- package/dist/commands/db-cli.js +0 -23
- package/dist/indexer/db/db-backup.js +0 -376
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
2
|
+
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
3
|
+
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
4
|
+
/**
|
|
5
|
+
* Symmetric valence weighting for the improve eligibility sort (#614).
|
|
6
|
+
*
|
|
7
|
+
* BACKGROUND. The improve attention/eligibility ranking historically combined
|
|
8
|
+
* utility with a NEGATIVE-ONLY feedback term: `negative / (positive + negative)`.
|
|
9
|
+
* Under that formula a strong-positive asset contributes a feedback ratio of
|
|
10
|
+
* `0` — i.e. positive feedback never drives attention. Only complaints could
|
|
11
|
+
* lift an asset up the ranking, so a heavily-praised, heavily-used asset that
|
|
12
|
+
* deserves REINFORCEMENT (distill / promote the win) is treated identically to
|
|
13
|
+
* a never-rated one.
|
|
14
|
+
*
|
|
15
|
+
* FIX (gated, default-off). When symmetric valence is enabled we replace the
|
|
16
|
+
* negative-only ratio with a |valence| MAGNITUDE term so that BOTH strong
|
|
17
|
+
* positive and strong negative feedback drive attention. Utility remains the
|
|
18
|
+
* dominant ordering factor — valence is a secondary attention nudge with a
|
|
19
|
+
* small fixed weight, never a utility override.
|
|
20
|
+
*
|
|
21
|
+
* This module is intentionally pure and storage-free: it takes pre-aggregated
|
|
22
|
+
* positive/negative counts plus a utility lookup and returns a deterministic
|
|
23
|
+
* score and lane. All DB access stays in the caller.
|
|
24
|
+
*/
|
|
25
|
+
/** Weight on utility in the combined eligibility score. Utility is dominant. */
|
|
26
|
+
export const UTILITY_WEIGHT = 0.7;
|
|
27
|
+
/** Weight on the feedback attention term in the combined eligibility score. */
|
|
28
|
+
export const FEEDBACK_WEIGHT = 0.3;
|
|
29
|
+
/**
|
|
30
|
+
* Minimum |valence| magnitude for an item to be ROUTED to the fix / reinforce
|
|
31
|
+
* lane. Below this the feedback is too weak/mixed to be a confident signal and
|
|
32
|
+
* the item carries no attention lane (`null`). Pure magnitude in [0, 1].
|
|
33
|
+
*/
|
|
34
|
+
export const STRONG_VALENCE_THRESHOLD = 0.5;
|
|
35
|
+
/**
|
|
36
|
+
* Compute the symmetric-valence attention score for one asset's feedback.
|
|
37
|
+
*
|
|
38
|
+
* Deterministic: depends only on the integer counts. No clock, no randomness.
|
|
39
|
+
*/
|
|
40
|
+
export function computeValenceScore(counts) {
|
|
41
|
+
const positive = Math.max(0, counts.positive);
|
|
42
|
+
const negative = Math.max(0, counts.negative);
|
|
43
|
+
const total = positive + negative;
|
|
44
|
+
if (total === 0) {
|
|
45
|
+
return { valence: 0, magnitude: 0, attention: 0, lane: null };
|
|
46
|
+
}
|
|
47
|
+
const valence = (positive - negative) / total;
|
|
48
|
+
const magnitude = Math.abs(valence);
|
|
49
|
+
let lane = null;
|
|
50
|
+
if (magnitude >= STRONG_VALENCE_THRESHOLD) {
|
|
51
|
+
lane = valence < 0 ? "fix" : "reinforce";
|
|
52
|
+
}
|
|
53
|
+
return { valence, magnitude, attention: magnitude, lane };
|
|
54
|
+
}
|
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
2
|
+
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
3
|
+
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
4
|
+
import { warn } from "../../core/warn.js";
|
|
5
|
+
import { closeDatabase, openExistingDatabase } from "../../indexer/db/db.js";
|
|
6
|
+
// ── Constants ─────────────────────────────────────────────────────────────────
|
|
7
|
+
/** Default days-since-last-retrieval threshold to consider an asset stale. */
|
|
8
|
+
export const DEFAULT_STALE_DAYS = 30;
|
|
9
|
+
/** Default retrievalSalience demotion factor for stale assets. */
|
|
10
|
+
export const DEFAULT_DEMOTION_FACTOR = 0.5;
|
|
11
|
+
/** Default epsilon for schema-similarity gate (looser than dedup's 0.97). */
|
|
12
|
+
export const DEFAULT_SCHEMA_SIMILARITY_EPSILON = 0.85;
|
|
13
|
+
/** Default multiplicative confidence penalty applied to schema-consistent candidates. */
|
|
14
|
+
export const DEFAULT_SCHEMA_CONFIDENCE_PENALTY = 0.5;
|
|
15
|
+
/** Default max generation depth before merge is refused. */
|
|
16
|
+
export const DEFAULT_MAX_GENERATION = 2;
|
|
17
|
+
/** Default fraction of pool to fill with random (non-similar) clusters. */
|
|
18
|
+
export const DEFAULT_RANDOM_CLUSTER_FRACTION = 0.05;
|
|
19
|
+
/** Default number of adjacent lessons/knowledge for CLS interleaving. */
|
|
20
|
+
export const DEFAULT_CLS_ADJACENT_COUNT = 3;
|
|
21
|
+
/**
|
|
22
|
+
* Demote `retrievalSalience` in state.db for stale/low-value assets.
|
|
23
|
+
*
|
|
24
|
+
* "Stale" = the asset has a salience row with `updated_at` older than
|
|
25
|
+
* `staleDays` AND `retrieval_salience > 0`. Demotion multiplies the current
|
|
26
|
+
* `retrieval_salience` by `demotionFactor` (default 0.5) and records
|
|
27
|
+
* `homeostatic_demoted_at` so the pass can be observed.
|
|
28
|
+
*
|
|
29
|
+
* Pure state.db operation — no file I/O, no LLM calls. Idempotent: running
|
|
30
|
+
* twice in the same run only demotes the already-demoted value a second time,
|
|
31
|
+
* which is bounded (0.5 × 0.5 = 0.25) and corrected on re-retrieval.
|
|
32
|
+
*
|
|
33
|
+
* Called BEFORE the dedup/LLM-merge pool is assembled so the merge pool
|
|
34
|
+
* already reflects the updated scores.
|
|
35
|
+
*/
|
|
36
|
+
export function runHomeostaticDemotion(db, config, now) {
|
|
37
|
+
const warnings = [];
|
|
38
|
+
if (!config.enabled)
|
|
39
|
+
return { demoted: 0, warnings };
|
|
40
|
+
const staleDays = config.staleDays ?? DEFAULT_STALE_DAYS;
|
|
41
|
+
const demotionFactor = config.demotionFactor ?? DEFAULT_DEMOTION_FACTOR;
|
|
42
|
+
const nowMs = now ?? Date.now();
|
|
43
|
+
const staleThresholdMs = nowMs - staleDays * 86_400_000;
|
|
44
|
+
try {
|
|
45
|
+
// Find assets whose salience row is stale AND has non-zero retrievalSalience.
|
|
46
|
+
// updated_at reflects the last time salience was computed (i.e. the last run
|
|
47
|
+
// that touched this asset). If the asset hasn't been seen recently, its
|
|
48
|
+
// retrieval_salience is stale.
|
|
49
|
+
const staleRows = db
|
|
50
|
+
.prepare(`SELECT asset_ref, retrieval_salience, rank_score, encoding_salience, outcome_salience
|
|
51
|
+
FROM asset_salience
|
|
52
|
+
WHERE updated_at < ? AND retrieval_salience > 0`)
|
|
53
|
+
.all(staleThresholdMs);
|
|
54
|
+
if (staleRows.length === 0)
|
|
55
|
+
return { demoted: 0, warnings };
|
|
56
|
+
// Batch update in a transaction for atomicity and performance.
|
|
57
|
+
const updateStmt = db.prepare(`UPDATE asset_salience
|
|
58
|
+
SET retrieval_salience = ?,
|
|
59
|
+
rank_score = ?,
|
|
60
|
+
homeostatic_demoted_at = ?,
|
|
61
|
+
updated_at = ?
|
|
62
|
+
WHERE asset_ref = ?`);
|
|
63
|
+
let demoted = 0;
|
|
64
|
+
db.exec("BEGIN");
|
|
65
|
+
try {
|
|
66
|
+
for (const row of staleRows) {
|
|
67
|
+
const newRetrieval = row.retrieval_salience * demotionFactor;
|
|
68
|
+
// Recompute rank_score with the demoted retrieval value.
|
|
69
|
+
// We use simplified WS-1 parity weights here (no outcome weight by
|
|
70
|
+
// default) so the demotion is consistent with what salience.ts computes.
|
|
71
|
+
// The next full computeSalience call will overwrite with the exact value.
|
|
72
|
+
const newRank = Math.min(1, Math.max(0, (0.3 * row.encoding_salience + 0.0 * row.outcome_salience + 0.7 * newRetrieval) *
|
|
73
|
+
// Apply a mild size penalty assumption (200 bytes floor gives 1/log10(200)≈0.43)
|
|
74
|
+
0.43));
|
|
75
|
+
updateStmt.run(newRetrieval, newRank, nowMs, nowMs, row.asset_ref);
|
|
76
|
+
demoted++;
|
|
77
|
+
}
|
|
78
|
+
db.exec("COMMIT");
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
db.exec("ROLLBACK");
|
|
82
|
+
throw e;
|
|
83
|
+
}
|
|
84
|
+
warn(`[homeostatic] demoted retrievalSalience for ${demoted} stale asset(s) (staleDays=${staleDays}, factor=${demotionFactor})`);
|
|
85
|
+
return { demoted, warnings };
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
const msg = `[homeostatic] demotion failed: ${err instanceof Error ? err.message : String(err)}`;
|
|
89
|
+
warn(msg);
|
|
90
|
+
warnings.push(msg);
|
|
91
|
+
return { demoted: 0, warnings };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Check whether a candidate body embedding is schema-consistent with an existing
|
|
96
|
+
* derived-layer lesson/knowledge node. Returns `true` when the candidate is
|
|
97
|
+
* within ε of ANY existing derived node (i.e. it's likely covering ground the
|
|
98
|
+
* derived layer already knows about, so give it lower priority).
|
|
99
|
+
*
|
|
100
|
+
* One embedding lookup via the body_embeddings cache; no LLM call.
|
|
101
|
+
* Fails open: returns `false` (not schema-consistent) on any error so the
|
|
102
|
+
* candidate is not silently dropped.
|
|
103
|
+
*
|
|
104
|
+
* @param candidateEmbedding - Float32 embedding vector for the candidate body.
|
|
105
|
+
* @param existingDerivedEmbeddings - Pre-loaded embeddings for existing derived assets.
|
|
106
|
+
* @param config - Schema-similarity gate config.
|
|
107
|
+
*/
|
|
108
|
+
export function isSchemaConsistent(candidateEmbedding, existingDerivedEmbeddings, config) {
|
|
109
|
+
if (!config.enabled || existingDerivedEmbeddings.length === 0) {
|
|
110
|
+
return { consistent: false };
|
|
111
|
+
}
|
|
112
|
+
const epsilon = config.epsilon ?? DEFAULT_SCHEMA_SIMILARITY_EPSILON;
|
|
113
|
+
let bestSim = -Infinity;
|
|
114
|
+
let bestRef;
|
|
115
|
+
for (const { ref, embedding } of existingDerivedEmbeddings) {
|
|
116
|
+
// cosine similarity: dot(a,b) / (|a| * |b|)
|
|
117
|
+
let dot = 0;
|
|
118
|
+
let magA = 0;
|
|
119
|
+
let magB = 0;
|
|
120
|
+
for (let i = 0; i < candidateEmbedding.length; i++) {
|
|
121
|
+
const a = candidateEmbedding[i] ?? 0;
|
|
122
|
+
const b = embedding[i] ?? 0;
|
|
123
|
+
dot += a * b;
|
|
124
|
+
magA += a * a;
|
|
125
|
+
magB += b * b;
|
|
126
|
+
}
|
|
127
|
+
const sim = magA === 0 || magB === 0 ? 0 : dot / (Math.sqrt(magA) * Math.sqrt(magB));
|
|
128
|
+
if (sim > bestSim) {
|
|
129
|
+
bestSim = sim;
|
|
130
|
+
bestRef = ref;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (bestSim >= epsilon) {
|
|
134
|
+
return { consistent: true, matchedRef: bestRef, similarity: bestSim };
|
|
135
|
+
}
|
|
136
|
+
return { consistent: false };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* WS-3b Step-0b: apply the schema-similarity intake gate to one extract
|
|
140
|
+
* candidate. Pure/deterministic given `embedText`, so it is directly unit
|
|
141
|
+
* testable without the full extract→LLM harness.
|
|
142
|
+
*
|
|
143
|
+
* Returns the (possibly penalised) effective confidence plus a `penalised` flag
|
|
144
|
+
* and an optional human-readable `warning`. Parity guarantees:
|
|
145
|
+
* - `ctx === null` (gate disabled / default-off) → no change, never embeds.
|
|
146
|
+
* - empty `derivedEmbeddings` → no change, never embeds.
|
|
147
|
+
* - candidate type not lesson/knowledge → no change, never embeds.
|
|
148
|
+
* - embed throws → fail open (no change), warns.
|
|
149
|
+
*/
|
|
150
|
+
export async function applySchemaSimilarityPenalty(candidate, ctx, embedText) {
|
|
151
|
+
const baseConfidence = typeof candidate.confidence === "number" ? candidate.confidence : undefined;
|
|
152
|
+
if (ctx === null || ctx.derivedEmbeddings.length === 0) {
|
|
153
|
+
return { effectiveConfidence: baseConfidence, penalised: false };
|
|
154
|
+
}
|
|
155
|
+
if (candidate.type !== "lesson" && candidate.type !== "knowledge") {
|
|
156
|
+
return { effectiveConfidence: baseConfidence, penalised: false };
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
const candidateVec = await embedText(candidate.body);
|
|
160
|
+
const check = isSchemaConsistent(candidateVec, ctx.derivedEmbeddings, ctx.config);
|
|
161
|
+
if (check.consistent) {
|
|
162
|
+
const penalty = ctx.config.confidencePenalty ?? DEFAULT_SCHEMA_CONFIDENCE_PENALTY;
|
|
163
|
+
return {
|
|
164
|
+
effectiveConfidence: (baseConfidence ?? 1.0) * penalty,
|
|
165
|
+
penalised: true,
|
|
166
|
+
warning: `[extract] schema-consistent candidate ${candidate.type}:${candidate.name} ` +
|
|
167
|
+
`(sim=${check.similarity?.toFixed(3)} vs ${check.matchedRef}) — confidence penalised ×${penalty}`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
return { effectiveConfidence: baseConfidence, penalised: false };
|
|
171
|
+
}
|
|
172
|
+
catch (embedErr) {
|
|
173
|
+
// Fail open: embed errors must never abort extraction.
|
|
174
|
+
return {
|
|
175
|
+
effectiveConfidence: baseConfidence,
|
|
176
|
+
penalised: false,
|
|
177
|
+
warning: `[extract] schema-similarity embed failed for ${candidate.type}:${candidate.name} — skipping gate: ` +
|
|
178
|
+
(embedErr instanceof Error ? embedErr.message : String(embedErr)),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Load persisted body embeddings for all indexed **derived-layer**
|
|
184
|
+
* (lesson + knowledge) entries from index.db. Returns an empty array when
|
|
185
|
+
* the DB is unavailable, empty, or the embeddings table has no entries for
|
|
186
|
+
* those types — the caller treats an empty array as "gate inactive".
|
|
187
|
+
*
|
|
188
|
+
* FAIL-OPEN: any error emits a debug warning and returns an empty array.
|
|
189
|
+
* This ensures the extract pass never fails because of a missing index.
|
|
190
|
+
*
|
|
191
|
+
* The returned entries are keyed by `entry_key` (e.g. "lesson:foo",
|
|
192
|
+
* "knowledge:bar"). Only entries whose embedding dimension matches the first
|
|
193
|
+
* observed dimension are included (mixed-dim BLOBs are silently skipped).
|
|
194
|
+
*
|
|
195
|
+
* @param dbPath - Optional path override for index.db (for testing).
|
|
196
|
+
*/
|
|
197
|
+
export function loadDerivedLayerEmbeddings(dbPath) {
|
|
198
|
+
let db;
|
|
199
|
+
try {
|
|
200
|
+
db = openExistingDatabase(dbPath);
|
|
201
|
+
const rows = db
|
|
202
|
+
.prepare(`SELECT e.entry_key, emb.embedding
|
|
203
|
+
FROM entries e
|
|
204
|
+
JOIN embeddings emb ON emb.id = e.id
|
|
205
|
+
WHERE e.entry_type IN ('lesson', 'knowledge')`)
|
|
206
|
+
.all();
|
|
207
|
+
if (rows.length === 0)
|
|
208
|
+
return [];
|
|
209
|
+
let expectedDim;
|
|
210
|
+
const result = [];
|
|
211
|
+
for (const row of rows) {
|
|
212
|
+
const buf = row.embedding;
|
|
213
|
+
if (!buf || buf.byteLength === 0 || buf.byteLength % 4 !== 0)
|
|
214
|
+
continue;
|
|
215
|
+
const dim = buf.byteLength / 4;
|
|
216
|
+
if (expectedDim === undefined)
|
|
217
|
+
expectedDim = dim;
|
|
218
|
+
if (dim !== expectedDim)
|
|
219
|
+
continue;
|
|
220
|
+
const aligned = new ArrayBuffer(buf.byteLength);
|
|
221
|
+
new Uint8Array(aligned).set(buf);
|
|
222
|
+
const f32 = new Float32Array(aligned);
|
|
223
|
+
result.push({ ref: row.entry_key, embedding: Array.from(f32) });
|
|
224
|
+
}
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
warn("[homeostatic] loadDerivedLayerEmbeddings: failed to load from index.db — gate inactive:", err instanceof Error ? err.message : String(err));
|
|
229
|
+
return [];
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
if (db) {
|
|
233
|
+
try {
|
|
234
|
+
closeDatabase(db);
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
// ignore close errors
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Read the `generation` field from an asset's frontmatter.
|
|
244
|
+
* Returns 0 when absent (no generation metadata = original asset).
|
|
245
|
+
*/
|
|
246
|
+
export function readAssetGeneration(frontmatterData) {
|
|
247
|
+
const gen = frontmatterData.generation;
|
|
248
|
+
if (typeof gen === "number" && Number.isFinite(gen) && gen >= 0) {
|
|
249
|
+
return Math.floor(gen);
|
|
250
|
+
}
|
|
251
|
+
return 0;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Compute the new generation for a merged asset.
|
|
255
|
+
* Rule: `merged.generation = max(source generations) + 1`.
|
|
256
|
+
*/
|
|
257
|
+
export function computeMergedGeneration(sourceGenerations) {
|
|
258
|
+
if (sourceGenerations.length === 0)
|
|
259
|
+
return 1;
|
|
260
|
+
return Math.max(...sourceGenerations) + 1;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Check whether a merge of the given assets should be refused due to the
|
|
264
|
+
* anti-collapse generation guard.
|
|
265
|
+
*
|
|
266
|
+
* Returns `{ refused: true, reason }` when BOTH assets have generation > maxGeneration.
|
|
267
|
+
* Returns `{ refused: false }` when the merge is allowed.
|
|
268
|
+
*
|
|
269
|
+
* @param sourceGenerations - Generation values for all merge participants.
|
|
270
|
+
* @param config - Anti-collapse config.
|
|
271
|
+
*/
|
|
272
|
+
export function checkGenerationGuard(sourceGenerations, config) {
|
|
273
|
+
if (!config.enabled)
|
|
274
|
+
return { refused: false };
|
|
275
|
+
const maxGen = config.maxGeneration ?? DEFAULT_MAX_GENERATION;
|
|
276
|
+
const highGenCount = sourceGenerations.filter((g) => g > maxGen).length;
|
|
277
|
+
if (highGenCount >= 2) {
|
|
278
|
+
return {
|
|
279
|
+
refused: true,
|
|
280
|
+
reason: `Anti-collapse: ${highGenCount} merge participants have generation > ${maxGen} (${sourceGenerations.join(", ")}); refusing to merge over-consolidated assets.`,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
return { refused: false };
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Compute the bigram n-gram diversity of a text string.
|
|
287
|
+
* Returns a value in [0, 1] where 0 = all identical bigrams, 1 = all unique.
|
|
288
|
+
* Used by the lexical-diversity check to detect correlated-extraction artifacts.
|
|
289
|
+
*/
|
|
290
|
+
export function computeBigramDiversity(text) {
|
|
291
|
+
const words = text
|
|
292
|
+
.toLowerCase()
|
|
293
|
+
.split(/\s+/)
|
|
294
|
+
.filter((w) => w.length > 0);
|
|
295
|
+
if (words.length < 2)
|
|
296
|
+
return 1; // too short to have bigrams; treat as diverse
|
|
297
|
+
const total = words.length - 1;
|
|
298
|
+
const unique = new Set();
|
|
299
|
+
for (let i = 0; i < total; i++) {
|
|
300
|
+
unique.add(`${words[i]}\t${words[i + 1]}`);
|
|
301
|
+
}
|
|
302
|
+
return unique.size / total;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Check whether a cluster of memories exhibits suspiciously low lexical diversity.
|
|
306
|
+
* When true, the cluster is likely a correlated-extraction artifact; the merge
|
|
307
|
+
* threshold should be raised.
|
|
308
|
+
*
|
|
309
|
+
* @param bodies - The stripped body texts of the cluster members.
|
|
310
|
+
* @param config - Anti-collapse config.
|
|
311
|
+
* @returns `{ lowDiversity: true, diversity }` when the cluster diversity is
|
|
312
|
+
* below the 0.3 threshold; `{ lowDiversity: false }` otherwise.
|
|
313
|
+
*/
|
|
314
|
+
export function checkLexicalDiversity(bodies, config) {
|
|
315
|
+
if (!config.enabled || config.lexicalDiversityCheck === false) {
|
|
316
|
+
return { lowDiversity: false };
|
|
317
|
+
}
|
|
318
|
+
if (bodies.length === 0)
|
|
319
|
+
return { lowDiversity: false };
|
|
320
|
+
// Average bigram diversity across all bodies in the cluster.
|
|
321
|
+
const avg = bodies.reduce((sum, b) => sum + computeBigramDiversity(b), 0) / bodies.length;
|
|
322
|
+
const DIVERSITY_FLOOR = 0.3;
|
|
323
|
+
if (avg < DIVERSITY_FLOOR) {
|
|
324
|
+
return { lowDiversity: true, diversity: avg };
|
|
325
|
+
}
|
|
326
|
+
return { lowDiversity: false };
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Build a CLS (Complementary Learning System) context snippet for injection
|
|
330
|
+
* into distill/memoryInference prompts.
|
|
331
|
+
*
|
|
332
|
+
* Given a list of embedding-retrieved adjacent lessons/knowledge, formats them
|
|
333
|
+
* as a markdown section to append to the prompt so the LLM avoids overwriting
|
|
334
|
+
* prior generalizations.
|
|
335
|
+
*
|
|
336
|
+
* Returns an empty string when CLS is disabled or no adjacent items are found.
|
|
337
|
+
*
|
|
338
|
+
* @param adjacentItems - Top-N adjacent lessons/knowledge retrieved by embedding.
|
|
339
|
+
* @param config - CLS config.
|
|
340
|
+
*/
|
|
341
|
+
export function buildClsContext(adjacentItems, config) {
|
|
342
|
+
if (!config.enabled || adjacentItems.length === 0)
|
|
343
|
+
return "";
|
|
344
|
+
const lines = [
|
|
345
|
+
"",
|
|
346
|
+
"## Existing adjacent lessons / knowledge (CLS context)",
|
|
347
|
+
"The following are semantically related entries already in the stash.",
|
|
348
|
+
"Your proposal MUST NOT contradict or silently overwrite these — if you",
|
|
349
|
+
"disagree with one, flag it as contradicted (do not ignore it).",
|
|
350
|
+
"",
|
|
351
|
+
];
|
|
352
|
+
for (const item of adjacentItems) {
|
|
353
|
+
lines.push(`### ${item.ref}`);
|
|
354
|
+
// Truncate to 400 chars to keep the prompt size reasonable.
|
|
355
|
+
lines.push(item.content.trim().slice(0, 400));
|
|
356
|
+
lines.push("");
|
|
357
|
+
}
|
|
358
|
+
return lines.join("\n");
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Check a distill proposal against its cited source memories for contradictions.
|
|
362
|
+
*
|
|
363
|
+
* Uses a simple heuristic: looks for explicit negation of key claims in the
|
|
364
|
+
* proposal body that appear in the source bodies. A full LLM-based
|
|
365
|
+
* contradiction check is expensive (one LLM call per proposal); this cheap
|
|
366
|
+
* heuristic catches the most obvious cases and flags them for human review.
|
|
367
|
+
*
|
|
368
|
+
* When `fidelityCheck.enabled` is false, returns `{ contradictionDetected: false }`
|
|
369
|
+
* immediately (no work done).
|
|
370
|
+
*
|
|
371
|
+
* @param proposalBody - The stripped body of the distill proposal.
|
|
372
|
+
* @param sourceBodies - The stripped bodies of the cited source memories.
|
|
373
|
+
* @param config - Fidelity check config.
|
|
374
|
+
*/
|
|
375
|
+
export function checkDistillFidelity(proposalBody, sourceBodies, config) {
|
|
376
|
+
if (!config.enabled || sourceBodies.length === 0) {
|
|
377
|
+
return { contradictionDetected: false };
|
|
378
|
+
}
|
|
379
|
+
// Heuristic: detect explicit negation of "never" / "always" / "must" claims.
|
|
380
|
+
// A proposal that says "always X" while the source says "never X" (or vice
|
|
381
|
+
// versa) is a clear contradiction worth flagging.
|
|
382
|
+
//
|
|
383
|
+
// This is intentionally conservative: it only flags when both the proposal
|
|
384
|
+
// AND the source contain the opposing polarity of the same key term. False
|
|
385
|
+
// negatives (missed contradictions) are preferred over false positives
|
|
386
|
+
// (blocking valid proposals) since the consequence of a false positive is
|
|
387
|
+
// a human review request, while the cost of a false negative is a slightly
|
|
388
|
+
// degraded stash.
|
|
389
|
+
const proposalLow = proposalBody.toLowerCase();
|
|
390
|
+
// Extract "always/never/must/must not" claims from the proposal.
|
|
391
|
+
const strongClaims = extractStrongClaims(proposalLow);
|
|
392
|
+
if (strongClaims.length === 0)
|
|
393
|
+
return { contradictionDetected: false };
|
|
394
|
+
for (const sourceBody of sourceBodies) {
|
|
395
|
+
const sourceLow = sourceBody.toLowerCase();
|
|
396
|
+
for (const { polarity, term } of strongClaims) {
|
|
397
|
+
const oppositePolarity = polarity === "positive" ? "negative" : "positive";
|
|
398
|
+
const sourceHasOpposite = hasStrongClaim(sourceLow, term, oppositePolarity);
|
|
399
|
+
if (sourceHasOpposite) {
|
|
400
|
+
return {
|
|
401
|
+
contradictionDetected: true,
|
|
402
|
+
reason: `Proposal makes a ${polarity} strong claim about "${term}" that conflicts with an opposing claim in a cited source. Route to human review.`,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
// Also flag proposals whose source_refs are empty (broken provenance).
|
|
408
|
+
// This is a degradation signal, not a contradiction, but worth surfacing.
|
|
409
|
+
return { contradictionDetected: false };
|
|
410
|
+
}
|
|
411
|
+
function extractStrongClaims(text) {
|
|
412
|
+
const claims = [];
|
|
413
|
+
// Match "always <term>", "never <term>", "must <term>", "must not <term>".
|
|
414
|
+
const patterns = [
|
|
415
|
+
{ polarity: "positive", re: /\b(?:always|must)\s+(\w+)/g },
|
|
416
|
+
{ polarity: "negative", re: /\b(?:never|must\s+not|should\s+not)\s+(\w+)/g },
|
|
417
|
+
];
|
|
418
|
+
for (const { polarity, re } of patterns) {
|
|
419
|
+
re.lastIndex = 0;
|
|
420
|
+
let m = re.exec(text);
|
|
421
|
+
while (m !== null) {
|
|
422
|
+
const term = m[1];
|
|
423
|
+
if (term && term.length > 2)
|
|
424
|
+
claims.push({ polarity, term });
|
|
425
|
+
m = re.exec(text);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return claims;
|
|
429
|
+
}
|
|
430
|
+
function hasStrongClaim(text, term, polarity) {
|
|
431
|
+
if (polarity === "positive") {
|
|
432
|
+
return /\b(?:always|must)\s/.test(text) && text.includes(term);
|
|
433
|
+
}
|
|
434
|
+
return /\b(?:never|must\s+not|should\s+not)\s/.test(text) && text.includes(term);
|
|
435
|
+
}
|
|
436
|
+
// ── captureMode: hot-probation helpers ───────────────────────────────────────
|
|
437
|
+
/**
|
|
438
|
+
* captureMode value for system-generated extractions in probation.
|
|
439
|
+
* Automatic counterpart to the user-explicit `captureMode: hot`.
|
|
440
|
+
*/
|
|
441
|
+
export const CAPTURE_MODE_HOT_PROBATION = "hot-probation";
|
|
442
|
+
/**
|
|
443
|
+
* Returns true when an asset is in hot-probation (system-generated, not yet
|
|
444
|
+
* graduated from the intake dedup+quality pass).
|
|
445
|
+
*/
|
|
446
|
+
export function isHotProbation(captureModeValue) {
|
|
447
|
+
return captureModeValue === CAPTURE_MODE_HOT_PROBATION;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Returns true when an asset should be skipped by the consolidation LLM
|
|
451
|
+
* because it's still in hot-probation (hasn't completed the intake pass yet).
|
|
452
|
+
*
|
|
453
|
+
* Hot-probation assets are processed by the consolidation dedup pre-pass
|
|
454
|
+
* (runDeterministicDedup) but excluded from the LLM merge clustering, so
|
|
455
|
+
* noisy extractions can't pollute the LLM context.
|
|
456
|
+
*/
|
|
457
|
+
export function shouldSkipHotProbationInLlm(frontmatterData) {
|
|
458
|
+
return isHotProbation(frontmatterData.captureMode);
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Build frontmatter fields to inject when creating a hot-probation proposal.
|
|
462
|
+
* The proposal will carry `captureMode: hot-probation` so downstream logic
|
|
463
|
+
* knows to run the intake dedup pass before graduating it.
|
|
464
|
+
*/
|
|
465
|
+
export function buildHotProbationFrontmatter() {
|
|
466
|
+
return { captureMode: CAPTURE_MODE_HOT_PROBATION };
|
|
467
|
+
}
|