@unblocklabs/unblock-memory 0.3.15 → 0.3.16

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.
package/README.md CHANGED
@@ -1,5 +1,203 @@
1
1
  # Unblock Memory
2
2
 
3
+ ## Response quality tracking (opt-in)
4
+
5
+ `responseAudit` evaluates bounded human-agent exchanges in the background. It is
6
+ separate from chunk-quality auditing and never changes memories or prompts. It
7
+ creates private response-review tasks, not memory-curation tasks.
8
+ Its primary purpose is tracking delivery quality over time: visible fulfillment,
9
+ deliverable fit, clear underdelivery and its observable reason. Memory gaps are only
10
+ an optional diagnostic lead, not a proxy for performance.
11
+ Only approved Slack sender IDs with trusted `senderKind: human` or owner metadata
12
+ qualify (older Slack records use unknown senderKind even for known owners).
13
+ Explicit bots, unverified identities, internal messages, other senders and thread changes form
14
+ hard boundaries. Synthetic delivery mirrors and gateway-injected answers are excluded.
15
+ Assistant progress messages are grouped with the terminal answer.
16
+ Recognized Slack envelopes are stripped even inside `upstreamUserText`; embedded
17
+ history is not treated as current human text. Ambiguous envelopes are excluded.
18
+ Removed history marks the context as limited; ordinary Markdown/JSON is preserved.
19
+ Human feedback closes when the next assistant turn starts. Still-open feedback,
20
+ no-response exchanges, incomplete/failed turns and oversized inputs are not graded.
21
+
22
+ ```json
23
+ {
24
+ "responseAudit": {
25
+ "enabled": true,
26
+ "sentimentEnabled": true,
27
+ "senderIds": ["YOUR_SLACK_USER_ID"],
28
+ "chatTypes": ["direct"],
29
+ "historyMessages": 6,
30
+ "lookbackDays": 30,
31
+ "maxEpisodes": 20,
32
+ "intervalMinutes": 60,
33
+ "memoryCorpora": ["memory", "knowledge"]
34
+ }
35
+ }
36
+ ```
37
+
38
+ This is explicit approval to send those exchanges to TypeSafe. Sender IDs apply
39
+ across the agent's Slack accounts; use only identities approved in all such accounts.
40
+ `memoryCorpora` is optional and separately approves configured **file** corpora for
41
+ memory-gap investigation. Leave it empty to send no indexed memory evidence.
42
+ `typesafe.enabled: false` or missing credentials prevents evaluation. An interval
43
+ of zero means manual-only. Defaults are disabled, no approved senders, direct chats,
44
+ 6 preceding visible messages, 30 days, 20 episodes per run and a 60-minute interval.
45
+ `sentimentEnabled` defaults to **true within that opt-in audit**; it does not bypass
46
+ approved senders or TypeSafe credentials. Set it false to omit polarity, annoyance,
47
+ frustration and intensity questions while retaining quality/repair judgments.
48
+ `intervalMinutes` controls their shared cadence; no second sentiment timer is needed.
49
+ The Gateway checks a durable per-agent due time on startup and every minute (no
50
+ agent-turn cron or separate launchd job). First enablement waits one interval;
51
+ restarts preserve the due time and an overdue schedule gets one bounded catch-up,
52
+ not one run per missed interval. Each attempt advances the due time before work,
53
+ including missing-key skips, failures or interrupted runs, to prevent retry storms.
54
+ Changing the interval recalculates the due time from the last scheduled attempt
55
+ (or initial enablement). The Gateway must be running; manual audits do not change
56
+ the automatic schedule. Missing/unreadable credentials skip all quality and sentiment
57
+ inference without failing Gateway startup or normal memory functionality.
58
+ Changing the interval does not invalidate cached results. Changing the sentiment
59
+ toggle selects a separate reporting cohort, so older missing sentiment is not
60
+ treated as neutral; unchanged quality/feedback stages are reused across the toggle.
61
+
62
+ Operator commands (not agent tools):
63
+
64
+ ```sh
65
+ openclaw memory-responses audit --agent main --dry-run
66
+ openclaw memory-responses audit --agent main
67
+ openclaw memory-responses report --agent main
68
+ openclaw memory-responses report --agent main --episode EPISODE_ID
69
+ openclaw memory-responses report --agent main --sender SLACK_USER_ID --account ACCOUNT_SCOPE --bucket day --since 2026-09-01 --until 2026-10-01
70
+ openclaw memory-responses report --agent main --person PERSON_ID
71
+ openclaw memory-responses tasks --agent main
72
+ openclaw memory-responses review --agent main --id TASK_ID --status deferred --reviewer human --note "Review the linked exchanges before changing preferences"
73
+ openclaw memory-responses annotate --agent main --date 2026-09-18 --kind prompt --note "Known prompt revision deployed"
74
+ openclaw memory-responses retry-failed --agent main
75
+ ```
76
+
77
+ Reports group by scoped human identity as well as task/model/time. Names are not
78
+ identity keys. Existing active people-store links are resolved read-only at assessment
79
+ time; missing links do not prevent analysis. Unknown account scopes stay isolated
80
+ per session. No new identity fields are sent to TypeSafe. Date ranges are UTC with
81
+ an inclusive start and exclusive end. `periodStart` identifies a day/week bucket;
82
+ legacy `week`/`fromWeek`/`toWeek` fields remain aliases. `--task-type` and `--model`
83
+ further narrow comparisons. Human-specific scores are not rankings of the humans:
84
+ task difficulty, feedback habits and selection bias remain important.
85
+
86
+ Session checkpoints hash bounded active source bytes; unchanged sessions skip
87
+ extraction and all inference. Changed sessions are re-extracted within the existing
88
+ budget, then stage hashes reuse unchanged quality, feedback, sentiment and later
89
+ evidence judgments. Only hashes/counts are checkpointed, never a transcript copy.
90
+ A persisted cursor rotates through discovery and tracked-session reconciliation;
91
+ `deferredByLimit` includes known backlog and a lower-bound marker for unvisited
92
+ sessions. `stages` exposes pending/failed/succeeded counts and exhausted retries
93
+ for the cohort/date range, before person filters. `retry-failed` only resets failed
94
+ work; successful stages remain cached. Source freshness is checked before activation.
95
+
96
+ Review tasks distinguish concrete delivery shortfalls from high-intensity human
97
+ experience complaints. Stable task keys include exchange, scoped human and issue
98
+ family. Decisions survive rescoring; stale source evidence and superseded findings
99
+ are labeled separately. Review status/provenance never changes the raw judgments.
100
+ Tasks and change annotations are operator-only and stay out of memory/whisperer
101
+ prompts. `--reviewer` records human/agent provenance, not authentication or a new
102
+ permission grant. Task lists disclose their 1,000-item cap. There are no automatic
103
+ dossier updates: review the evidence and approve any concrete preference separately.
104
+ Old cohorts remain stored; the first staged-cohort run does not silently import
105
+ unverified older rubric judgments. Audit-history retention is not automatic.
106
+
107
+ Two separate TypeSafe requests prevent human feedback from influencing the original
108
+ fulfillment/deliverable-fit grade. The feedback pass distinguishes acceptance,
109
+ correction, continuation, unrelated replies, expressed sentiment, repeated constraints
110
+ and avoidable rework. Current-index memory investigation runs only for a strong
111
+ memory-gap signal: lexical retrieval selects up to three whole short documents from
112
+ approved collections. This is an investigation lead, **not proof of historical
113
+ availability, factual truth, or agent fault**. Tool-call counts do not establish what
114
+ the model saw or whether it should have searched. Unseen artifacts are unassessable.
115
+
116
+ Deliverable kind/format/scope has its own assessability gate, independent of whether
117
+ execution or external facts can be verified. Feedback attribution distinguishes the
118
+ current answer, earlier behavior, delivery, missing proactive action, external events,
119
+ new work and mixed/unclear targets. A reported forgotten instruction does not prove
120
+ searchable memory existed. A third, separate request examines the original exchange,
121
+ human feedback and available next assistant block for specific reported shortfalls,
122
+ acknowledgment, explicit factual corrections, delivery failures and regressions. These are
123
+ retrospective signals, not independently verified facts and never inputs to the
124
+ original grade. Clean text preceding a synthetic error/delivery notice can be assessed
125
+ as **partial** evidence; the notice itself is excluded and no successful completion
126
+ is inferred. Later evidence is capped at six messages/12K characters; incomplete,
127
+ unsafe or oversized blocks stay explicitly pending/unavailable/oversized. New later
128
+ evidence changes the input hash; only changed assessment stages are re-evaluated,
129
+ within normal audit budgets. Successful stages survive failures in later stages.
130
+ When the next block is unavailable, the third pass uses only the original exchange
131
+ and feedback; it cannot infer a missing delivery from missing later evidence.
132
+
133
+ Code combines narrow, confident evidence into an **observed outcome**, preserving
134
+ its basis and reason. A concrete original-answer shortfall or later admission takes
135
+ precedence over praise. Broad reported failures are used only when they do not
136
+ depend on a newly introduced requirement. Accurate explanations of earlier mistakes,
137
+ ordinary follow-ups, necessary clarification and unseen work are not automatically
138
+ failures. Sentiment and earlier-workflow complaints remain separate review signals.
139
+ Sentiment includes independent annoyance and frustration yes-probabilities (both
140
+ can apply), plus an expressed-dissatisfaction intensity score from 0 to 3. Intensity
141
+ means no expressed displeasure / restrained displeasure / pointed complaint /
142
+ explicit rejection or loss of trust. It is **not confidence or failure severity**.
143
+ External frustration, brevity and factual corrections alone do not establish
144
+ annoyance or frustration; mixed praise and complaints can still carry both signals.
145
+ Weekly reports show dissatisfaction, annoyance and frustration rates, intensity
146
+ means, unknown counts and their own assessment denominators. Unassessed results
147
+ are never counted as neutral. Sentiment deltas require 20 samples in both periods
148
+ and matching assessment coverage; they remain descriptive, not causal evidence.
149
+ Outcome, evidence basis and failure reasons remain distinct: a correction does not
150
+ automatically mean `incorrect_claim`. Confident reason judgments and direct
151
+ delivery/regression admissions supply reasons; otherwise `reasonStatus` is
152
+ `uncertain`. `reasonDetails` retain each label's source and strength, distinguishing
153
+ Choice confidence from Noul yes-probability. Multiple supported reasons can coexist.
154
+ `reportVersion` identifies composition/reporting semantics independently of the
155
+ judge rubric, allowing cached judgments to be re-reported without re-inference.
156
+
157
+ Results live in the agent's private `unblock-memory/response-audit.sqlite`, outside
158
+ the memory index. It stores judgments and source event references/hashes, not copies
159
+ of conversations. Identical successful inputs are cached; source rewrites invalidate
160
+ in-scope results on the next scan. Reports partition by fixed judge/rubric/context
161
+ configuration, UTC week, task type and agent model. They expose eligible/assessed
162
+ counts, excluded cases, confidence-qualified score means with per-dimension denominators, rework rates with Wilson
163
+ intervals, and evidence IDs. Small groups (<20) are marked explicitly. Confidence
164
+ thresholds are provisional, not calibrated guarantees. Human-reviewed evaluation
165
+ data is still needed before drawing performance conclusions.
166
+ Reports include dated clear-underdelivery examples and reason counts. Descriptive
167
+ score deltas compare successive available UTC weeks within the same task type,
168
+ agent model and rubric/configuration, with at least 20 confident scores per dimension
169
+ in each period and unchanged scored coverage; changed coverage withholds the score
170
+ delta. Outcome trends show acknowledgment, reported-shortfall and unknown rates
171
+ against **all evaluated exchanges**, with at least 20 evaluated exchanges per period.
172
+ Read the three rates together: fewer acknowledgments can mean more unknowns, not
173
+ more failures. Every delta includes before/after values, sample counts, denominator
174
+ and coverage-change flags. Unknown task types/models cannot produce deltas. These
175
+ are not statistical change-point detections or proof of causality; model/version
176
+ changes remain visible as separate groups rather than silently mixing cohorts.
177
+ The legacy `observedSuccessRate` group field remains acknowledgment / known outcomes
178
+ for compatibility, but is not used for trends. Unknowns are never successes.
179
+ Coverage changes and threshold variability can move rates; acknowledgment is not
180
+ factual verification. Week buckets
181
+ may be partial, and several exchanges in one session are not independent. Wilson
182
+ intervals are descriptive, not calibrated confidence about overall agent ability.
183
+
184
+ Each run selects at most 100 recent sessions for inference, each at most 2,000 active events/2M
185
+ characters; episodes must fit 24K characters and six feedback messages without
186
+ truncating the answer. Coverage counts describe the scanned sessions; only episodes
187
+ within `lookbackDays` are judged. Caps, failures and no-feedback cases remain visible.
188
+ Saved sessions in the report window are also reconciled independently of that
189
+ selection, so removing an entire active branch retires its scores. Oversized saved
190
+ sessions defer reconciliation rather than being treated as deleted; the report
191
+ exposes `reconciledSessions` and `reconciliationDeferred`. All reconciliation shares
192
+ the run deadline. Freshness checks compare the assessed episode, not unrelated
193
+ later session activity. Actual snapshot races do not exhaust provider retries.
194
+ The whole run has a two-minute deadline, at most three provider attempts per input (ten-minute
195
+ backoff), and a cross-process lease. Scheduling never starts inference on the agent
196
+ turn path or boots a QMD manager. No model downloads or source re-indexing occur.
197
+ The report is observational: different task mixes, selective human replies and judge
198
+ changes can produce apparent trends. It does not automatically declare regressions,
199
+ rewrite prompts, or treat silence as success.
200
+
3
201
  ## Review and diagnostics
