@unblocklabs/unblock-memory 0.11.1 → 0.12.1

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 (43) hide show
  1. package/README.md +1 -1
  2. package/dist/src/agent-transcript.js +16 -0
  3. package/dist/src/config.d.ts +2 -0
  4. package/dist/src/config.js +4 -1
  5. package/dist/src/evidence-review.d.ts +2 -0
  6. package/dist/src/evidence-review.js +1 -1
  7. package/dist/src/people-background.d.ts +3 -1
  8. package/dist/src/people-background.js +10 -1
  9. package/dist/src/people-dossier-review.d.ts +5 -1
  10. package/dist/src/people-dossier-review.js +40 -23
  11. package/dist/src/people-hooks.js +10 -6
  12. package/dist/src/people-learning-config.d.ts +39 -0
  13. package/dist/src/people-learning-config.js +36 -0
  14. package/dist/src/people-learning-cron.d.ts +14 -0
  15. package/dist/src/people-learning-cron.js +101 -0
  16. package/dist/src/people-learning-inventory.d.ts +58 -0
  17. package/dist/src/people-learning-inventory.js +260 -0
  18. package/dist/src/people-learning-prompt.d.ts +1 -0
  19. package/dist/src/people-learning-prompt.js +11 -0
  20. package/dist/src/people-learning-runtime.d.ts +6 -0
  21. package/dist/src/people-learning-runtime.js +374 -0
  22. package/dist/src/people-learning-store.d.ts +153 -0
  23. package/dist/src/people-learning-store.js +281 -0
  24. package/dist/src/people-learning-time.d.ts +7 -0
  25. package/dist/src/people-learning-time.js +33 -0
  26. package/dist/src/people-primer-tool.js +1 -1
  27. package/dist/src/people-primer.js +19 -17
  28. package/dist/src/people-store.d.ts +16 -5
  29. package/dist/src/people-store.js +67 -7
  30. package/dist/src/people-tools.js +10 -6
  31. package/dist/src/plugin.js +8 -4
  32. package/dist/src/response-store.d.ts +2 -0
  33. package/dist/src/response-store.js +8 -0
  34. package/dist/src/typesafe-review.d.ts +2 -0
  35. package/dist/src/typesafe-review.js +9 -8
  36. package/docs/configuration.md +6 -2
  37. package/docs/people-learning.md +239 -0
  38. package/docs/peoplesql.md +30 -22
  39. package/openclaw.plugin.json +34 -5
  40. package/package.json +5 -2
  41. package/scripts/people-nightly-inventory.mjs +9 -0
  42. package/scripts/people-review-coverage.mjs +65 -0
  43. package/skills/people-whisperer/SKILL.md +123 -123
