akm-cli 0.9.0-beta.3 → 0.9.0-beta.31

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.
Files changed (107) hide show
  1. package/CHANGELOG.md +613 -0
  2. package/dist/assets/prompts/consolidate-system.md +23 -0
  3. package/dist/assets/prompts/contradiction-judge.md +33 -0
  4. package/dist/assets/prompts/distill-knowledge-system.md +22 -0
  5. package/dist/assets/prompts/distill-lesson-system.md +36 -0
  6. package/dist/assets/prompts/extract-session.md +5 -1
  7. package/dist/assets/prompts/graph-extract-system.md +1 -0
  8. package/dist/assets/prompts/memory-infer-system.md +1 -0
  9. package/dist/assets/prompts/memory-infer-user.md +5 -0
  10. package/dist/assets/prompts/metadata-enhance-system.md +1 -0
  11. package/dist/assets/prompts/procedural-system.md +44 -0
  12. package/dist/assets/prompts/recombine-system.md +40 -0
  13. package/dist/assets/prompts/staleness-detect-system.md +6 -0
  14. package/dist/assets/prompts/validate-summary-judge.md +1 -0
  15. package/dist/assets/templates/html/health.html +281 -111
  16. package/dist/cli.js +14 -3
  17. package/dist/commands/agent/contribute-cli.js +16 -3
  18. package/dist/commands/feedback-cli.js +15 -6
  19. package/dist/commands/graph/graph.js +75 -71
  20. package/dist/commands/health/checks.js +48 -0
  21. package/dist/commands/health/html-report.js +422 -80
  22. package/dist/commands/health.js +381 -9
  23. package/dist/commands/improve/calibration.js +161 -0
  24. package/dist/commands/improve/consolidate.js +634 -111
  25. package/dist/commands/improve/dedup.js +482 -0
  26. package/dist/commands/improve/distill.js +145 -69
  27. package/dist/commands/improve/encoding-salience.js +205 -0
  28. package/dist/commands/improve/extract-cli.js +115 -1
  29. package/dist/commands/improve/extract-prompt.js +33 -2
  30. package/dist/commands/improve/extract-watch.js +140 -0
  31. package/dist/commands/improve/extract.js +244 -35
  32. package/dist/commands/improve/feedback-valence.js +54 -0
  33. package/dist/commands/improve/homeostatic.js +467 -0
  34. package/dist/commands/improve/improve-auto-accept.js +113 -6
  35. package/dist/commands/improve/improve-profiles.js +12 -0
  36. package/dist/commands/improve/improve.js +1974 -614
  37. package/dist/commands/improve/memory/memory-contradiction-detect.js +23 -28
  38. package/dist/commands/improve/outcome-loop.js +256 -0
  39. package/dist/commands/improve/proactive-maintenance.js +87 -0
  40. package/dist/commands/improve/procedural.js +409 -0
  41. package/dist/commands/improve/recombine.js +593 -0
  42. package/dist/commands/improve/reflect.js +26 -1
  43. package/dist/commands/improve/related-sessions.js +120 -0
  44. package/dist/commands/improve/salience.js +386 -0
  45. package/dist/commands/improve/triage.js +95 -0
  46. package/dist/commands/lint/agent-linter.js +19 -24
  47. package/dist/commands/lint/base-linter.js +173 -60
  48. package/dist/commands/lint/command-linter.js +19 -24
  49. package/dist/commands/lint/env-key-rules.js +34 -1
  50. package/dist/commands/lint/fact-linter.js +39 -0
  51. package/dist/commands/lint/index.js +31 -13
  52. package/dist/commands/lint/memory-linter.js +1 -1
  53. package/dist/commands/lint/registry.js +7 -2
  54. package/dist/commands/lint/task-linter.js +3 -3
  55. package/dist/commands/lint/workflow-linter.js +26 -1
  56. package/dist/commands/proposal/proposal.js +5 -0
  57. package/dist/commands/proposal/validators/proposals.js +71 -54
  58. package/dist/commands/read/curate.js +344 -80
  59. package/dist/commands/read/search-cli.js +7 -0
  60. package/dist/commands/read/search.js +1 -0
  61. package/dist/commands/read/show.js +67 -2
  62. package/dist/commands/sources/installed-stashes.js +5 -1
  63. package/dist/commands/sources/stash-cli.js +10 -2
  64. package/dist/core/asset/asset-registry.js +2 -0
  65. package/dist/core/asset/asset-spec.js +14 -0
  66. package/dist/core/asset/frontmatter.js +166 -167
  67. package/dist/core/asset/markdown.js +8 -0
  68. package/dist/core/config/config-schema.js +259 -2
  69. package/dist/core/config/config.js +2 -2
  70. package/dist/core/logs-db.js +4 -3
  71. package/dist/core/paths.js +3 -0
  72. package/dist/core/state-db.js +649 -30
  73. package/dist/indexer/db/db.js +364 -38
  74. package/dist/indexer/db/graph-db.js +129 -86
  75. package/dist/indexer/ensure-index.js +152 -17
  76. package/dist/indexer/graph/graph-boost.js +51 -41
  77. package/dist/indexer/graph/graph-extraction.js +203 -3
  78. package/dist/indexer/index-writer-lock.js +99 -0
  79. package/dist/indexer/indexer.js +114 -111
  80. package/dist/indexer/passes/memory-inference.js +10 -3
  81. package/dist/indexer/passes/staleness-detect.js +2 -5
  82. package/dist/indexer/search/db-search.js +15 -4
  83. package/dist/indexer/search/ranking-contributors.js +22 -0
  84. package/dist/indexer/search/ranking.js +4 -0
  85. package/dist/indexer/walk/matchers.js +9 -0
  86. package/dist/integrations/agent/prompts.js +1 -0
  87. package/dist/integrations/harnesses/claude/session-log.js +11 -1
  88. package/dist/integrations/harnesses/opencode/session-log.js +9 -0
  89. package/dist/integrations/session-logs/index.js +16 -0
  90. package/dist/llm/client.js +23 -4
  91. package/dist/llm/embedder.js +27 -3
  92. package/dist/llm/embedders/local.js +66 -2
  93. package/dist/llm/graph-extract.js +2 -1
  94. package/dist/llm/memory-infer.js +4 -8
  95. package/dist/llm/metadata-enhance.js +9 -1
  96. package/dist/output/renderers.js +73 -1
  97. package/dist/output/shapes/curate.js +14 -2
  98. package/dist/output/text/helpers.js +9 -0
  99. package/dist/runtime.js +25 -1
  100. package/dist/scripts/migrate-storage.js +1242 -594
  101. package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +473 -270
  102. package/dist/sources/providers/tar-utils.js +16 -8
  103. package/dist/storage/sqlite-pragmas.js +146 -0
  104. package/dist/workflows/db.js +3 -4
  105. package/dist/workflows/validate-summary.js +2 -7
  106. package/docs/data-and-telemetry.md +1 -0
  107. package/package.json +9 -6
