@devflow-tools/database 0.16.20 → 0.16.22

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.
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapLearningCandidateRow = mapLearningCandidateRow;
4
+ exports.mapLearningEvidenceRow = mapLearningEvidenceRow;
5
+ exports.mapLearningVersionRow = mapLearningVersionRow;
6
+ exports.stableLearningJson = stableLearningJson;
7
+ function mapLearningCandidateRow(row) {
8
+ return {
9
+ id: String(row.id),
10
+ projectRoot: String(row.project_root),
11
+ scope: row.scope === 'global' ? 'global' : 'project',
12
+ state: row.state,
13
+ kind: row.kind,
14
+ trigger: parseRecord(row.trigger_json),
15
+ instruction: String(row.instruction),
16
+ confidence: Number(row.confidence),
17
+ overlayVersion: Number(row.overlay_version),
18
+ supportingSessions: Number(row.supporting_sessions),
19
+ successfulOutcomes: Number(row.successful_outcomes),
20
+ contradictions: Number(row.contradictions),
21
+ manualOnly: Number(row.manual_only) === 1,
22
+ risk: row.risk === 'high' ? 'high' : row.risk === 'medium' ? 'medium' : 'low',
23
+ graderReceipt: optionalString(row.grader_receipt),
24
+ expiresAt: optionalNumber(row.expires_at),
25
+ createdAt: Number(row.created_at),
26
+ updatedAt: Number(row.updated_at),
27
+ };
28
+ }
29
+ function mapLearningEvidenceRow(row) {
30
+ return {
31
+ id: String(row.id),
32
+ candidateId: String(row.candidate_id),
33
+ projectRoot: String(row.project_root),
34
+ sessionId: String(row.session_id),
35
+ executionId: optionalString(row.execution_id),
36
+ memoryObservationId: optionalString(row.memory_observation_id),
37
+ outcomeId: optionalString(row.outcome_id),
38
+ sourceType: row.source_type,
39
+ polarity: row.polarity,
40
+ outcome: row.outcome,
41
+ evidenceHash: String(row.evidence_hash),
42
+ receipt: optionalString(row.receipt),
43
+ payload: parseRecord(row.payload_json),
44
+ createdAt: Number(row.created_at),
45
+ resolvedAt: optionalNumber(row.resolved_at),
46
+ };
47
+ }
48
+ function mapLearningVersionRow(row) {
49
+ return {
50
+ candidateId: String(row.candidate_id),
51
+ version: Number(row.version),
52
+ trigger: parseRecord(row.trigger_json),
53
+ instruction: String(row.instruction),
54
+ createdAt: Number(row.created_at),
55
+ };
56
+ }
57
+ function stableLearningJson(value) {
58
+ if (Array.isArray(value))
59
+ return `[${value.map(stableLearningJson).join(',')}]`;
60
+ if (!value || typeof value !== 'object')
61
+ return JSON.stringify(value) ?? 'null';
62
+ const record = value;
63
+ return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${stableLearningJson(record[key])}`).join(',')}}`;
64
+ }
65
+ function parseRecord(value) {
66
+ try {
67
+ const parsed = typeof value === 'string' ? JSON.parse(value) : value;
68
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
69
+ ? parsed
70
+ : {};
71
+ }
72
+ catch {
73
+ return {};
74
+ }
75
+ }
76
+ function optionalString(value) {
77
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
78
+ }
79
+ function optionalNumber(value) {
80
+ return value === null || value === undefined ? undefined : Number(value);
81
+ }
@@ -1,4 +1,4 @@
1
- export type WorkKind = 'memory.explicit_commit' | 'memory.explicit_enrichment' | 'memory.turn_capture' | 'memory.turn_distill' | 'memory.vector_backfill' | 'session.bootstrap' | 'session.finalize' | 'telemetry.reconcile';
1
+ export type WorkKind = 'memory.explicit_commit' | 'memory.explicit_enrichment' | 'memory.turn_capture' | 'memory.turn_distill' | 'memory.vector_backfill' | 'context.prefetch' | 'learning.analyze_session' | 'session.bootstrap' | 'session.finalize' | 'telemetry.reconcile';
2
2
  export type WorkState = 'pending' | 'leased' | 'completed' | 'failed' | 'dead_letter';