package/README.md CHANGED
@@ -119,7 +119,7 @@ Everything below is off until you configure it.
119
119
  | [Safety Whisperer](docs/configuration.md#safety-whisperer) | Reminds the agent not to share sensitive topics, such as one person's salary, with requestors you haven't approved. A prompt-level guardrail, not access control; fails open if TypeSafe is unavailable. |
120
120
  | [My Turn](docs/configuration.md#my-turn) | Asks Jev whether a group/channel conversation needs this agent's response. Advises `NO_REPLY` only when silence is clearly favored; the agent keeps the final say. Opt-in; failures leave the turn unchanged. |
121
121
  | [People dossiers](docs/peoplesql.md) | Lets the agent keep a short, evidence-backed note about each person it works with. |
122
- | [People Whisperer](docs/peoplesql.md#injection-and-person-state) | Shows the agent its note about a person once per Slack thread. Local lookup, no model call. |
122
+ | [People Whisperer](docs/peoplesql.md#injection-and-person-state) | Supplies identity, scoped preferences and unexpired lessons on each Slack user turn. Includes [private nightly learning and weekly validation](docs/people-learning.md) by default. |
123
123
  | [People Primer](docs/peoplesql.md#optional-people-dossier-primer) | Gathers evidence for a person's note and reviews proposed notes before they are saved. |
124
124
  | [Session memory extraction](docs/extraction.md) | Pulls lasting facts from past conversations, checks each against exact quotes, and can make them searchable. Starts in shadow mode. |
125
125
  | [Clustering and curation](docs/retrieval.md#memory-analysis) | Groups related memories so the agent can spot duplicates and maintain its knowledge. Needs a local analysis worker. |
@@ -35,6 +35,8 @@ export class AgentTranscriptReader {
35
35
  #compressed;
36
36
  #cold;
37
37
  #utf8Storage;
38
+ #indexed;
39
+ #classified;
38
40
  constructor(db, agentId, errorMessage) {
39
41
  this.db = db;
40
42
  const version = agentTranscriptSchemaVersion(db, errorMessage);
@@ -59,6 +61,11 @@ export class AgentTranscriptReader {
59
61
  this.#cold = columns("session_transcript_cold_archives").has("session_id");
60
62
  if (version >= 20 && !this.#cold)
61
63
  throw new Error("Unsupported transcript cold-storage capabilities");
64
+ const index = columns("session_transcript_index_state");
65
+ this.#indexed = ["session_id", "indexed_seq", "needs_rebuild"].every(name => index.has(name));
66
+ if ((version >= 25 || index.size > 0) && !this.#indexed)
67
+ throw new Error("Unsupported transcript index capabilities");
68
+ this.#classified = columns("session_transcript_active_events").has("context_eligible");
62
69
  }
63
70
  /** Include storage availability in incremental fingerprints, not just hot row counts. */
64
71
  coldSql(sessionIdExpression) {
@@ -75,6 +82,15 @@ export class AgentTranscriptReader {
75
82
  if (this.#cold && this.db.prepare("SELECT 1 FROM session_transcript_cold_archives WHERE session_id=?").get(sessionId)) {
76
83
  return { kind: "cold" };
77
84
  }
85
+ if (this.#indexed) {
86
+ const state = this.db.prepare("SELECT indexed_seq,needs_rebuild FROM session_transcript_index_state WHERE session_id=?").get(sessionId);
87
+ const latest = this.db.prepare("SELECT COALESCE(MAX(seq),0) seq FROM transcript_events WHERE session_id=?").get(sessionId);
88
+ if (!state || state.needs_rebuild !== 0 || state.indexed_seq !== latest.seq)
89
+ return { kind: "unreadable" };
90
+ }
91
+ if (this.#classified && this.db.prepare("SELECT 1 FROM session_transcript_active_events WHERE session_id=? AND context_eligible IS NULL LIMIT 1").get(sessionId)) {
92
+ return { kind: "unreadable" };
93
+ }
78
94
  const maxEvents = limits.maxEvents ?? 50_000, maxBytes = limits.maxBytes ?? 64 * 1024 * 1024;
79
95
  const maxSeq = limits.maxSeq ?? Number.MAX_SAFE_INTEGER;
80
96
  // SQLite's BLOB length measures the database encoding, not decoded UTF-8.
@@ -1,6 +1,7 @@
1
1
  import { type ExtractionConfig } from "./extraction-config.js";
2
2
  import { type ResponseAuditConfig } from "./response-config.js";
3
3
  import { type PeoplePrimerConfig } from "./people-primer-config.js";
4
+ import { type PeopleLearningConfig } from "./people-learning-config.js";
4
5
  import { type InsideOutConfig } from "./inside-out.js";
5
6
  import { type SafetyWhispererConfig } from "./safety-config.js";
6
7
  import { type MyTurnConfig } from "./my-turn.js";
@@ -60,6 +61,7 @@ export type UnblockMemoryConfig = {
60
61
  todos: {
61
62
  maxOpen: number;
62
63
  };
64
+ learning: PeopleLearningConfig;
63
65
  };
64
66
  skillWhisperer: {
65
67
  enabled: boolean;
@@ -2,6 +2,7 @@ import { isAbsolute } from "node:path";
2
2
  import { resolveExtraction } from "./extraction-config.js";
3
3
  import { resolveResponseAudit } from "./response-config.js";
4
4
  import { resolvePeoplePrimer } from "./people-primer-config.js";
5
+ import { DEFAULT_LEARNING, resolvePeopleLearning } from "./people-learning-config.js";
5
6
  import { resolveInsideOut } from "./inside-out.js";
6
7
  import { resolveSafetyWhisperer } from "./safety-config.js";
7
8
  import { resolveMyTurn } from "./my-turn.js";
@@ -20,6 +21,7 @@ export const DEFAULT_PEOPLE_CONFIG = {
20
21
  enabled: false,
21
22
  whisperer: { enabled: false, maxChars: 1200 },
22
23
  todos: { maxOpen: 1000 },
24
+ learning: DEFAULT_LEARNING,
23
25
  };
24
26
  const DEFAULT_TYPESAFE_CONFIG = {
25
27
  enabled: true,
@@ -261,7 +263,7 @@ function resolvePeople(value) {
261
263
  throw new Error("unblock-memory people must be an object");
262
264
  }
263
265
  const people = value;
264
- assertOnlyKeys(people, ["enabled", "whisperer", "todos"], "people");
266
+ assertOnlyKeys(people, ["enabled", "whisperer", "todos", "learning"], "people");
265
267
  const enabled = people.enabled ?? false;
266
268
  if (typeof enabled !== "boolean")
267
269
  throw new Error("unblock-memory people.enabled must be a boolean");
@@ -283,6 +285,7 @@ function resolvePeople(value) {
283
285
  assertOnlyKeys(todosRecord, ["maxOpen"], "people.todos");
284
286
  return {
285
287
  enabled,
288
+ learning: resolvePeopleLearning(people.learning, enabled && whispererEnabled),
286
289
  whisperer: {
287
290
  enabled: whispererEnabled,
288
291
  maxChars: positiveInteger(whispererRecord.maxChars, DEFAULT_PEOPLE_CONFIG.whisperer.maxChars, "people.whisperer.maxChars", 4000),
@@ -16,6 +16,8 @@ export declare function reviewIndexedClaim(params: {
16
16
  personBackground?: {
17
17
  name: string;
18
18
  agentName: string;
19
+ kind?: "interaction";
20
+ inferred?: boolean;
19
21
  };
20
22
  read?: <T>(run: () => T) => Promise<T>;
21
23
  }): Promise<{
@@ -46,7 +46,7 @@ export async function reviewIndexedClaim(params) {
46
46
  }
47
47
  return { status: "ok", ...judgment,
48
48
  evidence: evidence.map(({ text: _text, ...citation }) => citation),
49
- policy: `${TYPESAFE_MODEL}:${params.personBackground ? "person-background-v2" : "claim-v1"}`,
49
+ policy: `${TYPESAFE_MODEL}:${params.personBackground?.kind === "interaction" ? "person-interaction-v1" : params.personBackground ? "person-background-v2" : "claim-v1"}`,
50
50
  scope: "Advisory support check against cited indexed excerpts only, not current truth or authorization to write. Verify original sources and identity before promotion." };
51
51
  });
52
52
  }
@@ -1,3 +1,5 @@
1
- /** A recognition aid, never a behavioral profile. Existing records remain readable. */
1
+ import type { PersonDossier } from "./people-store.js";
2
+ /** Keep identity brief; interaction preferences are stored separately with evidence. */
2
3
  export declare const PEOPLE_BACKGROUND_MAX_WORDS = 70;
3
4
  export declare function backgroundWordCount(text: string): number;
5
+ export declare function renderPeopleDossier(dossier: PersonDossier, now?: number): string;
@@ -1,5 +1,14 @@
1
- /** A recognition aid, never a behavioral profile. Existing records remain readable. */
1
+ /** Keep identity brief; interaction preferences are stored separately with evidence. */
2
2
  export const PEOPLE_BACKGROUND_MAX_WORDS = 70;
3
3
  export function backgroundWordCount(text) {
4
4
  return text.trim().split(/\s+/u).filter(Boolean).length;
5
5
  }
6
+ export function renderPeopleDossier(dossier, now = Date.now()) {
7
+ const preferences = dossier.sections.flatMap(section => ["preferences", "workingStyle"].includes(section.category)
8
+ ? section.claims.filter(claim => claim.scope && claim.reviewedAt && Number.isFinite(Date.parse(claim.reviewedAt)) && Date.parse(claim.reviewedAt) <= now &&
9
+ (claim.epistemicType === "observed" || claim.epistemicType === "reported" ||
10
+ (claim.epistemicType === "agent_assessment" && claim.expiresAt && Date.parse(claim.expiresAt) - Date.parse(claim.reviewedAt) <= 30 * 86400_000)) &&
11
+ (!claim.expiresAt || Date.parse(claim.expiresAt) > now)).map(claim => `- ${claim.epistemicType === "agent_assessment" ? "Provisional agent lesson: " : ""}${claim.statement}${claim.scope ? ` [Scope: ${claim.scope}]` : ""}`)
12
+ : []);
13
+ return [dossier.blurb.trim(), ...(preferences.length ? ["Interaction preferences and lessons:\n" + preferences.join("\n")] : [])].join("\n\n");
14
+ }
@@ -2,7 +2,7 @@ import type { UnblockMemoryConfig } from "./config.js";
2
2
  import type { Person, PersonDossier } from "./people-store.js";
3
3
  import type { QmdMemoryRuntime } from "./runtime.js";
4
4
  import type { getContext } from "./tool-context.js";
5
- /** Review the injected blurb using only exact indexed references already on its claims. */
5
+ /** Review every saved assertion against its own evidence, including interaction lessons. */
6
6
  export declare function reviewPersonDossier(params: {
7
7
  config: UnblockMemoryConfig;
8
8
  runtime: QmdMemoryRuntime;
@@ -38,4 +38,8 @@ export declare function reviewPersonDossier(params: {
38
38
  status: "unavailable";
39
39
  needsReview: boolean;
40
40
  reason: string;
41
+ } | {
42
+ status: "ok";
43
+ needsReview: boolean;
44
+ assertionsReviewed: number;
41
45
  }>;
@@ -1,29 +1,40 @@
1
1
  import { resolveAgentIdentity } from "openclaw/plugin-sdk/agent-runtime";
2
2
  import { abortable } from "./abortable.js";
3
3
  import { resolveTypeSafeApiKey } from "./typesafe-client.js";
4
- /** Review the injected blurb using only exact indexed references already on its claims. */
4
+ /** Review every saved assertion against its own evidence, including interaction lessons. */
5
5
  export async function reviewPersonDossier(params) {
6
6
  const unavailable = (reason) => ({ status: "unavailable", needsReview: true, reason });
7
7
  const { config, runtime, active, person, dossier } = params;
8
8
  if (!config.peoplePrimer.enabled || !config.typesafe.enabled) {
9
9
  return unavailable("TypeSafe background review is disabled; verify manually before saving");
10
10
  }
11
- const citations = new Map();
12
- for (const section of dossier.sections)
13
- for (const claim of section.claims)
14
- for (const ref of claim.evidence) {
15
- const match = /^(qmd:\/\/[^#]+)#L([1-9]\d*)(?:-L([1-9]\d*))?$/.exec(ref.locator);
16
- if (!match)
17
- return unavailable("Evidence needs exact qmd://path#Lstart-Lend references or explicit manual verification");
18
- const from = Number(match[2]), end = Number(match[3] ?? match[2]);
19
- if (!Number.isSafeInteger(from) || !Number.isSafeInteger(end) || end < from || end - from >= 120) {
20
- return unavailable("Evidence ranges must contain 1–120 lines");
21
- }
22
- const citation = { path: match[1], from, lines: end - from + 1 };
23
- citations.set(JSON.stringify(citation), citation);
24
- }
25
- if (!citations.size || citations.size > 3)
26
- return unavailable("Choose 1–3 distinct indexed evidence ranges or verify manually");
11
+ const checks = [
12
+ { statement: dossier.blurb, kind: undefined, inferred: false,
13
+ evidence: dossier.sections.filter(s => s.category === "role" || s.category === "relationship").flatMap(s => s.claims.flatMap(c => c.evidence)) },
14
+ ...dossier.sections.flatMap(section => section.claims.map(claim => ({
15
+ statement: claim.statement + (claim.scope ? ` [Scope: ${claim.scope}]` : ""),
16
+ kind: ["preferences", "workingStyle"].includes(section.category) ? "interaction" : undefined,
17
+ inferred: claim.epistemicType === "agent_assessment", evidence: claim.evidence,
18
+ }))),
19
+ ];
20
+ const reviews = new Map();
21
+ for (const check of checks) {
22
+ const citations = new Map();
23
+ for (const ref of check.evidence) {
24
+ const match = /^(qmd:\/\/[^#]+)#L([1-9]\d*)(?:-L([1-9]\d*))?$/.exec(ref.locator);
25
+ if (!match)
26
+ return unavailable("Every assertion needs exact qmd://path#Lstart-Lend evidence or explicit manual verification");
27
+ const from = Number(match[2]), end = Number(match[3] ?? match[2]);
28
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(end) || end < from || end - from >= 120)
29
+ return unavailable("Evidence ranges must contain 1–120 lines");
30
+ const citation = { path: match[1], from, lines: end - from + 1 };
31
+ citations.set(JSON.stringify(citation), citation);
32
+ }
33
+ if (!citations.size || citations.size > 3)
34
+ return unavailable("Each assertion needs 1–3 distinct indexed evidence ranges or manual verification");
35
+ const review = { statement: check.statement, kind: check.kind, inferred: check.inferred, citations: [...citations.values()] };
36
+ reviews.set(JSON.stringify(review), review);
37
+ }
27
38
  const deadline = AbortSignal.timeout(120_000);
28
39
  const signal = params.signal ? AbortSignal.any([params.signal, deadline]) : deadline;
29
40
  try {
@@ -34,12 +45,18 @@ export async function reviewPersonDossier(params) {
34
45
  const { manager } = await abortable(runtime.getMemorySearchManager(active), signal);
35
46
  if (!manager)
36
47
  return unavailable("Memory index unavailable; verify manually before saving");
37
- return await abortable(manager.reviewClaim({
38
- claim: dossier.blurb, citations: [...citations.values()],
39
- personBackground: { name: person.preferredName ?? person.displayName,
40
- agentName: resolveAgentIdentity(active.cfg, active.agentId)?.name?.trim() || params.agentName?.trim() || "the assistant" },
41
- corpora: config.peoplePrimer.corpora, apiKey, timeoutMs: config.peoplePrimer.timeoutMs, signal,
42
- }), signal);
48
+ for (const check of reviews.values()) {
49
+ const review = await abortable(manager.reviewClaim({
50
+ claim: check.statement, citations: check.citations,
51
+ personBackground: { name: person.preferredName ?? person.displayName,
52
+ agentName: resolveAgentIdentity(active.cfg, active.agentId)?.name?.trim() || params.agentName?.trim() || "the assistant",
53
+ ...(check.kind ? { kind: check.kind, inferred: check.inferred } : {}) },
54
+ corpora: config.peoplePrimer.corpora, apiKey, timeoutMs: config.peoplePrimer.timeoutMs, signal,
55
+ }), signal);
56
+ if (review.status !== "ok" || review.needsReview)
57
+ return review;
58
+ }
59
+ return { status: "ok", needsReview: false, assertionsReviewed: reviews.size };
43
60
  }
44
61
  catch {
45
62
  return unavailable("Background review failed or was cancelled; no dossier written");
@@ -1,5 +1,6 @@
1
1
  import { parseAgentSessionKey } from "openclaw/plugin-sdk/routing";
2
2
  import { nonBlank } from "./guards.js";
3
+ import { renderPeopleDossier } from "./people-background.js";
3
4
  function identifier(value) {
4
5
  if (typeof value === "number" && Number.isFinite(value))
5
6
  return String(value);
@@ -112,18 +113,21 @@ export function registerPeopleHooks(api, stores, config) {
112
113
  const person = store.findPersonByIdentity("slack", accountScope, externalId);
113
114
  if (!person || person.status !== "active" || !person.injectionEnabled)
114
115
  return;
115
- const previous = store.getWhisperReceipt(threadKey, person.id);
116
+ // Refresh on every user turn, including reused/compacted Slack threads.
117
+ // A retry of this exact run replays the same snapshot.
118
+ const receiptKey = JSON.stringify([threadKey, runId]);
119
+ const previous = store.getWhisperReceipt(receiptKey, person.id);
116
120
  if (previous) {
117
121
  return previous.runId === runId ? peopleContext(previous.contribution) : undefined;
118
122
  }
119
- const blurb = store.getDossierBlurb(person.id);
120
- const contribution = blurb
121
- ? renderPeopleWhisper(blurb, config.whisperer.maxChars)
122
- : undefined;
123
+ const dossier = store.getDossier(person.id);
124
+ const text = dossier && !store.isDossierVerified(person.id)
125
+ ? undefined : dossier ? renderPeopleDossier(dossier.dossier) : undefined;
126
+ const contribution = text ? renderPeopleWhisper(text, config.whisperer.maxChars) : undefined;
123
127
  if (!contribution)
124
128
  return;
125
129
  const receipt = store.recordWhisperReceipt({
126
- threadKey,
130
+ threadKey: receiptKey,
127
131
  personId: person.id,
128
132
  runId,
129
133
  contribution,
@@ -0,0 +1,39 @@
1
+ import { Type, type Static } from "typebox";
2
+ export declare const PEOPLE_LEARNING_SCHEMA: Type.TObject<{
3
+ agents: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
4
+ enabled: Type.TOptional<Type.TBoolean>;
5
+ nightly: Type.TOptional<Type.TBoolean>;
6
+ weekly: Type.TOptional<Type.TBoolean>;
7
+ nightlySchedule: Type.TOptional<Type.TString>;
8
+ weeklySchedule: Type.TOptional<Type.TString>;
9
+ timezone: Type.TOptional<Type.TString>;
10
+ legacyJobIds: Type.TOptional<Type.TArray<Type.TString>>;
11
+ }>>>;
12
+ enabled: Type.TOptional<Type.TBoolean>;
13
+ nightly: Type.TOptional<Type.TBoolean>;
14
+ weekly: Type.TOptional<Type.TBoolean>;
15
+ nightlySchedule: Type.TOptional<Type.TString>;
16
+ weeklySchedule: Type.TOptional<Type.TString>;
17
+ timezone: Type.TOptional<Type.TString>;
18
+ legacyJobIds: Type.TOptional<Type.TArray<Type.TString>>;
19
+ }>;
20
+ export type PeopleLearningConfig = Static<typeof PEOPLE_LEARNING_SCHEMA>;
21
+ export declare const DEFAULT_LEARNING: {
22
+ enabled: boolean;
23
+ nightly: boolean;
24
+ weekly: boolean;
25
+ nightlySchedule: string;
26
+ weeklySchedule: string;
27
+ agents: {};
28
+ };
29
+ export declare function resolvePeopleLearning(value: unknown, enabled: boolean): PeopleLearningConfig;
30
+ export declare function learningForAgent(config: PeopleLearningConfig, agentId: string): {
31
+ enabled: boolean;
32
+ nightly: boolean;
33
+ weekly: boolean;
34
+ nightlySchedule: string;
35
+ weeklySchedule: string;
36
+ timezone?: string | undefined;
37
+ legacyJobIds?: string[] | undefined;
38
+ agents: {};
39
+ };
@@ -0,0 +1,36 @@
1
+ import { Type } from "typebox";
2
+ import { Value } from "typebox/value";
3
+ const overrides = Type.Object({
4
+ enabled: Type.Optional(Type.Boolean()),
5
+ nightly: Type.Optional(Type.Boolean()),
6
+ weekly: Type.Optional(Type.Boolean()),
7
+ nightlySchedule: Type.Optional(Type.String({ pattern: "\\S" })),
8
+ weeklySchedule: Type.Optional(Type.String({ pattern: "\\S" })),
9
+ timezone: Type.Optional(Type.String({ pattern: "\\S" })),
10
+ legacyJobIds: Type.Optional(Type.Array(Type.String({ pattern: "\\S" }))),
11
+ }, { additionalProperties: false });
12
+ export const PEOPLE_LEARNING_SCHEMA = Type.Object({
13
+ ...overrides.properties,
14
+ agents: Type.Optional(Type.Record(Type.String({ pattern: "^[a-z0-9][a-z0-9_-]*$" }), overrides, { additionalProperties: false })),
15
+ }, { additionalProperties: false });
16
+ export const DEFAULT_LEARNING = { enabled: false, nightly: true, weekly: true,
17
+ nightlySchedule: "10 3 * * *", weeklySchedule: "0 4 * * 0", agents: {} };
18
+ export function resolvePeopleLearning(value, enabled) {
19
+ if (value !== undefined && !Value.Check(PEOPLE_LEARNING_SCHEMA, value))
20
+ throw new Error("Invalid people.learning configuration");
21
+ const input = value;
22
+ for (const options of [input, ...Object.values(input?.agents ?? {})]) {
23
+ if (options?.timezone)
24
+ new Intl.DateTimeFormat("en", { timeZone: options.timezone }).format();
25
+ for (const expr of [options?.nightlySchedule, options?.weeklySchedule]) {
26
+ if (expr && expr.trim().split(/\s+/u).length !== 5)
27
+ throw new Error("people.learning schedules require five-field cron expressions");
28
+ }
29
+ }
30
+ return { ...DEFAULT_LEARNING, enabled, ...input };
31
+ }
32
+ export function learningForAgent(config, agentId) {
33
+ const { agents, ...base } = config;
34
+ const options = { ...DEFAULT_LEARNING, ...base, ...agents?.[agentId] };
35
+ return { ...options, enabled: config.enabled !== false && options.enabled };
36
+ }
@@ -0,0 +1,14 @@
1
+ import type { OpenClawConfig, OpenClawPluginServiceContext } from "openclaw/plugin-sdk/plugin-entry";
2
+ import { type PeopleLearningConfig } from "./people-learning-config.js";
3
+ export declare const LEARNING_TOOLS: string[];
4
+ export type PeopleCron = Pick<NonNullable<ReturnType<NonNullable<OpenClawPluginServiceContext["getCron"]>>>, "list" | "add" | "update">;
5
+ export type LearningJob = {
6
+ id: string;
7
+ agentId: string;
8
+ kind: "nightly" | "weekly";
9
+ };
10
+ /** Service-owned cron, not bundled-only scheduleSessionTurn.
11
+ * Stable declarations make a lost add response/reload safe. Legacy history stays on disabled originals.
12
+ */
13
+ export declare function reconcilePeopleLearning(cron: PeopleCron, cfg: OpenClawConfig, config: PeopleLearningConfig, active?: () => boolean): Promise<LearningJob[]>;
14
+ export declare function learningSession(sessionKey: string | undefined, jobs: readonly LearningJob[]): LearningJob | undefined;
@@ -0,0 +1,101 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
3
+ import { record, nonBlank } from "./guards.js";
4
+ import { learningForAgent } from "./people-learning-config.js";
5
+ import { resolveTimezone } from "./session-projector.js";
6
+ import { peopleLearningPrompt } from "./people-learning-prompt.js";
7
+ const PREFIX = "unblock-memory:people-learning:";
8
+ const legacyNames = {
9
+ nightly: "People Whisperer — nightly dreaming and interaction learning",
10
+ weekly: "People Whisperer — full weekly statement validation",
11
+ };
12
+ function containsDeclaration(actual, expected) {
13
+ const fields = record(expected), source = record(actual);
14
+ return fields && source ? Object.entries(fields).every(([key, value]) => containsDeclaration(source[key], value))
15
+ : isDeepStrictEqual(actual, expected);
16
+ }
17
+ export const LEARNING_TOOLS = ["read", "memory_people_learning", "memory_people_inspect", "memory_people_update",
18
+ "memory_people_prime", "memory_search", "memory_get"];
19
+ /** Service-owned cron, not bundled-only scheduleSessionTurn.
20
+ * Stable declarations make a lost add response/reload safe. Legacy history stays on disabled originals.
21
+ */
22
+ export async function reconcilePeopleLearning(cron, cfg, config, active = () => true) {
23
+ const jobs = [];
24
+ {
25
+ const all = await cron.list({ includeDisabled: true });
26
+ if (!Array.isArray(all))
27
+ throw new Error("Unsupported service cron.list response");
28
+ for (const item of all) {
29
+ const job = record(item);
30
+ if (!job || !nonBlank(job.id))
31
+ throw new Error("Invalid cron job inventory");
32
+ jobs.push(job);
33
+ }
34
+ }
35
+ const result = [], owned = new Set();
36
+ for (const agentId of listAgentIds(cfg)) {
37
+ const options = learningForAgent(config, agentId);
38
+ for (const kind of ["nightly", "weekly"]) {
39
+ const key = `${PREFIX}${agentId}:${kind}`;
40
+ const matches = jobs.filter(job => job.agentId === agentId && (job.declarationKey === key ||
41
+ job.name === key || job.name === legacyNames[kind] ||
42
+ (options.legacyJobIds?.includes(String(job.id)) && record(job.payload)?.kind === "agentTurn" &&
43
+ String(record(job.payload)?.message).includes(`people-${kind === "nightly" ? "nightly-dreaming" : "weekly-validation"}.md`))));
44
+ const primary = matches.find(job => job.declarationKey === key);
45
+ const legacy = matches.filter(job => job.declarationKey !== key);
46
+ const migrationPaused = config.agents?.[agentId]?.enabled !== true &&
47
+ (primary ? String(primary.description).includes("[migration-paused]") : legacy.length > 0 && legacy.every(job => job.enabled === false));
48
+ const enabled = options.enabled && options[kind] && !migrationPaused;
49
+ if (!primary && !legacy.length && !enabled)
50
+ continue;
51
+ const desired = {
52
+ declarationKey: key, agentId, name: key,
53
+ description: "Plugin-owned private People Whisperer review; opt out in people.learning." + (migrationPaused ? " [migration-paused]" : ""),
54
+ enabled, schedule: { kind: "cron", expr: options[`${kind}Schedule`],
55
+ tz: options.timezone ?? resolveTimezone(cfg.agents?.defaults?.userTimezone), staggerMs: 0 },
56
+ sessionTarget: "isolated", wakeMode: "now", deleteAfterRun: false,
57
+ payload: { kind: "agentTurn", message: peopleLearningPrompt(kind, agentId), timeoutSeconds: kind === "nightly" ? 2700 : 3600,
58
+ toolsAllow: LEARNING_TOOLS },
59
+ delivery: { mode: "none" }, failureAlert: false,
60
+ };
61
+ if (!active())
62
+ return result;
63
+ let id;
64
+ if (primary) {
65
+ id = String(primary.id);
66
+ }
67
+ else {
68
+ // declarationKey is creation-only in the installed SDK. Never "migrate"
69
+ // it through update, which silently ignores that field. Create disabled
70
+ // before pausing the originals so a lost reply cannot leave two runners.
71
+ const added = record(await cron.add({ ...desired, enabled: false }));
72
+ const addedId = nonBlank(added?.id) ?? nonBlank(record(added?.job)?.id);
73
+ if (!addedId)
74
+ throw new Error("Cron creation unconfirmed; retry reconciliation with the same declaration key");
75
+ id = addedId;
76
+ }
77
+ owned.add(id);
78
+ result.push({ id, agentId, kind });
79
+ // Keep duplicate IDs and histories recoverable, but prevent a second run.
80
+ for (const duplicate of matches)
81
+ if (duplicate.id !== id && duplicate.enabled !== false && active()) {
82
+ await cron.update(String(duplicate.id), { enabled: false });
83
+ }
84
+ const { declarationKey: _key, ...patch } = desired;
85
+ if (active() && (!primary || !containsDeclaration(primary, patch)))
86
+ await cron.update(id, patch);
87
+ }
88
+ }
89
+ // Only this exact namespace is owned. Never sweep other agents' maintenance jobs.
90
+ for (const job of jobs)
91
+ if (String(job.declarationKey ?? "").startsWith(PREFIX) && !owned.has(String(job.id)) && job.enabled !== false && active()) {
92
+ await cron.update(String(job.id), { enabled: false });
93
+ }
94
+ return result;
95
+ }
96
+ export function learningSession(sessionKey, jobs) {
97
+ if (!sessionKey)
98
+ return undefined;
99
+ return jobs.find(job => sessionKey === `agent:${job.agentId}:cron:${job.id}` ||
100
+ sessionKey.startsWith(`agent:${job.agentId}:cron:${job.id}:run:`));
101
+ }
@@ -0,0 +1,58 @@
1
+ import type { PeopleStore, PersonDossier } from "./people-store.js";
2
+ import { reviewWindow } from "./people-learning-time.js";
3
+ export type ReviewKind = "nightly" | "weekly";
4
+ type ReviewGap = {
5
+ id: string;
6
+ reason: string;
7
+ sessionId?: string;
8
+ };
9
+ export type ReviewAssertion = {
10
+ id: string;
11
+ personId: string;
12
+ category: string;
13
+ statement: string;
14
+ claim?: PersonDossier["sections"][number]["claims"][number];
15
+ };
16
+ type ReviewPerson = {
17
+ personId: string;
18
+ name: string;
19
+ status: string;
20
+ injectionEnabled: boolean;
21
+ identities: {
22
+ provider: string;
23
+ accountScope: string;
24
+ externalId: string;
25
+ }[];
26
+ sessionIds: string[];
27
+ };
28
+ export type ReviewManifest = {
29
+ id: string;
30
+ agentId: string;
31
+ kind: ReviewKind;
32
+ createdAt: string;
33
+ refreshedAt?: string;
34
+ window: ReturnType<typeof reviewWindow>;
35
+ fullValidation: boolean;
36
+ roster: ReviewPerson[];
37
+ assertions: ReviewAssertion[];
38
+ sourceGaps: ReviewGap[];
39
+ sessions: {
40
+ sessionId: string;
41
+ file: string;
42
+ revision: string;
43
+ }[];
44
+ inventoryPending?: boolean;
45
+ };
46
+ export declare function dossierAssertions(personId: string, dossier: PersonDossier): ReviewAssertion[];
47
+ export declare function privateJson(root: string, name: string, value: unknown): string;
48
+ export declare function inventoryPeople(options: {
49
+ agentId: string;
50
+ timezone: string;
51
+ kind: ReviewKind;
52
+ now?: number;
53
+ day?: string;
54
+ people: PeopleStore;
55
+ databasePath: string;
56
+ exportRoot: string;
57
+ }): ReviewManifest;
58
+ export {};