@@ -0,0 +1,120 @@
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
+ * #627 — getRelatedSessions helper.
6
+ *
7
+ * Finds session assets related to a seed by SHARED TAGS / GRAPH ENTITIES —
8
+ * NEVER embedding similarity. Modeled on recombine.ts buildRelatednessClusters:
9
+ * two sessions relate when they share at least one *topic* tag or graph entity;
10
+ * two textually near-identical sessions with no shared topic signal do NOT
11
+ * relate. This makes the helper a pure query-layer relatedness lookup that
12
+ * makes NO network / embedding calls.
13
+ *
14
+ * The generic base tags every session asset carries (`session` + the harness
15
+ * id, see session-asset.ts) are IGNORED for relatedness — otherwise every
16
+ * session would trivially relate to every other. Callers should therefore seed
17
+ * with derived topic tags, but the helper defensively strips the generic base
18
+ * tags from candidate sessions too.
19
+ *
20
+ * Relatedness source:
21
+ * - `"tags"` — score by count of (seedTags ∩ session tags).
22
+ * - `"graph"` — score by count of (seedEntities ∩ session graph entities);
23
+ * falls open to tag relatedness when the graph table is empty.
24
+ * - `"both"` — sum of the tag + entity overlap.
25
+ */
26
+ import { makeAssetRef } from "../../core/asset/asset-ref.js";
27
+ import { closeDatabase, getAllEntries, getEntitiesByEntryIds, openExistingDatabase, } from "../../indexer/db/db.js";
28
+ /** Generic base tags every session asset carries — never a relatedness signal. */
29
+ const GENERIC_SESSION_TAGS = new Set(["session"]);
30
+ /**
31
+ * Build the set of topic tags for a session entry, excluding generic base tags
32
+ * (`session`) and the harness segment of the entry name (the harness id is the
33
+ * first path component of `<harness>/<id>` and is also carried as a base tag).
34
+ */
35
+ function topicTagsForSession(entry) {
36
+ const harness = entry.entry.name.split("/")[0];
37
+ const result = new Set();
38
+ for (const tag of entry.entry.tags ?? []) {
39
+ if (GENERIC_SESSION_TAGS.has(tag))
40
+ continue;
41
+ if (harness && tag === harness)
42
+ continue;
43
+ result.add(tag);
44
+ }
45
+ return result;
46
+ }
47
+ /**
48
+ * Find session assets related to a seed by shared tags / graph entities.
49
+ * Relatedness is signal-based, NOT embedding similarity.
50
+ */
51
+ export function getRelatedSessions(opts) {
52
+ const seedTags = (opts.seedTags ?? [])
53
+ .filter((t) => !GENERIC_SESSION_TAGS.has(t))
54
+ .map((t) => t.trim())
55
+ .filter(Boolean);
56
+ const seedEntities = (opts.seedEntities ?? []).map((e) => e.trim().toLowerCase()).filter(Boolean);
57
+ const minShared = opts.minShared ?? 1;
58
+ const limit = opts.limit ?? 5;
59
+ const relatednessSource = opts.relatednessSource ?? "tags";
60
+ const excludeRefs = new Set(opts.excludeRefs ?? []);
61
+ // Empty seed input → nothing to relate to.
62
+ if (seedTags.length === 0 && seedEntities.length === 0)
63
+ return [];
64
+ const seedTagSet = new Set(seedTags);
65
+ const seedEntitySet = new Set(seedEntities);
66
+ let db = opts.db;
67
+ let ownsDb = false;
68
+ if (!db) {
69
+ db = openExistingDatabase();
70
+ ownsDb = true;
71
+ }
72
+ try {
73
+ const sessions = getAllEntries(db, "session");
74
+ // Resolve graph entities for the candidate sessions when requested. Fail
75
+ // open to tag relatedness when the graph table is empty (no rows).
76
+ let entityByEntryId;
77
+ const wantGraph = relatednessSource === "graph" || relatednessSource === "both";
78
+ if (wantGraph) {
79
+ try {
80
+ entityByEntryId = getEntitiesByEntryIds(db, sessions.map((s) => s.id));
81
+ }
82
+ catch {
83
+ entityByEntryId = undefined;
84
+ }
85
+ }
86
+ const hasEntities = !!entityByEntryId && entityByEntryId.size > 0;
87
+ // Effective signal selection. "graph" with no entities falls open to tags.
88
+ const useTags = relatednessSource === "tags" || relatednessSource === "both" || (wantGraph && !hasEntities);
89
+ const useGraph = wantGraph && hasEntities;
90
+ const scored = [];
91
+ for (const session of sessions) {
92
+ const ref = makeAssetRef(session.entry.type, session.entry.name);
93
+ if (excludeRefs.has(ref))
94
+ continue;
95
+ let sharedCount = 0;
96
+ if (useTags && seedTagSet.size > 0) {
97
+ for (const tag of topicTagsForSession(session)) {
98
+ if (seedTagSet.has(tag))
99
+ sharedCount += 1;
100
+ }
101
+ }
102
+ if (useGraph && seedEntitySet.size > 0 && entityByEntryId) {
103
+ for (const ent of entityByEntryId.get(session.id) ?? []) {
104
+ if (seedEntitySet.has(ent))
105
+ sharedCount += 1;
106
+ }
107
+ }
108
+ if (sharedCount >= minShared) {
109
+ scored.push({ ref, name: session.entry.name, sharedCount });
110
+ }
111
+ }
112
+ // Rank by shared-signal count desc, then ref for a deterministic tiebreak.
113
+ scored.sort((a, b) => b.sharedCount - a.sharedCount || a.ref.localeCompare(b.ref));
114
+ return scored.slice(0, Math.max(0, limit));
115
+ }
116
+ finally {
117
+ if (ownsDb && db)
118
+ closeDatabase(db);
119
+ }
120
+ }
@@ -0,0 +1,386 @@
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
+ * WS-1 — Unified SALIENCE model (S1 seam).
6
+ *
7
+ * Replaces the three competing attention formulas that existed across:
8
+ * - proactive-maintenance.ts:186 — `importance × log(1+freq) × recencyDecay / log10(size)`
9
+ * - feedback-valence.ts:111 — `combinedEligibilityScore = utility·0.7 + valence·0.3`
10
+ * - getUtilityScoresByIds — MemRL utility EMA (#386)
11
+ *
12
+ * ## Salience vector (three independently-stored, independently-decayable sub-scores)
13
+ *
14
+ * | Sub-score | Brain analogy | Source |
15
+ * |-------------------|------------------------|---------------------------------|
16
+ * | `encodingSalience`| Amygdala tagging (Gap 1)| Set at extract; v1 = type weight|
17
+ * | `outcomeSalience` | Dopaminergic outcome | WS-2 (0 until that lands) |
18
+ * | `retrievalSalience`| Hippocampal frequency+recency | usage_events + utility_scores |
19
+ *
20
+ * ## Projection
21
+ *
22
+ * `rankScore = (w_e·encoding + w_o·outcome + w_r·retrieval) × sizePenalty`, normalized [0,1].
23
+ *
24
+ * **WS-2 default-off (Part-V gate):**
25
+ * `w_o = 0.15` is the target but is applied only when `outcomeWeightEnabled=true`
26
+ * (set via `improve.salience.outcomeWeightEnabled: true` in config after running
27
+ * Part-V T0 baseline). Default: WS-1 parity weights `w_e=0.30, w_r=0.70, w_o=0`.
28
+ * `outcomeSalience` is populated from `asset_outcome.outcome_score` (WS-2) for
29
+ * observability regardless of the flag.
30
+ *
31
+ * ## Plasticity
32
+ *
33
+ * `consecutive_no_ops` (INTEGER column in `asset_salience`) dampens CONSOLIDATION-
34
+ * SELECTION only — it is intentionally NOT applied to `rankScore`, so a stable
35
+ * asset stays fully retrievable while no longer consuming repeated LLM merge
36
+ * attempts. See `getConsecutiveNoOps` / `recordNoOp` / `resetConsecutiveNoOps`.
37
+ *
38
+ * ## Canonical store
39
+ *
40
+ * The three sub-scores live in `state.db :: asset_salience` (canonical).
41
+ * An optional frontmatter mirror of the stable `encodingSalience` is allowed for
42
+ * portability (issue #608 may write it there), but state.db is the source of truth
43
+ * for ranking. This prevents the frontmatter-vs-state.db split that issue #608
44
+ * would otherwise create (#608 pull-forward decision from Part VI).
45
+ *
46
+ * @module salience
47
+ */
48
+ import { makeAssetRef } from "../../core/asset/asset-ref.js";
49
+ import { getAllEntries, getUtilityScoresByIds } from "../../indexer/db/db.js";
50
+ import { WARM_START_CAP } from "./outcome-loop.js";
51
+ // ── One day in ms ─────────────────────────────────────────────────────────────
52
+ const DAY_MS = 86_400_000;
53
+ // ── Recency decay half-life (mirrors the proactive-maintenance prototype) ─────
54
+ const RECENCY_HALFLIFE_DAYS = 21;
55
+ // ── Size proxy floor (avoids log10(0)) ────────────────────────────────────────
56
+ const SIZE_FLOOR_BYTES = 200;
57
+ // ── Projection weights ────────────────────────────────────────────────────────
58
+ //
59
+ // These constants reflect the WS-2 TARGET values (used when outcomeWeightEnabled=true).
60
+ // Default ranking uses WS-1 parity weights (w_e=0.30, w_r=0.70, w_o=0) until the
61
+ // maintainer opts in via `improve.salience.outcomeWeightEnabled: true` after running
62
+ // the Part-V T0 baseline (scripts/akm-eval + health report).
63
+ //
64
+ // WS-2 opt-in split (w_e=0.25, w_o=0.15, w_r=0.60, sum = 1.0):
65
+ // [exp] Expert recommendation: encoding should be moderate so a type-importance
66
+ // stub does not completely dominate; retrieval should be strong since it directly
67
+ // measures use; outcome provides a quality signal proportional to usefulness.
68
+ //
69
+ // Re-tune via the Part-V measurement protocol if the throughput/quality gate
70
+ // shows regression after enabling the outcome weight.
71
+ export const W_ENCODING = 0.25; // WS-2 target encoding weight (w_e)
72
+ export const W_OUTCOME = 0.15; // WS-2 target outcome weight (w_o)
73
+ export const W_RETRIEVAL = 0.6; // WS-2 target retrieval weight (w_r)
74
+ // Compile-time guard: weights must sum to 1.0 (±ε). The TS initializer runs
75
+ // at module load, not build time, so this acts as a startup assertion.
76
+ if (Math.abs(W_ENCODING + W_OUTCOME + W_RETRIEVAL - 1.0) > 1e-9) {
77
+ throw new Error(`salience.ts: W_ENCODING + W_OUTCOME + W_RETRIEVAL must equal 1.0 (got ${W_ENCODING + W_OUTCOME + W_RETRIEVAL})`);
78
+ }
79
+ // ── WS-1 parity weights ───────────────────────────────────────────────────────
80
+ //
81
+ // These constants reflect the default WS-1 parity weights used when
82
+ // `outcomeWeightEnabled` is false/absent (the default). They preserve the
83
+ // WS-1 two-way split (w_e=0.30, w_r=0.70) with w_o=0 so outcome does not
84
+ // affect rankScore until the operator opts in after the Part-V baseline run.
85
+ //
86
+ // Named here (rather than inline literals in the else branch) so a future
87
+ // re-tune has a single source of truth and the sum-to-1 guard below catches
88
+ // any accidental mis-edit.
89
+ export const W_ENCODING_PARITY = 0.3; // WS-1 parity encoding weight
90
+ export const W_OUTCOME_PARITY = 0; // WS-1 parity outcome weight (0 = disabled)
91
+ export const W_RETRIEVAL_PARITY = 0.7; // WS-1 parity retrieval weight
92
+ // Startup guard: parity triple must also sum to 1.0 (±ε).
93
+ if (Math.abs(W_ENCODING_PARITY + W_OUTCOME_PARITY + W_RETRIEVAL_PARITY - 1.0) > 1e-9) {
94
+ throw new Error(`salience.ts: W_ENCODING_PARITY + W_OUTCOME_PARITY + W_RETRIEVAL_PARITY must equal 1.0 (got ${W_ENCODING_PARITY + W_OUTCOME_PARITY + W_RETRIEVAL_PARITY})`);
95
+ }
96
+ // ── Type-importance fallback weights (#608 landed) ────────────────────────────
97
+ //
98
+ // The real encoding salience estimator is `scoreEncodingSalience` in
99
+ // `encoding-salience.ts` (#608). These weights are the fallback used when
100
+ // `SalienceInputs.encodingSalience` is absent (pre-#608 assets without a
101
+ // frontmatter `salience:` field or a state.db row seeded by distill).
102
+ export const DEFAULT_TYPE_ENCODING_WEIGHTS = Object.freeze({
103
+ skill: 0.9,
104
+ agent: 0.9,
105
+ command: 0.8,
106
+ workflow: 0.8,
107
+ lesson: 0.75,
108
+ knowledge: 0.7,
109
+ script: 0.6,
110
+ memory: 0.5,
111
+ });
112
+ /** Default encoding salience for types not in the table above. */
113
+ export const DEFAULT_ENCODING_SALIENCE = 0.5;
114
+ // ── Core computation ─────────────────────────────────────────────────────────
115
+ /**
116
+ * Compute the salience vector for one asset.
117
+ *
118
+ * Pure function — no I/O. All inputs are pre-fetched by the caller.
119
+ */
120
+ export function computeSalience(inputs) {
121
+ const now = inputs.now ?? Date.now();
122
+ // ── Encoding salience ────────────────────────────────────────────────────────
123
+ //
124
+ // When `inputs.encodingSalience` is provided (computed by `scoreEncodingSalience`
125
+ // in encoding-salience.ts at extract/distill time, #608), use it directly.
126
+ // Fall back to the type-importance stub only when the caller has not yet
127
+ // computed a content-based score (e.g. on older assets before the first
128
+ // staleness refresh runs).
129
+ const encoding = inputs.encodingSalience !== undefined
130
+ ? Math.min(1, Math.max(0, inputs.encodingSalience))
131
+ : (DEFAULT_TYPE_ENCODING_WEIGHTS[inputs.type] ?? DEFAULT_ENCODING_SALIENCE);
132
+ // ── Outcome salience (WS-2 active) ────────────────────────────────────────
133
+ //
134
+ // When `inputs.outcomeSalience` is provided (WS-2 has populated asset_outcome
135
+ // for this ref), use it directly — it has already been normalised by
136
+ // `outcomeScoreToSalience` in outcome-loop.ts (value in [DIVERSITY_FLOOR, 1]).
137
+ //
138
+ // When absent (new asset, no WS-2 row yet): fall back to the warm-start seed
139
+ // from `utilityScore` clipped to [0, WARM_START_CAP], matching the seed
140
+ // value that `updateAssetOutcome` writes on first row creation. This ensures
141
+ // `outcomeSalience` is non-zero at launch for assets with utility history
142
+ // (avoiding the starvation problem described in the plan §WS-2 warm start).
143
+ let outcome;
144
+ if (inputs.outcomeSalience !== undefined) {
145
+ // Direct pass-through — caller already normalised via outcomeScoreToSalience.
146
+ outcome = Math.min(1, Math.max(0, inputs.outcomeSalience));
147
+ }
148
+ else {
149
+ // Warm-start fallback: clip utility to [0, WARM_START_CAP] so the
150
+ // outcomeSalience term contributes a modest non-zero baseline.
151
+ outcome = Math.min(WARM_START_CAP, Math.max(0, inputs.utilityScore ?? 0));
152
+ }
153
+ // ── Retrieval salience ─────────────────────────────────────────────────────
154
+ //
155
+ // Formula: log(1 + freq) × recencyDecay
156
+ // log(1+freq): sub-linear frequency term (same as proactive-maintenance prototype).
157
+ // recencyDecay: 0.1 + 0.5^(useAgeDays/halflife) — decays to 0.1 floor when stale.
158
+ // lastUseMs=0/undefined → useAgeDays=9999 → recencyDecay≈0.1 (floor).
159
+ //
160
+ // The recency term is MANDATORY (plan requirement §WS-1 step 2). Without it
161
+ // retrievalSalience degenerates to a non-decaying frequency count and the WS-3
162
+ // homeostatic step-0 demotion has nothing to act on.
163
+ const lastUseMs = inputs.lastUseMs ?? 0;
164
+ const useAgeDays = lastUseMs > 0 ? (now - lastUseMs) / DAY_MS : 9999;
165
+ const recencyDecay = 0.1 + 0.5 ** (useAgeDays / RECENCY_HALFLIFE_DAYS);
166
+ const rawRetrieval = Math.log(1 + inputs.retrievalFreq) * recencyDecay;
167
+ // ── Size penalty ─────────────────────────────────────────────────────────────
168
+ // 1/log10(size): larger assets are slightly deprioritized (same as proactive prototype).
169
+ const sizeProxy = Math.max(SIZE_FLOOR_BYTES, inputs.sizeBytes ?? 0);
170
+ const sizePenalty = 1 / Math.log10(sizeProxy);
171
+ // ── Projection → rankScore ────────────────────────────────────────────────
172
+ //
173
+ // Raw projection may be > 1 (log retrieval terms can exceed 1 for high freq + fresh use).
174
+ // Normalize by the theoretical maximum of the retrieval component:
175
+ // max retrievalRaw = log(1 + Infinity) × (0.1 + 1.0) = Infinity, so we
176
+ // cap instead — rankScore is clamped to [0,1] after applying the size penalty.
177
+ //
178
+ // Normalization approach: we scale the combined linear sum to [0,1] by clamping,
179
+ // after applying the size penalty. The encoding term is already in [0,1]; the
180
+ // retrieval term is open-ended but bounded in practice by log(1+N)×1.1 where N
181
+ // is the retrieval count. We normalize `retrieval` to [0,1] using a soft cap:
182
+ // retrieval_normalized = rawRetrieval / (rawRetrieval + 1)
183
+ // which asymptotes to 1 and equals 0.5 at rawRetrieval=1. This is the same
184
+ // formula used for MemRL utility updates.
185
+ const retrieval = rawRetrieval / (rawRetrieval + 1);
186
+ // ── Weight selection (Part-V gate) ────────────────────────────────────────
187
+ //
188
+ // When `outcomeWeightEnabled` is false/absent (default): use WS-1 parity
189
+ // weights (w_e=0.30, w_r=0.70, w_o=0) so ranking is unchanged from the WS-1
190
+ // baseline. The `outcome` sub-score is still computed and stored in the
191
+ // salience vector for observability, but it does not affect rankScore.
192
+ //
193
+ // When `outcomeWeightEnabled` is true (operator opt-in after Part-V run):
194
+ // use WS-2 weights (w_e=0.25, w_o=0.15, w_r=0.60).
195
+ //
196
+ // The constants W_ENCODING, W_OUTCOME, W_RETRIEVAL always reflect the
197
+ // WS-2 target values for documentation and re-tune reference.
198
+ let we;
199
+ let wo;
200
+ let wr;
201
+ if (inputs.outcomeWeightEnabled === true) {
202
+ // WS-2 active: three-way split from Part-V operator opt-in.
203
+ we = W_ENCODING; // 0.25
204
+ wo = W_OUTCOME; // 0.15
205
+ wr = W_RETRIEVAL; // 0.60
206
+ }
207
+ else {
208
+ // WS-1 parity (default): w_o=0, redistribute to WS-1 proportions.
209
+ // Original WS-1 split was w_e=0.30, w_r=0.70.
210
+ we = W_ENCODING_PARITY;
211
+ wo = W_OUTCOME_PARITY;
212
+ wr = W_RETRIEVAL_PARITY;
213
+ }
214
+ const rawRankScore = (we * encoding + wo * outcome + wr * retrieval) * sizePenalty;
215
+ const rankScore = Math.min(1, Math.max(0, rawRankScore));
216
+ return { encoding, outcome, retrieval, rankScore };
217
+ }
218
+ /**
219
+ * Upsert salience scores for one asset into state.db.
220
+ *
221
+ * Idempotent: safe to call every run; updates all columns on conflict.
222
+ */
223
+ export function upsertAssetSalience(db, ref, vector, now) {
224
+ const ts = now ?? Date.now();
225
+ db.prepare(`INSERT INTO asset_salience
226
+ (asset_ref, encoding_salience, outcome_salience, retrieval_salience, rank_score, consecutive_no_ops, updated_at)
227
+ VALUES (?, ?, ?, ?, ?, 0, ?)
228
+ ON CONFLICT(asset_ref) DO UPDATE SET
229
+ encoding_salience = excluded.encoding_salience,
230
+ outcome_salience = excluded.outcome_salience,
231
+ retrieval_salience = excluded.retrieval_salience,
232
+ rank_score = excluded.rank_score,
233
+ updated_at = excluded.updated_at`).run(ref, vector.encoding, vector.outcome, vector.retrieval, vector.rankScore, ts);
234
+ }
235
+ /**
236
+ * Load the salience row for one asset, or undefined if not yet computed.
237
+ */
238
+ export function getAssetSalience(db, ref) {
239
+ const row = db
240
+ .prepare(`SELECT asset_ref, encoding_salience, outcome_salience, retrieval_salience,
241
+ rank_score, consecutive_no_ops, updated_at
242
+ FROM asset_salience WHERE asset_ref = ?`)
243
+ .get(ref);
244
+ // Bun SQLite returns null (not undefined) when no row found.
245
+ return row == null ? undefined : row;
246
+ }
247
+ /**
248
+ * Load ALL rank scores from the asset_salience table (full-stash query).
249
+ *
250
+ * Used by the forgetting-safety report (plan §WS-1 step 7) to compute stash-wide
251
+ * rank positions rather than pool-relative positions. Returns an empty Map when the
252
+ * table is empty (first WS-1 run = no pre-existing rows).
253
+ *
254
+ * Order is unspecified; callers must sort before assigning 1-indexed positions.
255
+ */
256
+ export function getAllRankScores(db) {
257
+ const rows = db.prepare("SELECT asset_ref, rank_score FROM asset_salience").all();
258
+ const result = new Map();
259
+ for (const row of rows) {
260
+ result.set(row.asset_ref, row.rank_score);
261
+ }
262
+ return result;
263
+ }
264
+ // ── Plasticity helpers ────────────────────────────────────────────────────────
265
+ /**
266
+ * Increment `consecutive_no_ops` for an asset. Called after a no-op reflect/distill.
267
+ * Has NO effect on `rank_score` — the plasticity counter only dampens consolidation
268
+ * selection, not retrieval ranking. See plan §WS-1 step 8.
269
+ *
270
+ * Invariant: recordNoOp must never originate rank_score semantics. If the asset has
271
+ * no salience row yet (persistence's best-effort try/catch may have swallowed an
272
+ * error), we do nothing — a no-op counter is meaningless without a rank_score row,
273
+ * and a synthetic INSERT would fabricate a rank_score=0 entry that could produce
274
+ * false catastrophic-forgetting signals in buildRankChangeReport.
275
+ */
276
+ export function recordNoOp(db, ref) {
277
+ db.prepare(`UPDATE asset_salience SET consecutive_no_ops = consecutive_no_ops + 1, updated_at = ? WHERE asset_ref = ?`).run(Date.now(), ref);
278
+ // If changes === 0 the asset has no salience row yet — leave the table unchanged.
279
+ }
280
+ /**
281
+ * Reset `consecutive_no_ops` to 0 when an asset produces an accepted change.
282
+ * Call after a successful proposal acceptance or detected mutation.
283
+ */
284
+ export function resetConsecutiveNoOps(db, ref) {
285
+ db.prepare(`UPDATE asset_salience SET consecutive_no_ops = 0, updated_at = ? WHERE asset_ref = ?`).run(Date.now(), ref);
286
+ }
287
+ /**
288
+ * Return the `consecutive_no_ops` count for one asset. 0 when unknown.
289
+ */
290
+ export function getConsecutiveNoOps(db, ref) {
291
+ const row = db.prepare(`SELECT consecutive_no_ops FROM asset_salience WHERE asset_ref = ?`).get(ref);
292
+ return row?.consecutive_no_ops ?? 0;
293
+ }
294
+ // ── Consolidation-selection dampener constants ────────────────────────────────
295
+ //
296
+ // Assets with consecutive_no_ops >= THRESHOLD are deprioritised in the
297
+ // SELECTION ORDER only. The persisted rank_score is intentionally left
298
+ // unchanged so stable assets remain fully retrievable by other callers.
299
+ //
300
+ // Tuning guidance:
301
+ // THRESHOLD — how many consecutive no-op runs before dampening kicks in.
302
+ // 3 means "skipped three times in a row", which signals the
303
+ // LLM consistently has nothing to say about this asset.
304
+ // FACTOR — multiplicative penalty on the effective selection score.
305
+ // 0.5 halves the apparent score so a dampened asset sorts
306
+ // after any peer with >= half its rankScore.
307
+ export const SALIENCE_NO_OP_DAMPEN_THRESHOLD = 3;
308
+ export const SALIENCE_NO_OP_DAMPEN_FACTOR = 0.5;
309
+ /**
310
+ * Emit the forgetting-safety rank-change distribution report.
311
+ *
312
+ * Compares the provided `newRanks` (Map<ref, position (1-indexed)>) against
313
+ * the provided `oldRanks` and flags refs that were in the old top-200 but
314
+ * are now below position 500 as "forgetting candidates".
315
+ *
316
+ * Caller is responsible for computing old/new rank positions before and after
317
+ * the WS-1 formula cutover. Called once at cutover, not every run.
318
+ *
319
+ * @param oldRanks - Map<ref, 1-indexed rank position> under the OLD formula.
320
+ * @param newRanks - Map<ref, 1-indexed rank position> under the NEW formula.
321
+ * @param oldTopN - Assets in old top-N to guard (default: 200).
322
+ * @param forgettingThreshold - New rank position below which a fall is flagged (default: 500).
323
+ */
324
+ export function buildRankChangeReport(oldRanks, newRanks, oldTopN = 200, forgettingThreshold = 500) {
325
+ const allChanges = [];
326
+ const forgettingCandidates = [];
327
+ for (const [ref, oldRank] of oldRanks) {
328
+ const newRank = newRanks.get(ref);
329
+ if (newRank === undefined)
330
+ continue; // ref not in new ranking
331
+ const rankDelta = newRank - oldRank; // positive = fell in rank
332
+ allChanges.push({ ref, oldRank, newRank, rankDelta });
333
+ if (oldRank <= oldTopN && newRank > forgettingThreshold) {
334
+ forgettingCandidates.push({ ref, oldRank, newRank, rankDelta });
335
+ }
336
+ }
337
+ // Sort by magnitude of rank drop (most dramatic first).
338
+ forgettingCandidates.sort((a, b) => b.rankDelta - a.rankDelta);
339
+ return { forgettingCandidates, allChanges };
340
+ }
341
+ // ── Last-use timestamp lookup helper ─────────────────────────────────────────
342
+ //
343
+ // Wraps the index DB query to retrieve the last-retrieval timestamp per ref,
344
+ // so callers do not need to import the raw db helpers directly. Returns a Map
345
+ // keyed by the same ref strings passed in.
346
+ //
347
+ // Source: `utility_scores.last_used_at` (ISO-8601 string) joined to entries
348
+ // via entry_id. WS-2 may later supersede this with `asset_outcome.last_retrieved_at`.
349
+ /**
350
+ * Build a Map<ref, lastUseMs> from the index database's utility_scores table.
351
+ *
352
+ * Returns only refs that have a non-null `last_used_at`. Refs absent from the
353
+ * map should be treated as never retrieved (lastUseMs = 0).
354
+ *
355
+ * @param indexDb - An open read-capable index database connection.
356
+ * @param refs - The set of asset refs to look up.
357
+ */
358
+ export function getLastUseMsByRef(indexDb, refs) {
359
+ const result = new Map();
360
+ if (refs.length === 0)
361
+ return result;
362
+ const refSet = new Set(refs);
363
+ const allEntries = getAllEntries(indexDb);
364
+ const idToRef = new Map();
365
+ for (const indexed of allEntries) {
366
+ const ref = makeAssetRef(indexed.entry.type, indexed.entry.name);
367
+ if (refSet.has(ref))
368
+ idToRef.set(indexed.id, ref);
369
+ }
370
+ const ids = [...idToRef.keys()];
371
+ if (ids.length === 0)
372
+ return result;
373
+ const { global: scores } = getUtilityScoresByIds(indexDb, ids);
374
+ for (const [id, row] of scores) {
375
+ const ref = idToRef.get(id);
376
+ if (!ref)
377
+ continue;
378
+ const lastUsedAt = row.lastUsedAt;
379
+ if (!lastUsedAt)
380
+ continue;
381
+ const ms = typeof lastUsedAt === "number" ? lastUsedAt : Date.parse(lastUsedAt);
382
+ if (ms > 0)
383
+ result.set(ref, ms);
384
+ }
385
+ return result;
386
+ }
@@ -0,0 +1,95 @@
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
+ * Default minimum total score a session must reach to PASS the gate. Tuned
6
+ * conservatively: a single real narrative-lesson session, or a procedurally
7
+ * dense session, clears it — but pure read-only Q&A does not. Config-overridable
8
+ * via `processes.extract.triage.minScore`.
9
+ */
10
+ export const DEFAULT_TRIAGE_MIN_SCORE = 2;
11
+ // Decision / outcome / error narrative markers. Case-insensitive, word-bounded.
12
+ const MARKER_RE = /\b(error|failed|fix(?:ed)?|root cause|turns out|because|decided|instead|gotcha|workaround|regress(?:ed)?|broke|TIL)\b/i;
13
+ // Edit / commit / file-write markers in tool event text.
14
+ const EDIT_COMMIT_RE = /\b(Edit|Write|MultiEdit|git commit|diff)\b/i;
15
+ // A substantive turn is an assistant or tool turn whose text is non-trivial.
16
+ const SUBSTANTIVE_MIN_CHARS = 40;
17
+ /**
18
+ * Pure heuristic scorer. Operates only on `data.events`. Each sub-signal is
19
+ * normalized to a small bounded contribution; `score` is their sum and
20
+ * `pass = score >= minScore`.
21
+ *
22
+ * Sub-signals:
23
+ * - markers: presence of decision/outcome/error keywords across event text
24
+ * (capped, narrative-lesson signal).
25
+ * - toolDensity: bounded contribution from tool-use events (procedural).
26
+ * - editCommit: bounded contribution from edit/write/commit events (procedural).
27
+ * - substantiveRatio: scaled fraction of non-trivial assistant+tool turns,
28
+ * filtering pure short Q&A.
29
+ *
30
+ * The procedural sub-signals (toolDensity + editCommit) alone can clear
31
+ * DEFAULT_TRIAGE_MIN_SCORE so high-action / no-narrative sessions are KEPT (#615).
32
+ */
33
+ export function scoreSessionTriage(data, minScore) {
34
+ const events = data.events;
35
+ const total = events.length;
36
+ // (a) markers — count word-bounded marker hits across all event text, capped.
37
+ let markerHits = 0;
38
+ for (const e of events) {
39
+ if (MARKER_RE.test(e.text))
40
+ markerHits += 1;
41
+ }
42
+ // Each marker-bearing event contributes 1 point, capped at 2 (a single real
43
+ // narrative session clears the bar on markers alone).
44
+ const markers = Math.min(markerHits, 2);
45
+ // (b) toolDensity — bounded contribution from tool-use events.
46
+ let toolEvents = 0;
47
+ for (const e of events) {
48
+ if (e.role === "tool")
49
+ toolEvents += 1;
50
+ }
51
+ // 0.25 per tool event, capped at 1.5.
52
+ const toolDensity = Math.min(toolEvents * 0.25, 1.5);
53
+ // (c) editCommit — bounded contribution from edit/write/commit markers on
54
+ // events (filePath present, or text matching the edit/commit regex).
55
+ let editCommitEvents = 0;
56
+ for (const e of events) {
57
+ if (e.filePath || EDIT_COMMIT_RE.test(e.text))
58
+ editCommitEvents += 1;
59
+ }
60
+ // 0.25 per edit/commit event, capped at 1.5. Together with toolDensity a
61
+ // procedurally dense session reaches well above the default threshold.
62
+ const editCommit = Math.min(editCommitEvents * 0.25, 1.5);
63
+ // (d) substantiveRatio — scaled fraction of non-trivial assistant+tool turns.
64
+ let substantive = 0;
65
+ for (const e of events) {
66
+ if ((e.role === "assistant" || e.role === "tool") && e.text.length >= SUBSTANTIVE_MIN_CHARS) {
67
+ substantive += 1;
68
+ }
69
+ }
70
+ const ratio = total > 0 ? substantive / total : 0;
71
+ // Scale to a bounded [0,1] contribution.
72
+ const substantiveRatio = Math.min(ratio, 1);
73
+ const subscores = { markers, toolDensity, editCommit, substantiveRatio };
74
+ const score = markers + toolDensity + editCommit + substantiveRatio;
75
+ const pass = score >= minScore;
76
+ return {
77
+ pass,
78
+ score,
79
+ subscores,
80
+ ...(pass ? {} : { reason: "low_signal" }),
81
+ };
82
+ }
83
+ /**
84
+ * Resolve the effective triage config from the extract process config. Mirrors
85
+ * the minContentChars / schemaSimilarity resolution style in akmExtract.
86
+ *
87
+ * Default-off: `enabled` is FALSE unless `triage.enabled === true`. `minScore`
88
+ * defaults to {@link DEFAULT_TRIAGE_MIN_SCORE}.
89
+ */
90
+ export function resolveTriageConfig(extractProcess) {
91
+ const triage = extractProcess?.triage;
92
+ const enabled = triage?.enabled === true;
93
+ const minScore = typeof triage?.minScore === "number" ? triage.minScore : DEFAULT_TRIAGE_MIN_SCORE;
94
+ return { enabled, minScore };
95
+ }
@@ -1,22 +1,25 @@
1
1
  // This Source Code Form is subject to the terms of the Mozilla Public
2
2
  // License, v. 2.0. If a copy of the MPL was not distributed with this
3
3
  // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
- import path from "node:path";
5
4
  import { BaseLinter } from "./base-linter.js";
5
+ /** Valid values for the `type` field in agent frontmatter. */
6
+ const VALID_AGENT_TYPES = ["agent"];
6
7
  /**
7
8
  * Linter for `agents/` assets.
8
9
  *
9
- * Extra check beyond base:
10
+ * Extra checks beyond base:
10
11
  * - `missing-name-or-type`: frontmatter exists but `name` or `type` field is
11
12
  * absent. Not auto-fixable; detail includes a suggested slug.
13
+ * - `missing-name-or-type` (invalid value): `type` is present but not a
14
+ * recognised agent type value.
12
15
  */
13
16
  export class AgentLinter extends BaseLinter {
14
17
  types = ["agents"];
15
18
  lint(ctx) {
16
19
  const issues = this.runBaseChecks(ctx);
17
- const missingFieldDetail = this.#checkMissingNameOrType(ctx.data, ctx.frontmatter);
20
+ const missingFieldDetail = this.checkMissingNameOrType(ctx.data, ctx.frontmatter);
18
21
  if (missingFieldDetail) {
19
- const slug = this.#suggestSlug(ctx.filePath);
22
+ const slug = this.suggestSlug(ctx.filePath);
20
23
  issues.push({
21
24
  file: ctx.relPath,
22
25
  issue: "missing-name-or-type",
@@ -24,26 +27,18 @@ export class AgentLinter extends BaseLinter {
24
27
  fixed: false,
25
28
  });
26
29
  }
30
+ else {
31
+ // Only validate the value when the field is actually present.
32
+ const invalidTypeDetail = this.checkInvalidTypeValue(ctx.data, VALID_AGENT_TYPES);
33
+ if (invalidTypeDetail) {
34
+ issues.push({
35
+ file: ctx.relPath,
36
+ issue: "missing-name-or-type",
37
+ detail: invalidTypeDetail,
38
+ fixed: false,
39
+ });
40
+ }
41
+ }
27
42
  return issues;
28
43
  }
29
- #checkMissingNameOrType(data, frontmatterText) {
30
- if (!frontmatterText)
31
- return null;
32
- const missingFields = [];
33
- if (!("name" in data) || !data.name)
34
- missingFields.push("name");
35
- if (!("type" in data) || !data.type)
36
- missingFields.push("type");
37
- if (missingFields.length === 0)
38
- return null;
39
- return `missing fields: ${missingFields.join(", ")}`;
40
- }
41
- #suggestSlug(filePath) {
42
- return path
43
- .basename(filePath, ".md")
44
- .toLowerCase()
45
- .replace(/[^a-z0-9-]+/g, "-")
46
- .replace(/-+/g, "-")
47
- .replace(/^-|-$/g, "");
48
- }
49
44
  }