akm-cli 0.9.0-beta.4 → 0.9.0-beta.40

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 (131) hide show
  1. package/CHANGELOG.md +626 -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 +6 -2
  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/stash-skeleton/facts/conventions/assets/agent.md +22 -0
  16. package/dist/assets/stash-skeleton/facts/conventions/assets/command.md +22 -0
  17. package/dist/assets/stash-skeleton/facts/conventions/assets/fact.md +24 -0
  18. package/dist/assets/stash-skeleton/facts/conventions/assets/knowledge.md +22 -0
  19. package/dist/assets/stash-skeleton/facts/conventions/assets/lesson.md +25 -0
  20. package/dist/assets/stash-skeleton/facts/conventions/assets/memory.md +21 -0
  21. package/dist/assets/stash-skeleton/facts/conventions/assets/script.md +21 -0
  22. package/dist/assets/stash-skeleton/facts/conventions/assets/skill.md +23 -0
  23. package/dist/assets/stash-skeleton/facts/conventions/assets/workflow.md +22 -0
  24. package/dist/assets/templates/html/health.html +281 -111
  25. package/dist/cli.js +14 -3
  26. package/dist/commands/agent/contribute-cli.js +16 -3
  27. package/dist/commands/feedback-cli.js +15 -6
  28. package/dist/commands/graph/graph.js +75 -71
  29. package/dist/commands/health/checks.js +48 -0
  30. package/dist/commands/health/html-report.js +422 -80
  31. package/dist/commands/health.js +381 -9
  32. package/dist/commands/improve/calibration.js +161 -0
  33. package/dist/commands/improve/consolidate.js +631 -111
  34. package/dist/commands/improve/dedup.js +482 -0
  35. package/dist/commands/improve/distill.js +163 -69
  36. package/dist/commands/improve/encoding-salience.js +205 -0
  37. package/dist/commands/improve/extract-cli.js +115 -1
  38. package/dist/commands/improve/extract-prompt.js +39 -2
  39. package/dist/commands/improve/extract-watch.js +140 -0
  40. package/dist/commands/improve/extract.js +403 -40
  41. package/dist/commands/improve/feedback-valence.js +54 -0
  42. package/dist/commands/improve/homeostatic.js +467 -0
  43. package/dist/commands/improve/improve-auto-accept.js +113 -6
  44. package/dist/commands/improve/improve-profiles.js +12 -0
  45. package/dist/commands/improve/improve.js +2042 -612
  46. package/dist/commands/improve/memory/memory-contradiction-detect.js +23 -28
  47. package/dist/commands/improve/outcome-loop.js +256 -0
  48. package/dist/commands/improve/proactive-maintenance.js +115 -0
  49. package/dist/commands/improve/procedural.js +418 -0
  50. package/dist/commands/improve/recombine.js +602 -0
  51. package/dist/commands/improve/reflect-noise.js +0 -0
  52. package/dist/commands/improve/reflect.js +46 -4
  53. package/dist/commands/improve/related-sessions.js +120 -0
  54. package/dist/commands/improve/salience.js +438 -0
  55. package/dist/commands/improve/triage.js +93 -0
  56. package/dist/commands/lint/agent-linter.js +19 -24
  57. package/dist/commands/lint/base-linter.js +173 -60
  58. package/dist/commands/lint/command-linter.js +19 -24
  59. package/dist/commands/lint/env-key-rules.js +34 -1
  60. package/dist/commands/lint/fact-linter.js +39 -0
  61. package/dist/commands/lint/index.js +31 -13
  62. package/dist/commands/lint/memory-linter.js +1 -1
  63. package/dist/commands/lint/registry.js +7 -2
  64. package/dist/commands/lint/task-linter.js +3 -3
  65. package/dist/commands/lint/workflow-linter.js +26 -1
  66. package/dist/commands/proposal/drain-policies.js +5 -0
  67. package/dist/commands/proposal/drain.js +17 -1
  68. package/dist/commands/proposal/proposal.js +5 -0
  69. package/dist/commands/proposal/propose.js +5 -0
  70. package/dist/commands/proposal/validators/proposal-quality-validators.js +9 -8
  71. package/dist/commands/proposal/validators/proposals.js +187 -57
  72. package/dist/commands/read/curate.js +344 -80
  73. package/dist/commands/read/search-cli.js +7 -0
  74. package/dist/commands/read/search.js +1 -0
  75. package/dist/commands/read/show.js +67 -2
  76. package/dist/commands/sources/init.js +36 -9
  77. package/dist/commands/sources/installed-stashes.js +5 -1
  78. package/dist/commands/sources/schema-repair.js +13 -1
  79. package/dist/commands/sources/stash-cli.js +19 -3
  80. package/dist/commands/sources/stash-skeleton.js +23 -8
  81. package/dist/core/asset/asset-registry.js +2 -0
  82. package/dist/core/asset/asset-spec.js +14 -0
  83. package/dist/core/asset/frontmatter.js +166 -167
  84. package/dist/core/asset/markdown.js +8 -0
  85. package/dist/core/authoring-rules.js +83 -0
  86. package/dist/core/config/config-schema.js +274 -2
  87. package/dist/core/config/config.js +2 -2
  88. package/dist/core/logs-db.js +4 -3
  89. package/dist/core/paths.js +3 -0
  90. package/dist/core/standards/resolve-standards-context.js +87 -0
  91. package/dist/core/standards/resolve-stash-standards.js +99 -0
  92. package/dist/core/standards/resolve-type-conventions.js +66 -0
  93. package/dist/core/state-db.js +691 -30
  94. package/dist/indexer/db/db.js +364 -38
  95. package/dist/indexer/db/graph-db.js +129 -86
  96. package/dist/indexer/ensure-index.js +152 -17
  97. package/dist/indexer/graph/graph-boost.js +51 -41
  98. package/dist/indexer/graph/graph-extraction.js +203 -3
  99. package/dist/indexer/index-writer-lock.js +99 -0
  100. package/dist/indexer/indexer.js +114 -111
  101. package/dist/indexer/passes/memory-inference.js +10 -3
  102. package/dist/indexer/passes/staleness-detect.js +2 -5
  103. package/dist/indexer/search/db-search.js +15 -4
  104. package/dist/indexer/search/ranking-contributors.js +22 -0
  105. package/dist/indexer/search/ranking.js +4 -0
  106. package/dist/indexer/walk/matchers.js +9 -0
  107. package/dist/integrations/agent/prompts.js +33 -0
  108. package/dist/integrations/harnesses/claude/session-log.js +11 -1
  109. package/dist/integrations/harnesses/opencode/session-log.js +173 -3
  110. package/dist/integrations/session-logs/index.js +16 -0
  111. package/dist/llm/client.js +23 -4
  112. package/dist/llm/embedder.js +27 -3
  113. package/dist/llm/embedders/local.js +66 -2
  114. package/dist/llm/feature-gate.js +8 -4
  115. package/dist/llm/graph-extract.js +2 -1
  116. package/dist/llm/memory-infer.js +4 -8
  117. package/dist/llm/metadata-enhance.js +9 -1
  118. package/dist/output/renderers.js +73 -1
  119. package/dist/output/shapes/curate.js +14 -2
  120. package/dist/output/text/helpers.js +16 -1
  121. package/dist/runtime.js +25 -1
  122. package/dist/scripts/migrate-storage.js +1378 -599
  123. package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +479 -270
  124. package/dist/setup/setup.js +3 -3
  125. package/dist/sources/providers/tar-utils.js +16 -8
  126. package/dist/storage/sqlite-pragmas.js +146 -0
  127. package/dist/wiki/wiki.js +37 -0
  128. package/dist/workflows/db.js +3 -4
  129. package/dist/workflows/validate-summary.js +2 -7
  130. package/docs/data-and-telemetry.md +1 -0
  131. package/package.json +8 -6
