@unblocklabs/unblock-memory 0.12.3 → 0.14.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 (138) hide show
  1. package/README.md +19 -18
  2. package/defaults.json +162 -0
  3. package/dist/src/analysis.js +1 -1
  4. package/dist/src/cluster-review.d.ts +2 -0
  5. package/dist/src/cluster-review.js +9 -8
  6. package/dist/src/config.d.ts +9 -6
  7. package/dist/src/config.js +59 -45
  8. package/dist/src/curation.d.ts +1 -1
  9. package/dist/src/decision-client.d.ts +45 -0
  10. package/dist/src/decision-client.js +87 -0
  11. package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
  12. package/dist/src/decision-ranking.js +155 -0
  13. package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
  14. package/dist/src/decision-review.js +193 -0
  15. package/dist/src/defaults.d.ts +8 -0
  16. package/dist/src/defaults.js +128 -0
  17. package/dist/src/diagnostics.d.ts +5 -5
  18. package/dist/src/emotion-baselines.d.ts +28 -3
  19. package/dist/src/emotion-baselines.js +312 -115
  20. package/dist/src/evidence-review.d.ts +22 -8
  21. package/dist/src/evidence-review.js +11 -8
  22. package/dist/src/extraction-chunk.d.ts +3 -0
  23. package/dist/src/extraction-chunk.js +25 -6
  24. package/dist/src/extraction-config.js +4 -2
  25. package/dist/src/extraction-model.d.ts +25 -17
  26. package/dist/src/extraction-model.js +232 -104
  27. package/dist/src/extraction-runtime.d.ts +3 -1
  28. package/dist/src/extraction-runtime.js +48 -20
  29. package/dist/src/extraction-source.d.ts +1 -1
  30. package/dist/src/extraction-source.js +21 -12
  31. package/dist/src/extraction-store.d.ts +29 -3
  32. package/dist/src/extraction-store.js +149 -25
  33. package/dist/src/extraction-worker.d.ts +3 -3
  34. package/dist/src/extraction-worker.js +250 -95
  35. package/dist/src/inside-out-runtime.js +43 -30
  36. package/dist/src/inside-out-sources.js +2 -1
  37. package/dist/src/inside-out-store.d.ts +2 -2
  38. package/dist/src/inside-out-store.js +111 -69
  39. package/dist/src/inside-out.d.ts +10 -9
  40. package/dist/src/inside-out.js +194 -106
  41. package/dist/src/manager.d.ts +22 -9
  42. package/dist/src/manager.js +279 -172
  43. package/dist/src/memory-database.js +3 -2
  44. package/dist/src/memory-passage.d.ts +2 -2
  45. package/dist/src/memory-passage.js +3 -2
  46. package/dist/src/memory-search.d.ts +4 -2
  47. package/dist/src/memory-search.js +5 -5
  48. package/dist/src/memory-whisperer.d.ts +1 -1
  49. package/dist/src/memory-whisperer.js +195 -129
  50. package/dist/src/my-turn.d.ts +1 -1
  51. package/dist/src/my-turn.js +90 -70
  52. package/dist/src/people-background.d.ts +5 -1
  53. package/dist/src/people-background.js +31 -7
  54. package/dist/src/people-dossier-review.d.ts +20 -8
  55. package/dist/src/people-dossier-review.js +15 -11
  56. package/dist/src/people-hooks.js +127 -22
  57. package/dist/src/people-learning-cron.d.ts +1 -1
  58. package/dist/src/people-learning-cron.js +107 -57
  59. package/dist/src/people-learning-inventory.d.ts +1 -0
  60. package/dist/src/people-learning-inventory.js +283 -172
  61. package/dist/src/people-learning-prompt.js +1 -1
  62. package/dist/src/people-learning-runtime.d.ts +1 -1
  63. package/dist/src/people-learning-runtime.js +360 -203
  64. package/dist/src/people-learning-store.d.ts +27 -4
  65. package/dist/src/people-learning-store.js +312 -96
  66. package/dist/src/people-primer-tool.js +13 -10
  67. package/dist/src/people-primer.d.ts +3 -1
  68. package/dist/src/people-primer.js +66 -48
  69. package/dist/src/people-store.d.ts +18 -21
  70. package/dist/src/people-store.js +188 -64
  71. package/dist/src/people-tools.js +138 -93
  72. package/dist/src/plugin.js +19 -18
  73. package/dist/src/quality-audit.d.ts +2 -0
  74. package/dist/src/quality-audit.js +11 -9
  75. package/dist/src/quality-triage.js +4 -3
  76. package/dist/src/query-generator.js +5 -2
  77. package/dist/src/response-audit.d.ts +1 -1
  78. package/dist/src/response-audit.js +78 -44
  79. package/dist/src/response-config.js +3 -1
  80. package/dist/src/response-episodes.d.ts +1 -1
  81. package/dist/src/response-episodes.js +15 -19
  82. package/dist/src/response-identity.js +2 -1
  83. package/dist/src/response-judge.d.ts +151 -145
  84. package/dist/src/response-judge.js +535 -204
  85. package/dist/src/response-memory.js +2 -1
  86. package/dist/src/response-outcome.js +9 -8
  87. package/dist/src/response-reviews.d.ts +29 -1
  88. package/dist/src/response-reviews.js +113 -15
  89. package/dist/src/response-runtime.js +10 -9
  90. package/dist/src/response-stages.d.ts +50 -53
  91. package/dist/src/response-stages.js +10 -4
  92. package/dist/src/response-store.d.ts +7 -6
  93. package/dist/src/response-store.js +335 -212
  94. package/dist/src/review-tools.d.ts +8 -2
  95. package/dist/src/review-tools.js +22 -21
  96. package/dist/src/runtime.d.ts +7 -4
  97. package/dist/src/runtime.js +625 -98
  98. package/dist/src/safety-config.js +3 -2
  99. package/dist/src/safety-whisperer.d.ts +2 -2
  100. package/dist/src/safety-whisperer.js +90 -73
  101. package/dist/src/session-sync.d.ts +3 -1
  102. package/dist/src/session-sync.js +202 -96
  103. package/dist/src/skill-whisperer.d.ts +2 -2
  104. package/dist/src/skill-whisperer.js +55 -32
  105. package/dist/src/slack-directory.js +3 -2
  106. package/dist/src/training-gate.d.ts +9 -22
  107. package/dist/src/training-gate.js +34 -36
  108. package/dist/src/training-input.js +4 -3
  109. package/dist/src/training-judge.d.ts +9 -16
  110. package/dist/src/training-judge.js +6 -5
  111. package/dist/src/training-models.d.ts +1 -1
  112. package/dist/src/training-models.js +9 -7
  113. package/dist/src/training-queries.d.ts +14 -9
  114. package/dist/src/training-queries.js +374 -231
  115. package/dist/src/training-retrieval.d.ts +17 -27
  116. package/dist/src/training-retrieval.js +186 -139
  117. package/dist/src/training-runtime.d.ts +3 -0
  118. package/dist/src/training-runtime.js +76 -18
  119. package/dist/src/training-store.d.ts +18 -3
  120. package/dist/src/training-store.js +141 -52
  121. package/dist/src/training.js +9 -11
  122. package/dist/src/whisperer-context.d.ts +13 -0
  123. package/dist/src/whisperer-context.js +22 -1
  124. package/docs/configuration.md +83 -64
  125. package/docs/extraction.md +26 -35
  126. package/docs/memory-training.md +7 -6
  127. package/docs/people-learning.md +2 -2
  128. package/docs/peoplesql.md +6 -6
  129. package/docs/response-audit.md +10 -8
  130. package/docs/retrieval.md +43 -47
  131. package/openclaw.plugin.json +76 -75
  132. package/package.json +5 -2
  133. package/skills/memory-curator/SKILL.md +1 -1
  134. package/skills/people-whisperer/SKILL.md +1 -1
  135. package/dist/src/typesafe-client.d.ts +0 -30
  136. package/dist/src/typesafe-client.js +0 -92
  137. package/dist/src/typesafe-review.js +0 -154
  138. package/dist/src/typesafe.js +0 -147
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { DatabaseSync } from "node:sqlite";
2
3
  /** Current-index investigation only. No QMD manager startup, re-indexing or historical claims. */
