@jmtrin/opencode-kevin 0.4.0 → 0.6.0

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 (76) hide show
  1. package/README.md +580 -360
  2. package/dist/migrations/006_v05_glassbox.sql +118 -0
  3. package/dist/migrations/007_v06_pull.sql +145 -0
  4. package/dist/plugin/Archiver.d.ts +42 -0
  5. package/dist/plugin/Archiver.js +99 -0
  6. package/dist/plugin/Archiver.js.map +1 -0
  7. package/dist/plugin/ArtifactWriter.d.ts +50 -0
  8. package/dist/plugin/ArtifactWriter.js +240 -0
  9. package/dist/plugin/ArtifactWriter.js.map +1 -0
  10. package/dist/plugin/ContextInjector.d.ts +87 -0
  11. package/dist/plugin/ContextInjector.js +212 -44
  12. package/dist/plugin/ContextInjector.js.map +1 -1
  13. package/dist/plugin/Curator.d.ts +96 -0
  14. package/dist/plugin/Curator.js +252 -0
  15. package/dist/plugin/Curator.js.map +1 -0
  16. package/dist/plugin/Feedback.d.ts +67 -0
  17. package/dist/plugin/Feedback.js +138 -0
  18. package/dist/plugin/Feedback.js.map +1 -0
  19. package/dist/plugin/InjectionLedger.d.ts +9 -2
  20. package/dist/plugin/InjectionLedger.js +63 -9
  21. package/dist/plugin/InjectionLedger.js.map +1 -1
  22. package/dist/plugin/Materializer.d.ts +59 -0
  23. package/dist/plugin/Materializer.js +237 -0
  24. package/dist/plugin/Materializer.js.map +1 -0
  25. package/dist/plugin/MemoryService.d.ts +38 -0
  26. package/dist/plugin/MemoryService.js +265 -30
  27. package/dist/plugin/MemoryService.js.map +1 -1
  28. package/dist/plugin/Migrate.js +41 -0
  29. package/dist/plugin/Migrate.js.map +1 -1
  30. package/dist/plugin/QualityGate.d.ts +53 -0
  31. package/dist/plugin/QualityGate.js +50 -8
  32. package/dist/plugin/QualityGate.js.map +1 -1
  33. package/dist/plugin/Retrospective.d.ts +1 -0
  34. package/dist/plugin/Retrospective.js +24 -1
  35. package/dist/plugin/Retrospective.js.map +1 -1
  36. package/dist/plugin/capabilities.d.ts +15 -0
  37. package/dist/plugin/capabilities.js +42 -0
  38. package/dist/plugin/capabilities.js.map +1 -0
  39. package/dist/plugin/confidence.d.ts +3 -1
  40. package/dist/plugin/confidence.js +14 -2
  41. package/dist/plugin/confidence.js.map +1 -1
  42. package/dist/plugin/diff.d.ts +8 -0
  43. package/dist/plugin/diff.js +183 -0
  44. package/dist/plugin/diff.js.map +1 -0
  45. package/dist/plugin/index.d.ts +3 -1
  46. package/dist/plugin/index.js +371 -0
  47. package/dist/plugin/index.js.map +1 -1
  48. package/dist/plugin/inferability.d.ts +32 -0
  49. package/dist/plugin/inferability.js +89 -0
  50. package/dist/plugin/inferability.js.map +1 -0
  51. package/dist/plugin/kevin_approve.d.ts +34 -0
  52. package/dist/plugin/kevin_approve.js +50 -0
  53. package/dist/plugin/kevin_approve.js.map +1 -0
  54. package/dist/plugin/kevin_audit.d.ts +95 -0
  55. package/dist/plugin/kevin_audit.js +233 -0
  56. package/dist/plugin/kevin_audit.js.map +1 -0
  57. package/dist/plugin/kevin_propose.d.ts +23 -0
  58. package/dist/plugin/kevin_propose.js +15 -0
  59. package/dist/plugin/kevin_propose.js.map +1 -0
  60. package/dist/plugin/kevin_publish.d.ts +38 -0
  61. package/dist/plugin/kevin_publish.js +19 -0
  62. package/dist/plugin/kevin_publish.js.map +1 -0
  63. package/dist/plugin/kevin_why.js +23 -2
  64. package/dist/plugin/kevin_why.js.map +1 -1
  65. package/dist/plugin/metrics.d.ts +32 -1
  66. package/dist/plugin/metrics.js +86 -2
  67. package/dist/plugin/metrics.js.map +1 -1
  68. package/dist/plugin/replay-types.d.ts +327 -0
  69. package/dist/plugin/replay-types.js +65 -0
  70. package/dist/plugin/replay-types.js.map +1 -0
  71. package/dist/plugin/replay.d.ts +36 -0
  72. package/dist/plugin/replay.js +203 -0
  73. package/dist/plugin/replay.js.map +1 -0
  74. package/migrations/006_v05_glassbox.sql +118 -0
  75. package/migrations/007_v06_pull.sql +145 -0
  76. package/package.json +3 -2