@@ -23,12 +23,16 @@
23
23
  * descriptionQualityValidator passes — same pattern as the
24
24
  * consolidate-writer fix.
25
25
  */
26
+ import fs from "node:fs";
27
+ import path from "node:path";
26
28
  import { assembleAsset } from "../../core/asset/asset-serialize.js";
27
29
  import { resolveStashDir, timestampForFilename } from "../../core/common.js";
28
30
  import { getDefaultLlmConfig, loadConfig } from "../../core/config/config.js";
29
31
  import { ConfigError, UsageError } from "../../core/errors.js";
30
32
  import { appendEvent } from "../../core/events.js";
31
- import { getExtractedSessionsMap, openStateDatabase, shouldSkipAlreadyExtractedSession, upsertExtractedSession, } from "../../core/state-db.js";
33
+ import { probeLock, releaseLock, tryAcquireLockSync } from "../../core/file-lock.js";
34
+ import { resolveStashStandards } from "../../core/standards/resolve-stash-standards.js";
35
+ import { getExtractedSessionsMap, getLastExtractRunAt, getStateDbPath, openStateDatabase, shouldSkipAlreadyExtractedSession, upsertExtractedSession, } from "../../core/state-db.js";
32
36
  import { repairTruncatedDescription } from "../../core/text-truncation.js";
33
37
  import { warn } from "../../core/warn.js";
34
38
  import { resolveImproveProcessRunnerFromProfile, runnerIsLlm } from "../../integrations/agent/runner.js";
@@ -36,10 +40,15 @@ import { normalizeHarnessId } from "../../integrations/harnesses/index.js";
36
40
  import { getAvailableHarnesses } from "../../integrations/session-logs/index.js";
37
41
  import { preFilterSession } from "../../integrations/session-logs/pre-filter.js";
38
42
  import { chatCompletion } from "../../llm/client.js";
39
- import { isLlmFeatureEnabled, tryLlmFeature } from "../../llm/feature-gate.js";
43
+ import { embed } from "../../llm/embedder.js";
44
+ import { tryLlmFeature } from "../../llm/feature-gate.js";
45
+ import { sha256Hex } from "../../runtime.js";
40
46
  import { createProposal, isProposalSkipped } from "../proposal/validators/proposals.js";
41
47
  import { buildExtractPrompt, EXTRACT_JSON_SCHEMA, parseExtractPayload } from "./extract-prompt.js";
48
+ import { applySchemaSimilarityPenalty, buildHotProbationFrontmatter, loadDerivedLayerEmbeddings, } from "./homeostatic.js";
49
+ import { resolveProcessEnabled } from "./improve-profiles.js";
42
50
  import { buildSessionSummaryPrompt, parseSessionSummary, SESSION_SUMMARY_JSON_SCHEMA, sessionMeetsDurationGate, writeSessionAsset, } from "./session-asset.js";
51
+ import { resolveTriageConfig, scoreSessionTriage } from "./triage.js";
43
52
  /** Default minimum session duration (minutes) for session indexing (#561). */
44
53
  const DEFAULT_MIN_SESSION_DURATION_MINUTES = 5;
45
54
  /**
@@ -50,6 +59,96 @@ const DEFAULT_MIN_SESSION_DURATION_MINUTES = 5;
50
59
  * (0 chars, journal files) are safe to skip.
51
60
  */
52
61
  const DEFAULT_MIN_CONTENT_CHARS = 10;