3
3
  export interface WorkError {
4
4
  category: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devflow-tools/database",
3
- "version": "0.16.20",
3
+ "version": "0.16.22",
4
4
  "description": "DevFlow SQLite database package",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/database.ts CHANGED
@@ -42,6 +42,19 @@ import {
42
42
  type RetrievalSessionRecord,
43
43
  type RetrievalSessionState,
44
44
  } from './retrieval-sessions';
45
+ import {
46
+ mapLearningCandidateRow,
47
+ mapLearningEvidenceRow,
48
+ mapLearningVersionRow,
49
+ stableLearningJson,
50
+ type AddLearningCandidateEvidenceInput,
51
+ type LearningCandidateEvidenceRecord,
52
+ type LearningCandidateRecord,
53
+ type LearningCandidateState,
54
+ type LearningCandidateVersionRecord,
55
+ type TransitionLearningCandidateInput,
56
+ type UpsertLearningCandidateInput,
57
+ } from './learning-candidates';
45
58
 
46
59
  export interface BenchmarkReportRecord {
47
60
  runId: string;
@@ -655,6 +668,74 @@ export class DevFlowDatabase {
655
668
  CREATE INDEX IF NOT EXISTS idx_session_closures_state
656
669
  ON devflow_session_closures(project_root, state, updated_at DESC);
657
670
 
671
+ CREATE TABLE IF NOT EXISTS devflow_learning_candidates (
672
+ id TEXT PRIMARY KEY,
673
+ project_root TEXT NOT NULL,
674
+ scope TEXT NOT NULL CHECK(scope IN ('project', 'global')),
675
+ state TEXT NOT NULL DEFAULT 'observed'
676
+ CHECK(state IN ('observed', 'candidate', 'shadow', 'evaluated', 'active', 'rejected', 'retired')),
677
+ kind TEXT NOT NULL CHECK(kind IN ('convention', 'workflow', 'tool_preference', 'correction')),
678
+ trigger_json TEXT NOT NULL,
679
+ instruction TEXT NOT NULL,
680
+ confidence REAL NOT NULL CHECK(confidence BETWEEN 0 AND 1),
681
+ overlay_version INTEGER NOT NULL DEFAULT 1 CHECK(overlay_version > 0),
682
+ supporting_sessions INTEGER NOT NULL DEFAULT 0 CHECK(supporting_sessions >= 0),
683
+ successful_outcomes INTEGER NOT NULL DEFAULT 0 CHECK(successful_outcomes >= 0),
684
+ contradictions INTEGER NOT NULL DEFAULT 0 CHECK(contradictions >= 0),
685
+ manual_only INTEGER NOT NULL DEFAULT 0 CHECK(manual_only IN (0, 1)),
686
+ risk TEXT NOT NULL DEFAULT 'low' CHECK(risk IN ('low', 'medium', 'high')),
687
+ grader_receipt TEXT,
688
+ expires_at INTEGER,
689
+ created_at INTEGER NOT NULL,
690
+ updated_at INTEGER NOT NULL
691
+ );
692
+ CREATE INDEX IF NOT EXISTS idx_learning_candidates_project
693
+ ON devflow_learning_candidates(project_root, state, kind, updated_at DESC);
694
+
695
+ CREATE TABLE IF NOT EXISTS devflow_learning_candidate_versions (
696
+ candidate_id TEXT NOT NULL,
697
+ version INTEGER NOT NULL CHECK(version > 0),
698
+ trigger_json TEXT NOT NULL,
699
+ instruction TEXT NOT NULL,
700
+ created_at INTEGER NOT NULL,
701
+ PRIMARY KEY(candidate_id, version)
702
+ );
703
+
704
+ CREATE TABLE IF NOT EXISTS devflow_learning_candidate_evidence (
705
+ id TEXT PRIMARY KEY,
706
+ candidate_id TEXT NOT NULL,
707
+ project_root TEXT NOT NULL,
708
+ session_id TEXT NOT NULL,
709
+ execution_id TEXT,
710
+ memory_observation_id TEXT,
711
+ outcome_id TEXT,
712
+ source_type TEXT NOT NULL
713
+ CHECK(source_type IN ('memory', 'correction', 'workflow_outcome', 'tool_preference', 'convention', 'grader', 'manual')),
714
+ polarity TEXT NOT NULL CHECK(polarity IN ('supporting', 'contradicting')),
715
+ outcome TEXT NOT NULL DEFAULT 'unknown' CHECK(outcome IN ('positive', 'negative', 'unknown')),
716
+ evidence_hash TEXT NOT NULL,
717
+ receipt TEXT,
718
+ payload_json TEXT NOT NULL DEFAULT '{}',
719
+ created_at INTEGER NOT NULL,
720
+ resolved_at INTEGER,
721
+ UNIQUE(candidate_id, evidence_hash)
722
+ );
723
+ CREATE INDEX IF NOT EXISTS idx_learning_evidence_candidate
724
+ ON devflow_learning_candidate_evidence(candidate_id, polarity, resolved_at, created_at);
725
+
726
+ CREATE TABLE IF NOT EXISTS devflow_learning_activation_history (
727
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
728
+ candidate_id TEXT NOT NULL,
729
+ from_state TEXT NOT NULL,
730
+ to_state TEXT NOT NULL,
731
+ reason TEXT NOT NULL,
732
+ grader_receipt TEXT,
733
+ manual_approval INTEGER NOT NULL DEFAULT 0 CHECK(manual_approval IN (0, 1)),
734
+ changed_at INTEGER NOT NULL
735
+ );
736
+ CREATE INDEX IF NOT EXISTS idx_learning_activation_candidate
737
+ ON devflow_learning_activation_history(candidate_id, changed_at DESC);
738
+
658
739
  CREATE TABLE IF NOT EXISTS devflow_host_actions (
659
740
  action_id TEXT PRIMARY KEY,
660
741
  run_id TEXT NOT NULL,
@@ -2231,6 +2312,352 @@ export class DevFlowDatabase {
2231
2312
  };
2232
2313
  }
2233
2314
 
2315
+ // ---- Governed Learning ----
2316
+
2317
+ upsertLearningCandidate(input: UpsertLearningCandidateInput): LearningCandidateRecord {
2318
+ if (!input.id.trim()) throw new Error('Learning candidate requires an ID');
2319
+ if (!input.projectRoot.trim()) throw new Error('Learning candidate requires a project root');
2320
+ if (!input.instruction.trim()) throw new Error('Learning candidate requires an instruction');
2321
+ if (!Number.isFinite(input.confidence) || input.confidence < 0 || input.confidence > 1) {
2322
+ throw new Error('Learning candidate confidence must be between 0 and 1');
2323
+ }
2324
+
2325
+ return this.db.transaction(() => {
2326
+ const now = Date.now();
2327
+ const existing = this.getLearningCandidate(input.id);
2328
+ const triggerJson = stableLearningJson(input.trigger);
2329
+ const instruction = input.instruction.trim().slice(0, 2_000);
2330
+ if (!existing) {
2331
+ this.db.prepare(`
2332
+ INSERT INTO devflow_learning_candidates (
2333
+ id, project_root, scope, state, kind, trigger_json, instruction,
2334
+ confidence, overlay_version, supporting_sessions, successful_outcomes,
2335
+ contradictions, manual_only, risk, expires_at, created_at, updated_at
2336
+ ) VALUES (?, ?, ?, 'observed', ?, ?, ?, ?, 1, 0, 0, 0, ?, ?, ?, ?, ?)
2337
+ `).run(
2338
+ input.id,
2339
+ input.projectRoot,
2340
+ input.scope,
2341
+ input.kind,
2342
+ triggerJson,
2343
+ instruction,
2344
+ input.confidence,
2345
+ input.manualOnly ? 1 : 0,
2346
+ input.risk ?? 'low',
2347
+ input.expiresAt ?? null,
2348
+ now,
2349
+ now,
2350
+ );
2351
+ this.insertLearningCandidateVersion(input.id, 1, triggerJson, instruction, now);
2352
+ return this.getLearningCandidate(input.id)!;
2353
+ }
2354
+ if (existing.projectRoot !== input.projectRoot || existing.scope !== input.scope || existing.kind !== input.kind) {
2355
+ throw new Error(`Learning candidate identity mismatch for ${input.id}`);
2356
+ }
2357
+
2358
+ const contentChanged = stableLearningJson(existing.trigger) !== triggerJson
2359
+ || existing.instruction !== instruction;
2360
+ const nextVersion = contentChanged ? existing.overlayVersion + 1 : existing.overlayVersion;
2361
+ const nextState = contentChanged && (existing.state === 'active' || existing.state === 'evaluated')
2362
+ ? 'shadow'
2363
+ : existing.state;
2364
+ this.db.prepare(`
2365
+ UPDATE devflow_learning_candidates
2366
+ SET trigger_json = ?, instruction = ?, confidence = ?, overlay_version = ?,
2367
+ state = ?, manual_only = MAX(manual_only, ?),
2368
+ risk = CASE
2369
+ WHEN risk = 'high' OR ? = 'high' THEN 'high'
2370
+ WHEN risk = 'medium' OR ? = 'medium' THEN 'medium'
2371
+ ELSE 'low'
2372
+ END,
2373
+ expires_at = ?, updated_at = ?
2374
+ WHERE id = ?
2375
+ `).run(
2376
+ triggerJson,
2377
+ instruction,
2378
+ Math.max(existing.confidence, input.confidence),
2379
+ nextVersion,
2380
+ nextState,
2381
+ input.manualOnly ? 1 : 0,
2382
+ input.risk ?? 'low',
2383
+ input.risk ?? 'low',
2384
+ input.expiresAt ?? existing.expiresAt ?? null,
2385
+ now,
2386
+ input.id,
2387
+ );
2388
+ if (contentChanged) {
2389
+ this.insertLearningCandidateVersion(input.id, nextVersion, triggerJson, instruction, now);
2390
+ if (nextState !== existing.state) {
2391
+ this.insertLearningActivation(input.id, existing.state, nextState, 'candidate_content_changed', undefined, false, now);
2392
+ }
2393
+ }
2394
+ return this.getLearningCandidate(input.id)!;
2395
+ });
2396
+ }
2397
+
2398
+ getLearningCandidate(id: string): LearningCandidateRecord | null {
2399
+ const row = this.db.prepare('SELECT * FROM devflow_learning_candidates WHERE id = ?')
2400
+ .get(id) as Record<string, unknown> | undefined;
2401
+ return row ? mapLearningCandidateRow(row) : null;
2402
+ }
2403
+
2404
+ listLearningCandidates(options: {
2405
+ projectRoot?: string;
2406
+ states?: LearningCandidateState[];
2407
+ limit?: number;
2408
+ } = {}): LearningCandidateRecord[] {
2409
+ const predicates: string[] = [];
2410
+ const params: unknown[] = [];
2411
+ if (options.projectRoot) {
2412
+ predicates.push('(project_root = ? OR scope = \'global\')');
2413
+ params.push(options.projectRoot);
2414
+ }
2415
+ const states = [...new Set(options.states ?? [])];
2416
+ if (states.length > 0) {
2417
+ predicates.push(`state IN (${states.map(() => '?').join(',')})`);
2418
+ params.push(...states);
2419
+ }
2420
+ const rows = this.db.prepare(`
2421
+ SELECT * FROM devflow_learning_candidates
2422
+ ${predicates.length > 0 ? `WHERE ${predicates.join(' AND ')}` : ''}
2423
+ ORDER BY updated_at DESC, id ASC
2424
+ LIMIT ?
2425
+ `).all(...params, Math.max(1, Math.min(options.limit ?? 200, 2_000))) as Array<Record<string, unknown>>;
2426
+ return rows.map(mapLearningCandidateRow);
2427
+ }
2428
+
2429
+ addLearningCandidateEvidence(input: AddLearningCandidateEvidenceInput): LearningCandidateRecord {
2430
+ if (!input.evidenceHash.trim()) throw new Error('Learning evidence requires a hash');
2431
+ if (!input.sessionId.trim()) throw new Error('Learning evidence requires a session ID');
2432
+ return this.db.transaction(() => {
2433
+ const candidate = this.getLearningCandidate(input.candidateId);
2434
+ if (!candidate) throw new Error(`Learning candidate ${input.candidateId} does not exist`);
2435
+ if (candidate.projectRoot !== input.projectRoot && candidate.scope !== 'global') {
2436
+ throw new Error(`Learning evidence project mismatch for ${input.candidateId}`);
2437
+ }
2438
+ const createdAt = input.createdAt ?? Date.now();
2439
+ const inserted = this.db.prepare(`
2440
+ INSERT OR IGNORE INTO devflow_learning_candidate_evidence (
2441
+ id, candidate_id, project_root, session_id, execution_id,
2442
+ memory_observation_id, outcome_id, source_type, polarity, outcome,
2443
+ evidence_hash, receipt, payload_json, created_at
2444
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2445
+ `).run(
2446
+ input.id,
2447
+ input.candidateId,
2448
+ input.projectRoot,
2449
+ input.sessionId,
2450
+ input.executionId ?? null,
2451
+ input.memoryObservationId ?? null,
2452
+ input.outcomeId ?? null,
2453
+ input.sourceType,
2454
+ input.polarity,
2455
+ input.outcome ?? 'unknown',
2456
+ input.evidenceHash,
2457
+ input.receipt ?? null,
2458
+ stableLearningJson(input.payload ?? {}),
2459
+ createdAt,
2460
+ ).changes === 1;
2461
+ if (!inserted) return candidate;
2462
+
2463
+ const previousState = candidate.state;
2464
+ const aggregates = this.getLearningEvidenceAggregates(input.candidateId);
2465
+ let state = previousState;
2466
+ if (state === 'observed' && aggregates.supportingSessions > 0) state = 'candidate';
2467
+ if (aggregates.contradictions > 0 && (state === 'active' || state === 'evaluated')) state = 'shadow';
2468
+ this.db.prepare(`
2469
+ UPDATE devflow_learning_candidates
2470
+ SET state = ?, supporting_sessions = ?, successful_outcomes = ?,
2471
+ contradictions = ?, updated_at = ?
2472
+ WHERE id = ?
2473
+ `).run(
2474
+ state,
2475
+ aggregates.supportingSessions,
2476
+ aggregates.successfulOutcomes,
2477
+ aggregates.contradictions,
2478
+ createdAt,
2479
+ input.candidateId,
2480
+ );
2481
+ if (state !== previousState) {
2482
+ this.insertLearningActivation(
2483
+ input.candidateId,
2484
+ previousState,
2485
+ state,
2486
+ aggregates.contradictions > 0 ? 'unresolved_contradiction' : 'first_supporting_evidence',
2487
+ undefined,
2488
+ false,
2489
+ createdAt,
2490
+ );
2491
+ }
2492
+ return this.getLearningCandidate(input.candidateId)!;
2493
+ });
2494
+ }
2495
+
2496
+ listLearningCandidateEvidence(candidateId: string): LearningCandidateEvidenceRecord[] {
2497
+ const rows = this.db.prepare(`
2498
+ SELECT * FROM devflow_learning_candidate_evidence
2499
+ WHERE candidate_id = ? ORDER BY created_at ASC, id ASC
2500
+ `).all(candidateId) as Array<Record<string, unknown>>;
2501
+ return rows.map(mapLearningEvidenceRow);
2502
+ }
2503
+
2504
+ resolveLearningContradiction(candidateId: string, evidenceId: string, resolvedAt = Date.now()): LearningCandidateRecord {
2505
+ return this.db.transaction(() => {
2506
+ this.db.prepare(`
2507
+ UPDATE devflow_learning_candidate_evidence
2508
+ SET resolved_at = ?
2509
+ WHERE id = ? AND candidate_id = ? AND polarity = 'contradicting' AND resolved_at IS NULL
2510
+ `).run(resolvedAt, evidenceId, candidateId);
2511
+ const aggregates = this.getLearningEvidenceAggregates(candidateId);
2512
+ this.db.prepare(`
2513
+ UPDATE devflow_learning_candidates
2514
+ SET supporting_sessions = ?, successful_outcomes = ?, contradictions = ?, updated_at = ?
2515
+ WHERE id = ?
2516
+ `).run(
2517
+ aggregates.supportingSessions,
2518
+ aggregates.successfulOutcomes,
2519
+ aggregates.contradictions,
2520
+ resolvedAt,
2521
+ candidateId,
2522
+ );
2523
+ const candidate = this.getLearningCandidate(candidateId);
2524
+ if (!candidate) throw new Error(`Learning candidate ${candidateId} does not exist`);
2525
+ return candidate;
2526
+ });
2527
+ }
2528
+
2529
+ transitionLearningCandidate(
2530
+ candidateId: string,
2531
+ input: TransitionLearningCandidateInput,
2532
+ ): LearningCandidateRecord {
2533
+ return this.db.transaction(() => {
2534
+ const candidate = this.getLearningCandidate(candidateId);
2535
+ if (!candidate) throw new Error(`Learning candidate ${candidateId} does not exist`);
2536
+ if (candidate.state === input.target) return candidate;
2537
+ this.assertLearningTransition(candidate, input);
2538
+ const changedAt = input.changedAt ?? Date.now();
2539
+ const graderReceipt = input.graderReceipt ?? candidate.graderReceipt;
2540
+ this.db.prepare(`
2541
+ UPDATE devflow_learning_candidates
2542
+ SET state = ?, grader_receipt = COALESCE(?, grader_receipt), updated_at = ?
2543
+ WHERE id = ?
2544
+ `).run(input.target, graderReceipt ?? null, changedAt, candidateId);
2545
+ this.insertLearningActivation(
2546
+ candidateId,
2547
+ candidate.state,
2548
+ input.target,
2549
+ input.reason,
2550
+ graderReceipt,
2551
+ input.manualApproval === true,
2552
+ changedAt,
2553
+ );
2554
+ return this.getLearningCandidate(candidateId)!;
2555
+ });
2556
+ }
2557
+
2558
+ listLearningCandidateVersions(candidateId: string): LearningCandidateVersionRecord[] {
2559
+ const rows = this.db.prepare(`
2560
+ SELECT * FROM devflow_learning_candidate_versions
2561
+ WHERE candidate_id = ? ORDER BY version ASC
2562
+ `).all(candidateId) as Array<Record<string, unknown>>;
2563
+ return rows.map(mapLearningVersionRow);
2564
+ }
2565
+
2566
+ private assertLearningTransition(
2567
+ candidate: LearningCandidateRecord,
2568
+ input: TransitionLearningCandidateInput,
2569
+ ): void {
2570
+ const terminal = input.target === 'rejected' || input.target === 'retired';
2571
+ const rollback = input.target === 'shadow'
2572
+ && (candidate.state === 'active' || candidate.state === 'evaluated');
2573
+ const legal: Record<LearningCandidateState, LearningCandidateState[]> = {
2574
+ observed: ['candidate', 'rejected', 'retired'],
2575
+ candidate: ['shadow', 'rejected', 'retired'],
2576
+ shadow: ['evaluated', 'rejected', 'retired'],
2577
+ evaluated: ['active', 'shadow', 'rejected', 'retired'],
2578
+ active: ['shadow', 'retired'],
2579
+ rejected: ['retired'],
2580
+ retired: [],
2581
+ };
2582
+ if (!terminal && !rollback && !legal[candidate.state].includes(input.target)) {
2583
+ throw new Error(`Illegal learning transition ${candidate.state} -> ${input.target}`);
2584
+ }
2585
+ if (input.target === 'shadow') {
2586
+ if (candidate.supportingSessions < 3 || candidate.successfulOutcomes < 2) {
2587
+ throw new Error('Learning candidate requires three sessions and two verified outcomes before shadow');
2588
+ }
2589
+ }
2590
+ if (input.target === 'evaluated' && candidate.contradictions > 0) {
2591
+ throw new Error('Learning candidate has unresolved contradictions');
2592
+ }
2593
+ if (input.target === 'active') {
2594
+ const receipt = input.graderReceipt ?? candidate.graderReceipt;
2595
+ if (!receipt) throw new Error('Learning candidate activation requires a grader receipt');
2596
+ if (candidate.contradictions > 0) throw new Error('Learning candidate has unresolved contradictions');
2597
+ const manualRequired = candidate.scope === 'global' || candidate.manualOnly || candidate.risk === 'high';
2598
+ if (manualRequired && input.manualApproval !== true) {
2599
+ throw new Error('Learning candidate requires manual approval');
2600
+ }
2601
+ }
2602
+ }
2603
+
2604
+ private getLearningEvidenceAggregates(candidateId: string): {
2605
+ supportingSessions: number;
2606
+ successfulOutcomes: number;
2607
+ contradictions: number;
2608
+ } {
2609
+ const row = this.db.prepare(`
2610
+ SELECT
2611
+ COUNT(DISTINCT CASE WHEN polarity = 'supporting' THEN session_id END) AS supporting_sessions,
2612
+ COUNT(DISTINCT CASE WHEN polarity = 'supporting' AND outcome = 'positive' THEN session_id END) AS successful_outcomes,
2613
+ SUM(CASE WHEN polarity = 'contradicting' AND resolved_at IS NULL THEN 1 ELSE 0 END) AS contradictions
2614
+ FROM devflow_learning_candidate_evidence WHERE candidate_id = ?
2615
+ `).get(candidateId) as Record<string, unknown> | undefined;
2616
+ return {
2617
+ supportingSessions: Number(row?.supporting_sessions ?? 0),
2618
+ successfulOutcomes: Number(row?.successful_outcomes ?? 0),
2619
+ contradictions: Number(row?.contradictions ?? 0),
2620
+ };
2621
+ }
2622
+
2623
+ private insertLearningCandidateVersion(
2624
+ candidateId: string,
2625
+ version: number,
2626
+ triggerJson: string,
2627
+ instruction: string,
2628
+ createdAt: number,
2629
+ ): void {
2630
+ this.db.prepare(`
2631
+ INSERT OR IGNORE INTO devflow_learning_candidate_versions
2632
+ (candidate_id, version, trigger_json, instruction, created_at)
2633
+ VALUES (?, ?, ?, ?, ?)
2634
+ `).run(candidateId, version, triggerJson, instruction, createdAt);
2635
+ }
2636
+
2637
+ private insertLearningActivation(
2638
+ candidateId: string,
2639
+ fromState: LearningCandidateState,
2640
+ toState: LearningCandidateState,
2641
+ reason: string,
2642
+ graderReceipt: string | undefined,
2643
+ manualApproval: boolean,
2644
+ changedAt: number,
2645
+ ): void {
2646
+ this.db.prepare(`
2647
+ INSERT INTO devflow_learning_activation_history
2648
+ (candidate_id, from_state, to_state, reason, grader_receipt, manual_approval, changed_at)
2649
+ VALUES (?, ?, ?, ?, ?, ?, ?)
2650
+ `).run(
2651
+ candidateId,
2652
+ fromState,
2653
+ toState,
2654
+ reason.trim().slice(0, 500),
2655
+ graderReceipt ?? null,
2656
+ manualApproval ? 1 : 0,
2657
+ changedAt,
2658
+ );
2659
+ }
2660
+
2234
2661
  // ---- Durable Work Queue ----
2235
2662
 
2236
2663
  enqueueWork(input: EnqueueWorkInput): WorkItemRecord {
package/src/index.ts CHANGED
@@ -59,6 +59,24 @@ export {
59
59
  mapSessionObligationRow,
60
60
  normalizeTurnId,
61
61
  } from './obligation-ledger';
62
+ export {
63
+ mapLearningCandidateRow,
64
+ mapLearningEvidenceRow,
65
+ mapLearningVersionRow,
66
+ stableLearningJson,
67
+ } from './learning-candidates';
68
+ export type {
69
+ AddLearningCandidateEvidenceInput,
70
+ LearningCandidateEvidenceRecord,
71
+ LearningCandidateKind,
72
+ LearningCandidateRecord,
73
+ LearningCandidateState,
74
+ LearningCandidateVersionRecord,
75
+ LearningEvidencePolarity,
76
+ LearningOutcomeState,
77
+ TransitionLearningCandidateInput,
78
+ UpsertLearningCandidateInput,
79
+ } from './learning-candidates';
62
80
  export type {
63
81
  SessionObligationKind,
64
82
  SessionObligationRecord,