@@ -0,0 +1,36 @@
1
+ import type { ReplayTranscript } from "./replay-types.js";
2
+ /**
3
+ * v0.5.0 (K5-019 / plan §5.8, D5-12) — replay harness.
4
+ *
5
+ * Hermetic, deterministic driver: runs a recorded transcript through the
6
+ * plugin's components against an in-memory database with a frozen clock,
7
+ * then reports the outcome distribution. This is an artifact, not a
8
+ * release gate.
9
+ *
10
+ * The components are instantiated directly — NOT through `KevinPlugin`,
11
+ * which resolves a home-directory database path and registers tools.
12
+ * `Date.now()` must never be called in this path; every clock need is
13
+ * satisfied by the event's `at` timestamp (retrieval is frozen by the
14
+ * `deterministic_retrieval` setting; the Archiver clock is injected).
15
+ */
16
+ export interface ReplayResult {
17
+ readonly transcript: string;
18
+ readonly memoriesCreated: number;
19
+ readonly injections: {
20
+ total: number;
21
+ effective: number;
22
+ ineffective: number;
23
+ inconclusive: number;
24
+ unmeasured: number;
25
+ };
26
+ readonly precisionRate: number;
27
+ readonly coverageRate: number;
28
+ readonly tokensInjected: {
29
+ prePrompt: number;
30
+ compacting: number;
31
+ };
32
+ readonly blocked: Record<string, number>;
33
+ }
34
+ export declare function replay(transcript: ReplayTranscript, opts?: {
35
+ dbPath?: string;
36
+ }): Promise<ReplayResult>;
@@ -0,0 +1,203 @@
1
+ import { dirname, join } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { Archiver } from "./Archiver.js";
4
+ import { CausalChain } from "./CausalChain.js";
5
+ import { ContextInjector } from "./ContextInjector.js";
6
+ import { InjectionLedger } from "./InjectionLedger.js";
7
+ import { MemoryService } from "./MemoryService.js";
8
+ import { Migrate } from "./Migrate.js";
9
+ import { Reflector } from "./Reflector.js";
10
+ import { Store } from "./Store.js";
11
+ import { ToolCallObserver } from "./ToolCallObserver.js";
12
+ import { Metrics } from "./metrics.js";
13
+ const MIGRATIONS_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "migrations");
14
+ export async function replay(transcript, opts) {
15
+ const store = new Store({ path: opts?.dbPath ?? ":memory:" });
16
+ await new Migrate(store, MIGRATIONS_DIR).run();
17
+ // Freeze retrieval BEFORE any query happens (K5-008): deterministic
18
+ // mode uses the DATE_NOW sentinel, ignores recency and never bumps.
19
+ store
20
+ .prepare("INSERT OR IGNORE INTO kevin_settings (key, value) VALUES ('deterministic_retrieval', '1')")
21
+ .run();
22
+ store
23
+ .prepare("UPDATE kevin_settings SET value = '1' WHERE key = 'deterministic_retrieval'")
24
+ .run();
25
+ // v0.6.0 (K6-022) — the release floor (0.6) blocks every
26
+ // single-observation memory the v0.5-era fixture exercises; the replay
27
+ // harness preserves the v0.5 push semantics it was recorded under, the
28
+ // same opt-out the legacy plugin harnesses apply.
29
+ store
30
+ .prepare("INSERT OR IGNORE INTO kevin_settings (key, value) VALUES ('injection_confidence_floor', '0')")
31
+ .run();
32
+ store
33
+ .prepare("UPDATE kevin_settings SET value = '0' WHERE key = 'injection_confidence_floor'")
34
+ .run();
35
+ const metrics = new Metrics(store);
36
+ const memoryService = new MemoryService(store, metrics);
37
+ const observer = new ToolCallObserver(store, metrics);
38
+ // v0.3.0 fix (mirrors index.ts) — the Reflector stamps
39
+ // tool_calls.error_fingerprint with the stderr-based fingerprint the
40
+ // error memory uses; without it the recurrence queries in settle and
41
+ // the feedback loop never match (tool_calls.fingerprint is keyed on
42
+ // `${tool}|${args}|${success}`, memories on a hash of stderr/stdout).
43
+ const linkErrorStmt = store.prepare("UPDATE tool_calls SET error_fingerprint = ? WHERE id = ?");
44
+ const reflector = new Reflector(memoryService, {
45
+ throttleMs: 0,
46
+ onLinkError: (callID, fp) => {
47
+ linkErrorStmt.run(fp, callID);
48
+ },
49
+ }, metrics);
50
+ const ledger = new InjectionLedger(store, metrics);
51
+ const injector = new ContextInjector(memoryService, metrics, ledger);
52
+ const causalChain = new CausalChain(store, memoryService, metrics);
53
+ // The Archiver reads the clock through this accessor, which is updated
54
+ // to the current event's `at` before each event is processed.
55
+ let currentAt = new Date(transcript.events[0]?.at ?? Date.now());
56
+ const archiver = new Archiver(store, memoryService, metrics, () => currentAt);
57
+ const lastUserQueryBySession = new Map();
58
+ const callCache = new Map();
59
+ function resolveQuery(sessionId) {
60
+ return lastUserQueryBySession.get(sessionId) ?? "";
61
+ }
62
+ for (const event of transcript.events) {
63
+ currentAt = new Date(event.at);
64
+ await handleEvent(event);
65
+ }
66
+ metrics.flush();
67
+ const outcomeRows = store
68
+ .prepare("SELECT outcome, COUNT(*) AS n FROM kevin_injections GROUP BY outcome")
69
+ .all();
70
+ const counts = {
71
+ unmeasured: 0,
72
+ effective: 0,
73
+ ineffective: 0,
74
+ inconclusive: 0,
75
+ };
76
+ for (const r of outcomeRows) {
77
+ counts[r.outcome] = r.n;
78
+ }
79
+ const total = outcomeRows.reduce((acc, r) => acc + r.n, 0);
80
+ const tokenValue = (key) => {
81
+ const row = store
82
+ .prepare("SELECT value FROM kevin_metrics WHERE key = ?")
83
+ .get(key);
84
+ return row?.value ?? 0;
85
+ };
86
+ return {
87
+ transcript: transcript.name,
88
+ memoriesCreated: totalMemories(store),
89
+ injections: {
90
+ total,
91
+ effective: counts.effective,
92
+ ineffective: counts.ineffective,
93
+ inconclusive: counts.inconclusive,
94
+ unmeasured: counts.unmeasured,
95
+ },
96
+ precisionRate: metrics.precisionRate(),
97
+ coverageRate: metrics.coverageRate(),
98
+ tokensInjected: {
99
+ prePrompt: tokenValue("tokens_injected_pre_prompt"),
100
+ compacting: tokenValue("tokens_injected_compacting"),
101
+ },
102
+ blocked: metrics.blockedSnapshot(),
103
+ };
104
+ async function handleEvent(event) {
105
+ switch (event.kind) {
106
+ case "session.created":
107
+ // Mirror of the live wiring (index.ts): a fresh session must
108
+ // not inherit the previous session's injection seen-set
109
+ // (plan §5.1 rule 3). Without this, a multi-session
110
+ // transcript would block every memory in session 2 with
111
+ // `seen_this_session` while the live plugin would admit it.
112
+ injector.onSessionCreated(event.sessionId);
113
+ return;
114
+ case "chat.message": {
115
+ const derived = injector.deriveQuery([
116
+ { role: "user", content: event.text },
117
+ ]);
118
+ if (derived.length > 0) {
119
+ lastUserQueryBySession.set(event.sessionId, derived);
120
+ }
121
+ return;
122
+ }
123
+ case "tool.before": {
124
+ callCache.set(event.callId, {
125
+ tool: event.tool,
126
+ args: event.args,
127
+ });
128
+ observer.onBefore({
129
+ tool: event.tool,
130
+ args: event.args,
131
+ sessionId: event.sessionId,
132
+ callID: event.callId,
133
+ projectId: null,
134
+ }, {});
135
+ return;
136
+ }
137
+ case "tool.after": {
138
+ const cached = callCache.get(event.callId);
139
+ const tool = cached?.tool ?? "unknown";
140
+ const args = cached?.args ?? {};
141
+ const stderr = event.stderr ?? "";
142
+ const stdout = event.stdout ?? "";
143
+ observer.onAfter({
144
+ tool,
145
+ args,
146
+ sessionId: event.sessionId,
147
+ callID: event.callId,
148
+ projectId: null,
149
+ }, { success: event.success, stdout, stderr, exitCode: event.exitCode });
150
+ if (!event.success) {
151
+ await reflector.invoke({
152
+ toolName: tool,
153
+ argsSummary: observer.summarizeArgs(args),
154
+ stderr,
155
+ stdout,
156
+ exitCode: event.exitCode,
157
+ errorType: observer.inferErrorType(stderr, stdout, event.exitCode),
158
+ sessionId: event.sessionId,
159
+ callID: event.callId,
160
+ projectId: null,
161
+ });
162
+ }
163
+ else {
164
+ causalChain.onSuccess(tool, args, null, event.sessionId);
165
+ }
166
+ return;
167
+ }
168
+ case "system.transform": {
169
+ const query = resolveQuery(event.sessionId);
170
+ if (!query)
171
+ return;
172
+ const output = { system: [] };
173
+ injector.onSystemTransform({
174
+ sessionID: event.sessionId,
175
+ messages: [{ role: "user", content: query }],
176
+ }, output);
177
+ return;
178
+ }
179
+ case "compacting": {
180
+ const query = resolveQuery(event.sessionId);
181
+ if (!query)
182
+ return;
183
+ const output = { context: [] };
184
+ injector.onCompacting({
185
+ sessionID: event.sessionId,
186
+ messages: [{ role: "user", content: query }],
187
+ }, output);
188
+ return;
189
+ }
190
+ case "session.idle": {
191
+ ledger.settle(event.sessionId);
192
+ archiver.run();
193
+ metrics.flush();
194
+ return;
195
+ }
196
+ }
197
+ }
198
+ }
199
+ function totalMemories(store) {
200
+ const row = store.prepare("SELECT COUNT(*) AS n FROM memories").get();
201
+ return row.n ?? 0;
202
+ }
203
+ //# sourceMappingURL=replay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay.js","sourceRoot":"","sources":["../../plugin/replay.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAkCvC,MAAM,cAAc,GAAG,IAAI,CAC1B,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EACvC,IAAI,EACJ,YAAY,CACZ,CAAC;AAEF,MAAM,CAAC,KAAK,UAAU,MAAM,CAC3B,UAA4B,EAC5B,IAA0B;IAE1B,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,IAAI,UAAU,EAAE,CAAC,CAAC;IAC9D,MAAM,IAAI,OAAO,CAAC,KAAK,EAAE,cAAc,CAAC,CAA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EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;iBAC5C,EACD,MAAM,CACN,CAAC;gBACF,OAAO;YACR,CAAC;YACD,KAAK,cAAc,CAAC,CAAC,CAAC;gBACrB,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;gBAC/B,QAAQ,CAAC,GAAG,EAAE,CAAC;gBACf,OAAO,CAAC,KAAK,EAAE,CAAC;gBAChB,OAAO;YACR,CAAC;QACF,CAAC;IACF,CAAC;AACF,CAAC;AAED,SAAS,aAAa,CAAC,KAAY;IAClC,MAAM,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,oCAAoC,CAAC,CAAC,GAAG,EAElE,CAAC;IACF,OAAO,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;AACnB,CAAC"}
@@ -0,0 +1,118 @@
1
+ -- ============================================================================
2
+ -- 006_v05_glassbox.sql — v0.5.0 "Glass Box"
3
+ --
4
+ -- Honest measurement, human feedback, lifecycle completion.
5
+ --
6
+ -- Section 1: rebuild kevin_injections to admit a fourth outcome.
7
+ -- Section 2: human feedback storage.
8
+ -- Section 3: memory lifecycle columns.
9
+ -- Section 4: metric seeds.
10
+ -- Section 5: setting seeds.
11
+ -- Section 6: schema_version.
12
+ -- ============================================================================
13
+
14
+ -- ---------------------------------------------------------------------------
15
+ -- 1. kevin_injections: add 'inconclusive'.
16
+ --
17
+ -- SQLite cannot ALTER a CHECK constraint, so the table must be rebuilt.
18
+ -- Migration 004 set this precedent. kevin_injections has no FTS5 triggers,
19
+ -- so unlike 004 this is a straight four-step rebuild.
20
+ --
21
+ -- Existing rows with outcome='effective' are remapped to 'inconclusive'.
22
+ -- This is not data loss: v0.4's 'effective' meant "the error did not recur",
23
+ -- which is the exact definition of the new 'inconclusive' bucket. Rows that
24
+ -- genuinely earned the new 'effective' will be re-settled naturally, and the
25
+ -- post-apply hook re-derives the counters from the table.
26
+ -- ---------------------------------------------------------------------------
27
+ CREATE TABLE IF NOT EXISTS kevin_injections_new (
28
+ id TEXT PRIMARY KEY,
29
+ memory_id TEXT NOT NULL,
30
+ fingerprint TEXT NOT NULL,
31
+ session_id TEXT NOT NULL,
32
+ hook TEXT NOT NULL CHECK (hook IN ('pre_prompt','compacting')),
33
+ tokens INTEGER NOT NULL,
34
+ injected_at TEXT NOT NULL DEFAULT (datetime('now')),
35
+ outcome TEXT NOT NULL DEFAULT 'unmeasured'
36
+ CHECK (outcome IN ('unmeasured','effective','ineffective','inconclusive'))
37
+ );
38
+
39
+ INSERT INTO kevin_injections_new
40
+ (id, memory_id, fingerprint, session_id, hook, tokens, injected_at, outcome)
41
+ SELECT
42
+ id, memory_id, fingerprint, session_id, hook, tokens, injected_at,
43
+ CASE WHEN outcome = 'effective' THEN 'inconclusive' ELSE outcome END
44
+ FROM kevin_injections;
45
+
46
+ DROP TABLE kevin_injections;
47
+ ALTER TABLE kevin_injections_new RENAME TO kevin_injections;
48
+
49
+ CREATE INDEX IF NOT EXISTS idx_injections_fp ON kevin_injections(fingerprint);
50
+ CREATE INDEX IF NOT EXISTS idx_injections_session ON kevin_injections(session_id);
51
+ CREATE INDEX IF NOT EXISTS idx_injections_outcome ON kevin_injections(outcome);
52
+
53
+ -- ---------------------------------------------------------------------------
54
+ -- 2. Human feedback. Append-only audit trail; the hot path reads the
55
+ -- denormalized counters on `memories` (section 3), never this table.
56
+ -- ---------------------------------------------------------------------------
57
+ CREATE TABLE IF NOT EXISTS memory_feedback (
58
+ id TEXT PRIMARY KEY,
59
+ memory_id TEXT NOT NULL,
60
+ verdict TEXT NOT NULL CHECK (verdict IN ('useful','wrong','outdated','ignore')),
61
+ session_id TEXT,
62
+ note TEXT,
63
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
64
+ );
65
+
66
+ CREATE INDEX IF NOT EXISTS idx_feedback_memory ON memory_feedback(memory_id);
67
+ CREATE INDEX IF NOT EXISTS idx_feedback_created ON memory_feedback(created_at);
68
+
69
+ -- ---------------------------------------------------------------------------
70
+ -- 3. Memory lifecycle and feedback columns.
71
+ --
72
+ -- feedback_positive / feedback_negative are SEPARATE from evidence_count
73
+ -- and recurrence_count by design: human judgement is evidence about the
74
+ -- memory, causal counters are evidence about the world. Mixing them was
75
+ -- the confidence-poisoning defect closed in v0.4.0.
76
+ --
77
+ -- superseded_by has no REFERENCES clause on purpose. Store enables
78
+ -- PRAGMA foreign_keys=ON, and a hard FK would block deletion of a memory
79
+ -- that superseded another.
80
+ -- ---------------------------------------------------------------------------
81
+ ALTER TABLE memories ADD COLUMN feedback_positive INTEGER NOT NULL DEFAULT 0;
82
+ ALTER TABLE memories ADD COLUMN feedback_negative INTEGER NOT NULL DEFAULT 0;
83
+ ALTER TABLE memories ADD COLUMN ignored INTEGER NOT NULL DEFAULT 0;
84
+ ALTER TABLE memories ADD COLUMN superseded_by TEXT;
85
+ ALTER TABLE memories ADD COLUMN archived_at TEXT;
86
+
87
+ CREATE INDEX IF NOT EXISTS idx_memories_ignored ON memories(ignored);
88
+ CREATE INDEX IF NOT EXISTS idx_memories_archived ON memories(archived_at);
89
+
90
+ -- ---------------------------------------------------------------------------
91
+ -- 4. Metric seeds. Order matches the additions to METRIC_KEYS in metrics.ts.
92
+ -- ---------------------------------------------------------------------------
93
+ INSERT OR IGNORE INTO kevin_metrics (key, value) VALUES
94
+ ('injections_inconclusive', 0),
95
+ ('injections_blocked_seen', 0),
96
+ ('injections_blocked_weak', 0),
97
+ ('injections_blocked_recurrence',0),
98
+ ('injections_blocked_stale', 0),
99
+ ('injections_blocked_ignored', 0),
100
+ ('feedback_positive_total', 0),
101
+ ('feedback_negative_total', 0),
102
+ ('memories_archived', 0);
103
+
104
+ -- ---------------------------------------------------------------------------
105
+ -- 5. Setting seeds. Values are TEXT, always. Read them with an explicit
106
+ -- string comparison or an explicit Number() parse — never `=== 1`.
107
+ -- (That exact mistake kept cross_project_enabled unreachable for the
108
+ -- whole of v0.3.0.)
109
+ -- ---------------------------------------------------------------------------
110
+ INSERT OR IGNORE INTO kevin_settings (key, value) VALUES
111
+ ('deterministic_retrieval', '0'),
112
+ ('pre_prompt_budget_tokens', '900'),
113
+ ('archive_after_days', '30');
114
+
115
+ -- ---------------------------------------------------------------------------
116
+ -- 6. Version marker.
117
+ -- ---------------------------------------------------------------------------
118
+ INSERT OR IGNORE INTO schema_version (version) VALUES ('006');
@@ -0,0 +1,145 @@
1
+ -- ============================================================================
2
+ -- 007_v06_pull.sql — v0.6.0 "Pull"
3
+ --
4
+ -- Distribution: curated artifacts instead of a per-prompt token tax.
5
+ --
6
+ -- Section 1: curation_proposals — the persisted human decision record.
7
+ -- Section 2: artifact_writes — the disk audit trail, including refusals.
8
+ -- Section 3: memories curation + inferability columns.
9
+ -- Section 4: metric seeds.
10
+ -- Section 5: setting seeds.
11
+ -- Section 6: conditional push-budget demotion.
12
+ -- Section 7: schema_version.
13
+ --
14
+ -- Additive only. Every CHECK constraint introduced here is on a NEW table;
15
+ -- no existing constraint is widened, so unlike migration 006 there is no
16
+ -- table rebuild in this file.
17
+ -- ============================================================================
18
+
19
+ -- ---------------------------------------------------------------------------
20
+ -- 1. curation_proposals — one row per proposed artifact change.
21
+ --
22
+ -- This table is the "explicit human decision between generation and
23
+ -- application" of Principle 22. `kevin_propose` writes 'pending' rows and
24
+ -- nothing else; `kevin_approve` moves them to 'approved' → 'applied' or to
25
+ -- 'rejected'. Rows are never deleted: rejection history is the evidence
26
+ -- base for roadmap kill criterion K4 ("proposals rejected more often than
27
+ -- approved"), which is uncheckable if rejections are discarded.
28
+ --
29
+ -- memory_id has no REFERENCES clause. Store sets PRAGMA foreign_keys = ON,
30
+ -- and a hard FK would block deleting a memory that a historical proposal
31
+ -- once mentioned — the same reasoning as superseded_by in migration 006.
32
+ -- ---------------------------------------------------------------------------
33
+ CREATE TABLE IF NOT EXISTS curation_proposals (
34
+ id TEXT PRIMARY KEY,
35
+ project_id TEXT NOT NULL,
36
+ memory_id TEXT NOT NULL,
37
+ kind TEXT NOT NULL CHECK (kind IN ('agents_md','skill','reference')),
38
+ target_path TEXT NOT NULL,
39
+ proposed_text TEXT NOT NULL,
40
+ diff TEXT NOT NULL,
41
+ status TEXT NOT NULL DEFAULT 'pending'
42
+ CHECK (status IN ('pending','approved','rejected','applied','superseded')),
43
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
44
+ decided_at TEXT,
45
+ applied_at TEXT
46
+ );
47
+ CREATE INDEX IF NOT EXISTS idx_proposals_status ON curation_proposals(status);
48
+ CREATE INDEX IF NOT EXISTS idx_proposals_memory ON curation_proposals(memory_id);
49
+ CREATE INDEX IF NOT EXISTS idx_proposals_project ON curation_proposals(project_id);
50
+
51
+ -- ---------------------------------------------------------------------------
52
+ -- 2. artifact_writes — the append-only audit trail for every disk operation.
53
+ --
54
+ -- A row is written for EVERY ArtifactWriter.apply() call, including
55
+ -- outcome='noop' and outcome='refused'. A refusal that leaves no trace is
56
+ -- indistinguishable from a write that never happened, and the whole point
57
+ -- of §5.1 rule 3 is that a refusal is a reportable event.
58
+ --
59
+ -- hash_before / hash_after are SHA-256 of the full file contents, not of
60
+ -- the marker block. That is what makes rule 4 (bytes outside the markers
61
+ -- are byte-identical) auditable after the fact rather than only at test
62
+ -- time.
63
+ -- ---------------------------------------------------------------------------
64
+ CREATE TABLE IF NOT EXISTS artifact_writes (
65
+ id TEXT PRIMARY KEY,
66
+ proposal_id TEXT,
67
+ project_id TEXT NOT NULL,
68
+ path TEXT NOT NULL,
69
+ bytes_before INTEGER,
70
+ bytes_after INTEGER,
71
+ hash_before TEXT,
72
+ hash_after TEXT,
73
+ outcome TEXT NOT NULL CHECK (outcome IN ('written','noop','refused')),
74
+ reason TEXT,
75
+ wrote_at TEXT NOT NULL DEFAULT (datetime('now'))
76
+ );
77
+ CREATE INDEX IF NOT EXISTS idx_artifact_writes_path ON artifact_writes(path);
78
+
79
+ -- ---------------------------------------------------------------------------
80
+ -- 3. memories: curation state and inferability.
81
+ --
82
+ -- curated / curated_at record that a memory has already been published,
83
+ -- so the Curator does not re-propose it on every session idle.
84
+ --
85
+ -- inferable is deliberately NULLABLE with no default. Three states are
86
+ -- needed, not two: 1 = inferable (a self-describing diagnostic the model
87
+ -- resolves for free), 0 = non-inferable (project truth), NULL = unknown
88
+ -- (not yet classified, or classified as 'unknown'). The Curator predicate
89
+ -- is `inferable != 1`, so NULL rows stay eligible — an unclassified memory
90
+ -- must not be silently withheld from curation.
91
+ -- ---------------------------------------------------------------------------
92
+ ALTER TABLE memories ADD COLUMN curated INTEGER NOT NULL DEFAULT 0;
93
+ ALTER TABLE memories ADD COLUMN curated_at TEXT;
94
+ ALTER TABLE memories ADD COLUMN inferable INTEGER;
95
+
96
+ CREATE INDEX IF NOT EXISTS idx_memories_curated ON memories(curated);
97
+ CREATE INDEX IF NOT EXISTS idx_memories_inferable ON memories(inferable);
98
+
99
+ -- ---------------------------------------------------------------------------
100
+ -- 4. Metric seeds. Order matches the additions to METRIC_KEYS in metrics.ts.
101
+ -- injections_blocked_confidence is the sixth member of the v0.5 blocked
102
+ -- family and MUST be counted like the other five (Principle 16).
103
+ -- ---------------------------------------------------------------------------
104
+ INSERT OR IGNORE INTO kevin_metrics (key, value) VALUES
105
+ ('proposals_created', 0),
106
+ ('proposals_approved', 0),
107
+ ('proposals_rejected', 0),
108
+ ('artifact_writes_total', 0),
109
+ ('artifact_writes_noop', 0),
110
+ ('injections_blocked_confidence', 0);
111
+
112
+ -- ---------------------------------------------------------------------------
113
+ -- 5. Setting seeds. Values are TEXT, always. Read them with an explicit
114
+ -- string comparison or an explicit Number() parse — never `=== 1`.
115
+ -- (That exact mistake kept cross_project_enabled unreachable for the
116
+ -- whole of v0.3.0.)
117
+ --
118
+ -- skill_emission_enabled and reference_emission_enabled default to '0':
119
+ -- the pull channels ship OFF and are opted into, because they depend on a
120
+ -- v2 domain Kevin does not pin.
121
+ -- ---------------------------------------------------------------------------
122
+ INSERT OR IGNORE INTO kevin_settings (key, value) VALUES
123
+ ('curation_enabled', '1'),
124
+ ('agents_md_path', 'AGENTS.md'),
125
+ ('skill_emission_enabled', '0'),
126
+ ('reference_emission_enabled', '0'),
127
+ ('injection_confidence_floor', '0.6');
128
+
129
+ -- ---------------------------------------------------------------------------
130
+ -- 6. Push-budget demotion.
131
+ --
132
+ -- Lower the default push budget only where the user has not overridden it.
133
+ -- A user who deliberately set 1200 (or 1500, or 200) keeps their value;
134
+ -- only an installation still sitting on the v0.5 default of '900' is
135
+ -- moved to '400'. An unconditional UPDATE here would silently discard a
136
+ -- deliberate configuration choice, which is a worse defect than the token
137
+ -- cost it would save.
138
+ -- ---------------------------------------------------------------------------
139
+ UPDATE kevin_settings SET value = '400'
140
+ WHERE key = 'pre_prompt_budget_tokens' AND value = '900';
141
+
142
+ -- ---------------------------------------------------------------------------
143
+ -- 7. Version marker.
144
+ -- ---------------------------------------------------------------------------
145
+ INSERT OR IGNORE INTO schema_version (version) VALUES ('007');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jmtrin/opencode-kevin",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Kevin — Observa y aprende: capa de aprendizaje para OpenCode",
5
5
  "type": "module",
6
6
  "main": "dist/plugin/index.js",
@@ -21,7 +21,8 @@
21
21
  "typecheck": "tsc --noEmit",
22
22
  "lint": "biome check .",
23
23
  "format": "biome format --write .",
24
- "verify": "node --import tsx scripts/verify-install.ts"
24
+ "verify": "node --import tsx scripts/verify-install.ts",
25
+ "replay": "node --import tsx scripts/replay.ts"
25
26
  },
26
27
  "dependencies": {
27
28
  "@opencode-ai/plugin": "^1.17.6",