62
+ /**
63
+ * Default cap on NEW sessions the extract pass will LLM-process in a single run
64
+ * (`processes.extract.maxSessionsPerRun` overrides; `0` disables). Bounds per-run
65
+ * wall time + token spend so a backlog of accumulated sessions can't run a single
66
+ * pass past its scheduled-task timeout. Overflow sessions stay unseen and are
67
+ * processed by subsequent runs, so coverage is preserved — just spread out.
68
+ */
69
+ const DEFAULT_MAX_SESSIONS_PER_RUN = 25;
70
+ /**
71
+ * Floor for the default discovery window (48h). When no explicit `--since` /
72
+ * `defaultSince` is configured, discovery looks back to the LAST recorded
73
+ * extract run for the harness (so an intermittently-online host that was off for
74
+ * days still rediscovers sessions that ended during the gap), but never LESS
75
+ * than this — looking back less than the prior window could drop a session that
76
+ * a previous run deferred via `maxSessionsPerRun`. Widening is free of redundant
77
+ * LLM cost: the content-hash ledger skips unchanged sessions with zero LLM calls.
78
+ */
79
+ const DEFAULT_SINCE_FLOOR_MS = 48 * 60 * 60 * 1000;
80
+ /**
81
+ * Staleness window for the per-session extract lock. A single session's
82
+ * processing is bounded by the per-session LLM timeout (default 60s) plus the
83
+ * session-summary call, so a lock older than this must belong to a crashed
84
+ * holder and is safe to reclaim.
85
+ */
86
+ const EXTRACT_SESSION_LOCK_STALE_MS = 5 * 60 * 1000;
87
+ /**
88
+ * Resolve the discovery `sinceMs` cutoff when no explicit `since`/`defaultSince`
89
+ * is set: the later of (last recorded extract run for this harness) and
90
+ * (now − 48h). See {@link DEFAULT_SINCE_FLOOR_MS}. Best-effort — any state.db
91
+ * error falls back to the 48h floor.
92
+ */
93
+ function resolveDefaultSinceMs(harnessName, now, opts) {
94
+ const floor = now - DEFAULT_SINCE_FLOOR_MS;
95
+ if (opts.skipTracking)
96
+ return floor;
97
+ let db = opts.stateDb;
98
+ let opened = false;
99
+ try {
100
+ if (!db) {
101
+ db = openStateDatabase(opts.stateDbPath);
102
+ opened = true;
103
+ }
104
+ const lastRun = getLastExtractRunAt(db, harnessName);
105
+ return lastRun != null ? Math.min(lastRun, floor) : floor;
106
+ }
107
+ catch {
108
+ return floor;
109
+ }
110
+ finally {
111
+ if (opened && db) {
112
+ try {
113
+ db.close();
114
+ }
115
+ catch {
116
+ // best-effort close
117
+ }
118
+ }
119
+ }
120
+ }
121
+ /** Filesystem-safe per-session lock path, co-located with the state.db. */
122
+ function getExtractSessionLockPath(harness, sessionId, stateDbPath) {
123
+ const safe = `${harness}-${sessionId}`.replace(/[^A-Za-z0-9._-]/g, "_");
124
+ return path.join(path.dirname(stateDbPath), "extract-locks", `extract-${safe}.lock`);
125
+ }
126
+ /**
127
+ * Try to claim the per-session extract lock so a concurrent extract (e.g. a
128
+ * session-end hook firing `--session-id` while the hourly improve pass runs
129
+ * discovery) cannot double-process the SAME session — duplicate LLM spend and
130
+ * near-duplicate proposals. Reclaims a stale lock (dead holder PID or age past
131
+ * {@link EXTRACT_SESSION_LOCK_STALE_MS}). Returns false when another LIVE run
132
+ * holds it — the caller then skips the session without any LLM call. Best-effort:
133
+ * any filesystem error resolves to `true` (proceed) so locking never blocks
134
+ * extraction outright.
135
+ */
136
+ function acquireExtractSessionLock(lockPath) {
137
+ try {
138
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
139
+ if (tryAcquireLockSync(lockPath, String(process.pid)))
140
+ return true;
141
+ const probe = probeLock(lockPath, { staleAfterMs: EXTRACT_SESSION_LOCK_STALE_MS });
142
+ if (probe.state === "held")
143
+ return false;
144
+ // absent (released between attempt + probe) or stale → reclaim and retry once.
145
+ releaseLock(lockPath);
146
+ return tryAcquireLockSync(lockPath, String(process.pid));
147
+ }
148
+ catch {
149
+ return true;
150
+ }
151
+ }
53
152
  // ── Helpers ──────────────────────────────────────────────────────────────────