4
202
 
5
203
  - `memory_diagnostics` reports credential **availability only**, per-agent process-local
@@ -1,3 +1,4 @@
1
+ import { type ResponseAuditConfig } from "./response-config.js";
1
2
  export type FileCorpusConfig = {
2
3
  name: string;
3
4
  kind: "files";
@@ -40,6 +41,7 @@ export type UnblockMemoryConfig = {
40
41
  enabled: boolean;
41
42
  corpora: readonly string[];
42
43
  };
44
+ responseAudit: ResponseAuditConfig;
43
45
  people: {
44
46
  enabled: boolean;
45
47
  whisperer: {
@@ -1,4 +1,5 @@
1
1
  import { isAbsolute } from "node:path";
2
+ import { resolveResponseAudit } from "./response-config.js";
2
3
  const DEFAULT_PATHS = ["MEMORY.md", "USER.md", "memory/**/*.md"];
3
4
  const DEFAULT_SESSION_MAX_EXPANDED_TOKENS = 500;
4
5
  const MAX_SESSION_MAX_EXPANDED_TOKENS = 10_000;
@@ -262,6 +263,7 @@ export function resolveConfig(value) {
262
263
  typesafe: { ...DEFAULT_TYPESAFE_CONFIG },
263
264
  qualityAudit: { ...DEFAULT_QUALITY_AUDIT },
264
265
  evidenceReview: { enabled: false, corpora: [] },
266
+ responseAudit: resolveResponseAudit(undefined, DEFAULT_CORPORA),
265
267
  people: DEFAULT_PEOPLE_CONFIG,
266
268
  skillWhisperer: DEFAULT_SKILL_WHISPERER,
267
269
  memoryWhisperer: { ...DEFAULT_MEMORY_WHISPERER },
@@ -271,7 +273,7 @@ export function resolveConfig(value) {
271
273
  throw new Error("unblock-memory config must be an object");
272
274
  }
273
275
  const config = value;
274
- assertOnlyKeys(config, ["corpora", "keepEmbeddingModelWarm", "analysis", "people", "skillWhisperer", "memoryWhisperer", "typesafe", "qualityAudit", "evidenceReview"], "config");
276
+ assertOnlyKeys(config, ["corpora", "keepEmbeddingModelWarm", "analysis", "people", "skillWhisperer", "memoryWhisperer", "typesafe", "qualityAudit", "evidenceReview", "responseAudit"], "config");
275
277
  const corpora = resolveCorpora(config.corpora);
276
278
  const people = resolvePeople(config.people);
277
279
  let evidenceReview = { enabled: false, corpora: [] };
@@ -347,5 +349,6 @@ export function resolveConfig(value) {
347
349
  return { corpora, keepEmbeddingModelWarm, analysis: analysisConfig, people, skillWhisperer,
348
350
  qualityAudit: resolveQualityAudit(config.qualityAudit, corpora),
349
351
  evidenceReview,
352
+ responseAudit: resolveResponseAudit(config.responseAudit, corpora),
350
353
  memoryWhisperer: resolveMemoryWhisperer(config.memoryWhisperer, corpora), typesafe: resolveTypeSafe(config.typesafe) };
351
354
  }
@@ -12,6 +12,7 @@ import { registerMemoryWhisperer } from "./memory-whisperer.js";
12
12
  import { getContext } from "./tool-context.js";
13
13
  import { WhispererDiagnostics } from "./diagnostics.js";
14
14
  import { registerReviewTools } from "./review-tools.js";
15
+ import { registerResponseAudit } from "./response-runtime.js";
15
16
  const searchParameters = Type.Object({
16
17
  query: Type.String({ pattern: "\\S" }),
17
18
  corpora: Type.Optional(Type.Array(Type.String({ pattern: "\\S" }), { minItems: 1 })),
@@ -413,6 +414,7 @@ export function resolveFlushPlan(params = {}) {
413
414
  }
414
415
  export function registerUnblockMemory(api) {
415
416
  const config = resolveConfig(api.pluginConfig);
417
+ registerResponseAudit(api, config);
416
418
  if (api.registrationMode === "cli-metadata")
417
419
  return;
418
420
  const runtime = new QmdMemoryRuntime(config.corpora, {
@@ -0,0 +1,87 @@
1
+ import type { UnblockMemoryConfig } from "./config.js";
2
+ import type { ResolvedSource } from "./sources.js";
3
+ export declare function responseCohort(config: UnblockMemoryConfig["responseAudit"]): string;
4
+ export type ResponseAuditOptions = {
5
+ agentId: string;
6
+ databasePath: string;
7
+ storePath: string;
8
+ indexPath: string;
9
+ config: UnblockMemoryConfig;
10
+ sources: readonly ResolvedSource[];
11
+ signal?: AbortSignal;
12
+ dryRun?: boolean;
13
+ peoplePath?: string;
14
+ };
15
+ /** All inference is outside memory's mutation queue and outside transcript DB transactions. */
16
+ export declare function auditResponses(options: ResponseAuditOptions): Promise<{
17
+ status: "disabled";
18
+ reason?: undefined;
19
+ cohort?: undefined;
20
+ coverage?: undefined;
21
+ } | {
22
+ status: "unavailable";
23
+ reason: string;
24
+ cohort?: undefined;
25
+ coverage?: undefined;
26
+ } | {
27
+ status: "already_running";
28
+ reason?: undefined;
29
+ cohort?: undefined;
30
+ coverage?: undefined;
31
+ } | {
32
+ status: "ok" | "dry_run";
33
+ cohort: string;
34
+ coverage: {
35
+ sessions: number;
36
+ sessionLimitReached: boolean;
37
+ sessionsOverBudget: number;
38
+ completedResponses: number;
39
+ reconciledSessions: number;
40
+ reconciliationDeferred: number;
41
+ extractedSessions: number;
42
+ unchangedSessions: number;
43
+ stageAttempts: number;
44
+ stageCacheHits: number;
45
+ eligible: number;
46
+ noFeedback: number;
47
+ pendingFeedback: number;
48
+ oversized: number;
49
+ filteredEvents: number;
50
+ outsideLookback: number;
51
+ attempted: number;
52
+ evaluated: number;
53
+ cachedOrBackoff: number;
54
+ deferredByLimit: number;
55
+ failed: number;
56
+ stale: number;
57
+ };
58
+ reason?: undefined;
59
+ } | {
60
+ status: "unavailable";
61
+ reason: string;
62
+ cohort: string;
63
+ coverage: {
64
+ sessions: number;
65
+ sessionLimitReached: boolean;
66
+ sessionsOverBudget: number;
67
+ completedResponses: number;
68
+ reconciledSessions: number;
69
+ reconciliationDeferred: number;
70
+ extractedSessions: number;
71
+ unchangedSessions: number;
72
+ stageAttempts: number;
73
+ stageCacheHits: number;
74
+ eligible: number;
75
+ noFeedback: number;
76
+ pendingFeedback: number;
77
+ oversized: number;
78
+ filteredEvents: number;
79
+ outsideLookback: number;
80
+ attempted: number;
81
+ evaluated: number;
82
+ cachedOrBackoff: number;
83
+ deferredByLimit: number;
84
+ failed: number;
85
+ stale: number;
86
+ };
87
+ }>;
@@ -0,0 +1,193 @@
1
+ import { createHash } from "node:crypto";
2
+ import { abortable } from "./abortable.js";
3
+ import { resolveTypeSafeApiKey } from "./typesafe.js";
4
+ import { RESPONSE_EXTRACTOR_VERSION, ResponseTranscriptReader } from "./response-episodes.js";
5
+ import { RESPONSE_RUBRIC_VERSION, RESPONSE_STAGE_VERSIONS, judgeMemoryOpportunity } from "./response-judge.js";
6
+ import { ResponseAuditStore } from "./response-store.js";
7
+ import { responseMemoryCandidates } from "./response-memory.js";
8
+ import { assessResponseStages } from "./response-stages.js";
9
+ import { ResponsePeople } from "./response-identity.js";
10
+ import { TYPESAFE_REVIEW_MODEL } from "./typesafe-review.js";
11
+ export function responseCohort(config) {
12
+ return RESPONSE_RUBRIC_VERSION + ":" + createHash("sha256").update(JSON.stringify({
13
+ extractor: RESPONSE_EXTRACTOR_VERSION, historyMessages: config.historyMessages,
14
+ stages: RESPONSE_STAGE_VERSIONS,
15
+ sentimentEnabled: config.sentimentEnabled,
16
+ senderIds: [...config.senderIds].sort(), chatTypes: [...config.chatTypes].sort(), memoryCorpora: [...config.memoryCorpora].sort(),
17
+ })).digest("hex").slice(0, 16);
18
+ }
19
+ /** All inference is outside memory's mutation queue and outside transcript DB transactions. */
20
+ export async function auditResponses(options) {
21
+ const { config, agentId } = options;
22
+ if (!config.responseAudit.enabled || !config.typesafe.enabled)
23
+ return { status: "disabled" };
24
+ const signal = AbortSignal.any([AbortSignal.timeout(120_000), ...(options.signal ? [options.signal] : [])]);
25
+ const cohort = responseCohort(config.responseAudit);
26
+ let key;
27
+ if (!options.dryRun) {
28
+ try {
29
+ key = await abortable(resolveTypeSafeApiKey(config.typesafe), signal);
30
+ }
31
+ catch {
32
+ return { status: "unavailable", reason: "Credentials unavailable or audit cancelled" };
33
+ }
34
+ if (!key)
35
+ return { status: "unavailable", reason: "TypeSafe API key not configured" };
36
+ }
37
+ let reader, store, lease;
38
+ const people = new ResponsePeople(options.peoplePath);
39
+ const now = Date.now();
40
+ const coverage = { sessions: 0, sessionLimitReached: false, sessionsOverBudget: 0, completedResponses: 0,
41
+ reconciledSessions: 0, reconciliationDeferred: 0,
42
+ extractedSessions: 0, unchangedSessions: 0,
43
+ stageAttempts: 0, stageCacheHits: 0,
44
+ eligible: 0, noFeedback: 0, pendingFeedback: 0, oversized: 0, filteredEvents: 0, outsideLookback: 0,
45
+ attempted: 0, evaluated: 0, cachedOrBackoff: 0, deferredByLimit: 0, failed: 0, stale: 0 };
46
+ try {
47
+ signal.throwIfAborted();
48
+ if (!options.dryRun) {
49
+ store = new ResponseAuditStore(options.storePath);
50
+ lease = store.acquire(now);
51
+ if (!lease)
52
+ return { status: "already_running" };
53
+ }
54
+ reader = new ResponseTranscriptReader(options.databasePath, agentId);
55
+ const since = now - config.responseAudit.lookbackDays * 86400_000;
56
+ store?.reviews.refresh(cohort, since);
57
+ const cursor = store?.cursor(cohort) ?? "";
58
+ const tracked = new Set(store?.activeSessions(cohort, since) ?? []);
59
+ const sessions = [...new Set([...reader.sessions(config.responseAudit, now, cursor).map(s => s.sessionId),
60
+ ...[...tracked].filter(id => id > cursor)])].sort();
61
+ coverage.sessionLimitReached = sessions.length > 100;
62
+ let stoppedForBudget = false;
63
+ for (const session of sessions.slice(0, 100)) {
64
+ await new Promise(resolve => setImmediate(resolve));
65
+ signal.throwIfAborted();
66
+ coverage.sessions++;
67
+ const checkpoint = store?.checkpoint(cohort, session);
68
+ const work = store?.sessionWork(cohort, session, since, now);
69
+ const snapshot = reader.read(session, config.responseAudit, work?.due ? undefined : checkpoint?.revision);
70
+ if (snapshot === undefined) {
71
+ coverage.sessionsOverBudget++;
72
+ coverage.reconciliationDeferred++;
73
+ store?.advance(cohort, session);
74
+ continue;
75
+ }
76
+ if (snapshot === null) {
77
+ store?.observe(cohort, session, []);
78
+ store?.checkpointForget(cohort, session);
79
+ coverage.reconciledSessions++;
80
+ store?.advance(cohort, session);
81
+ continue;
82
+ }
83
+ if ("unchanged" in snapshot) {
84
+ coverage.unchangedSessions++;
85
+ coverage.cachedOrBackoff += work?.total ?? 0;
86
+ if (checkpoint)
87
+ for (const key of Object.keys(checkpoint.coverage))
88
+ coverage[key] += checkpoint.coverage[key];
89
+ store?.advance(cohort, session);
90
+ continue;
91
+ }
92
+ coverage.extractedSessions++;
93
+ if (tracked.has(session))
94
+ coverage.reconciledSessions++;
95
+ for (const key of Object.keys(snapshot.coverage))
96
+ coverage[key] += snapshot.coverage[key];
97
+ const episodes = snapshot.episodes.filter(e => e.timestamp >= now - config.responseAudit.lookbackDays * 86400_000);
98
+ coverage.outsideLookback += snapshot.episodes.length - episodes.length;
99
+ store?.observe(cohort, session, snapshot.episodes);
100
+ store?.checkpointSave(cohort, session, snapshot.revision, snapshot.coverage);
101
+ // Oldest first within a session; new data cannot forever starve its existing backlog.
102
+ for (const e of episodes) {
103
+ signal.throwIfAborted();
104
+ if (options.dryRun)
105
+ continue;
106
+ if (!store.needsJudgment(cohort, e, Date.now())) {
107
+ coverage.cachedOrBackoff++;
108
+ continue;
109
+ }
110
+ if (coverage.attempted >= config.responseAudit.maxEpisodes) {
111
+ coverage.deferredByLimit++;
112
+ continue;
113
+ }
114
+ coverage.attempted++;
115
+ store.attempted(cohort, e, Date.now());
116
+ try {
117
+ const params = { apiKey: key, timeoutMs: config.typesafe.timeoutMs, signal };
118
+ const judgment = await abortable(assessResponseStages(store, cohort, e, params, config.responseAudit.sentimentEnabled, coverage), signal);
119
+ let memory = { status: "not_requested", candidates: [] };
120
+ if (judgment.feedback.memoryGap.noul >= 0.8 && config.responseAudit.memoryCorpora.length) {
121
+ try {
122
+ const approved = options.sources.filter(s => config.responseAudit.memoryCorpora.includes(s.corpus));
123
+ const candidates = responseMemoryCandidates(options.indexPath, approved, e);
124
+ const memoryKey = createHash("sha256").update(JSON.stringify([TYPESAFE_REVIEW_MODEL, RESPONSE_STAGE_VERSIONS.memory,
125
+ e.id, e.session, e.senderId, e.request, e.answer, e.feedback, candidates,
126
+ [...config.responseAudit.memoryCorpora].sort()])).digest("hex");
127
+ let judged = store.stage(cohort, e, "memory", memoryKey);
128
+ if (judged)
129
+ coverage.stageCacheHits++;
130
+ else {
131
+ store.stageBegin([memoryKey], Date.now());
132
+ coverage.stageAttempts++;
133
+ judged = await abortable(judgeMemoryOpportunity(e, candidates, params), signal);
134
+ store.stageSave(memoryKey, judged, Date.now());
135
+ }
136
+ memory = { status: "checked", candidates: judged };
137
+ }
138
+ catch {
139
+ memory = { status: "unavailable", candidates: [] };
140
+ }
141
+ }
142
+ signal.throwIfAborted();
143
+ const fresh = reader.read(session, config.responseAudit);
144
+ if (!fresh?.episodes.some(candidate => candidate.id === e.id && candidate.inputHash === e.inputHash)) {
145
+ coverage.stale++;
146
+ store.stale(cohort, e);
147
+ if (fresh !== undefined) {
148
+ store.observe(cohort, session, fresh?.episodes ?? []);
149
+ store.checkpointForget(cohort, session);
150
+ }
151
+ break;
152
+ }
153
+ store.save(cohort, e, { ...judgment, human: people.resolve(e), references: references(e), agentModel: e.model,
154
+ contextLimited: e.contextLimited, memorySearchCalls: e.memorySearchCalls, memory }, Date.now());
155
+ coverage.evaluated++;
156
+ }
157
+ catch {
158
+ coverage.failed++;
159
+ if (signal.aborted)
160
+ throw new Error("Audit cancelled");
161
+ }
162
+ }
163
+ // Let stop/cancellation handlers run between bounded synchronous session reads.
164
+ await new Promise(resolve => setImmediate(resolve));
165
+ store?.advance(cohort, session);
166
+ if (coverage.attempted >= config.responseAudit.maxEpisodes && session !== sessions.at(-1)) {
167
+ stoppedForBudget = true;
168
+ coverage.deferredByLimit++; // At least one unvisited session; precise episode count is not yet known.
169
+ break;
170
+ }
171
+ }
172
+ if (!coverage.sessionLimitReached && !stoppedForBudget)
173
+ store?.advance(cohort, "");
174
+ coverage.deferredByLimit = Math.max(coverage.deferredByLimit, store?.pendingWork(cohort, since, Date.now()) ?? 0);
175
+ store?.scan(cohort, coverage, Date.now());
176
+ return { status: options.dryRun ? "dry_run" : "ok", cohort, coverage };
177
+ }
178
+ catch {
179
+ store?.scan(cohort, { ...coverage, interrupted: true }, Date.now());
180
+ return { status: "unavailable", reason: "Response audit failed or was cancelled", cohort, coverage };
181
+ }
182
+ finally {
183
+ reader?.close();
184
+ if (lease)
185
+ store?.release(lease);
186
+ store?.close();
187
+ people.close();
188
+ }
189
+ }
190
+ function references(e) {
191
+ return { sessionId: e.session.sessionId, request: e.request.map(m => m.seq), answer: e.answer.map(m => m.seq),
192
+ feedback: e.feedback.map(m => m.seq), followup: e.followup.messages.map(m => m.seq), inputHash: e.inputHash };
193
+ }
@@ -0,0 +1,13 @@
1
+ import type { ChatType, CorpusConfig } from "./config.js";
2
+ export type ResponseAuditConfig = {
3
+ enabled: boolean;
4
+ sentimentEnabled: boolean;
5
+ senderIds: string[];
6
+ chatTypes: ChatType[];
7
+ historyMessages: number;
8
+ lookbackDays: number;
9
+ maxEpisodes: number;
10
+ intervalMinutes: number;
11
+ memoryCorpora: string[];
12
+ };
13
+ export declare function resolveResponseAudit(value: unknown, corpora: readonly CorpusConfig[]): ResponseAuditConfig;
@@ -0,0 +1,43 @@
1
+ export function resolveResponseAudit(value, corpora) {
2
+ const defaults = { enabled: false, sentimentEnabled: true, senderIds: [], chatTypes: ["direct"],
3
+ historyMessages: 6, lookbackDays: 30, maxEpisodes: 20, intervalMinutes: 60, memoryCorpora: [] };
4
+ if (value === undefined)
5
+ return defaults;
6
+ if (!value || typeof value !== "object" || Array.isArray(value))
7
+ throw new Error("responseAudit must be an object");
8
+ const v = value;
9
+ for (const key of Object.keys(v))
10
+ if (!Object.hasOwn(defaults, key))
11
+ throw new Error(`unknown responseAudit property: ${key}`);
12
+ const enabled = v.enabled ?? false;
13
+ if (typeof enabled !== "boolean")
14
+ throw new Error("responseAudit.enabled must be boolean");
15
+ const sentimentEnabled = v.sentimentEnabled === undefined ? true : v.sentimentEnabled;
16
+ if (typeof sentimentEnabled !== "boolean")
17
+ throw new Error("responseAudit.sentimentEnabled must be boolean");
18
+ const strings = (key) => {
19
+ const raw = v[key] ?? defaults[key];
20
+ if (!Array.isArray(raw) || raw.length > 50 || !raw.every((x) => typeof x === "string" && !!x.trim())) {
21
+ throw new Error(`responseAudit.${key} must be a bounded string array`);
22
+ }
23
+ return [...new Set(raw.map(x => x.trim()))];
24
+ };
25
+ const senderIds = strings("senderIds"), chatTypes = strings("chatTypes"), memoryCorpora = strings("memoryCorpora");
26
+ if (!chatTypes.length || !chatTypes.every((x) => ["direct", "group", "channel"].includes(x))) {
27
+ throw new Error("responseAudit.chatTypes must specify direct, group or channel");
28
+ }
29
+ if (enabled && !senderIds.length)
30
+ throw new Error("responseAudit requires explicit approved human senderIds");
31
+ if (memoryCorpora.some(name => !corpora.some(c => c.name === name && c.kind === "files"))) {
32
+ throw new Error("responseAudit.memoryCorpora must name configured file corpora");
33
+ }
34
+ const integer = (key, min, max) => {
35
+ const n = v[key] ?? defaults[key];
36
+ if (typeof n !== "number" || !Number.isInteger(n) || n < min || n > max)
37
+ throw new Error(`invalid responseAudit.${key}`);
38
+ return n;
39
+ };
40
+ return { enabled, sentimentEnabled, senderIds, chatTypes, memoryCorpora, historyMessages: integer("historyMessages", 0, 20),
41
+ lookbackDays: integer("lookbackDays", 1, 90), maxEpisodes: integer("maxEpisodes", 1, 100),
42
+ intervalMinutes: integer("intervalMinutes", 0, 1440) };
43
+ }