3
4
  export function responseMemoryCandidates(indexPath, sources, episode) {
@@ -11,7 +12,7 @@ export function responseMemoryCandidates(indexPath, sources, episode) {
11
12
  const query = words.map(w => `"${w}"`).join(" OR ");
12
13
  const db = new DatabaseSync(indexPath, { readOnly: true });
13
14
  try {
14
- db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000");
15
+ db.exec(`PRAGMA query_only=ON; PRAGMA busy_timeout=${DEFAULTS.sqlite.readerBusyTimeoutMs}`);
15
16
  // Whole short indexed documents only: never call a truncated excerpt complete evidence.
16
17
  const rows = db.prepare(`SELECT d.collection,d.path,d.hash,c.doc text
17
18
  FROM documents_fts JOIN documents d ON d.id=documents_fts.rowid JOIN content c ON c.hash=d.hash
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  // Reporting/composition changes do not require paid re-inference of the same rubric.
2
3
  export const RESPONSE_REPORT_VERSION = "response-report-v4";
3
4
  /** Compose observed evidence, not a factual-verification or causal agent grade.
@@ -11,16 +12,16 @@ export function responseOutcome(result) {
11
12
  reasons.push(reason);
12
13
  reasonDetails.push({ reason, strength, measure, source });
13
14
  };
14
- if (result.quality.underdelivery.noul >= 0.8) {
15
+ if (result.quality.underdelivery.noul >= DEFAULTS.responseAudit.scoreHigh) {
15
16
  basis.push("visible_underdelivery");
16
17
  const reason = result.quality.failureReason;
17
- if (reason.confidence >= 0.8 && reason.choice !== "none_or_unclear")
18
+ if (reason.confidence >= DEFAULTS.responseAudit.scoreHigh && reason.choice !== "none_or_unclear")
18
19
  addReason(reason.choice, reason.confidence, "visible_quality");
19
20
  }
20
21
  if (later) {
21
- const correction = later.correction.noul >= 0.8;
22
- const delivery = later.deliveryAdmission.noul >= 0.8;
23
- const regression = later.regression.noul >= 0.8;
22
+ const correction = later.correction.noul >= DEFAULTS.responseAudit.scoreHigh;
23
+ const delivery = later.deliveryAdmission.noul >= DEFAULTS.responseAudit.scoreHigh;
24
+ const regression = later.regression.noul >= DEFAULTS.responseAudit.scoreHigh;
24
25
  if (correction)
25
26
  basis.push("later_correction");
26
27
  if (delivery) {
@@ -31,20 +32,20 @@ export function responseOutcome(result) {
31
32
  basis.push("regression_admission");
32
33
  addReason("regression", later.regression.noul, "regression_admission", "yes_probability");
33
34
  }
34
- const reported = later.outcome.confidence >= 0.8 && later.outcome.choice === "reported_shortfall" && later.scopeClarification.noul <= 0.2;
35
+ const reported = later.outcome.confidence >= DEFAULTS.responseAudit.scoreHigh && later.outcome.choice === "reported_shortfall" && later.scopeClarification.noul <= DEFAULTS.responseAudit.scoreLow;
35
36
  if (reported)
36
37
  basis.push("reported_shortfall");
37
38
  // A narrow admission can establish the shortfall even when the broad outcome
38
39
  // abstains. Its independently confident reason is still useful, not overridden
39
40
  // by a hard-coded assumption that every correction means incorrect_claim.
40
- if ((correction || delivery || regression || reported) && later.reason.confidence >= 0.8 && later.reason.choice !== "none_or_unclear") {
41
+ if ((correction || delivery || regression || reported) && later.reason.confidence >= DEFAULTS.responseAudit.scoreHigh && later.reason.choice !== "none_or_unclear") {
41
42
  addReason(later.reason.choice, later.reason.confidence, "retrospective_reason");
42
43
  }
43
44
  }
44
45
  if (basis.length)
45
46
  return { status: "reported_shortfall", basis, reasons: [...new Set(reasons)], reasonDetails,
46
47
  reasonStatus: reasonDetails.length ? "classified" : "uncertain" };
47
- if (later?.outcome.choice === "acknowledged_success" && later.outcome.confidence >= 0.8) {
48
+ if (later?.outcome.choice === "acknowledged_success" && later.outcome.confidence >= DEFAULTS.responseAudit.scoreHigh) {
48
49
  return { status: "acknowledged_success", basis: ["human_acknowledgment"], reasons: [], reasonDetails: [], reasonStatus: "not_applicable" };
49
50
  }
50
51
  return { status: "unknown", basis: [], reasons: [], reasonDetails: [], reasonStatus: "not_applicable" };
@@ -2,8 +2,13 @@ import type { DatabaseSync } from "node:sqlite";
2
2
  import type { ResponseResult } from "./response-store.js";
3
3
  export declare const RESPONSE_REVIEW_POLICY = "response-review-v2";
4
4
  export type ResponseReviewStatus = "pending" | "resolved" | "dismissed" | "deferred";
5
+ export type ResponseReviewDecisionOptions = {
6
+ expectedInputHash?: string;
7
+ expectedEvidenceHash?: string;
8
+ };
5
9
  /** Operator-only tasks, intentionally not exposed as memory-curation agent tools. */
6
10
  export declare class ResponseReviews {
11
+ #private;
7
12
  private readonly db;
8
13
  constructor(db: DatabaseSync);
9
14
  sync(cohort: string, episodeId: string, inputHash: string, result: ResponseResult, now: number): void;
@@ -14,6 +19,9 @@ export declare class ResponseReviews {
14
19
  episodeId: string;
15
20
  family: string;
16
21
  status: string;
22
+ cohort: string;
23
+ inputHash: string;
24
+ evidenceHash: string;
17
25
  evidenceStatus: string;
18
26
  reviewerKind: import("node:sqlite").SQLOutputValue;
19
27
  resolutionNote: import("node:sqlite").SQLOutputValue;
@@ -21,7 +29,27 @@ export declare class ResponseReviews {
21
29
  updatedAt: import("node:sqlite").SQLOutputValue;
22
30
  evidence: unknown;
23
31
  }[];
24
- decide(cohort: string, id: string, status: ResponseReviewStatus, reviewer: "human" | "agent", note: string, now?: number): void;
32
+ decisions(taskId?: string, cohort?: string): {
33
+ id: number;
34
+ taskId: string;
35
+ status: ResponseReviewStatus;
36
+ reviewerKind: "human" | "agent";
37
+ note: string;
38
+ decidedAt: number;
39
+ cohort: string | null;
40
+ inputHash: string | null;
41
+ evidenceHash: string | null;
42
+ }[];
43
+ decide(cohort: string, id: string, status: ResponseReviewStatus, reviewer: "human" | "agent", note: string, now?: number, options?: ResponseReviewDecisionOptions): {
44
+ taskId: string;
45
+ status: ResponseReviewStatus;
46
+ reviewerKind: "agent" | "human";
47
+ note: string;
48
+ decidedAt: number;
49
+ cohort: string;
50
+ inputHash: string;
51
+ evidenceHash: string;
52
+ };
25
53
  annotate(occurredAt: number, kind: string, note: string): `${string}-${string}-${string}-${string}-${string}`;
26
54
  annotations(since: number, until: number): Record<string, import("node:sqlite").SQLOutputValue>[];
27
55
  }
@@ -1,11 +1,17 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { responseOutcome } from "./response-outcome.js";
3
4
  import { immediateTransaction } from "./memory-database.js";
4
5
  import { jsonHash } from "./json-hash.js";
5
6
  export const RESPONSE_REVIEW_POLICY = "response-review-v2";
7
+ const DECISION_PROVENANCE_COLUMNS = ["cohort", "input_hash", "evidence_hash"];
8
+ function evidenceRevision(cohort, inputHash, detail) {
9
+ return jsonHash([cohort, inputHash, detail]);
10
+ }
6
11
  /** Operator-only tasks, intentionally not exposed as memory-curation agent tools. */
7
12
  export class ResponseReviews {
8
13
  db;
14
+ #provenanceColumnsReady = false;
9
15
  constructor(db) {
10
16
  this.db = db;
11
17
  db.exec(`CREATE TABLE IF NOT EXISTS response_review_tasks (
@@ -24,6 +30,20 @@ export class ResponseReviews {
24
30
  CREATE TABLE IF NOT EXISTS response_annotations (
25
31
  id TEXT PRIMARY KEY, occurred_at INTEGER NOT NULL, kind TEXT NOT NULL, note TEXT NOT NULL);`);
26
32
  }
33
+ #decisionColumns() {
34
+ const rows = this.db.prepare("PRAGMA table_info(response_review_decisions)").all();
35
+ return new Set(rows.map(row => String(row.name)));
36
+ }
37
+ #ensureDecisionProvenanceColumns() {
38
+ if (this.#provenanceColumnsReady)
39
+ return;
40
+ const existing = this.#decisionColumns();
41
+ for (const column of DECISION_PROVENANCE_COLUMNS) {
42
+ if (!existing.has(column)) {
43
+ this.db.exec(`ALTER TABLE response_review_decisions ADD COLUMN ${column} TEXT`);
44
+ }
45
+ }
46
+ }
27
47
  sync(cohort, episodeId, inputHash, result, now) {
28
48
  this.db.prepare(`UPDATE response_review_evidence SET active=-1 WHERE cohort=? AND task_id IN
29
49
  (SELECT id FROM response_review_tasks WHERE episode_id=?)`).run(cohort, episodeId);
@@ -35,8 +55,8 @@ export class ResponseReviews {
35
55
  const agentProbability = agentDirected.reduce((sum, key) => sum + f.target.probabilities[key], 0);
36
56
  const signals = [
37
57
  ...(outcome.status === "reported_shortfall" ? [{ family: "delivery_quality", detail: outcome }] : []),
38
- ...(intensity && intensity.probabilities["2"] + intensity.probabilities["3"] >= 0.8 && agentProbability >= 0.8 &&
39
- ((f.annoyance?.noul ?? 0) >= 0.8 || (f.frustration?.noul ?? 0) >= 0.8) ?
58
+ ...(intensity && intensity.probabilities["2"] + intensity.probabilities["3"] >= DEFAULTS.responseAudit.scoreHigh && agentProbability >= DEFAULTS.responseAudit.scoreHigh &&
59
+ ((f.annoyance?.noul ?? 0) >= DEFAULTS.responseAudit.scoreHigh || (f.frustration?.noul ?? 0) >= DEFAULTS.responseAudit.scoreHigh) ?
40
60
  [{ family: "human_experience", detail: { target: f.target, sentiment: f.sentiment, annoyance: f.annoyance,
41
61
  frustration: f.frustration, intensity } }] : []),
42
62
  ];
@@ -75,25 +95,103 @@ export class ResponseReviews {
75
95
  list(cohort, id) {
76
96
  return this.db.prepare(`SELECT t.*,e.input_hash,e.active,e.detail FROM response_review_tasks t
77
97
  JOIN response_review_evidence e ON e.task_id=t.id WHERE e.cohort=? ${id ? "AND t.id=?" : ""}
78
- ORDER BY t.updated_at DESC,t.id LIMIT 1001`).all(cohort, ...(id ? [id] : [])).map(row => ({
79
- id: String(row.id), episodeId: String(row.episode_id), family: String(row.family), status: String(row.status),
80
- evidenceStatus: row.active === 1 ? "current" : row.active === -1 ? "superseded" : "stale", reviewerKind: row.reviewer_kind,
81
- resolutionNote: row.resolution_note, createdAt: row.created_at, updatedAt: row.updated_at,
82
- evidence: JSON.parse(String(row.detail)),
98
+ ORDER BY t.updated_at DESC,t.id LIMIT 1001`).all(cohort, ...(id ? [id] : [])).map(row => {
99
+ const inputHash = String(row.input_hash);
100
+ const detail = String(row.detail);
101
+ return {
102
+ id: String(row.id), episodeId: String(row.episode_id), family: String(row.family), status: String(row.status),
103
+ cohort, inputHash, evidenceHash: evidenceRevision(cohort, inputHash, detail),
104
+ evidenceStatus: row.active === 1 ? "current" : row.active === -1 ? "superseded" : "stale", reviewerKind: row.reviewer_kind,
105
+ resolutionNote: row.resolution_note, createdAt: row.created_at, updatedAt: row.updated_at,
106
+ evidence: JSON.parse(detail),
107
+ };
108
+ });
109
+ }
110
+ decisions(taskId, cohort) {
111
+ const columns = this.#decisionColumns();
112
+ const hasCohort = columns.has("cohort");
113
+ const hasInputHash = columns.has("input_hash");
114
+ const hasEvidenceHash = columns.has("evidence_hash");
115
+ if (cohort !== undefined && !hasCohort)
116
+ return [];
117
+ const clauses = [];
118
+ const params = [];
119
+ if (taskId !== undefined) {
120
+ clauses.push("task_id=?");
121
+ params.push(taskId);
122
+ }
123
+ if (cohort !== undefined) {
124
+ clauses.push("cohort=?");
125
+ params.push(cohort);
126
+ }
127
+ const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
128
+ const select = [
129
+ "id", "task_id", "status", "reviewer_kind", "note", "decided_at",
130
+ hasCohort ? "cohort" : "NULL AS cohort",
131
+ hasInputHash ? "input_hash" : "NULL AS input_hash",
132
+ hasEvidenceHash ? "evidence_hash" : "NULL AS evidence_hash",
133
+ ].join(",");
134
+ return this.db.prepare(`SELECT ${select} FROM response_review_decisions ${where} ORDER BY decided_at,id`)
135
+ .all(...params)
136
+ .map(row => ({
137
+ id: Number(row.id),
138
+ taskId: String(row.task_id),
139
+ status: String(row.status),
140
+ reviewerKind: String(row.reviewer_kind),
141
+ note: String(row.note),
142
+ decidedAt: Number(row.decided_at),
143
+ cohort: row.cohort === null ? null : String(row.cohort),
144
+ inputHash: row.input_hash === null ? null : String(row.input_hash),
145
+ evidenceHash: row.evidence_hash === null ? null : String(row.evidence_hash),
83
146
  }));
84
147
  }
85
- decide(cohort, id, status, reviewer, note, now = Date.now()) {
148
+ decide(cohort, id, status, reviewer, note, now = Date.now(), options) {
149
+ const trimmedNote = note.trim();
86
150
  if (!["pending", "resolved", "dismissed", "deferred"].includes(status) || !["human", "agent"].includes(reviewer) ||
87
- !note.trim() || note.length > 4000)
151
+ !trimmedNote || note.length > 4000)
88
152
  throw new Error("Invalid response review decision");
89
- if (!this.list(cohort, id).length)
90
- throw new Error("Unknown response review task in current cohort");
91
- immediateTransaction(this.db, () => {
153
+ if (options?.expectedInputHash !== undefined && !options.expectedInputHash.trim()) {
154
+ throw new Error("Invalid expected response review input hash");
155
+ }
156
+ if (options?.expectedEvidenceHash !== undefined && !options.expectedEvidenceHash.trim()) {
157
+ throw new Error("Invalid expected response review evidence hash");
158
+ }
159
+ const recorded = immediateTransaction(this.db, () => {
160
+ const row = this.db.prepare(`SELECT t.episode_id,e.input_hash,e.active,e.detail
161
+ FROM response_review_tasks t
162
+ JOIN response_review_evidence e ON e.task_id=t.id
163
+ WHERE e.cohort=? AND t.id=?`).get(cohort, id);
164
+ if (!row)
165
+ throw new Error("Unknown response review task in current cohort");
166
+ const active = Number(row.active);
167
+ if (active !== 1) {
168
+ const state = active === -1 ? "superseded" : "stale";
169
+ throw new Error(`Cannot decide response review task with ${state} evidence`);
170
+ }
171
+ const inputHash = String(row.input_hash);
172
+ const currentResult = this.db.prepare(`SELECT 1 FROM response_results
173
+ WHERE cohort=? AND id=? AND input_hash=? AND active=1 AND status='ok'`)
174
+ .get(cohort, String(row.episode_id), inputHash);
175
+ if (!currentResult) {
176
+ throw new Error("Cannot decide response review task with stale evidence");
177
+ }
178
+ const evidenceHash = evidenceRevision(cohort, inputHash, String(row.detail));
179
+ if (options?.expectedInputHash !== undefined && options.expectedInputHash !== inputHash) {
180
+ throw new Error("Response review evidence input hash mismatch");
181
+ }
182
+ if (options?.expectedEvidenceHash !== undefined && options.expectedEvidenceHash !== evidenceHash) {
183
+ throw new Error("Response review evidence revision mismatch");
184
+ }
185
+ this.#ensureDecisionProvenanceColumns();
92
186
  this.db.prepare("UPDATE response_review_tasks SET status=?,reviewer_kind=?,resolution_note=?,updated_at=? WHERE id=?")
93
- .run(status, reviewer, note.trim(), now, id);
94
- this.db.prepare("INSERT INTO response_review_decisions(task_id,status,reviewer_kind,note,decided_at) VALUES(?,?,?,?,?)")
95
- .run(id, status, reviewer, note.trim(), now);
187
+ .run(status, reviewer, trimmedNote, now, id);
188
+ this.db.prepare(`INSERT INTO response_review_decisions(task_id,status,reviewer_kind,note,decided_at,cohort,input_hash,evidence_hash)
189
+ VALUES(?,?,?,?,?,?,?,?)`)
190
+ .run(id, status, reviewer, trimmedNote, now, cohort, inputHash, evidenceHash);
191
+ return { taskId: id, status, reviewerKind: reviewer, note: trimmedNote, decidedAt: now, cohort, inputHash, evidenceHash };
96
192
  });
193
+ this.#provenanceColumnsReady = true;
194
+ return recorded;
97
195
  }
98
196
  annotate(occurredAt, kind, note) {
99
197
  if (!Number.isFinite(occurredAt) || !["model", "prompt", "deployment", "other"].includes(kind) || !note.trim() || note.length > 4000)
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { hasMemoryTable, MEMORY_DATABASE } from "./memory-database.js";
2
3
  import { join } from "node:path";
3
4
  import { resolveAgentWorkspaceDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
@@ -22,6 +23,7 @@ export function registerResponseAudit(api, config) {
22
23
  .filter(c => config.responseAudit.memoryCorpora.includes(c.name))) };
23
24
  };
24
25
  api.registerCli(({ program, config: cfg }) => {
26
+ const cohort = () => responseCohort(config.responseAudit, config.decisionModel.model, config.decisionModel.endpoint);
25
27
  const root = program.command("memory-responses").description("Operator-only response quality audits and evidence-linked trend reports");
26
28
  root.command("audit").option("--agent <id>", "Agent id", "main").option("--dry-run", "Preview bounded coverage without inference or audit writes")
27
29
  .action(async (opts) => {
@@ -36,6 +38,8 @@ export function registerResponseAudit(api, config) {
36
38
  .option("--account <scope>", "Provider account scope; requires --sender").option("--person <id>", "Linked people-store person ID")
37
39
  .option("--task-type <type>", "Task classification").option("--model <id>", "Agent model")
38
40
  .action((opts) => {
41
+ if (opts.bucket !== "day" && opts.bucket !== "week")
42
+ throw new Error("Bucket must be day or week");
39
43
  if (!config.responseAudit.enabled) {
40
44
  console.log(JSON.stringify({ status: "disabled" }));
41
45
  return;
@@ -46,12 +50,8 @@ export function registerResponseAudit(api, config) {
46
50
  return;
47
51
  }
48
52
  const store = new ResponseAuditStore(storePath);
49
- if (opts.bucket !== "day" && opts.bucket !== "week") {
50
- store.close();
51
- throw new Error("Bucket must be day or week");
52
- }
53
53
  try {
54
- console.log(JSON.stringify(store.report(responseCohort(config.responseAudit), dateOption(opts.since, Date.now() - config.responseAudit.lookbackDays * 86400_000), opts.episode, { until: dateOption(opts.until, Number.MAX_SAFE_INTEGER), bucket: opts.bucket, senderId: opts.sender,
54
+ console.log(JSON.stringify(store.report(cohort(), dateOption(opts.since, Date.now() - config.responseAudit.lookbackDays * 86400_000), opts.episode, { until: dateOption(opts.until, Number.MAX_SAFE_INTEGER), bucket: opts.bucket, senderId: opts.sender,
55
55
  accountScope: opts.account, personId: opts.person, taskType: opts.taskType, agentModel: opts.model }), null, 2));
56
56
  }
57
57
  finally {
@@ -66,7 +66,7 @@ export function registerResponseAudit(api, config) {
66
66
  throw new Error("Response audit has not run");
67
67
  const store = new ResponseAuditStore(storePath);
68
68
  try {
69
- console.log(JSON.stringify(fn(store, responseCohort(config.responseAudit)), null, 2));
69
+ console.log(JSON.stringify(fn(store, cohort()), null, 2));
70
70
  }
71
71
  finally {
72
72
  store.close();
@@ -81,9 +81,10 @@ export function registerResponseAudit(api, config) {
81
81
  root.command("review").requiredOption("--id <id>", "Task ID").requiredOption("--status <status>", "pending, resolved, dismissed or deferred")
82
82
  .requiredOption("--reviewer <kind>", "human or agent: provenance, not an authorization grant")
83
83
  .requiredOption("--note <text>", "Evidence-based decision; no automatic whisperer write")
84
+ .requiredOption("--evidence-hash <hash>", "Evidence hash returned by memory-responses tasks")
84
85
  .option("--agent <id>", "Agent id", "main")
85
86
  .action((opts) => withStore(opts.agent, (store, cohort) => {
86
- store.reviews.decide(cohort, opts.id, opts.status, opts.reviewer, opts.note);
87
+ store.reviews.decide(cohort, opts.id, opts.status, opts.reviewer, opts.note, undefined, { expectedEvidenceHash: opts.evidenceHash });
87
88
  return store.reviews.list(cohort, opts.id);
88
89
  }));
89
90
  root.command("annotate").option("--agent <id>", "Agent id", "main").requiredOption("--date <date>", "UTC date YYYY-MM-DD")
@@ -93,7 +94,7 @@ export function registerResponseAudit(api, config) {
93
94
  .option("--agent <id>", "Agent id", "main")
94
95
  .action((opts) => withStore(opts.agent, (store, cohort) => store.retryFailed(cohort)));
95
96
  }, { descriptors: [{ name: "memory-responses", description: "Audit human-agent exchanges and report quality signals", hasSubcommands: true }] });
96
- if (api.registrationMode === "cli-metadata" || !config.responseAudit.enabled || !config.typesafe.enabled || !config.responseAudit.intervalMinutes)
97
+ if (api.registrationMode === "cli-metadata" || !config.responseAudit.enabled || !config.decisionModel.enabled || !config.responseAudit.intervalMinutes)
97
98
  return;
98
99
  let timer, running, lifetime = new AbortController();
99
100
  const tick = () => {
@@ -130,7 +131,7 @@ export function registerResponseAudit(api, config) {
130
131
  clearInterval(timer);
131
132
  lifetime = new AbortController();
132
133
  // A minute poll honors durable due times without relying on process uptime.
133
- timer = setInterval(tick, 60_000);
134
+ timer = setInterval(tick, DEFAULTS.responseAudit.pollIntervalMs);
134
135
  timer.unref();
135
136
  tick(); // New schedules wait one interval; overdue schedules get one bounded attempt.
136
137
  });
@@ -1,79 +1,76 @@
1
1
  import type { ResponseEpisode } from "./response-episodes.js";
2
+ import { type ResponseJudgeParams } from "./response-judge.js";
2
3
  import type { ResponseAuditStore } from "./response-store.js";
3
- export declare function assessResponseStages(store: ResponseAuditStore, cohort: string, e: ResponseEpisode, params: {
4
- apiKey: string;
5
- timeoutMs: number;
6
- signal: AbortSignal;
7
- }, sentimentEnabled: boolean, usage: {
4
+ export declare function assessResponseStages(store: ResponseAuditStore, cohort: string, e: ResponseEpisode, params: ResponseJudgeParams, sentimentEnabled: boolean, usage: {
8
5
  stageAttempts: number;
9
6
  stageCacheHits: number;
10
7
  }): Promise<{
11
8
  retrospective: {
12
9
  status: ResponseEpisode["followup"]["status"];
13
- judgment: import("typebox").Static<import("typebox").TObject<{
14
- answers: import("typebox").TObject<{
15
- correction: import("typebox").TObject<{
16
- type: import("typebox").TLiteral<"noul">;
17
- noul: import("typebox").TNumber;
18
- }>;
19
- deliveryAdmission: import("typebox").TObject<{
20
- type: import("typebox").TLiteral<"noul">;
21
- noul: import("typebox").TNumber;
22
- }>;
23
- regression: import("typebox").TObject<{
24
- type: import("typebox").TLiteral<"noul">;
25
- noul: import("typebox").TNumber;
26
- }>;
27
- scopeClarification: import("typebox").TObject<{
28
- type: import("typebox").TLiteral<"noul">;
29
- noul: import("typebox").TNumber;
30
- }>;
31
- outcome: import("typebox").TObject<{
32
- type: import("typebox").TLiteral<"choice">;
33
- choice: import("typebox").TEnum<("unknown" | "reported_shortfall" | "acknowledged_success")[]>;
34
- confidence: import("typebox").TNumber;
35
- probabilities: import("typebox").TObject<{
36
- [k: string]: import("typebox").TNumber;
37
- }>;
38
- }>;
39
- reason: import("typebox").TObject<{
40
- type: import("typebox").TLiteral<"choice">;
41
- choice: import("typebox").TEnum<("none_or_unclear" | "missing_requested_work" | "unnecessary_deferral" | "regression" | "incorrect_claim" | "wrong_scope" | "failed_delivery")[]>;
42
- confidence: import("typebox").TNumber;
43
- probabilities: import("typebox").TObject<{
44
- [k: string]: import("typebox").TNumber;
45
- }>;
46
- }>;
47
- }>;
48
- }>>["answers"] | null;
10
+ judgment: {
11
+ reason: {
12
+ type: "choice";
13
+ choice: "none_or_unclear" | "missing_requested_work" | "unnecessary_deferral" | "regression" | "incorrect_claim" | "wrong_scope" | "failed_delivery";
14
+ probabilities: {
15
+ [x: string]: number;
16
+ [x: number]: number;
17
+ };
18
+ confidence: number;
19
+ };
20
+ outcome: {
21
+ type: "choice";
22
+ choice: "unknown" | "reported_shortfall" | "acknowledged_success";
23
+ probabilities: {
24
+ [x: string]: number;
25
+ [x: number]: number;
26
+ };
27
+ confidence: number;
28
+ };
29
+ correction: {
30
+ type: "noul";
31
+ noul: number;
32
+ };
33
+ deliveryAdmission: {
34
+ type: "noul";
35
+ noul: number;
36
+ };
37
+ regression: {
38
+ type: "noul";
39
+ noul: number;
40
+ };
41
+ scopeClarification: {
42
+ type: "noul";
43
+ noul: number;
44
+ };
45
+ } | null;
49
46
  };
50
47
  quality: {
51
48
  taskType: {
52
49
  type: "choice";
53
- confidence: number;
54
- choice: "action" | "question" | "other" | "artifact" | "discussion";
50
+ choice: "question" | "action" | "other" | "artifact" | "discussion";
55
51
  probabilities: {
56
52
  [x: string]: number;
57
53
  [x: number]: number;
58
54
  };
55
+ confidence: number;
59
56
  };
60
57
  assessability: {
61
58
  type: "choice";
62
- confidence: number;
63
59
  choice: "assessable" | "not_assessable";
64
60
  probabilities: {
65
61
  [x: string]: number;
66
62
  [x: number]: number;
67
63
  };
64
+ confidence: number;
68
65
  };
69
66
  fitAssessability: {
70
67
  type: "choice";
71
- confidence: number;
72
68
  choice: "assessable" | "not_assessable";
73
69
  probabilities: {
74
70
  [x: string]: number;
75
71
  [x: number]: number;
76
72
  };
73
+ confidence: number;
77
74
  };
78
75
  underdelivery: {
79
76
  type: "noul";
@@ -81,63 +78,63 @@ export declare function assessResponseStages(store: ResponseAuditStore, cohort:
81
78
  };
82
79
  failureReason: {
83
80
  type: "choice";
84
- confidence: number;
85
81
  choice: "none_or_unclear" | "missing_requested_work" | "wrong_deliverable" | "missed_constraint" | "insufficient_answer_depth" | "unnecessary_deferral";
86
82
  probabilities: {
87
83
  [x: string]: number;
88
84
  [x: number]: number;
89
85
  };
86
+ confidence: number;
90
87
  };
91
88
  fulfillment: {
92
89
  type: "score";
93
- confidence: number;
94
90
  probabilities: {
95
91
  "0": number;
96
92
  "1": number;
97
93
  "2": number;
98
94
  "3": number;
99
95
  };
96
+ confidence: number;
100
97
  score: number;
101
98
  };
102
99
  deliverableFit: {
103
100
  type: "score";
104
- confidence: number;
105
101
  probabilities: {
106
102
  "0": number;
107
103
  "1": number;
108
104
  "2": number;
109
105
  "3": number;
110
106
  };
107
+ confidence: number;
111
108
  score: number;
112
109
  };
113
110
  consistency: {
114
111
  type: "choice";
115
- confidence: number;
116
112
  choice: "contradicted" | "not_assessable" | "consistent";
117
113
  probabilities: {
118
114
  [x: string]: number;
119
115
  [x: number]: number;
120
116
  };
117
+ confidence: number;
121
118
  };
122
119
  };
123
120
  feedback: {
124
121
  target: {
125
122
  type: "choice";
126
- confidence: number;
127
123
  choice: "delivery" | "mixed" | "unclear" | "current_answer" | "earlier_behavior" | "proactive_action" | "external" | "new_work";
128
124
  probabilities: {
129
125
  [x: string]: number;
130
126
  [x: number]: number;
131
127
  };
128
+ confidence: number;
132
129
  };
133
130
  feedbackType: {
134
131
  type: "choice";
135
- confidence: number;
136
132
  choice: "mixed" | "unrelated" | "unclear" | "acceptance" | "correction" | "continuation";
137
133
  probabilities: {
138
134
  [x: string]: number;
139
135
  [x: number]: number;
140
136
  };
137
+ confidence: number;
141
138
  };
142
139
  avoidableRework: {
143
140
  type: "noul";
@@ -154,12 +151,12 @@ export declare function assessResponseStages(store: ResponseAuditStore, cohort:
154
151
  } & Partial<{
155
152
  sentiment: {
156
153
  type: "choice";
157
- confidence: number;
158
154
  choice: "satisfied" | "dissatisfied" | "mixed" | "neutral" | "unrelated" | "unclear";
159
155
  probabilities: {
160
156
  [x: string]: number;
161
157
  [x: number]: number;
162
158
  };
159
+ confidence: number;
163
160
  };
164
161
  annoyance: {
165
162
  type: "noul";
@@ -171,13 +168,13 @@ export declare function assessResponseStages(store: ResponseAuditStore, cohort:
171
168
  };
172
169
  dissatisfactionIntensity: {
173
170
  type: "score";
174
- confidence: number;
175
171
  probabilities: {
176
172
  "0": number;
177
173
  "1": number;
178
174
  "2": number;
179
175
  "3": number;
180
176
  };
177
+ confidence: number;
181
178
  score: number;
182
179
  };
183
180
  }>;
@@ -1,13 +1,19 @@
1
1
  import { RESPONSE_EXTRACTOR_VERSION } from "./response-episodes.js";
2
- import { judgeResponse, judgeResponseFollowup, RESPONSE_STAGE_VERSIONS } from "./response-judge.js";
3
- import { TYPESAFE_MODEL } from "./typesafe-client.js";
2
+ import { judgeResponse, judgeResponseFollowup, RESPONSE_STAGE_VERSIONS, } from "./response-judge.js";
3
+ import { decisionModelScope, DEFAULT_DECISION_MODEL } from "./decision-client.js";
4
4
  import { jsonHash } from "./json-hash.js";
5
5
  export async function assessResponseStages(store, cohort, e, params, sentimentEnabled, usage) {
6
+ const scope = decisionModelScope(params.model ?? DEFAULT_DECISION_MODEL, params.endpoint);
6
7
  const original = { before: e.before, request: e.request, answer: e.answer, contextLimited: e.contextLimited };
7
8
  const feedback = { ...original, feedback: e.feedback };
8
- const evidence = { quality: original, feedback, sentiment: feedback, retrospective: { ...feedback, followup: e.followup } };
9
+ const evidence = {
10
+ quality: original,
11
+ feedback,
12
+ sentiment: feedback,
13
+ retrospective: { ...feedback, followup: e.followup },
14
+ };
9
15
  const keys = Object.fromEntries(Object.keys(evidence).map(stage => [stage,
10
- jsonHash([RESPONSE_EXTRACTOR_VERSION, TYPESAFE_MODEL, RESPONSE_STAGE_VERSIONS[stage],
16
+ jsonHash([RESPONSE_EXTRACTOR_VERSION, scope, RESPONSE_STAGE_VERSIONS[stage],
11
17
  e.id, e.session, e.senderId, e.thread, evidence[stage]]),
12
18
  ]));
13
19
  const cache = {
@@ -1,5 +1,5 @@
1
1
  import type { ResponseEpisode } from "./response-episodes.js";
2
- import type { ResponseJudgment, ResponseStages, judgeMemoryOpportunity, judgeResponseFollowup } from "./response-judge.js";
2
+ import { type ResponseJudgment, type ResponseStageContracts, type ResponseStages, type judgeMemoryOpportunity, type judgeResponseFollowup } from "./response-judge.js";
3
3
  import { responseOutcome } from "./response-outcome.js";
4
4
  import type { ResponseHuman } from "./response-identity.js";
5
5
  import { ResponseReviews } from "./response-reviews.js";
@@ -43,6 +43,7 @@ export declare class ResponseAuditStore {
43
43
  activeSessions(cohort: string, since: number): string[];
44
44
  observe(cohort: string, sessionId: string, episodes: readonly ResponseEpisode[]): void;
45
45
  needsJudgment(cohort: string, e: ResponseEpisode, now: number): boolean;
46
+ memoryRetryResult(cohort: string, e: ResponseEpisode): ResponseResult | undefined;
46
47
  attempted(cohort: string, e: ResponseEpisode, now: number): void;
47
48
  stale(cohort: string, e: ResponseEpisode): void;
48
49
  save(cohort: string, e: ResponseEpisode, result: ResponseResult, now: number): void;
@@ -61,12 +62,12 @@ export declare class ResponseAuditStore {
61
62
  pendingWork(cohort: string, since: number, now: number): number;
62
63
  /** Retry eligibility is not completion: include backoff and exhausted work. */
63
64
  unresolvedWork(cohort: string, since: number, until: number): number;
64
- stage<K extends keyof ResponseStages>(cohort: string, e: ResponseEpisode, stage: K, key: string): ResponseStages[K] | undefined;
65
+ stage<K extends keyof ResponseStages>(cohort: string, e: ResponseEpisode, stage: K, key: string, contract?: ResponseStageContracts[K]): ResponseStages[K] | undefined;
65
66
  stageBegin(keys: string[], now: number): void;
66
67
  stageSave<K extends keyof ResponseStages>(key: string, result: ResponseStages[K], now: number): void;
67
68
  retryFailed(cohort: string): {
68
- stages: number | bigint;
69
- episodes: number | bigint;
69
+ stages: number;
70
+ episodes: number;
70
71
  };
71
72
  scan(cohort: string, coverage: object, now: number): void;
72
73
  report(cohort: string, since: number, id?: string, options?: ResponseReportOptions): {
@@ -166,8 +167,8 @@ export declare class ResponseAuditStore {
166
167
  beforeCoverage: number;
167
168
  afterCoverage: number;
168
169
  coverageChanged: boolean;
169
- denominator: string;
170
- scale: string;
170
+ denominator: "confident_assessable_exchanges" | "all_evaluated_exchanges" | "sentiment_assessed_exchanges" | "emotion_assessed_exchanges" | "confident_intensity_exchanges";
171
+ scale: "0_to_3_visible_quality" | "0_to_1_observed_rate" | "0_to_3_expressed_dissatisfaction";
171
172
  delta: number | null;
172
173
  }[];
173
174
  examples: {