54
153
  /**
55
154
  * Parse a since-string into an absolute ms-epoch cutoff. Accepts:
@@ -112,9 +211,43 @@ function buildCandidateProposal(candidate, sourceRef) {
112
211
  if (candidate.type === "lesson" && candidate.when_to_use) {
113
212
  fm.when_to_use = candidate.when_to_use;
114
213
  }
214
+ // #615 WS-0: preserve ordered-action + outcome data in frontmatter so the data
215
+ // survives even if source transcripts are not re-extractable later. The
216
+ // procedural-compilation feature (detection/compilation) is deferred to 0.10+.
217
+ if (candidate.orderedActions && candidate.orderedActions.length > 0) {
218
+ fm.orderedActions = candidate.orderedActions;
219
+ if (candidate.outcomeData) {
220
+ fm.outcomeData = candidate.outcomeData;
221
+ }
222
+ }
115
223
  const content = assembleAsset(fm, candidate.body);
116
224
  return { ref, content, description };
117
225
  }
226
+ /**
227
+ * Canonicalize a session's content into a single deterministic string for
228
+ * hashing (#602). Each event is rendered `<role>\n<text>` and events are joined
229
+ * with a NUL-delimited separator (`\n\0\n`) so event boundaries cannot be forged
230
+ * by text that itself contains newlines.
231
+ *
232
+ * The input is the RAW `data.events` stream — NOT the pre-filtered / truncated
233
+ * set — so the hash is stable across `maxTotalChars` (and any other pre-filter)
234
+ * config changes: changing config must NEVER change the hash (idempotency AC).
235
+ * `inlineRefs` and ref metadata (title, startedAt/endedAt timestamps) are
236
+ * deliberately EXCLUDED so clock/title churn (and an agent adding an inline
237
+ * `akm remember` mid-session) does not change the hash.
238
+ */
239
+ function canonicalizeSessionContent(data) {
240
+ return data.events.map((e) => `${e.role ?? "unknown"}\n${e.text}`).join("\n\0\n");
241
+ }
242
+ /**
243
+ * sha256 (hex) of the normalized session content (#602). This is the byte-exact,
244
+ * clock-independent skip authority that replaced the old `session_ended_at`
245
+ * timestamp comparison. See {@link canonicalizeSessionContent} for exactly what
246
+ * is (and is not) hashed.
247
+ */
248
+ export function hashSessionContent(data) {
249
+ return sha256Hex(canonicalizeSessionContent(data));
250
+ }
118
251
  /**
119
252
  * Process one session through the full pipeline: read → pre-filter → LLM →
120
253
  * parse → createProposal-per-candidate. Returns the per-session result.
@@ -123,7 +256,21 @@ function buildCandidateProposal(candidate, sourceRef) {
123
256
  * proposal validation failure) the session result records a warning and
124
257
  * keeps going — one session's bad luck never aborts a multi-session run.
125
258
  */
126
- async function processSession(harness, sessionRef, stashDir, config, llmConfig, chat, ctx, sourceRun, dryRun, timeoutMs, maxTotalChars, minContentChars, sessionIndexing) {
259
+ async function processSession(harness, sessionRef, stashDir, config, llmConfig, chat, ctx, sourceRun, dryRun, timeoutMs, maxTotalChars, minContentChars,
260
+ // #626 — pre-LLM heuristic triage gate. Default-off (enabled:false) takes the
261
+ // exact pre-change path (no scorer call, no new skipReason).
262
+ // #641 — proceduralAwareFloor is opt-in, DEFAULT OFF.
263
+ triage, sessionIndexing, schemaSimilarityCtx,
264
+ // #602 — already-extracted skip moved INSIDE processSession: the content hash
265
+ // can only be computed after readSession, so the skip decision lives here. The
266
+ // prior row + bypass flags are threaded in from the caller. Skipping here still
267
+ // costs ZERO LLM calls (the expensive resource #602 protects); only the cheap
268
+ // file read is incurred.
269
+ prior, force,
270
+ // Stash authoring standards (convention/meta fact bodies) for non-wiki
271
+ // output. Resolved ONCE per run by the caller and threaded in so facts are
272
+ // not re-read per session. Empty string when none exist.
273
+ standardsContext) {
127
274
  const warnings = [];
128
275
  let data;
129
276
  try {
@@ -141,6 +288,27 @@ async function processSession(harness, sessionRef, stashDir, config, llmConfig,
141
288
  skipReason: "read_failed",
142
289
  };
143
290
  }
291
+ // #602 — content-hash skip. Computed on the RAW event stream immediately after
292
+ // a successful read, BEFORE the pre-filter / minContentChars / triage gates, so
293
+ // an unchanged session never reaches the LLM. Hash-based ⇒ clock-independent
294
+ // (immune to the Jun 11-12 timestamp double-extract/over-throttle bug). The skip
295
+ // applies UNIFORMLY — including explicit `--session-id` targeting (so a
296
+ // session-end hook firing `extract --session-id <id>` is idempotent). ONLY
297
+ // `--force` overrides it to re-extract a previously-extracted session.
298
+ const contentHash = hashSessionContent(data);
299
+ if (!force && shouldSkipAlreadyExtractedSession(prior, contentHash)) {
300
+ return {
301
+ sessionId: sessionRef.sessionId,
302
+ harness: harness.name,
303
+ candidateCount: 0,
304
+ proposalIds: [],
305
+ preFilter: { inputCount: 0, outputCount: 0, truncatedCount: 0 },
306
+ warnings: [`already extracted (content unchanged) at ${prior?.processed_at}; pass --force to re-process`],
307
+ skipped: true,
308
+ skipReason: "already_extracted",
309
+ contentHash,
310
+ };
311
+ }
144
312
  const filtered = preFilterSession(data, {
145
313
  ...(typeof maxTotalChars === "number" ? { maxTotalChars } : {}),
146
314
  });
@@ -167,9 +335,42 @@ async function processSession(harness, sessionRef, stashDir, config, llmConfig,
167
335
  warnings: [],
168
336
  skipped: true,
169
337
  skipReason: "too_short",
338
+ contentHash,
170
339
  };
171
340
  }
172
- const prompt = buildExtractPrompt({ data, events: filtered.events, inlineRefs: data.inlineRefs });
341
+ // #626 pre-LLM heuristic triage gate. Runs AFTER minContentChars + the
342
+ // already-extracted skip check (both in the caller / above), BEFORE the
343
+ // extraction prompt and the session-asset write. When the session scores below
344
+ // the configured threshold we triage it out: no chat() call, no session asset,
345
+ // no proposals. Pure-heuristic — zero added LLM cost. Default-off → skipped.
346
+ if (triage.enabled) {
347
+ const t = scoreSessionTriage(data, triage.minScore, {
348
+ proceduralAwareFloor: triage.proceduralAwareFloor,
349
+ });
350
+ if (!t.pass) {
351
+ return {
352
+ sessionId: sessionRef.sessionId,
353
+ harness: harness.name,
354
+ candidateCount: 0,
355
+ proposalIds: [],
356
+ preFilter: {
357
+ inputCount: filtered.stats.inputCount,
358
+ outputCount: filtered.stats.outputCount,
359
+ truncatedCount: filtered.stats.truncatedCount,
360
+ },
361
+ warnings: [],
362
+ skipped: true,
363
+ skipReason: "triaged_out",
364
+ contentHash,
365
+ };
366
+ }
367
+ }
368
+ const prompt = buildExtractPrompt({
369
+ data,
370
+ events: filtered.events,
371
+ inlineRefs: data.inlineRefs,
372
+ ...(standardsContext.trim() ? { standardsContext } : {}),
373
+ });
173
374
  // #561 — ADDITIVE session indexing. Generate + write the session asset
174
375
  // (`sessions/<harness>/<id>.md`). FAIL-OPEN: any failure only records a
175
376
  // warning; it NEVER changes the proposal/skip outcome of extract. Returns the
@@ -217,6 +418,7 @@ async function processSession(harness, sessionRef, stashDir, config, llmConfig,
217
418
  warnings: ["session_extraction feature returned empty (disabled / timeout / error)"],
218
419
  skipped: true,
219
420
  skipReason: "llm_unavailable",
421
+ contentHash,
220
422
  };
221
423
  }
