-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathoutcomes.ts
More file actions
1007 lines (934 loc) · 42.9 KB
/
Copy pathoutcomes.ts
File metadata and controls
1007 lines (934 loc) · 42.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Outcomes — Sprint 1 Phase C (v0.11.0)
* ======================================
*
* Resolvers that produce deferred outcome tags for previously-recorded
* actions (tool_calls, tasks, skill_runs, etc.). Without outcome data,
* Sprint 2's mutation engine has nothing to learn from.
*
* THREE RESOLVERS shipped in Sprint 1:
*
* 1. git_commit — detects commits in bash output; tracks revert later
* 2. user_prompt — sentiment heuristic on the next user message
* 3. follow_up — pattern detection: zc_file_summary(X) → Read(X)
* within N minutes ⇒ "summary insufficient"
*
* EACH RESOLVER:
* - Reads from tool_calls (and possibly other tables)
* - Writes to outcomes table (hash-chained via Sprint 0 hmac_chain)
* - Logs every resolution to logger.outcomes
* - Audit-logs unusual conditions (per §15.4 Sprint 1)
*
* SECURITY (per §15.4 Sprint 1):
* - git_commit resolver uses git library, NOT shell exec (no injection)
* - user_prompt resolver: rate-limited; results stored as boolean only,
* NOT raw prompt text
* - follow_up resolver: pure DB query; no external dependencies
*
* WHEN RESOLVERS RUN:
* - git_commit: triggered by PostToolUse Bash hook detecting `git commit`
* - user_prompt: triggered by next user message after a tool sequence
* - follow_up: triggered inside recordToolCall (Sprint 1 hot-path)
*
* INTEGRATION POINT (Sprint 1 default):
* For now, follow_up runs inline. git_commit + user_prompt run as opt-in
* functions called by hooks (Phase D). The resolver registry is built so
* future Sprints can add more resolvers by registering callbacks.
*/
import { DatabaseSync } from "node:sqlite";
import { randomUUID, createHash } from "node:crypto";
import { join } from "node:path";
import { homedir } from "node:os";
import { mkdirSync, existsSync } from "node:fs";
import { logger } from "./logger.js";
import { auditLog } from "./security/audit_log.js";
import {
canonicalize,
type ChainableRow,
} from "./security/hmac_chain.js";
import { runMigrations } from "./migrations.js";
import { ChainedTableSqlite } from "./security/chained_table_sqlite.js";
import { verifyChainRows } from "./security/chained_table.js";
// ─── Types ─────────────────────────────────────────────────────────────────
export type OutcomeKind =
| "shipped" // git_commit found a commit + it wasn't reverted
| "reverted" // git_commit followed by a revert
| "accepted" // user_prompt sentiment = positive
| "rejected" // user_prompt sentiment = negative
| "sufficient" // tool_call achieved its purpose (no follow-up needed)
| "insufficient" // follow_up pattern detected (e.g. Read after summary)
| "errored" // tool_call returned status=error
// v0.18.1 — added so worker-agent skill outcome reporter (zc_record_skill_outcome)
// can produce a type-correct value for skill_run failures. The L1 mutation
// trigger already checks for this string at runtime; this just makes the
// TypeScript type agree with the runtime contract.
| "failed"; // skill_run fixture produced wrong output / threw error
export type SignalSource = "git_commit" | "user_prompt" | "follow_up" | "manual";
export type RefType = "tool_call" | "task" | "skill_run" | "session";
/** v0.15.0 §8.6 T3.2 — MAC-style classification (Chin & Older 2011 Ch5+Ch13) */
export type OutcomeClassification = "public" | "internal" | "confidential" | "restricted";
export interface RecordOutcomeInput {
refType: RefType;
refId: string;
outcomeKind: OutcomeKind;
signalSource: SignalSource;
confidence?: number; // 0-1; default 1.0 for direct, < 1.0 for inferred
scoreDelta?: number; // optional: how this changed parent score
evidence?: Record<string, unknown>; // structured supporting evidence (NEVER raw secrets)
projectPath: string; // for DB resolution
// v0.15.0 §8.6 T3.2 — read-access tier
/** Classification label. Default 'internal' (current behavior). */
classification?: OutcomeClassification;
/** Required when classification='restricted' — only this agent can read the row. */
createdByAgentId?: string;
}
export interface OutcomeRecord extends ChainableRow {
id: number;
outcome_id: string;
ref_type: string;
ref_id: string;
outcome_kind: string;
signal_source: string;
confidence: number;
score_delta: number | null;
evidence: string | null;
resolved_at: string;
prev_hash: string;
row_hash: string;
}
// ─── Public API ────────────────────────────────────────────────────────────
/**
* Record an outcome for a previously-recorded action.
* Never throws; loud failure via logger.
*/
export async function recordOutcome(input: RecordOutcomeInput): Promise<OutcomeRecord | null> {
// v0.12.1: Reference Monitor opt-in
const mode = (process.env.ZC_TELEMETRY_MODE || "local").toLowerCase();
let record: OutcomeRecord | null;
if (mode === "api" || mode === "dual") {
const apiResult = await _recordOutcomeViaApiPath(input);
if (mode === "api") record = apiResult;
else {
// dual: also write locally below — store the local result too, either wins
record = apiResult ?? await _recordOutcomeLocal(input);
}
} else {
record = await _recordOutcomeLocal(input);
}
// v0.17.1 L4 — auto-feedback into learnings JSONL. Best-effort, never throws,
// never affects the recorded outcome row. Only fires on kinds that signal
// failure (→ failures.jsonl) or high-confidence success (→ experiments.jsonl).
// This closes the learning loop: failures from THIS session become retrievable
// learnings for FUTURE sessions WITHOUT requiring agent discipline.
try {
const { feedbackFromOutcome } = await import("./outcome_feedback.js");
feedbackFromOutcome({
outcomeKind: input.outcomeKind,
signalSource: input.signalSource,
refType: input.refType,
refId: input.refId,
confidence: input.confidence,
evidence: input.evidence,
createdByAgentId: input.createdByAgentId,
outcomeId: record?.outcome_id,
projectPath: input.projectPath,
});
} catch { /* never fail the outcome write due to feedback */ }
// v0.18.1 L1 — outcome-triggered skill mutation.
// When an outcome with kind in {failed, insufficient, errored, reverted, rejected}
// is tied to a skill_run (refType='skill_run'), check guardrails and if they pass
// enqueue a mutation request task. Best-effort — never throws.
//
// Disabled by default; enable per-project by setting
// ZC_L1_MUTATION_ENABLED=1 in the MCP server's env. Gives operators a
// kill switch without touching code.
// v0.22.1 — L1 mutation hook firing moved entirely to the handler
// (zc_record_skill_outcome) so it can capture rich L1TriggerResult and
// surface accurate status to the user. Auto-firing here AND in the
// handler caused a double-enqueue bug (each call generates a new task_id;
// cooldown guardrail looks at skill_mutations not task_queue, so doesn't
// dedupe). The handler ALWAYS calls tryTriggerL1Mutation explicitly when
// outcome is failure-like + ZC_L1_MUTATION_ENABLED=1; resolvers
// (resolveGitCommitOutcome / resolveUserPromptOutcome / resolveFollowUpOutcomes)
// don't write skill_run outcomes so they're not affected.
// NOTE: if any future caller writes a skill_run outcome via recordOutcome
// directly (without going through zc_record_skill_outcome), they'll need
// to call tryTriggerL1Mutation themselves.
return record;
}
/**
* v0.22.1 — public version of maybeTriggerL1Mutation that exposes rich
* status so handlers can surface accurate "fired" / "bailed: <reason>"
* feedback to the user. Idempotent: a second call within the cooldown
* window correctly bails on the cooldown guardrail.
*/
export async function tryTriggerL1Mutation(
projectPath: string,
runId: string,
): Promise<L1TriggerResult> {
return maybeTriggerL1Mutation(projectPath, runId);
}
export interface L1TriggerResult {
triggered: boolean;
reason: string;
task_id?: string;
bailed_guardrail?: "cooldown" | "failure_threshold" | "daily_cap" | "skill_missing" | "retry_after_promotion" | "env_disabled";
}
/**
* Internal helper for the L1 trigger. Looks up the skill_id from the
* skill_run row, runs guardrails, and (if pass) enqueues a `role='mutator'`
* task with the right payload. v0.22.1: returns L1TriggerResult instead
* of void so callers can report accurate status.
*/
async function maybeTriggerL1Mutation(projectPath: string, runId: string): Promise<L1TriggerResult> {
const { DatabaseSync } = await import("node:sqlite");
const { join } = await import("node:path");
const { mkdirSync } = await import("node:fs");
const { createHash } = await import("node:crypto");
const { Config } = await import("./config.js");
mkdirSync(Config.DB_DIR, { recursive: true });
const dbPath = join(Config.DB_DIR, `${createHash("sha256").update(projectPath).digest("hex").slice(0,16)}.db`);
const db = new DatabaseSync(dbPath);
try {
db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA busy_timeout = 5000");
// Lookup skill_id from skill_runs (the run is the failure that triggered this outcome).
// v0.18.2 Sprint 2.6: also fetch was_retry_after_promotion + task_id so we can
// (a) skip mutation when this run was an auto-reassigned retry of a just-promoted
// version (avoid mutate→approve→fail→mutate infinite loop)
// (b) capture original_task_id/original_role for the eventual auto-reassign
const row = db.prepare(
`SELECT skill_id, failure_trace, task_id, was_retry_after_promotion
FROM skill_runs WHERE run_id = ?`
).get(runId) as { skill_id?: string; failure_trace?: string; task_id?: string; was_retry_after_promotion?: number } | undefined;
if (!row?.skill_id) return { triggered: false, reason: "skill_run row not found or skill_id missing", bailed_guardrail: "skill_missing" };
const { logger } = await import("./logger.js");
if (row.was_retry_after_promotion) {
// The retry-cap safeguard: a recently-promoted skill failed on its first
// post-promotion run. Don't spawn another mutation; this needs operator eyes.
logger.info("skills", "l1_mutation_skipped_retry_cap", {
skill_id: row.skill_id, run_id: runId, reason: "was_retry_after_promotion",
});
return { triggered: false, reason: "retry-cap: this run was a retry-after-promotion; no mutation cascade", bailed_guardrail: "retry_after_promotion" };
}
const { checkMutationGuardrails } = await import("./skills/mutation_guardrails.js");
const guard = checkMutationGuardrails(db, row.skill_id);
if (!guard.trigger) {
logger.debug("skills", "l1_mutation_skipped", { skill_id: row.skill_id, reason: guard.reason, metrics: guard.metrics });
// v0.22.1 — derive bailed_guardrail tag from the reason text
const tag: L1TriggerResult["bailed_guardrail"] =
guard.reason.startsWith("cooldown") ? "cooldown" :
guard.reason.startsWith("daily cap") ? "daily_cap" :
"failure_threshold";
return { triggered: false, reason: guard.reason, bailed_guardrail: tag };
}
// Resolve the skill so we can pass body + traces + fixtures into the mutator
const { getActiveSkill } = await import("./skills/storage.js");
const projectScope = `project:${createHash("sha256").update(projectPath).digest("hex").slice(0,16)}` as `project:${string}`;
const skill = await getActiveSkill(db, "skill_id_will_be_resolved_below" as never, projectScope).catch(() => null);
// The above would only work by name; fallback to direct skill_id lookup
const { getSkillById } = await import("./skills/storage.js");
let targetSkill = skill ?? await getSkillById(db, row.skill_id).catch(() => null);
// v0.20.1 — PG fallback. v0.20.0 added skill auto-import that lands
// skills in skills_pg (Postgres). The legacy SQLite getSkillById doesn't
// see those, so the L1 hook used to bail with skill_missing for every
// PG-imported skill. Discovered live: a developer agent recorded a
// failed skill_run for `developer-debugging-methodology@1@global`
// (which lives in skills_pg) and the mutator never fired.
//
// Fix: if the local lookup misses AND PG is configured, query skills_pg.
// Synthesize a Skill-shaped object the rest of the L1 path can consume.
// Falls through to the original missing-skill bail if PG is unreachable
// or the skill genuinely doesn't exist there either.
if (!targetSkill && (process.env.ZC_POSTGRES_HOST || process.env.ZC_POSTGRES_PASSWORD)) {
try {
const { withClient } = await import("./pg_pool.js");
const pgRow = await withClient(async (c) => {
const r = await c.query<{ skill_id: string; name: string; version: string; scope: string; description: string; frontmatter: Record<string, unknown>; body: string; body_hmac: string }>(
`SELECT skill_id, name, version, scope, description, frontmatter, body, body_hmac
FROM skills_pg WHERE skill_id=$1 AND archived_at IS NULL LIMIT 1`,
[row.skill_id],
);
return r.rows[0] ?? null;
});
if (pgRow) {
// Synthesize the Skill shape that getSkillById would have returned.
// The fields the downstream mutator path actually uses are:
// skill_id, name, version, scope, description, frontmatter, body
// Fixtures + acceptance_criteria come from frontmatter.
targetSkill = {
skill_id: pgRow.skill_id,
name: pgRow.name,
version: pgRow.version,
scope: pgRow.scope as never,
description: pgRow.description,
frontmatter: pgRow.frontmatter as never,
body: pgRow.body,
body_hmac: pgRow.body_hmac,
source_path: null,
} as never;
logger.info("skills", "l1_mutation_skill_resolved_from_pg", {
skill_id: row.skill_id, source: "skills_pg",
});
}
} catch (e) {
logger.warn("skills", "l1_mutation_pg_fallback_failed", {
skill_id: row.skill_id, error: (e as Error).message,
});
}
}
if (!targetSkill) {
logger.warn("skills", "l1_mutation_skill_missing", {
skill_id: row.skill_id,
note: "checked both SQLite (local) and skills_pg (PG); not in either",
});
return { triggered: false, reason: `skill ${row.skill_id} not found in SQLite or PG`, bailed_guardrail: "skill_missing" };
}
// Recent failure traces from skill_runs
const { getRecentSkillRuns } = await import("./skills/storage.js");
const recentRuns = getRecentSkillRuns(db, row.skill_id, 10);
const traces = recentRuns.filter((r) => r.failure_trace).map((r) => r.failure_trace as string);
// v0.18.2 Sprint 2.6 — capture the ORIGINAL task lineage so the eventual
// approval flow can auto-reassign a retry to the same role. Look up the
// task that produced this skill_run; if it had a payload.role, propagate it.
let originalRole: string | null = null;
const originalTaskId = row.task_id ?? null;
if (originalTaskId) {
// Best-effort PG lookup (task_queue is PG-only). Failures are logged but
// don't block mutation — auto-reassign just falls back to broadcasting
// a LAUNCH_ROLE-or-ASSIGN if the role can't be inferred.
try {
const { withClient } = await import("./pg_pool.js");
const r = await withClient(async (c) => {
const res = await c.query<{ role: string }>(
`SELECT role FROM task_queue_pg WHERE task_id = $1 LIMIT 1`, [originalTaskId],
);
return res.rows[0]?.role ?? null;
});
originalRole = r;
} catch { /* ignore — best-effort */ }
}
// v0.18.4 Sprint 2.7 — resolve mutator pool from intended_roles[0] (if set)
// OR from originalRole as fallback. Routes the mutation task to the right
// domain pool's queue (mutator-engineering, mutator-marketing, etc.).
const { resolveMutatorPool } = await import("./skills/mutator_pool.js");
const intendedRoles = (targetSkill.frontmatter as { intended_roles?: string[] }).intended_roles ?? [];
const primaryRole = intendedRoles[0] ?? originalRole ?? "";
const mutatorPool = resolveMutatorPool(primaryRole);
const mutationGuidance = (targetSkill.frontmatter as { mutation_guidance?: string }).mutation_guidance ?? null;
// v0.18.4 Sprint 2.7 — fetch recent decisions for this skill or pool to
// inject as `prior_decisions`. This is the operator-decision feedback loop:
// the mutator sees what got approved/rejected before + why, and adjusts.
let priorDecisions: unknown[] = [];
try {
const { fetchRecentDecisions } = await import("./skills/mutation_results.js");
priorDecisions = await fetchRecentDecisions(db, {
skill_id: row.skill_id,
mutator_pool: mutatorPool,
limit: 5,
});
} catch { /* tolerate — empty prior_decisions just means no context */ }
// Enqueue the mutation task — the mutator agent will pick it up
const { enqueueTask } = await import("./task_queue.js");
const { randomUUID } = await import("node:crypto");
const taskId = `mut-${randomUUID().slice(0, 12)}`;
const projectHash = createHash("sha256").update(projectPath).digest("hex").slice(0, 16);
await enqueueTask({
taskId,
projectHash,
role: mutatorPool, // v0.18.4: route to specific pool
payload: {
kind: "skill-mutation",
mutation_id: taskId,
skill_id: row.skill_id,
skill_name: targetSkill.frontmatter.name,
parent_body: targetSkill.body,
failure_traces: traces,
fixtures: targetSkill.frontmatter.fixtures ?? [],
acceptance_criteria: targetSkill.frontmatter.acceptance_criteria ?? null,
triggered_by: "l1-outcome",
// v0.18.2 — operator review / auto-reassign context
original_task_id: originalTaskId,
original_role: originalRole,
// v0.18.4 Sprint 2.7 — pool routing + skill domain context + feedback
mutator_pool: mutatorPool,
intended_roles: intendedRoles,
mutation_guidance: mutationGuidance,
prior_decisions: priorDecisions,
},
});
logger.info("skills", "l1_mutation_triggered", { skill_id: row.skill_id, task_id: taskId, reason: guard.reason });
return { triggered: true, reason: guard.reason, task_id: taskId };
} finally {
try { db.close(); } catch { /* noop */ }
}
}
async function _recordOutcomeViaApiPath(input: RecordOutcomeInput): Promise<OutcomeRecord | null> {
const { getOrFetchSessionToken, recordOutcomeViaApi } = await import("./telemetry_client.js");
// Outcomes are written by the resolver runtime, so the session token is
// bound to the writer's identity (orchestrator or whatever invoked the
// resolver). For now we use ZC_AGENT_ID + ZC_AGENT_ROLE.
const agentId = process.env.ZC_AGENT_ID || "outcomes-resolver";
const role = process.env.ZC_AGENT_ROLE || "developer";
const token = await getOrFetchSessionToken(input.projectPath, agentId, role);
if (!token) return _recordOutcomeLocal(input);
const r = await recordOutcomeViaApi(input, token);
if (r === null) return _recordOutcomeLocal(input);
return r;
}
/**
* Local-mode dispatch — chooses storage backend based on ZC_TELEMETRY_BACKEND.
* Default 'sqlite'. 'postgres' routes through ChainedTablePostgres + RLS.
* 'dual' writes to both for migration verification.
*/
async function _recordOutcomeLocal(input: RecordOutcomeInput): Promise<OutcomeRecord | null> {
const backend = (process.env.ZC_TELEMETRY_BACKEND || "sqlite").toLowerCase();
if (backend === "postgres" || backend === "dual") {
const pgResult = await _recordOutcomePostgres(input);
if (backend === "postgres") return pgResult;
// dual: also write to sqlite below
}
return _recordOutcomeSqlite(input);
}
/**
* v0.16.0 Postgres backend for outcomes.
* RLS policies on outcomes_pg gate cross-agent reads on 'restricted' rows
* (T3.2). Per-query SET LOCAL ROLE applies T3.1.
*/
async function _recordOutcomePostgres(input: RecordOutcomeInput): Promise<OutcomeRecord | null> {
try {
const { ChainedTablePostgres } = await import("./security/chained_table_postgres.js");
const { runPgMigrations } = await import("./pg_migrations.js");
await runPgMigrations();
const outcomeId = `out-${randomUUID().slice(0, 12)}`;
const resolvedAt = new Date().toISOString();
const confidence = input.confidence ?? 1.0;
const evidenceJson = input.evidence ? JSON.stringify(input.evidence, sortedReplacer) : null;
// Same classification + creator-binding logic as the SQLite path
const allowed: OutcomeClassification[] = ["public", "internal", "confidential", "restricted"];
let safeClassification: OutcomeClassification = "internal";
if (input.classification && allowed.includes(input.classification)) {
safeClassification = input.classification;
}
let safeCreatedBy: string | null = null;
if (typeof input.createdByAgentId === "string" && input.createdByAgentId.length > 0) {
safeCreatedBy = input.createdByAgentId.slice(0, 200);
}
if (safeClassification === "restricted" && !safeCreatedBy) {
logger.warn("outcomes", "restricted_without_creator_downgraded_pg", {
ref_id: input.refId, kind: input.outcomeKind,
});
safeClassification = "confidential";
}
const writerAgentId = safeCreatedBy ?? "outcomes-resolver";
const canonicalFields = buildCanonicalFields({
outcomeId,
refType: input.refType,
refId: input.refId,
outcomeKind: input.outcomeKind,
signalSource: input.signalSource,
confidence,
scoreDelta: input.scoreDelta ?? null,
evidence: evidenceJson,
resolvedAt,
});
const chain = new ChainedTablePostgres({ tableName: "outcomes_pg" });
const result = await chain.appendChainedWith(
{ agentId: writerAgentId, projectHash: sha256ProjectHash(input.projectPath), canonicalFields },
async ({ prevHash, rowHash, client }) => {
const r = await client.query(`
INSERT INTO outcomes_pg (
outcome_id, ref_type, ref_id, outcome_kind,
signal_source, confidence, score_delta, evidence, resolved_at,
prev_hash, row_hash, classification, created_by_agent_id
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, $10, $11, $12, $13)
RETURNING id
`, [
outcomeId, input.refType, input.refId, input.outcomeKind,
input.signalSource, confidence, input.scoreDelta ?? null,
evidenceJson, resolvedAt, prevHash, rowHash,
safeClassification, safeCreatedBy,
]);
return { id: r.rows[0]?.id ?? 0 };
}
);
logger.info("outcomes", "outcome_recorded_pg", {
outcome_id: outcomeId, kind: input.outcomeKind, classification: safeClassification, id: result.id,
});
return {
id: result.id,
outcome_id: outcomeId,
ref_type: input.refType,
ref_id: input.refId,
outcome_kind: input.outcomeKind,
signal_source: input.signalSource,
confidence,
score_delta: input.scoreDelta ?? null,
evidence: evidenceJson,
resolved_at: resolvedAt,
prev_hash: result.prevHash,
row_hash: result.rowHash,
} as unknown as OutcomeRecord;
} catch (e) {
logger.error("outcomes", "outcome_pg_failed", {
ref_id: input.refId, kind: input.outcomeKind, error: (e as Error).message,
});
return null;
}
}
async function _recordOutcomeSqlite(input: RecordOutcomeInput): Promise<OutcomeRecord | null> {
try {
const db = openProjectDb(input.projectPath);
try {
const outcomeId = `out-${randomUUID().slice(0, 12)}`;
const resolvedAt = new Date().toISOString();
const confidence = input.confidence ?? 1.0;
const evidenceJson = input.evidence ? JSON.stringify(input.evidence, sortedReplacer) : null;
// v0.12.0: ChainedTableSqlite handles BEGIN IMMEDIATE atomicity + Tier 1
// per-agent HMAC subkey. The outcomes table has a single chain per DB
// (no project-hash filter — the DB itself is per-project).
const chain = new ChainedTableSqlite(db, { tableName: "outcomes" });
// The "agent" for outcome rows is implied by the action being resolved.
// For now we use a constant "outcomes-resolver" identity — Sprint 3
// will refine to attribute per-resolver runs to the calling agent.
const writerAgentId = "outcomes-resolver";
const canonicalFields = buildCanonicalFields({
outcomeId,
refType: input.refType,
refId: input.refId,
outcomeKind: input.outcomeKind,
signalSource: input.signalSource,
confidence,
scoreDelta: input.scoreDelta ?? null,
evidence: evidenceJson,
resolvedAt,
});
// v0.15.0 §8.6 T3.2 — classification label + creator binding.
// Default 'internal' preserves v0.14.0 behavior for callers that
// don't supply classification. 'restricted' rows MUST carry a
// createdByAgentId — coerce to 'internal' if author missing
// (defensive: don't silently lose readability).
const allowed: OutcomeClassification[] = ["public", "internal", "confidential", "restricted"];
let safeClassification: OutcomeClassification = "internal";
if (input.classification && allowed.includes(input.classification)) {
safeClassification = input.classification;
}
let safeCreatedBy: string | null = null;
if (typeof input.createdByAgentId === "string" && input.createdByAgentId.length > 0) {
safeCreatedBy = input.createdByAgentId.slice(0, 200);
}
if (safeClassification === "restricted" && !safeCreatedBy) {
// Restricted rows require a creator — downgrade to 'confidential'
// so the row remains readable by registered agents on this project.
// Logged so this isn't silent.
logger.warn("outcomes", "restricted_without_creator_downgraded", {
ref_id: input.refId, kind: input.outcomeKind,
});
safeClassification = "confidential";
}
await chain.appendChainedWith(
{ agentId: writerAgentId, projectHash: sha256ProjectHash(input.projectPath), canonicalFields },
({ prevHash, rowHash, db: txnDb }) => {
txnDb.prepare(`
INSERT INTO outcomes (
outcome_id, ref_type, ref_id, outcome_kind,
signal_source, confidence, score_delta, evidence, resolved_at,
prev_hash, row_hash, classification, created_by_agent_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
outcomeId, input.refType, input.refId, input.outcomeKind,
input.signalSource, confidence, input.scoreDelta ?? null, evidenceJson, resolvedAt,
prevHash, rowHash, safeClassification, safeCreatedBy
);
}
);
logger.info("outcomes", "outcome_recorded", {
outcome_id: outcomeId,
ref_type: input.refType,
ref_id: input.refId,
kind: input.outcomeKind,
source: input.signalSource,
confidence,
});
return readOutcome(db, outcomeId);
} finally {
db.close();
}
} catch (e) {
logger.error("outcomes", "record_failed", {
ref_type: input.refType,
ref_id: input.refId,
kind: input.outcomeKind,
error: (e as Error).message,
});
return null;
}
}
// ─── Resolver: git_commit ──────────────────────────────────────────────────
/**
* Detect a git commit in the given bash output. If present, record an
* outcome of kind="shipped" linking the commit hash to the most recent
* tool_call in the same session (likely the agent's "edit + commit" sequence).
*
* Returns the recorded outcome, or null if no commit detected.
*/
export async function resolveGitCommitOutcome(input: {
projectPath: string;
sessionId: string;
bashOutput: string;
}): Promise<OutcomeRecord | null> {
// Match `[branch hash] message` (git commit's standard output format)
// e.g. `[main abc123ef] Fix typo`
const m = input.bashOutput.match(/\[(\S+)\s+([0-9a-f]{7,40})\]/);
if (!m) return null;
const branch = m[1];
const hash = m[2];
// Find the most recent tool_call in this session — it's likely the action
// that triggered the commit (Edit/Write/Bash that ended in `git commit`)
const recentCall = await getMostRecentToolCallForSession(input.projectPath, input.sessionId);
if (!recentCall) {
logger.warn("outcomes", "git_commit_no_recent_call", {
session_id: input.sessionId,
commit_hash: hash,
});
return null;
}
return await recordOutcome({
projectPath: input.projectPath,
refType: "tool_call",
refId: recentCall.call_id,
outcomeKind: "shipped",
signalSource: "git_commit",
confidence: 0.95, // high but not 1.0 — could be reverted later
evidence: { branch, commit_hash: hash, session_id: input.sessionId },
});
}
// ─── Resolver: user_prompt ─────────────────────────────────────────────────
/**
* Apply a simple sentiment heuristic to the user's next message and record
* an outcome (accepted vs rejected) for the most recent tool_call.
*
* Heuristic (rate-limited; never stores raw prompt):
* - accepted: contains thanks / great / perfect / good / works / nice /
* yes / continue / proceed
* - rejected: contains stop / wrong / no / not what / incorrect / undo
* - neutral: neither → no outcome recorded
*
* Confidence is intentionally low (0.5) since this is a weak inferred signal.
*/
export async function resolveUserPromptOutcome(input: {
projectPath: string;
sessionId: string;
userMessage: string;
/** v0.15.0 §8.6 T3.2 — agent the prompt belongs to (becomes the row's
* created_by_agent_id, gating cross-agent reads). Defaults to ZC_AGENT_ID. */
agentId?: string;
}): Promise<OutcomeRecord | null> {
const sentiment = classifySentiment(input.userMessage);
if (sentiment === "neutral") return null;
const recentCall = await getMostRecentToolCallForSession(input.projectPath, input.sessionId);
if (!recentCall) return null;
// v0.15.0 §8.6 T3.2 — sentiment about a user message is sensitive to the
// ORIGINATING agent. Cross-agent reads of these outcomes leak information
// about how a specific user spoke to a specific worker. Tag 'restricted'
// with the agent_id binding so only the originating agent can read.
const writerAgent = input.agentId
?? process.env.ZC_AGENT_ID
?? recentCall.agent_id
?? "outcomes-resolver";
return await recordOutcome({
projectPath: input.projectPath,
refType: "tool_call",
refId: recentCall.call_id,
outcomeKind: sentiment === "positive" ? "accepted" : "rejected",
signalSource: "user_prompt",
confidence: 0.5, // weak inference
// Only store the sentiment + length, NOT the raw message text
evidence: { sentiment, message_length: input.userMessage.length },
classification: "restricted",
createdByAgentId: writerAgent,
});
}
// ─── Resolver: follow_up ───────────────────────────────────────────────────
/**
* Detect: a Read of file X happens shortly after a zc_file_summary of file X
* (in the same session). Indicates the summary was insufficient. Record an
* outcome of kind="insufficient" against the file_summary call.
*
* Window: default 5 minutes between summary and re-read.
*
* Returns array of outcomes recorded (typically 0 or 1).
*/
export async function resolveFollowUpOutcomes(input: {
projectPath: string;
sessionId: string;
newToolName: string;
newToolInput: Record<string, unknown> | undefined;
windowMinutes?: number;
}): Promise<OutcomeRecord[]> {
// Only Read tool calls trigger this resolver
if (input.newToolName !== "Read") return [];
const filePath = (input.newToolInput?.file_path ?? input.newToolInput?.path) as string | undefined;
if (!filePath) return [];
const windowMs = (input.windowMinutes ?? 5) * 60 * 1000;
const recentSummary = findRecentFileSummary(input.projectPath, input.sessionId, filePath, windowMs);
if (!recentSummary) return [];
const outcome = await recordOutcome({
projectPath: input.projectPath,
refType: "tool_call",
refId: recentSummary.call_id,
outcomeKind: "insufficient",
signalSource: "follow_up",
confidence: 0.85,
evidence: {
file_path: filePath,
summary_call_id: recentSummary.call_id,
summary_at: recentSummary.ts,
read_at: new Date().toISOString(),
delay_seconds: Math.round((Date.now() - new Date(recentSummary.ts).getTime()) / 1000),
},
});
return outcome ? [outcome] : [];
}
// ─── Verification ──────────────────────────────────────────────────────────
/**
* Verify the hash chain on the outcomes table for tamper detection.
* Returns OK or the breaking row id.
*/
export function verifyOutcomesChain(projectPath: string): {
ok: boolean;
totalRows: number;
brokenAt?: number;
brokenKind?: "hash-mismatch" | "prev-mismatch";
} {
const db = openProjectDb(projectPath);
try {
const rows = db.prepare(`
SELECT id, outcome_id, ref_type, ref_id, outcome_kind,
signal_source, confidence, score_delta, evidence, resolved_at,
prev_hash, row_hash
FROM outcomes
ORDER BY id ASC
`).all() as unknown as OutcomeRecord[];
// v0.12.0 Tier 1: outcomes are written by the "outcomes-resolver" identity
// (see recordOutcome). Verifier derives the matching subkey to validate.
const rowsForVerify = rows.map((r) => ({ ...r, agentIdForVerify: "outcomes-resolver" }));
return verifyChainRows(rowsForVerify, (row) => canonicalize(buildCanonicalFields({
outcomeId: row.outcome_id,
refType: row.ref_type,
refId: row.ref_id,
outcomeKind: row.outcome_kind,
signalSource: row.signal_source,
confidence: row.confidence,
scoreDelta: row.score_delta,
evidence: row.evidence,
resolvedAt: row.resolved_at,
})));
} finally {
db.close();
}
}
/**
* Get all outcomes for a given tool_call.
*
* v0.15.0 §8.6 T3.2 — MAC-style read filter:
* public/internal → returned to all callers (default)
* confidential → returned to callers identified as a registered
* agent on this project (we approximate by
* "requestingAgentId is non-empty")
* restricted → returned ONLY when requestingAgentId === created_by_agent_id
*
* Pass `requestingAgentId` to enable the filter. Omit to retain v0.14.0
* behavior (returns ALL rows — admin/back-compat path).
*/
export function getOutcomesForToolCall(
projectPath: string,
callId: string,
requestingAgentId?: string,
): OutcomeRecord[] {
const db = openProjectDb(projectPath);
try {
const all = db.prepare(`
SELECT * FROM outcomes WHERE ref_type = 'tool_call' AND ref_id = ?
ORDER BY id ASC
`).all(callId) as unknown as OutcomeRecord[];
// No filter requested → preserve legacy admin behavior
if (requestingAgentId === undefined) return all;
return all.filter((row) => {
// Legacy rows pre-migration-19 may lack `classification` (UNKNOWN);
// treat as 'internal' for safety (readable by any registered agent).
const cls: string = (row as unknown as Record<string, unknown>).classification as string ?? "internal";
const createdBy: string | null = ((row as unknown as Record<string, unknown>).created_by_agent_id as string | null) ?? null;
if (cls === "public" || cls === "internal") return true;
if (cls === "confidential") {
// Confidential = readable by any non-empty agent identity. The Postgres
// backend in v0.16.0 will tighten this to a registered agent_role check.
return requestingAgentId !== "";
}
if (cls === "restricted") {
return createdBy !== null && createdBy === requestingAgentId;
}
// Unknown classification value — fail closed (don't return)
return false;
});
} finally {
db.close();
}
}
// ─── Internal ──────────────────────────────────────────────────────────────
const POSITIVE_PATTERNS = [
/\b(thanks?|thx|thank you)\b/i,
/\b(great|perfect|excellent|wonderful)\b/i,
/\b(good|nice|awesome)\b/i,
/\b(works?|working|fixed|done)\b/i,
/\b(yes|yep|yeah|sure)\b/i,
/\b(continue|proceed|go ahead|ship it)\b/i,
];
const NEGATIVE_PATTERNS = [
/\b(stop|halt|pause)\b/i,
/\b(wrong|incorrect|broken|broke)\b/i,
/\b(no|nope)\b/i,
/\b(not what|that's not|undo|revert|rollback)\b/i,
];
function classifySentiment(text: string): "positive" | "negative" | "neutral" {
if (text.length === 0) return "neutral";
const positive = POSITIVE_PATTERNS.some((re) => re.test(text));
const negative = NEGATIVE_PATTERNS.some((re) => re.test(text));
if (positive && !negative) return "positive";
if (negative && !positive) return "negative";
return "neutral";
}
function sha256ProjectHash(projectPath: string): string {
return createHash("sha256").update(projectPath).digest("hex").slice(0, 16);
}
function openProjectDb(projectPath: string): DatabaseSync {
const dbDir = join(homedir(), ".claude", "zc-ctx", "sessions");
if (!existsSync(dbDir)) mkdirSync(dbDir, { recursive: true });
const dbPath = join(dbDir, sha256ProjectHash(projectPath) + ".db");
const db = new DatabaseSync(dbPath);
db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA busy_timeout = 5000");
runMigrations(db);
return db;
}
/**
* v0.17.0 fix: backend-aware session lookup.
*
* Before: SQLite-only. When ZC_TELEMETRY_BACKEND=postgres was set, session
* tool_calls lived in tool_calls_pg and this function silently returned null,
* causing resolveGitCommitOutcome + resolveFollowUpOutcomes to no-op — no
* outcomes were recorded even though commits / file-summary-then-read
* patterns actually occurred.
*
* Now routes to Postgres when backend is postgres|dual, with SQLite fallback
* for dual mode (so either store can satisfy the lookup).
*/
async function getMostRecentToolCallForSession(
projectPath: string,
sessionId: string,
): Promise<{ call_id: string; tool_name: string; ts: string; agent_id: string } | null> {
const backend = (process.env.ZC_TELEMETRY_BACKEND || "sqlite").toLowerCase();
if (backend === "postgres" || backend === "dual") {
try {
const { withClient } = await import("./pg_pool.js");
const pgRow = await withClient(async (c) => {
const r = await c.query<{ call_id: string; tool_name: string; ts: Date; agent_id: string }>(
`SELECT call_id, tool_name, ts, agent_id FROM tool_calls_pg
WHERE session_id = $1
ORDER BY id DESC LIMIT 1`,
[sessionId],
);
return r.rows[0] ?? null;
});
if (pgRow) {
return {
call_id: pgRow.call_id,
tool_name: pgRow.tool_name,
ts: pgRow.ts instanceof Date ? pgRow.ts.toISOString() : String(pgRow.ts),
agent_id: pgRow.agent_id,
};
}
if (backend === "postgres") return null; // PG-only: nowhere else to look
// fall through to SQLite for dual mode
} catch {
if (backend === "postgres") return null; // PG unavailable: can't lookup
// dual mode: fall through
}
}
// SQLite path (default backend OR dual-mode fallback)
const db = openProjectDb(projectPath);
try {
const row = db.prepare(`
SELECT call_id, tool_name, ts, agent_id FROM tool_calls
WHERE session_id = ?
ORDER BY id DESC LIMIT 1
`).get(sessionId) as { call_id: string; tool_name: string; ts: string; agent_id: string } | undefined;
return row ?? null;
} finally {
db.close();
}
}
function findRecentFileSummary(
projectPath: string,
sessionId: string,
filePath: string,
windowMs: number,
): { call_id: string; ts: string } | null {
const db = openProjectDb(projectPath);
try {
const sinceMs = Date.now() - windowMs;
const since = new Date(sinceMs).toISOString();
// We don't store tool inputs in tool_calls. We approximate by:
// - Look for recent zc_file_summary calls in this session
// - Match by tool_name (we don't have file_path in tool_calls Sprint 1
// — Sprint 2 may add it, for now this is a rougher heuristic)
const row = db.prepare(`
SELECT call_id, ts FROM tool_calls
WHERE session_id = ?
AND tool_name LIKE '%zc_file_summary%'
AND ts >= ?
ORDER BY id DESC LIMIT 1
`).get(sessionId, since) as { call_id: string; ts: string } | undefined;
return row ?? null;
} finally {
db.close();
}
}
function buildCanonicalFields(input: {
outcomeId: string;
refType: string;
refId: string;
outcomeKind: string;
signalSource: string;
confidence: number;
scoreDelta: number | null;
evidence: string | null;
resolvedAt: string;
}): Array<string | number> {
return [
input.outcomeId,
input.refType,
input.refId,
input.outcomeKind,
input.signalSource,
input.confidence.toFixed(4),
input.scoreDelta === null ? "" : input.scoreDelta.toFixed(4),
input.evidence ?? "",
input.resolvedAt,
];
}
function readOutcome(db: DatabaseSync, outcomeId: string): OutcomeRecord | null {
const row = db.prepare(`SELECT * FROM outcomes WHERE outcome_id = ?`).get(outcomeId);
return row ? (row as unknown as OutcomeRecord) : null;
}
/** Sorted JSON.stringify replacer — matches src/security/audit_log.ts pattern. */
function sortedReplacer(_key: string, value: unknown): unknown {
if (value && typeof value === "object" && !Array.isArray(value)) {
const sorted: Record<string, unknown> = {};