222
424
  const payload = parseExtractPayload(llmRaw);
@@ -248,15 +450,34 @@ async function processSession(harness, sessionRef, stashDir, config, llmConfig,
248
450
  truncatedCount: filtered.stats.truncatedCount,
249
451
  },
250
452
  warnings,
453
+ contentHash,
251
454
  ...sessionAsset,
252
455
  };
253
456
  }
457
+ // WS-3b step 0c: hot-probation intake buffer (#604).
458
+ // When enabled, system-generated extractions enter captureMode: hot-probation
459
+ // so they spend ONE consolidation cycle in probation before the deterministic
460
+ // dedup+quality pass promotes them. Default OFF.
461
+ const hotProbationEnabled = config.profiles?.improve?.default?.processes?.extract?.hotProbation
462
+ ?.enabled === true;
254
463
  for (const candidate of payload.candidates) {
255
464
  if (dryRun) {
256
465
  proposalIds.push(`dry-run:${candidate.type}:${candidate.name}`);
257
466
  continue;
258
467
  }
259
468
  try {
469
+ // WS-3b Step-0b: schema-similarity intake gate. When enabled and the
470
+ // candidate is a lesson/knowledge whose body embedding is within ε of an
471
+ // existing derived-layer node, down-prioritize by multiplying confidence by
472
+ // the penalty. PARITY: schemaSimilarityCtx is null when the flag is off →
473
+ // applySchemaSimilarityPenalty returns the original confidence untouched and
474
+ // never embeds. (Logic lives in homeostatic.ts so it is unit-testable.)
475
+ const gateResult = await applySchemaSimilarityPenalty(candidate, schemaSimilarityCtx, (text) => schemaSimilarityCtx?.embedFn
476
+ ? schemaSimilarityCtx.embedFn(text)
477
+ : embed(text, schemaSimilarityCtx?.embeddingConfig));
478
+ const effectiveConfidence = gateResult.effectiveConfidence;
479
+ if (gateResult.warning)
480
+ warn(gateResult.warning);
260
481
  const { ref, content, description } = buildCandidateProposal(candidate, sessionRef);
261
482
  const result = createProposal(stashDir, {
262
483
  ref,
@@ -267,9 +488,22 @@ async function processSession(harness, sessionRef, stashDir, config, llmConfig,
267
488
  frontmatter: {
268
489
  description,
269
490
  ...(candidate.when_to_use ? { when_to_use: candidate.when_to_use } : {}),
270
- ...(typeof candidate.confidence === "number" ? { confidence: candidate.confidence } : {}),
491
+ ...(effectiveConfidence !== undefined ? { confidence: effectiveConfidence } : {}),
271
492
  sources: [`session:${sessionRef.harness}:${sessionRef.sessionId}`],
272
493
  evidence: candidate.evidence,
494
+ // #615 WS-0: mirror ordered-action + outcome data in the proposal
495
+ // frontmatter record so downstream tooling can read it without
496
+ // re-parsing the content body. Omitted when not present.
497
+ ...(candidate.orderedActions && candidate.orderedActions.length > 0
498
+ ? { orderedActions: candidate.orderedActions }
499
+ : {}),
500
+ ...(candidate.outcomeData ? { outcomeData: candidate.outcomeData } : {}),
501
+ // WS-3b step 0c: tag system-generated extractions as hot-probation
502
+ // when the feature is enabled. The consolidation pass will exclude
503
+ // them from the LLM merge pool until the intake dedup+quality pass
504
+ // runs against them. User-explicit `akm remember` (captureMode: hot)
505
+ // is unaffected — this only applies to extract-generated proposals.
506
+ ...(hotProbationEnabled ? buildHotProbationFrontmatter() : {}),
273
507
  },
274
508
  },
275
509
  }, ctx);
@@ -310,6 +544,7 @@ async function processSession(harness, sessionRef, stashDir, config, llmConfig,
310
544
  truncatedCount: filtered.stats.truncatedCount,
311
545
  },
312
546
  warnings,
547
+ contentHash,
313
548
  ...sessionAsset,
314
549
  };
315
550
  }
@@ -323,13 +558,24 @@ export async function akmExtract(options) {
323
558
  const stashDir = options.stashDir ?? resolveStashDir();
324
559
  const dryRun = options.dryRun ?? false;
325
560
  const sourceRun = options.sourceRun ?? `extract-${timestampForFilename()}`;
326
- // Read the per-process extract config from the active improve profile. Matches
327
- // the pattern reflect/distill/consolidate use: `profiles.improve.<active>.processes.extract`.
328
- // Only the `default` improve profile is consulted here extract isn't invoked
329
- // with a profile flag yet (parity item for a future change).
330
- const extractProcess = config.profiles?.improve?.default?.processes?.extract;
561
+ // Read the per-process extract config + enabled-state from the ACTIVE improve
562
+ // profile when `akmImprove` threaded it; otherwise fall back to the `default`
563
+ // profile (the explicit `akm extract` path, which has no active profile). This
564
+ // is what stops a non-default profile's `extract.enabled` from being silently
565
+ // overridden by the default profile and vice-versa.
566
+ const activeProfile = options.improveProfile;
567
+ const extractProcess = activeProfile
568
+ ? activeProfile.processes?.extract
569
+ : config.profiles?.improve?.default?.processes?.extract;
570
+ // The `extract.enabled` process toggle gates extract as a STAGE of `akm improve`
571
+ // (the activeProfile path) — consistent with #593/#594 where the active profile,
572
+ // not `default`, is the source of truth. An EXPLICIT `akm extract` invocation
573
+ // (no activeProfile) is a direct user/cron action and always runs; gating it on
574
+ // the default improve profile's stage toggle was a footgun — dropping extract
575
+ // from the daily improve profile would silently disable the standalone command.
576
+ const extractEnabled = activeProfile ? resolveProcessEnabled("extract", activeProfile) : true;
331
577
  // Feature-gate early so we get a clean "skipped because disabled" envelope.
332
- if (!isLlmFeatureEnabled(config, "session_extraction")) {
578
+ if (!extractEnabled) {
333
579
  return {
334
580
  schemaVersion: 1,
335
581
  ok: true,
@@ -375,8 +621,17 @@ export async function akmExtract(options) {
375
621
  // #595/#596 — minimum raw session size; sessions below it skip the LLM call
376
622
  // entirely. Set `processes.extract.minContentChars: 0` to disable the gate.
377
623
  const minContentChars = typeof extractProcess?.minContentChars === "number" ? extractProcess.minContentChars : DEFAULT_MIN_CONTENT_CHARS;
624
+ // Cap on NEW sessions LLM-processed per run; 0 disables. Absent = default.
625
+ // Bounds per-run wall time / LLM cost so a backlog can't push a run past its
626
+ // task timeout — the overflow stays unseen and is picked up by later runs.
627
+ const maxSessionsPerRun = typeof extractProcess?.maxSessionsPerRun === "number"
628
+ ? extractProcess.maxSessionsPerRun
629
+ : DEFAULT_MAX_SESSIONS_PER_RUN;
378
630
  // Default discovery window — process config can override the built-in 24h.
379
631
  const effectiveSince = options.since ?? extractProcess?.defaultSince;
632
+ // #626 — resolve the triage gate config once per run. Default-off → the
633
+ // per-session path never calls the scorer and emits no telemetry.
634
+ const triage = resolveTriageConfig(extractProcess);
380
635
  // #561 — resolve session-indexing config. Default ON: we only reach this code
381
636
  // when `session_extraction` is enabled AND an LLM is configured (both checked
382
637
  // above), so defaulting on costs nothing offline (the summary call fails open)
@@ -465,7 +720,16 @@ export async function akmExtract(options) {
465
720
  candidates = [target];
466
721
  }
467
722
  else {
468
- const sinceMs = parseSinceArg(effectiveSince);
723
+ // No explicit `--since`/`defaultSince` → default to "since the last run"
724
+ // (floored at 48h) so an intermittently-online host doesn't lose sessions
725
+ // that ended while it was off. See {@link resolveDefaultSinceMs}.
726
+ const sinceMs = effectiveSince
727
+ ? parseSinceArg(effectiveSince)
728
+ : resolveDefaultSinceMs(harness.name, startMs, {
729
+ ...(options.stateDb ? { stateDb: options.stateDb } : {}),
730
+ ...(options.stateDbPath ? { stateDbPath: options.stateDbPath } : {}),
731
+ ...(options.skipTracking ? { skipTracking: options.skipTracking } : {}),
732
+ });
469
733
  candidates = harness.listSessions({
470
734
  sinceMs,
471
735
  ...(options.location ? { location: options.location } : {}),
@@ -474,6 +738,10 @@ export async function akmExtract(options) {
474
738
  const sessions = [];
475
739
  let processedCount = 0;
476
740
  let skippedCount = 0;
741
+ // #626 — per-run triage aggregation counters (counts-only telemetry, AC4).
742
+ let triageEvaluated = 0;
743
+ let triagePassed = 0;
744
+ let triagedOut = 0;
477
745
  const allProposalIds = [];
478
746
  const topLevelWarnings = [];
479
747
  const chat = options.chat ?? chatCompletion;
@@ -497,39 +765,95 @@ export async function akmExtract(options) {
497
765
  stateDb = undefined;
498
766
  }
499
767
  }
768
+ // WS-3b Step-0b: schema-similarity intake gate.
769
+ // Load derived-layer (lesson/knowledge) embeddings once per run, but ONLY
770
+ // when the gate is enabled in config. When disabled (the default) this block
771
+ // is fully skipped and schemaSimilarityCtx stays null → byte-identical to
772
+ // prior behaviour.
773
+ const schemaSimilarityCfg = extractProcess?.schemaSimilarity;
774
+ let schemaSimilarityCtx = null;
775
+ if (schemaSimilarityCfg?.enabled === true) {
776
+ const derivedEmbeddings = options.schemaSimilarityEmbeddings ?? loadDerivedLayerEmbeddings();
777
+ schemaSimilarityCtx = {
778
+ config: schemaSimilarityCfg,
779
+ derivedEmbeddings,
780
+ embeddingConfig: config.embedding,
781
+ embedFn: options.schemaSimilarityEmbedFn,
782
+ };
783
+ }
784
+ // Stash authoring standards (convention/meta fact bodies) for non-wiki
785
+ // extract output. Resolved ONCE per run and threaded into each session's
786
+ // prompt so facts are not re-read per session.
787
+ const extractStandardsContext = resolveStashStandards(stashDir);
500
788
  for (const summary of candidates) {
501
- // Skip-tracking: if this session was already processed AND no new events
502
- // have arrived since (live endedAt <= recorded endedAt), don't burn an LLM
503
- // call. --force or single-session mode (explicit sessionId) bypasses.
789
+ // #602 the already-extracted skip moved INTO processSession (the content
790
+ // hash needs the session body, only available after readSession). The prior
791
+ // row + bypass flags are threaded through; an unchanged session returns
792
+ // skipReason 'already_extracted' WITHOUT any LLM call.
504
793
  const prior = seenMap.get(summary.sessionId);
505
- if (!options.force && !options.sessionId && shouldSkipAlreadyExtractedSession(prior, summary.endedAt)) {
506
- sessions.push({
507
- sessionId: summary.sessionId,
508
- harness: harness.name,
509
- candidateCount: 0,
510
- proposalIds: [],
511
- preFilter: { inputCount: 0, outputCount: 0, truncatedCount: 0 },
512
- warnings: [
513
- `already extracted at ${prior?.processed_at}; pass --force to re-process or wait until the session has new content`,
514
- ],
515
- skipped: true,
516
- skipReason: "already_extracted",
517
- });
518
- skippedCount += 1;
519
- continue;
794
+ // Per-run cap on LLM-processed sessions (skip-tracked seen sessions above
795
+ // don't count). Single-session / --force modes bypass the cap (explicit
796
+ // intent). Overflow sessions are left unseen for the next run.
797
+ if (!options.sessionId && !options.force && maxSessionsPerRun > 0 && processedCount >= maxSessionsPerRun) {
798
+ topLevelWarnings.push(`Reached maxSessionsPerRun=${maxSessionsPerRun}; ${candidates.length - processedCount - skippedCount} session(s) deferred to a later run.`);
799
+ break;
800
+ }
801
+ // Q5 — per-session lock so two concurrent extracts (e.g. a session-end hook
802
+ // firing `--session-id` while the hourly improve discovery pass runs) can't
803
+ // both LLM-process the SAME session. The holder records the outcome; a
804
+ // second run skips without any LLM call. Engaged only for real cross-process
805
+ // runs (those that open their own state.db): dry-run is read-only, an
806
+ // injected `stateDb` handle is an in-process/test scenario with no cross-
807
+ // process race, and skip-tracking-off opts out entirely.
808
+ let sessionLockPath;
809
+ if (trackingEnabled && !dryRun && !options.stateDb) {
810
+ sessionLockPath = getExtractSessionLockPath(harness.name, summary.sessionId, options.stateDbPath ?? getStateDbPath());
811
+ if (!acquireExtractSessionLock(sessionLockPath)) {
812
+ sessions.push({
813
+ sessionId: summary.sessionId,
814
+ harness: harness.name,
815
+ candidateCount: 0,
816
+ proposalIds: [],
817
+ preFilter: { inputCount: 0, outputCount: 0, truncatedCount: 0 },
818
+ warnings: ["concurrent extract holds this session's lock — skipped (handled by the other run)"],
819
+ skipped: true,
820
+ skipReason: "locked_concurrent",
821
+ });
822
+ skippedCount += 1;
823
+ continue;
824
+ }
520
825
  }
521
826
  try {
522
- const result = await processSession(harness, summary, stashDir, config, llmConfig, chat, options.ctx, sourceRun, dryRun, timeoutMs, maxTotalChars, minContentChars, sessionIndexing);
827
+ const result = await processSession(harness, summary, stashDir, config, llmConfig, chat, options.ctx, sourceRun, dryRun, timeoutMs, maxTotalChars, minContentChars, triage, sessionIndexing, schemaSimilarityCtx, prior, options.force === true, extractStandardsContext);
523
828
  sessions.push(result);
829
+ // #626 — triage aggregation. A session reached the triage gate only when it
830
+ // was NOT already preempted by an earlier skip (read_failed / too_short /
831
+ // already_extracted handled above the processSession call). When triage is
832
+ // enabled, processSession either triages-out (skipReason 'triaged_out') or
833
+ // proceeds past the gate — both count as "evaluated".
834
+ if (triage.enabled) {
835
+ const preemptedBeforeTriage = result.skipReason === "read_failed" ||
836
+ result.skipReason === "too_short" ||
837
+ result.skipReason === "already_extracted";
838
+ if (!preemptedBeforeTriage) {
839
+ triageEvaluated += 1;
840
+ if (result.skipReason === "triaged_out")
841
+ triagedOut += 1;
842
+ else
843
+ triagePassed += 1;
844
+ }
845
+ }
524
846
  if (result.skipped)
525
847
  skippedCount += 1;
526
848
  else
527
849
  processedCount += 1;
528
850
  allProposalIds.push(...result.proposalIds);
529
- // Persist outcome so the next run skips this session unless new events
530
- // arrive. We only track non-dry-run paths — dry-run is for inspection
531
- // and should never poison the seen-table.
532
- if (trackingEnabled && stateDb && !dryRun) {
851
+ // Persist outcome so the next run skips this session unless its content
852
+ // changes. We only track non-dry-run paths — dry-run is for inspection
853
+ // and should never poison the seen-table. #602: an `already_extracted`
854
+ // skip is a no-op (the row already carries the matching hash), so don't
855
+ // re-write it — that keeps `processed_at` stable across unchanged runs.
856
+ if (trackingEnabled && stateDb && !dryRun && result.skipReason !== "already_extracted") {
533
857
  try {
534
858
  const outcome = result.skipped
535
859
  ? result.skipReason === "read_failed" || result.skipReason === "exception"
@@ -548,6 +872,10 @@ export async function akmExtract(options) {
548
872
  proposalCount: result.proposalIds.length,
549
873
  rationale: result.rationaleIfEmpty ?? null,
550
874
  sourceRun,
875
+ // #602 — persist the freshly computed content hash so the NEXT run
876
+ // can compare byte-for-byte. read_failed (before hash) → null, which
877
+ // keeps the row eligible for retry (matches failed-row semantics).
878
+ contentHash: result.contentHash ?? null,
551
879
  metadata: {
552
880
  preFilterInputCount: result.preFilter.inputCount,
553
881
  preFilterOutputCount: result.preFilter.outputCount,
@@ -584,6 +912,10 @@ export async function akmExtract(options) {
584
912
  });
585
913
  skippedCount += 1;
586
914
  }
915
+ finally {
916
+ if (sessionLockPath)
917
+ releaseLock(sessionLockPath);
918
+ }
587
919
  }
588
920
  // Close the state.db connection we opened. Callers that injected stateDb
589
921
  // via the test seam own its lifecycle.
@@ -595,6 +927,20 @@ export async function akmExtract(options) {
595
927
  // best-effort close
596
928
  }
597
929
  }
930
+ // #626 — counts-only triage telemetry (AC4). Exactly ONE aggregated event per
931
+ // run, emitted only when the gate was enabled and actually evaluated at least
932
+ // one session. No per-session events (avoids the log-spam the issue warns of).
933
+ if (triage.enabled && triageEvaluated > 0) {
934
+ appendEvent({
935
+ eventType: "extract_triaged",
936
+ metadata: {
937
+ evaluated: triageEvaluated,
938
+ passed: triagePassed,
939
+ triagedOut,
940
+ sourceRun,
941
+ },
942
+ }, options.ctx);
943
+ }
598
944
  return {
599
945
  schemaVersion: 1,
600
946
  ok: true,
@@ -616,20 +962,34 @@ export async function akmExtract(options) {
616
962
  * logic in {@link akmExtract} so the `#554 minNewSessions` gate in `improve`
617
963
  * can decide whether the extract pass is worth running before any work begins.
618
964
  *
619
- * A session is a "new candidate" when it is in the `since` window AND it would
620
- * not be skipped by {@link shouldSkipAlreadyExtractedSession} (i.e. it has never
621
- * been extracted, or new events have arrived since it was last extracted).
965
+ * #602 this gate is intentionally CHEAP: it does NOT read session bodies, so
966
+ * it cannot compute the content hash that {@link shouldSkipAlreadyExtractedSession}
967
+ * now uses. It therefore uses a CONSERVATIVE row-presence approximation: a
968
+ * session counts as "new" when there is NO prior row OR the prior row's
969
+ * `content_hash` is null (never-seen or backfill-eligible). A prior row WITH a
970
+ * non-null content_hash counts as NOT new — it MIGHT have changed, but the
971
+ * precise per-session hash check happens downstream in processSession, so an
972
+ * over-/under-count here only affects whether the pass RUNS, never whether a
973
+ * changed session is actually re-processed.
622
974
  */
623
975
  export function countNewExtractCandidates(config, options = {}) {
624
976
  const extractProcess = config.profiles?.improve?.default?.processes?.extract;
625
977
  const effectiveSince = options.since ?? extractProcess?.defaultSince;
626
- const sinceMs = parseSinceArg(effectiveSince);
978
+ // Mirror akmExtract: when no explicit window is set, default per-harness to
979
+ // "since the last run" (floored at 48h) instead of a fixed 24h. Keeps this
980
+ // gate's discovery window identical to what akmExtract will actually scan.
981
+ const explicitSinceMs = effectiveSince ? parseSinceArg(effectiveSince) : undefined;
627
982
  const harnesses = (options.harnesses ?? getAvailableHarnesses()).filter((h) => h.isAvailable());
628
983
  let stateDb = options.stateDb;
629
984
  let openedStateDb = false;
630
985
  let total = 0;
631
986
  try {
632
987
  for (const harness of harnesses) {
988
+ const sinceMs = explicitSinceMs ??
989
+ resolveDefaultSinceMs(harness.name, Date.now(), {
990
+ ...(options.stateDb ? { stateDb: options.stateDb } : {}),
991
+ ...(options.stateDbPath ? { stateDbPath: options.stateDbPath } : {}),
992
+ });
633
993
  const candidates = harness.listSessions({ sinceMs });
634
994
  if (candidates.length === 0)
635
995
  continue;
@@ -652,7 +1012,10 @@ export function countNewExtractCandidates(config, options = {}) {
652
1012
  }
653
1013
  for (const summary of candidates) {
654
1014
  const prior = seenMap.get(summary.sessionId);
655
- if (shouldSkipAlreadyExtractedSession(prior, summary.endedAt))
1015
+ // #602 row-presence approximation (see fn doc): a prior row WITH a
1016
+ // non-null content_hash is treated as not-new here; everything else
1017
+ // (never-seen, or null-hash backfill-eligible) counts as new.
1018
+ if (prior && prior.content_hash != null)
656
1019
  continue;
657
1020
  total += 1;
658
1021
  }