@clawmem-ai/clawmem 0.1.16 → 0.1.17

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/src/service.ts CHANGED
@@ -1,15 +1,15 @@
1
1
  // Thin orchestrator: wires conversation mirroring, memory store, and plugin lifecycle.
2
- import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
2
+ import type { MemoryPluginCapability, OpenClawPluginApi } from "openclaw/plugin-sdk/core";
3
3
  import { hasDefaultRepo, isAgentConfigured, resolveAgentRoute, resolvePluginConfig } from "./config.js";
4
4
  import { filterDirectCollaborators, listRepoAccessTeams, resolveOrgInvitationRole } from "./collaboration.js";
5
5
  import { ConversationMirror } from "./conversation.js";
6
6
  import { GitHubIssueClient } from "./github-client.js";
7
7
  import { KeyedAsyncQueue } from "./keyed-async-queue.js";
8
- import { MemoryStore, mergeMemoryCandidates } from "./memory.js";
8
+ import { MemoryStore } from "./memory.js";
9
9
  import { sanitizeRecallQueryInput } from "./recall-sanitize.js";
10
10
  import { loadState, resolveStatePath, saveState } from "./state.js";
11
11
  import { readTranscriptSnapshot } from "./transcript.js";
12
- import type { BootstrapIdentityResponse, ClawMemPluginConfig, ClawMemResolvedRoute, PluginState, SessionDerivedState, SessionMirrorState, TranscriptSnapshot } from "./types.js";
12
+ import type { BootstrapIdentityResponse, ClawMemPluginConfig, ClawMemResolvedRoute, MemoryCandidate, PluginState, SessionDerivedState, SessionMirrorState, TranscriptSnapshot } from "./types.js";
13
13
  import { buildAgentBootstrapRegistration, inferAgentIdFromTranscriptPath, normalizeAgentId, sessionScopeKey } from "./utils.js";
14
14
  import { getOpenClawAgentIdFromEnv, getOpenClawHostVersionFromEnv } from "./runtime-env.js";
15
15
 
@@ -17,22 +17,20 @@ type TurnPayload = { sessionId?: string; sessionKey?: string; agentId?: string;
17
17
  type FinalizePayload = { sessionId?: string; sessionKey?: string; sessionFile?: string; agentId?: string; reason?: string; messages?: unknown[] };
18
18
  type CollaborationPermission = "read" | "write" | "admin";
19
19
  type CollaborationTeamRole = "member" | "maintainer";
20
+ type MemoryPromptBuilder = NonNullable<MemoryPluginCapability["promptBuilder"]>;
21
+ type MemoryPromptBuilderParams = Parameters<MemoryPromptBuilder>[0];
20
22
 
21
- const DERIVED_WORK_RECOVERY_DELAYS_MS = [5000, 30000, 120000] as const;
22
23
  const MODERN_PROMPT_HOOK_MIN_HOST_VERSION = "2026.3.7";
23
24
  type PromptHookMode = "modern" | "legacy";
24
25
 
25
26
  class ClawMemService {
26
27
  private readonly config: ClawMemPluginConfig;
27
28
  private readonly ioQueue = new KeyedAsyncQueue();
28
- private readonly deriveQueue = new KeyedAsyncQueue();
29
29
  private readonly repoWriteQueue = new KeyedAsyncQueue();
30
30
  private readonly stateQueue = new KeyedAsyncQueue();
31
31
  private readonly pending = new Set<Promise<unknown>>();
32
- private readonly syncTimers = new Map<string, ReturnType<typeof setTimeout>>();
33
- private readonly recoveryTimers = new Map<string, ReturnType<typeof setTimeout>>();
34
32
  private statePath = "";
35
- private state: PluginState = { version: 3, sessions: {} };
33
+ private state: PluginState = { version: 4, sessions: {} };
36
34
  private unsubTranscript?: () => void;
37
35
  private loadPromise: Promise<void> | null = null;
38
36
  private readonly configPromises = new Map<string, Promise<boolean>>();
@@ -43,14 +41,33 @@ class ClawMemService {
43
41
 
44
42
  register(): void {
45
43
  const promptHookMode = resolvePromptHookMode(this.api);
44
+ this.registerMemoryPromptGuidance();
46
45
  if (promptHookMode === "modern") {
47
46
  this.api.on("before_prompt_build", async (ev, ctx) => this.handleBeforePromptBuild(ev, ctx.agentId));
48
47
  } else {
49
48
  this.api.on("before_agent_start", async (ev, ctx) => this.handleBeforeAgentStart(ev, ctx.agentId));
50
49
  }
51
- this.api.on("agent_end", (ev, ctx) => this.scheduleTurn({ sessionId: ctx.sessionId, sessionKey: ctx.sessionKey, agentId: ctx.agentId, messages: ev.messages }));
52
- this.api.on("before_reset", (ev, ctx) => this.enqueueFinalize({ sessionId: ctx.sessionId, sessionKey: ctx.sessionKey, sessionFile: ev.sessionFile, agentId: ctx.agentId, reason: ev.reason, messages: ev.messages }));
53
- this.api.on("session_end", (ev, ctx) => this.enqueueFinalize({ sessionId: ev.sessionId ?? ctx.sessionId, sessionKey: ev.sessionKey ?? ctx.sessionKey, agentId: ctx.agentId, reason: "session_end" }));
50
+ this.api.on("agent_end", async (ev, ctx) => {
51
+ try {
52
+ await this.handleAgentEnd({ sessionId: ctx.sessionId, sessionKey: ctx.sessionKey, agentId: ctx.agentId, messages: ev.messages });
53
+ } catch (error) {
54
+ this.warn("turn sync", error);
55
+ }
56
+ });
57
+ this.api.on("before_reset", async (ev, ctx) => {
58
+ try {
59
+ await this.handleFinalize({ sessionId: ctx.sessionId, sessionKey: ctx.sessionKey, sessionFile: ev.sessionFile, agentId: ctx.agentId, reason: ev.reason, messages: ev.messages });
60
+ } catch (error) {
61
+ this.warn("finalize", error);
62
+ }
63
+ });
64
+ this.api.on("session_end", async (ev, ctx) => {
65
+ try {
66
+ await this.handleFinalize({ sessionId: ev.sessionId ?? ctx.sessionId, sessionKey: ev.sessionKey ?? ctx.sessionKey, agentId: ctx.agentId, reason: "session_end" });
67
+ } catch (error) {
68
+ this.warn("finalize", error);
69
+ }
70
+ });
54
71
  this.registerTools();
55
72
 
56
73
  this.api.registerService({
@@ -62,7 +79,6 @@ class ClawMemService {
62
79
  this.unsubTranscript = this.api.runtime.events.onSessionTranscriptUpdate((u) => {
63
80
  void this.track(this.handleTranscript(u.sessionFile)).catch((e) => this.warn("transcript update", e));
64
81
  });
65
- this.recoverDerivedWorkOnStart();
66
82
  const configuredCount = Object.keys(this.config.agents).filter((agentId) => {
67
83
  const route = resolveAgentRoute(this.config, agentId);
68
84
  return isAgentConfigured(route) && hasDefaultRepo(route);
@@ -76,15 +92,44 @@ class ClawMemService {
76
92
  },
77
93
  stop: async () => {
78
94
  this.unsubTranscript?.();
79
- for (const t of this.syncTimers.values()) clearTimeout(t);
80
- this.syncTimers.clear();
81
- for (const t of this.recoveryTimers.values()) clearTimeout(t);
82
- this.recoveryTimers.clear();
83
95
  await Promise.allSettled([...this.pending]);
84
96
  },
85
97
  });
86
98
  }
87
99
 
100
+ private registerMemoryPromptGuidance(): void {
101
+ if (!this.isSelectedMemoryPlugin()) return;
102
+
103
+ const api = this.api as OpenClawPluginApi & {
104
+ registerMemoryCapability?: OpenClawPluginApi["registerMemoryCapability"];
105
+ registerMemoryPromptSection?: OpenClawPluginApi["registerMemoryPromptSection"];
106
+ };
107
+
108
+ if (typeof api.registerMemoryCapability === "function") {
109
+ api.registerMemoryCapability({ promptBuilder: buildClawMemPromptSection });
110
+ return;
111
+ }
112
+
113
+ if (typeof api.registerMemoryPromptSection === "function") {
114
+ api.registerMemoryPromptSection(buildClawMemPromptSection);
115
+ return;
116
+ }
117
+
118
+ this.api.logger.warn?.("clawmem: host does not expose memory prompt registration; always-on prompt guidance is disabled");
119
+ }
120
+
121
+ private isSelectedMemoryPlugin(): boolean {
122
+ try {
123
+ const root = this.api.runtime.config.loadConfig();
124
+ const plugins = asRecord(root.plugins);
125
+ const slots = asRecord(plugins.slots);
126
+ const slot = typeof slots.memory === "string" ? String(slots.memory).trim() : "";
127
+ return slot === this.api.id;
128
+ } catch {
129
+ return false;
130
+ }
131
+ }
132
+
88
133
  private registerTools(): void {
89
134
  this.api.registerTool({
90
135
  name: "memory_repos",
@@ -430,6 +475,7 @@ class ClawMemService {
430
475
  return toolText(`Marked memory [${forgotten.memoryId}] stale in ${resolved.route.repo}: ${forgotten.detail}`);
431
476
  },
432
477
  });
478
+
433
479
  this.registerCollaborationTools();
434
480
  }
435
481
 
@@ -507,6 +553,147 @@ class ClawMemService {
507
553
  },
508
554
  });
509
555
 
556
+ this.api.registerTool({
557
+ name: "collaboration_org_members",
558
+ description: "List visible members in an organization, optionally filtering to admins only.",
559
+ required: true,
560
+ parameters: {
561
+ type: "object",
562
+ additionalProperties: false,
563
+ properties: {
564
+ org: { type: "string", minLength: 1, description: "Organization login." },
565
+ role: { type: "string", enum: ["admin"], description: "Optional role filter. Use admin to show org owners only." },
566
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
567
+ },
568
+ required: ["org"],
569
+ },
570
+ execute: async (_id: string, params: unknown) => {
571
+ const p = asRecord(params);
572
+ const org = typeof p.org === "string" ? p.org.trim() : "";
573
+ if (!org) return toolText("org is empty.");
574
+ const role = p.role === "admin" ? "admin" : undefined;
575
+ const agentId = this.resolveToolAgentId(p.agentId);
576
+ const resolved = await this.requireToolIdentity(agentId);
577
+ if ("error" in resolved) return toolText(resolved.error);
578
+ try {
579
+ const members = await resolved.client.listOrgMembers(org, role);
580
+ if (members.length === 0) {
581
+ return toolText(role === "admin"
582
+ ? `No org admins are visible in "${org}".`
583
+ : `No org members are visible in "${org}".`);
584
+ }
585
+ return toolText([
586
+ role === "admin" ? `Org admins in "${org}":` : `Org members in "${org}":`,
587
+ ...members.map((member) => `- ${renderCollaboratorLine(member)}`),
588
+ ].join("\n"));
589
+ } catch (error) {
590
+ return toolText(`Unable to list members for org "${org}": ${String(error)}`);
591
+ }
592
+ },
593
+ });
594
+
595
+ this.api.registerTool({
596
+ name: "collaboration_org_membership",
597
+ description: "Inspect one user's organization membership state, including active versus pending invitation state.",
598
+ required: true,
599
+ parameters: {
600
+ type: "object",
601
+ additionalProperties: false,
602
+ properties: {
603
+ org: { type: "string", minLength: 1, description: "Organization login." },
604
+ username: { type: "string", minLength: 1, description: "Username to inspect." },
605
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
606
+ },
607
+ required: ["org", "username"],
608
+ },
609
+ execute: async (_id: string, params: unknown) => {
610
+ const p = asRecord(params);
611
+ const org = typeof p.org === "string" ? p.org.trim() : "";
612
+ const username = typeof p.username === "string" ? p.username.trim() : "";
613
+ if (!org || !username) return toolText("org and username are required.");
614
+ const agentId = this.resolveToolAgentId(p.agentId);
615
+ const resolved = await this.requireToolIdentity(agentId);
616
+ if ("error" in resolved) return toolText(resolved.error);
617
+ try {
618
+ const membership = await resolved.client.getOrgMembership(org, username);
619
+ return toolText(`Organization membership in "${org}":\n- ${renderOrganizationMembershipLine(membership)}`);
620
+ } catch (error) {
621
+ if (isHttpStatusError(error, 404)) {
622
+ return toolText(`No active or pending organization membership was found for ${username} in "${org}".`);
623
+ }
624
+ return toolText(`Unable to inspect organization membership for ${username} in "${org}": ${String(error)}`);
625
+ }
626
+ },
627
+ });
628
+
629
+ this.api.registerTool({
630
+ name: "collaboration_org_member_remove",
631
+ description: "Remove an active organization member. Requires confirmed=true after explicit user approval.",
632
+ required: true,
633
+ parameters: {
634
+ type: "object",
635
+ additionalProperties: false,
636
+ properties: {
637
+ org: { type: "string", minLength: 1, description: "Organization login." },
638
+ username: { type: "string", minLength: 1, description: "Active org member to remove." },
639
+ confirmed: { type: "boolean", description: "Must be true after the user approves the exact write action." },
640
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
641
+ },
642
+ required: ["org", "username"],
643
+ },
644
+ execute: async (_id: string, params: unknown) => {
645
+ const p = asRecord(params);
646
+ const blocked = this.requireMutationConfirmation(p, "remove an organization member");
647
+ if (blocked) return toolText(blocked);
648
+ const org = typeof p.org === "string" ? p.org.trim() : "";
649
+ const username = typeof p.username === "string" ? p.username.trim() : "";
650
+ if (!org || !username) return toolText("org and username are required.");
651
+ const agentId = this.resolveToolAgentId(p.agentId);
652
+ const resolved = await this.requireToolIdentity(agentId);
653
+ if ("error" in resolved) return toolText(resolved.error);
654
+ try {
655
+ await resolved.client.removeOrgMember(org, username);
656
+ return toolText(`Removed active organization member ${username} from "${org}". Server-side org-scoped team memberships were cleaned up as part of the removal.`);
657
+ } catch (error) {
658
+ return toolText(`Unable to remove ${username} from org "${org}": ${String(error)}`);
659
+ }
660
+ },
661
+ });
662
+
663
+ this.api.registerTool({
664
+ name: "collaboration_org_membership_remove",
665
+ description: "Remove an active organization membership or revoke a pending org invitation for that user. Requires confirmed=true after explicit user approval.",
666
+ required: true,
667
+ parameters: {
668
+ type: "object",
669
+ additionalProperties: false,
670
+ properties: {
671
+ org: { type: "string", minLength: 1, description: "Organization login." },
672
+ username: { type: "string", minLength: 1, description: "Username whose active membership or pending invite should be removed." },
673
+ confirmed: { type: "boolean", description: "Must be true after the user approves the exact write action." },
674
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
675
+ },
676
+ required: ["org", "username"],
677
+ },
678
+ execute: async (_id: string, params: unknown) => {
679
+ const p = asRecord(params);
680
+ const blocked = this.requireMutationConfirmation(p, "remove an organization membership");
681
+ if (blocked) return toolText(blocked);
682
+ const org = typeof p.org === "string" ? p.org.trim() : "";
683
+ const username = typeof p.username === "string" ? p.username.trim() : "";
684
+ if (!org || !username) return toolText("org and username are required.");
685
+ const agentId = this.resolveToolAgentId(p.agentId);
686
+ const resolved = await this.requireToolIdentity(agentId);
687
+ if ("error" in resolved) return toolText(resolved.error);
688
+ try {
689
+ await resolved.client.removeOrgMembership(org, username);
690
+ return toolText(`Removed organization membership state for ${username} in "${org}". This deletes an active membership or revokes a pending org invitation, depending on current state.`);
691
+ } catch (error) {
692
+ return toolText(`Unable to remove organization membership state for ${username} in "${org}": ${String(error)}`);
693
+ }
694
+ },
695
+ });
696
+
510
697
  this.api.registerTool({
511
698
  name: "collaboration_teams",
512
699
  description: "List teams in an organization before granting repo access or managing membership.",
@@ -540,6 +727,37 @@ class ClawMemService {
540
727
  },
541
728
  });
542
729
 
730
+ this.api.registerTool({
731
+ name: "collaboration_team",
732
+ description: "Inspect one organization team by slug.",
733
+ required: true,
734
+ parameters: {
735
+ type: "object",
736
+ additionalProperties: false,
737
+ properties: {
738
+ org: { type: "string", minLength: 1, description: "Organization login." },
739
+ teamSlug: { type: "string", minLength: 1, description: "Team slug." },
740
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
741
+ },
742
+ required: ["org", "teamSlug"],
743
+ },
744
+ execute: async (_id: string, params: unknown) => {
745
+ const p = asRecord(params);
746
+ const org = typeof p.org === "string" ? p.org.trim() : "";
747
+ const teamSlug = typeof p.teamSlug === "string" ? p.teamSlug.trim() : "";
748
+ if (!org || !teamSlug) return toolText("org and teamSlug are required.");
749
+ const agentId = this.resolveToolAgentId(p.agentId);
750
+ const resolved = await this.requireToolIdentity(agentId);
751
+ if ("error" in resolved) return toolText(resolved.error);
752
+ try {
753
+ const team = await resolved.client.getTeam(org, teamSlug);
754
+ return toolText(`Team in "${org}":\n- ${renderTeamLine(team)}`);
755
+ } catch (error) {
756
+ return toolText(`Unable to inspect team ${org}/${teamSlug}: ${String(error)}`);
757
+ }
758
+ },
759
+ });
760
+
543
761
  this.api.registerTool({
544
762
  name: "collaboration_team_create",
545
763
  description: "Create a team inside an organization. Requires confirmed=true after explicit user approval.",
@@ -581,6 +799,122 @@ class ClawMemService {
581
799
  },
582
800
  });
583
801
 
802
+ this.api.registerTool({
803
+ name: "collaboration_team_update",
804
+ description: "Update a team's name, description, or privacy. Requires confirmed=true after explicit user approval.",
805
+ required: true,
806
+ parameters: {
807
+ type: "object",
808
+ additionalProperties: false,
809
+ properties: {
810
+ org: { type: "string", minLength: 1, description: "Organization login." },
811
+ teamSlug: { type: "string", minLength: 1, description: "Current team slug." },
812
+ name: { type: "string", minLength: 1, description: "Optional new team display name." },
813
+ description: { type: "string", minLength: 1, description: "Optional new team description." },
814
+ privacy: { type: "string", enum: ["closed", "secret"], description: "Optional team privacy." },
815
+ confirmed: { type: "boolean", description: "Must be true after the user approves the exact write action." },
816
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
817
+ },
818
+ required: ["org", "teamSlug"],
819
+ },
820
+ execute: async (_id: string, params: unknown) => {
821
+ const p = asRecord(params);
822
+ const blocked = this.requireMutationConfirmation(p, "update a team");
823
+ if (blocked) return toolText(blocked);
824
+ const org = typeof p.org === "string" ? p.org.trim() : "";
825
+ const teamSlug = typeof p.teamSlug === "string" ? p.teamSlug.trim() : "";
826
+ if (!org || !teamSlug) return toolText("org and teamSlug are required.");
827
+ const name = typeof p.name === "string" && p.name.trim() ? p.name.trim() : undefined;
828
+ const description = typeof p.description === "string" && p.description.trim() ? p.description.trim() : undefined;
829
+ const privacy = p.privacy === "secret" ? "secret" : p.privacy === "closed" ? "closed" : undefined;
830
+ if (!name && !description && !privacy) {
831
+ return toolText("Provide at least one of name, description, or privacy when updating a team.");
832
+ }
833
+ const agentId = this.resolveToolAgentId(p.agentId);
834
+ const resolved = await this.requireToolIdentity(agentId);
835
+ if ("error" in resolved) return toolText(resolved.error);
836
+ try {
837
+ const updated = await resolved.client.updateTeam(org, teamSlug, {
838
+ ...(name ? { name } : {}),
839
+ ...(description ? { description } : {}),
840
+ ...(privacy ? { privacy } : {}),
841
+ });
842
+ return toolText(`Updated team in "${org}": ${renderTeamLine(updated)}.`);
843
+ } catch (error) {
844
+ return toolText(`Unable to update team ${org}/${teamSlug}: ${String(error)}`);
845
+ }
846
+ },
847
+ });
848
+
849
+ this.api.registerTool({
850
+ name: "collaboration_team_delete",
851
+ description: "Delete a team. Requires confirmed=true after explicit user approval.",
852
+ required: true,
853
+ parameters: {
854
+ type: "object",
855
+ additionalProperties: false,
856
+ properties: {
857
+ org: { type: "string", minLength: 1, description: "Organization login." },
858
+ teamSlug: { type: "string", minLength: 1, description: "Team slug." },
859
+ confirmed: { type: "boolean", description: "Must be true after the user approves the exact write action." },
860
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
861
+ },
862
+ required: ["org", "teamSlug"],
863
+ },
864
+ execute: async (_id: string, params: unknown) => {
865
+ const p = asRecord(params);
866
+ const blocked = this.requireMutationConfirmation(p, "delete a team");
867
+ if (blocked) return toolText(blocked);
868
+ const org = typeof p.org === "string" ? p.org.trim() : "";
869
+ const teamSlug = typeof p.teamSlug === "string" ? p.teamSlug.trim() : "";
870
+ if (!org || !teamSlug) return toolText("org and teamSlug are required.");
871
+ const agentId = this.resolveToolAgentId(p.agentId);
872
+ const resolved = await this.requireToolIdentity(agentId);
873
+ if ("error" in resolved) return toolText(resolved.error);
874
+ try {
875
+ await resolved.client.deleteTeam(org, teamSlug);
876
+ return toolText(`Deleted team ${org}/${teamSlug}.`);
877
+ } catch (error) {
878
+ return toolText(`Unable to delete team ${org}/${teamSlug}: ${String(error)}`);
879
+ }
880
+ },
881
+ });
882
+
883
+ this.api.registerTool({
884
+ name: "collaboration_team_members",
885
+ description: "List members of an organization team.",
886
+ required: true,
887
+ parameters: {
888
+ type: "object",
889
+ additionalProperties: false,
890
+ properties: {
891
+ org: { type: "string", minLength: 1, description: "Organization login." },
892
+ teamSlug: { type: "string", minLength: 1, description: "Team slug." },
893
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
894
+ },
895
+ required: ["org", "teamSlug"],
896
+ },
897
+ execute: async (_id: string, params: unknown) => {
898
+ const p = asRecord(params);
899
+ const org = typeof p.org === "string" ? p.org.trim() : "";
900
+ const teamSlug = typeof p.teamSlug === "string" ? p.teamSlug.trim() : "";
901
+ if (!org || !teamSlug) return toolText("org and teamSlug are required.");
902
+ const agentId = this.resolveToolAgentId(p.agentId);
903
+ const resolved = await this.requireToolIdentity(agentId);
904
+ if ("error" in resolved) return toolText(resolved.error);
905
+ try {
906
+ const members = await resolved.client.listTeamMembers(org, teamSlug);
907
+ if (members.length === 0) return toolText(`No members found in ${org}/${teamSlug}.`);
908
+ return toolText([
909
+ `Members of ${org}/${teamSlug}:`,
910
+ ...members.map((member) => `- ${renderCollaboratorLine(member)}`),
911
+ ].join("\n"));
912
+ } catch (error) {
913
+ return toolText(`Unable to list members for ${org}/${teamSlug}: ${String(error)}`);
914
+ }
915
+ },
916
+ });
917
+
584
918
  this.api.registerTool({
585
919
  name: "collaboration_team_membership_set",
586
920
  description: "Add or update a user's membership in an organization team. Requires confirmed=true after explicit user approval.",
@@ -763,6 +1097,40 @@ class ClawMemService {
763
1097
  },
764
1098
  });
765
1099
 
1100
+ this.api.registerTool({
1101
+ name: "collaboration_repo_transfer",
1102
+ description: "Transfer a repository to a new owner, commonly used to move a personal memory repo into an existing org. Requires confirmed=true after explicit user approval.",
1103
+ required: true,
1104
+ parameters: {
1105
+ type: "object",
1106
+ additionalProperties: false,
1107
+ properties: {
1108
+ repo: { type: "string", minLength: 3, description: "Optional source repo in owner/repo form. Defaults to the agent's defaultRepo." },
1109
+ newOwner: { type: "string", minLength: 1, description: "Destination owner login, often an organization login." },
1110
+ confirmed: { type: "boolean", description: "Must be true after the user approves the exact write action." },
1111
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
1112
+ },
1113
+ required: ["newOwner"],
1114
+ },
1115
+ execute: async (_id: string, params: unknown) => {
1116
+ const p = asRecord(params);
1117
+ const blocked = this.requireMutationConfirmation(p, "transfer a repository");
1118
+ if (blocked) return toolText(blocked);
1119
+ const newOwner = typeof p.newOwner === "string" ? p.newOwner.trim() : "";
1120
+ if (!newOwner) return toolText("newOwner is empty.");
1121
+ const agentId = this.resolveToolAgentId(p.agentId);
1122
+ const target = await this.requireCollaborationRepo(agentId, p.repo);
1123
+ if ("error" in target) return toolText(target.error);
1124
+ try {
1125
+ const transferred = await target.client.transferRepo(target.owner, target.repo, newOwner);
1126
+ const nextFullName = repoSummaryFullName(transferred) || `${newOwner}/${target.repo}`;
1127
+ return toolText(`Transferred ${target.fullName} to ${nextFullName}. If this repo was your configured defaultRepo, retarget future memory operations to ${nextFullName} explicitly until config is updated.`);
1128
+ } catch (error) {
1129
+ return toolText(`Unable to transfer ${target.fullName} to ${newOwner}: ${String(error)}`);
1130
+ }
1131
+ },
1132
+ });
1133
+
766
1134
  this.api.registerTool({
767
1135
  name: "collaboration_repo_collaborators",
768
1136
  description: "List direct collaborators on a repo before changing repository-level access.",
@@ -1088,6 +1456,41 @@ class ClawMemService {
1088
1456
  },
1089
1457
  });
1090
1458
 
1459
+ this.api.registerTool({
1460
+ name: "collaboration_org_invitation_revoke",
1461
+ description: "Revoke a pending organization invitation from the org side. Requires confirmed=true after explicit user approval.",
1462
+ required: true,
1463
+ parameters: {
1464
+ type: "object",
1465
+ additionalProperties: false,
1466
+ properties: {
1467
+ org: { type: "string", minLength: 1, description: "Organization login." },
1468
+ invitationId: { type: "integer", minimum: 1, description: "Pending organization invitation id." },
1469
+ confirmed: { type: "boolean", description: "Must be true after the user approves the exact write action." },
1470
+ agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
1471
+ },
1472
+ required: ["org", "invitationId"],
1473
+ },
1474
+ execute: async (_id: string, params: unknown) => {
1475
+ const p = asRecord(params);
1476
+ const blocked = this.requireMutationConfirmation(p, "revoke an organization invitation");
1477
+ if (blocked) return toolText(blocked);
1478
+ const org = typeof p.org === "string" ? p.org.trim() : "";
1479
+ if (!org) return toolText("org is empty.");
1480
+ const invitationId = this.resolvePositiveInteger(p.invitationId, "invitationId");
1481
+ if ("error" in invitationId) return toolText(invitationId.error);
1482
+ const agentId = this.resolveToolAgentId(p.agentId);
1483
+ const resolved = await this.requireToolIdentity(agentId);
1484
+ if ("error" in resolved) return toolText(resolved.error);
1485
+ try {
1486
+ await resolved.client.revokeOrgInvitation(org, invitationId.value);
1487
+ return toolText(`Revoked organization invitation ${invitationId.value} in "${org}".`);
1488
+ } catch (error) {
1489
+ return toolText(`Unable to revoke organization invitation ${invitationId.value} in "${org}": ${String(error)}`);
1490
+ }
1491
+ },
1492
+ });
1493
+
1091
1494
  this.api.registerTool({
1092
1495
  name: "collaboration_user_org_invitations",
1093
1496
  description: "List pending organization invitations for the current ClawMem identity before concluding that no shared org access is available.",
@@ -1234,6 +1637,7 @@ class ClawMemService {
1234
1637
  additionalProperties: false,
1235
1638
  properties: {
1236
1639
  repo: { type: "string", minLength: 3, description: "Optional target repo in owner/repo form. Defaults to the agent's defaultRepo." },
1640
+ username: { type: "string", minLength: 1, description: "Optional username to inspect for org-level base permission and membership state on org-owned repos." },
1237
1641
  agentId: { type: "string", minLength: 1, description: "Optional agent identity override. Defaults to the current agent when available." },
1238
1642
  },
1239
1643
  },
@@ -1246,7 +1650,10 @@ class ClawMemService {
1246
1650
  try {
1247
1651
  const lines = [`Repo access inspection for ${target.fullName}:`];
1248
1652
  const notes: string[] = [];
1653
+ const username = typeof p.username === "string" ? p.username.trim() : "";
1249
1654
  let orgName: string | undefined;
1655
+ let orgDefaultPermission: "none" | CollaborationPermission | undefined;
1656
+ let orgContextAvailable = false;
1250
1657
 
1251
1658
  try {
1252
1659
  const repo = await target.client.getRepo(target.owner, target.repo);
@@ -1259,12 +1666,49 @@ class ClawMemService {
1259
1666
  }
1260
1667
 
1261
1668
  try {
1262
- const org = await target.client.getOrg(orgName);
1263
- lines.push(`- Org default repository permission: ${org.default_repository_permission?.trim() || "unknown"}`);
1669
+ const ownerOrg = orgName || target.owner;
1670
+ const org = await target.client.getOrg(ownerOrg);
1671
+ orgContextAvailable = true;
1672
+ orgDefaultPermission = normalizePermissionAlias(org.default_repository_permission);
1673
+ lines.push(`- Org default repository permission: ${orgDefaultPermission || "unknown"}`);
1264
1674
  } catch (error) {
1265
1675
  notes.push(`Org metadata unavailable for "${orgName}": ${String(error)}`);
1266
1676
  }
1267
1677
 
1678
+ if (username) {
1679
+ lines.push("");
1680
+ lines.push(`Org membership for "${username}" in "${orgName}":`);
1681
+ if (!orgName || !orgContextAvailable) {
1682
+ lines.push("- Not applicable because the owner org could not be resolved.");
1683
+ } else {
1684
+ try {
1685
+ const membership = await target.client.getOrgMembership(orgName, username);
1686
+ lines.push(`- ${renderOrganizationMembershipLine(membership)}`);
1687
+ if (membership.state === "active") {
1688
+ if (orgDefaultPermission && orgDefaultPermission !== "none") {
1689
+ lines.push(`- Org base repo access is active via default permission "${orgDefaultPermission}".`);
1690
+ notes.push(`Because ${username} is an active org member and "${orgName}" default repository permission is ${orgDefaultPermission}, removing direct collaborators or team grants alone may not remove repo access.`);
1691
+ } else {
1692
+ lines.push("- No org base repo access is visible because the org default permission is none.");
1693
+ }
1694
+ } else {
1695
+ lines.push("- Org base repo access is not active yet because the org membership is still pending.");
1696
+ }
1697
+ } catch (error) {
1698
+ if (isHttpStatusError(error, 404)) {
1699
+ lines.push("- No active or pending org membership was found.");
1700
+ if (orgDefaultPermission && orgDefaultPermission !== "none") {
1701
+ lines.push("- Org base repo access does not apply unless the user becomes an org member.");
1702
+ }
1703
+ } else {
1704
+ notes.push(`Org membership lookup failed for "${username}" in "${orgName}": ${String(error)}`);
1705
+ }
1706
+ }
1707
+ }
1708
+ } else if (orgDefaultPermission && orgDefaultPermission !== "none") {
1709
+ notes.push(`Any active org member can still inherit ${orgDefaultPermission} access from "${orgName}" even after direct collaborator or team grants are removed.`);
1710
+ }
1711
+
1268
1712
  try {
1269
1713
  const collaborators = filterDirectCollaborators(await target.client.listRepoCollaborators(target.owner, target.repo), target.owner);
1270
1714
  lines.push("");
@@ -1299,7 +1743,8 @@ class ClawMemService {
1299
1743
  }
1300
1744
 
1301
1745
  try {
1302
- const outside = await target.client.listOrgOutsideCollaborators(orgName);
1746
+ const ownerOrg = orgName || target.owner;
1747
+ const outside = await target.client.listOrgOutsideCollaborators(ownerOrg);
1303
1748
  lines.push("");
1304
1749
  lines.push(`Outside collaborators in owner org "${orgName}":`);
1305
1750
  if (outside.length === 0) lines.push("- None visible");
@@ -1321,9 +1766,12 @@ class ClawMemService {
1321
1766
  });
1322
1767
  }
1323
1768
 
1324
- private async handleBeforePromptBuild(event: unknown, agentId?: string): Promise<{ prependSystemContext: string } | void> {
1769
+ private async handleBeforePromptBuild(event: unknown, agentId?: string): Promise<{ prependContext: string } | void> {
1325
1770
  const context = await this.collectAutoRecallContext(event, agentId);
1326
- return context ? { prependSystemContext: context } : undefined;
1771
+ // Auto-recall is per-turn dynamic context, so keep it out of the system prompt.
1772
+ // OpenClaw documents dynamic context on `prependContext`: https://github.com/maweibin/openclaw/blob/d9a2869ad69db9449336a2e2846bd9de0e647ac6/docs/concepts/agent-loop.md?plain=1#L85
1773
+ // Changing the system prompt can defeat provider prefix caching.
1774
+ return context ? { prependContext: context } : undefined;
1327
1775
  }
1328
1776
 
1329
1777
  private async handleBeforeAgentStart(event: unknown, agentId?: string): Promise<{ prependContext: string } | void> {
@@ -1331,6 +1779,16 @@ class ClawMemService {
1331
1779
  return context ? { prependContext: context } : undefined;
1332
1780
  }
1333
1781
 
1782
+ private async handleAgentEnd(payload: TurnPayload): Promise<void> {
1783
+ if (!payload.sessionId) return;
1784
+ await this.enqueueSessionIo(sessionScopeKey(payload.sessionId, payload.agentId), () => this.syncTurn(payload));
1785
+ }
1786
+
1787
+ private async handleFinalize(payload: FinalizePayload): Promise<void> {
1788
+ if (!payload.sessionId) return;
1789
+ await this.enqueueSessionIo(sessionScopeKey(payload.sessionId, payload.agentId), () => this.finalize(payload));
1790
+ }
1791
+
1334
1792
  private async collectAutoRecallContext(event: unknown, agentId?: string): Promise<string | undefined> {
1335
1793
  const routeAgentId = normalizeAgentId(agentId);
1336
1794
  if (!(await this.ensureDefaultRepoConfigured(routeAgentId))) return undefined;
@@ -1369,26 +1827,13 @@ class ClawMemService {
1369
1827
  });
1370
1828
  }
1371
1829
 
1372
- private scheduleTurn(p: TurnPayload): void {
1373
- if (!p.sessionId) return;
1374
- const scopeKey = sessionScopeKey(p.sessionId, p.agentId);
1375
- const prev = this.syncTimers.get(scopeKey);
1376
- if (prev) clearTimeout(prev);
1377
- const timer = setTimeout(() => {
1378
- this.syncTimers.delete(scopeKey);
1379
- void this.track(this.enqueueSessionIo(scopeKey, () => this.syncTurn(p))).catch((e) => this.warn("turn sync", e));
1380
- }, this.config.turnCommentDelayMs);
1381
- timer.unref?.();
1382
- this.syncTimers.set(scopeKey, timer);
1383
- }
1384
-
1385
1830
  private async syncTurn(p: TurnPayload): Promise<void> {
1386
1831
  if (!p.sessionId) return;
1387
1832
  const agentId = normalizeAgentId(p.agentId);
1388
- const scopeKey = sessionScopeKey(p.sessionId, agentId);
1389
1833
  if (!(await this.ensureDefaultRepoConfigured(agentId))) return;
1390
1834
  const { conv } = this.getServices(agentId);
1391
1835
  const s = this.getOrCreate(p.sessionId, agentId);
1836
+ if (s.finalizedAt) return;
1392
1837
  s.sessionKey = p.sessionKey ?? s.sessionKey; s.agentId = agentId; s.updatedAt = new Date().toISOString();
1393
1838
  const snap = await conv.loadSnapshot(s, p.messages);
1394
1839
  if (!conv.shouldMirror(s.sessionId, snap.messages) || snap.messages.length === 0) { await this.persistState(); return; }
@@ -1396,43 +1841,183 @@ class ClawMemService {
1396
1841
  await conv.syncLabels(s, snap, false);
1397
1842
  const next = snap.messages.slice(s.lastMirroredCount);
1398
1843
  if (next.length > 0) { const n = await conv.appendComments(s.issueNumber!, next); s.lastMirroredCount += n; s.turnCount += n; }
1399
- this.markPostMirrorTasks(s);
1400
1844
  await this.persistState();
1401
- this.kickDerivedWork(scopeKey, agentId, "turn");
1402
- }
1403
-
1404
- private enqueueFinalize(p: FinalizePayload): void {
1405
- if (!p.sessionId) return;
1406
- const scopeKey = sessionScopeKey(p.sessionId, p.agentId);
1407
- const prev = this.syncTimers.get(scopeKey);
1408
- if (prev) { clearTimeout(prev); this.syncTimers.delete(scopeKey); }
1409
- void this.track(this.enqueueSessionIo(scopeKey, () => this.finalize(p))).catch((e) => this.warn("finalize", e));
1410
1845
  }
1411
1846
 
1412
1847
  private async finalize(p: FinalizePayload): Promise<void> {
1413
1848
  if (!p.sessionId) return;
1414
1849
  const agentId = normalizeAgentId(p.agentId);
1415
- const scopeKey = sessionScopeKey(p.sessionId, agentId);
1416
1850
  if (!(await this.ensureDefaultRepoConfigured(agentId))) return;
1417
- const { conv } = this.getServices(agentId);
1851
+ const { conv, mem, route } = this.getServices(agentId);
1418
1852
  const s = this.getOrCreate(p.sessionId, agentId);
1419
- if (s.finalizedAt) return;
1420
1853
  s.sessionKey = p.sessionKey ?? s.sessionKey; s.sessionFile = p.sessionFile ?? s.sessionFile;
1421
1854
  s.agentId = agentId; s.updatedAt = new Date().toISOString();
1422
1855
  const snap = await conv.loadSnapshot(s, p.messages ?? []);
1423
1856
  if (!conv.shouldMirror(s.sessionId, snap.messages)) { await this.persistState(); return; }
1424
1857
  if (snap.messages.length === 0 && !s.issueNumber) { await this.persistState(); return; }
1425
- await conv.ensureIssue(s, snap);
1426
- const next = snap.messages.slice(s.lastMirroredCount);
1427
- let allOk = true;
1428
- if (next.length > 0) { const n = await conv.appendComments(s.issueNumber!, next); s.lastMirroredCount += n; s.turnCount += n; allOk = n === next.length; }
1429
- await conv.syncLabels(s, snap, true);
1430
- await conv.syncBody(s, snap, "pending", true);
1431
- if (allOk) s.finalizedAt = new Date().toISOString();
1432
- this.markPostMirrorTasks(s);
1433
- this.markSummaryPending(s);
1858
+ await this.captureSessionFinalState(s, snap, conv, mem, route, { markFinalized: true, reason: "finalize" });
1859
+ }
1860
+
1861
+ private async captureSessionFinalState(
1862
+ session: SessionMirrorState,
1863
+ snapshot: TranscriptSnapshot,
1864
+ conv: ConversationMirror,
1865
+ mem: MemoryStore,
1866
+ route: ClawMemResolvedRoute,
1867
+ options: { markFinalized: boolean; reason: string },
1868
+ ): Promise<void> {
1869
+ await conv.ensureIssue(session, snapshot);
1870
+ const next = snapshot.messages.slice(session.lastMirroredCount);
1871
+ if (next.length > 0) {
1872
+ const n = await conv.appendComments(session.issueNumber!, next);
1873
+ session.lastMirroredCount += n;
1874
+ session.turnCount += n;
1875
+ }
1876
+
1877
+ const derived = this.ensureDerived(session);
1878
+ let summaryText = derived.summary.text?.trim() || "pending";
1879
+ let titleOverride = derived.summary.title?.trim() || session.issueTitle;
1880
+ let generatedTitle = Boolean(derived.summary.title?.trim());
1881
+ const targetCursor = snapshot.messages.length;
1882
+ const meaningfulTranscript = snapshot.messages.filter((message) => message.text.trim()).length >= 2;
1883
+
1884
+ if (meaningfulTranscript) {
1885
+ try {
1886
+ const artifacts = await this.resolveFinalArtifacts(session, snapshot, conv, mem);
1887
+ summaryText = artifacts.summary;
1888
+ if (artifacts.title?.trim()) {
1889
+ titleOverride = artifacts.title.trim();
1890
+ generatedTitle = true;
1891
+ }
1892
+ const storedCount = await this.applyFinalMemoryCandidates(session, mem, route, targetCursor, artifacts.candidates);
1893
+ if (storedCount > 0) {
1894
+ this.api.logger.info?.(
1895
+ `clawmem: ${options.reason} stored ${storedCount} memor${storedCount === 1 ? "y" : "ies"} for ${session.sessionId}`,
1896
+ );
1897
+ }
1898
+ } catch (error) {
1899
+ derived.summary.status = "error";
1900
+ derived.summary.lastError = String(error);
1901
+ derived.summary.updatedAt = new Date().toISOString();
1902
+ derived.memory.status = "error";
1903
+ derived.memory.lastError = String(error);
1904
+ derived.memory.updatedAt = new Date().toISOString();
1905
+ this.warn(`${options.reason} derive for ${session.sessionId}`, error);
1906
+ }
1907
+ } else {
1908
+ derived.summary.status = "complete";
1909
+ derived.summary.basedOnCursor = targetCursor;
1910
+ derived.summary.lastError = undefined;
1911
+ derived.summary.updatedAt = new Date().toISOString();
1912
+ derived.memory.capturedCursor = targetCursor;
1913
+ derived.memory.status = "complete";
1914
+ derived.memory.lastError = undefined;
1915
+ derived.memory.updatedAt = new Date().toISOString();
1916
+ }
1917
+
1918
+ try {
1919
+ await conv.syncLabels(session, snapshot, true);
1920
+ await conv.syncBody(session, snapshot, summaryText, true, titleOverride);
1921
+ derived.summary.text = summaryText;
1922
+ derived.summary.basedOnCursor = targetCursor;
1923
+ derived.summary.status = "complete";
1924
+ derived.summary.lastError = undefined;
1925
+ derived.summary.updatedAt = new Date().toISOString();
1926
+ if (titleOverride?.trim()) {
1927
+ derived.summary.title = titleOverride.trim();
1928
+ session.issueTitle = titleOverride.trim();
1929
+ if (generatedTitle) session.titleSource = "llm";
1930
+ }
1931
+ if (options.markFinalized && !session.finalizedAt) session.finalizedAt = new Date().toISOString();
1932
+ } catch (error) {
1933
+ derived.summary.status = "error";
1934
+ derived.summary.lastError = String(error);
1935
+ derived.summary.updatedAt = new Date().toISOString();
1936
+ this.warn(`${options.reason} summary sync for ${session.sessionId}`, error);
1937
+ }
1938
+
1939
+ session.updatedAt = new Date().toISOString();
1434
1940
  await this.persistState();
1435
- this.kickDerivedWork(scopeKey, agentId, p.reason ?? "finalize");
1941
+ }
1942
+
1943
+ private async resolveFinalArtifacts(
1944
+ session: SessionMirrorState,
1945
+ snapshot: TranscriptSnapshot,
1946
+ conv: ConversationMirror,
1947
+ mem: MemoryStore,
1948
+ ): Promise<{ summary: string; title?: string; candidates: MemoryCandidate[] }> {
1949
+ const cached = getCachedFinalArtifacts(session, snapshot.messages.length);
1950
+ if (cached) return cached;
1951
+
1952
+ let schema;
1953
+ try {
1954
+ schema = await mem.listSchema();
1955
+ } catch (error) {
1956
+ this.warn(`finalize schema load for ${session.sessionId}`, error);
1957
+ }
1958
+
1959
+ const artifacts = await conv.generateFinalArtifacts(session, snapshot, schema);
1960
+ const derived = this.ensureDerived(session);
1961
+ const now = new Date().toISOString();
1962
+ derived.summary.text = artifacts.summary;
1963
+ derived.summary.title = artifacts.title?.trim() || undefined;
1964
+ derived.summary.basedOnCursor = snapshot.messages.length;
1965
+ derived.summary.lastError = undefined;
1966
+ derived.summary.updatedAt = now;
1967
+ derived.memory.candidates = artifacts.candidates;
1968
+ derived.memory.lastError = undefined;
1969
+ derived.memory.updatedAt = now;
1970
+ return artifacts;
1971
+ }
1972
+
1973
+ private async applyFinalMemoryCandidates(
1974
+ session: SessionMirrorState,
1975
+ mem: MemoryStore,
1976
+ route: ClawMemResolvedRoute,
1977
+ targetCursor: number,
1978
+ candidates: MemoryCandidate[],
1979
+ ): Promise<number> {
1980
+ const derived = this.ensureDerived(session);
1981
+ if (derived.memory.capturedCursor >= targetCursor && derived.memory.status === "complete") {
1982
+ derived.memory.candidates = undefined;
1983
+ return 0;
1984
+ }
1985
+ if (candidates.length === 0) {
1986
+ derived.memory.candidates = undefined;
1987
+ derived.memory.capturedCursor = targetCursor;
1988
+ derived.memory.status = "complete";
1989
+ derived.memory.lastError = undefined;
1990
+ derived.memory.updatedAt = new Date().toISOString();
1991
+ return 0;
1992
+ }
1993
+ try {
1994
+ const result = await this.enqueueRepoWrite(this.repoWriteKey(route), async () => {
1995
+ let createdCount = 0;
1996
+ for (const candidate of candidates) {
1997
+ const stored = await mem.store({
1998
+ ...(candidate.title ? { title: candidate.title } : {}),
1999
+ detail: candidate.detail,
2000
+ ...(candidate.kind ? { kind: candidate.kind } : {}),
2001
+ ...(candidate.topics?.length ? { topics: candidate.topics } : {}),
2002
+ });
2003
+ if (stored.created) createdCount++;
2004
+ }
2005
+ return createdCount;
2006
+ });
2007
+ derived.memory.candidates = undefined;
2008
+ derived.memory.capturedCursor = targetCursor;
2009
+ derived.memory.status = "complete";
2010
+ derived.memory.lastError = undefined;
2011
+ derived.memory.updatedAt = new Date().toISOString();
2012
+ return result;
2013
+ } catch (error) {
2014
+ derived.memory.candidates = candidates;
2015
+ derived.memory.status = "error";
2016
+ derived.memory.lastError = String(error);
2017
+ derived.memory.updatedAt = new Date().toISOString();
2018
+ this.warn(`finalize memory store for ${session.sessionId}`, error);
2019
+ return 0;
2020
+ }
1436
2021
  }
1437
2022
 
1438
2023
  // --- Infrastructure ---
@@ -1440,9 +2025,6 @@ class ClawMemService {
1440
2025
  private enqueueSessionIo<T>(sessionId: string, task: () => Promise<T>): Promise<T> {
1441
2026
  return this.ioQueue.enqueue(sessionId, async () => { await this.ensureLoaded(); return task(); });
1442
2027
  }
1443
- private enqueueSessionDerived<T>(sessionId: string, task: () => Promise<T>): Promise<T> {
1444
- return this.deriveQueue.enqueue(sessionId, async () => { await this.ensureLoaded(); return task(); });
1445
- }
1446
2028
  private enqueueRepoWrite<T>(repoKey: string, task: () => Promise<T>): Promise<T> {
1447
2029
  return this.repoWriteQueue.enqueue(repoKey, task);
1448
2030
  }
@@ -1469,15 +2051,10 @@ class ClawMemService {
1469
2051
  lastMirroredCount: 0,
1470
2052
  turnCount: 0,
1471
2053
  derived: {
1472
- digest: { cursor: 0, status: "idle", attempt: 0 },
1473
2054
  summary: { basedOnCursor: 0, status: "idle" },
1474
2055
  memory: {
1475
- extractCursor: 0,
1476
- appliedCursor: 0,
1477
- extractStatus: "idle",
1478
- reconcileStatus: "idle",
1479
- attempt: 0,
1480
- pendingCandidates: [],
2056
+ capturedCursor: 0,
2057
+ status: "idle",
1481
2058
  },
1482
2059
  },
1483
2060
  createdAt: now,
@@ -1490,68 +2067,15 @@ class ClawMemService {
1490
2067
  private ensureDerived(session: SessionMirrorState): SessionDerivedState {
1491
2068
  if (!session.derived) {
1492
2069
  session.derived = {
1493
- digest: { cursor: 0, status: "idle", attempt: 0 },
1494
2070
  summary: { basedOnCursor: 0, status: "idle" },
1495
2071
  memory: {
1496
- extractCursor: 0,
1497
- appliedCursor: session.lastMemorySyncCount ?? 0,
1498
- extractStatus: "idle",
1499
- reconcileStatus: "idle",
1500
- attempt: 0,
1501
- pendingCandidates: [],
2072
+ capturedCursor: 0,
2073
+ status: "idle",
1502
2074
  },
1503
2075
  };
1504
2076
  }
1505
2077
  return session.derived;
1506
2078
  }
1507
-
1508
- private syncLegacyTaskFields(session: SessionMirrorState): void {
1509
- const derived = this.ensureDerived(session);
1510
- session.summaryStatus = derived.summary.status === "complete" ? "complete" : session.finalizedAt ? "pending" : undefined;
1511
- session.lastMemorySyncCount = derived.memory.appliedCursor;
1512
- }
1513
-
1514
- private hasMeaningfulTranscript(session: SessionMirrorState): boolean {
1515
- return Math.max(session.lastMirroredCount, session.turnCount) >= 2;
1516
- }
1517
-
1518
- private needsDigest(session: SessionMirrorState): boolean {
1519
- if (!this.hasMeaningfulTranscript(session)) return false;
1520
- const derived = this.ensureDerived(session);
1521
- return derived.digest.cursor < session.lastMirroredCount;
1522
- }
1523
-
1524
- private needsFinalSummary(session: SessionMirrorState): boolean {
1525
- if (!session.finalizedAt || !this.hasMeaningfulTranscript(session)) return false;
1526
- const derived = this.ensureDerived(session);
1527
- return derived.summary.status !== "complete" || derived.summary.basedOnCursor < session.lastMirroredCount;
1528
- }
1529
-
1530
- private needsMemoryExtract(session: SessionMirrorState): boolean {
1531
- if (!this.hasMeaningfulTranscript(session)) return false;
1532
- const derived = this.ensureDerived(session);
1533
- return derived.memory.extractCursor < session.lastMirroredCount;
1534
- }
1535
-
1536
- private needsMemoryReconcile(session: SessionMirrorState): boolean {
1537
- if (!this.hasMeaningfulTranscript(session)) return false;
1538
- const derived = this.ensureDerived(session);
1539
- return derived.memory.pendingCandidates.length > 0 || derived.memory.appliedCursor < derived.memory.extractCursor;
1540
- }
1541
-
1542
- private markPostMirrorTasks(session: SessionMirrorState): void {
1543
- const derived = this.ensureDerived(session);
1544
- if (this.needsDigest(session)) derived.digest.status = "pending";
1545
- if (this.needsMemoryExtract(session)) derived.memory.extractStatus = "pending";
1546
- if (this.needsMemoryReconcile(session)) derived.memory.reconcileStatus = "pending";
1547
- this.syncLegacyTaskFields(session);
1548
- }
1549
-
1550
- private markSummaryPending(session: SessionMirrorState): void {
1551
- const derived = this.ensureDerived(session);
1552
- derived.summary.status = "pending";
1553
- this.syncLegacyTaskFields(session);
1554
- }
1555
2079
  private resolveTranscriptAgentId(sessionId: string, sessionFile: string): string | null {
1556
2080
  const fromPath = inferAgentIdFromTranscriptPath(sessionFile);
1557
2081
  if (fromPath) return fromPath;
@@ -1676,279 +2200,6 @@ class ClawMemService {
1676
2200
  },
1677
2201
  });
1678
2202
  }
1679
- private clearRecoveryTimer(scopeKey: string): void {
1680
- const prev = this.recoveryTimers.get(scopeKey);
1681
- if (!prev) return;
1682
- clearTimeout(prev);
1683
- this.recoveryTimers.delete(scopeKey);
1684
- }
1685
-
1686
- private recoverDerivedWorkOnStart(): void {
1687
- const recoverableSessions = Object.values(this.state.sessions)
1688
- .filter((session) => this.sessionNeedsDerivedWork(session))
1689
- .sort((a, b) => Date.parse(b.updatedAt ?? b.createdAt ?? "") - Date.parse(a.updatedAt ?? a.createdAt ?? ""));
1690
- for (const session of recoverableSessions) {
1691
- this.scheduleDerivedRecovery(sessionScopeKey(session.sessionId, session.agentId), normalizeAgentId(session.agentId), {
1692
- delayMs: 0,
1693
- attempt: 0,
1694
- reason: "startup-recovery",
1695
- });
1696
- }
1697
- }
1698
-
1699
- private kickDerivedWork(scopeKey: string, agentId: string, reason: string): void {
1700
- this.clearRecoveryTimer(scopeKey);
1701
- void this.track(this.enqueueSessionDerived(scopeKey, () => this.runSessionDerivedWork(scopeKey, agentId, 0, reason)))
1702
- .catch((error) => this.warn(`derived work for ${scopeKey}`, error));
1703
- }
1704
-
1705
- private scheduleDerivedRecovery(
1706
- scopeKey: string,
1707
- agentId: string,
1708
- options: { delayMs?: number; attempt?: number; reason?: string } = {},
1709
- ): void {
1710
- this.clearRecoveryTimer(scopeKey);
1711
- const delayMs = Math.max(0, options.delayMs ?? 0);
1712
- const attempt = Math.max(0, options.attempt ?? 0);
1713
- const reason = options.reason ?? "scheduled-recovery";
1714
- const timer = setTimeout(() => {
1715
- this.recoveryTimers.delete(scopeKey);
1716
- void this.track(this.enqueueSessionDerived(scopeKey, () => this.runSessionDerivedWork(scopeKey, agentId, attempt, reason)))
1717
- .catch((error) => this.warn(`derived recovery for ${scopeKey}`, error));
1718
- }, delayMs);
1719
- timer.unref?.();
1720
- this.recoveryTimers.set(scopeKey, timer);
1721
- }
1722
-
1723
- private async runSessionDerivedWork(scopeKey: string, agentId: string, attempt: number, reason: string): Promise<void> {
1724
- const session = this.state.sessions[scopeKey];
1725
- if (!session || !this.sessionNeedsDerivedWork(session)) return;
1726
- if (!(await this.ensureDefaultRepoConfigured(agentId))) return;
1727
- const { route, conv, mem, client } = this.getServices(agentId);
1728
- const snap = await conv.loadSnapshot(session, []);
1729
- if (!conv.shouldMirror(session.sessionId, snap.messages) || snap.messages.length === 0) return;
1730
-
1731
- let retryNeeded = false;
1732
- const derived = this.ensureDerived(session);
1733
- const updateLegacyAndPersist = async (): Promise<void> => {
1734
- this.syncLegacyTaskFields(session);
1735
- await this.persistState();
1736
- };
1737
- const mirroredCount = Math.min(session.lastMirroredCount, snap.messages.length);
1738
- if (mirroredCount <= 0) return;
1739
- const canCombineDeltaDerivation = this.needsDigest(session)
1740
- && this.needsMemoryExtract(session)
1741
- && derived.digest.cursor === derived.memory.extractCursor;
1742
-
1743
- if (canCombineDeltaDerivation) {
1744
- const deriveTarget = mirroredCount;
1745
- const deriveFromCursor = Math.min(derived.digest.cursor, deriveTarget);
1746
- const deriveSnapshot: TranscriptSnapshot = { ...snap, messages: snap.messages.slice(0, deriveTarget) };
1747
- const startedAt = new Date().toISOString();
1748
- derived.digest.status = "running";
1749
- derived.digest.updatedAt = startedAt;
1750
- derived.memory.extractStatus = "running";
1751
- derived.memory.updatedAt = startedAt;
1752
- await updateLegacyAndPersist();
1753
- try {
1754
- const result = await conv.deriveDelta(session, deriveSnapshot, deriveFromCursor, derived.digest.text);
1755
- derived.digest.text = result.digest.trim();
1756
- derived.digest.title = result.title?.trim() || derived.digest.title;
1757
- derived.digest.cursor = deriveTarget;
1758
- derived.digest.status = deriveTarget < session.lastMirroredCount ? "pending" : "complete";
1759
- derived.digest.attempt = 0;
1760
- derived.digest.lastError = undefined;
1761
- derived.digest.updatedAt = new Date().toISOString();
1762
- if (result.title?.trim() && session.issueNumber) {
1763
- await client.updateIssue(session.issueNumber, { title: result.title.trim() });
1764
- session.issueTitle = result.title.trim();
1765
- session.titleSource = "digest";
1766
- }
1767
-
1768
- derived.memory.pendingCandidates = mergeMemoryCandidates(derived.memory.pendingCandidates, result.candidates);
1769
- derived.memory.extractCursor = deriveTarget;
1770
- derived.memory.extractStatus = deriveTarget < session.lastMirroredCount ? "pending" : "complete";
1771
- derived.memory.attempt = 0;
1772
- derived.memory.lastError = undefined;
1773
- derived.memory.updatedAt = new Date().toISOString();
1774
- if (derived.memory.pendingCandidates.length === 0) {
1775
- derived.memory.appliedCursor = Math.max(derived.memory.appliedCursor, deriveTarget);
1776
- derived.memory.reconcileStatus = "complete";
1777
- } else {
1778
- derived.memory.reconcileStatus = "pending";
1779
- }
1780
- } catch (error) {
1781
- const failedAt = new Date().toISOString();
1782
- derived.digest.status = "error";
1783
- derived.digest.attempt += 1;
1784
- derived.digest.lastError = String(error);
1785
- derived.digest.updatedAt = failedAt;
1786
- derived.memory.extractStatus = "error";
1787
- derived.memory.attempt += 1;
1788
- derived.memory.lastError = String(error);
1789
- derived.memory.updatedAt = failedAt;
1790
- retryNeeded = true;
1791
- this.warn(`background derive delta for ${session.sessionId}`, error);
1792
- }
1793
- await updateLegacyAndPersist();
1794
- }
1795
-
1796
- if (!canCombineDeltaDerivation && this.needsDigest(session)) {
1797
- const digestTarget = mirroredCount;
1798
- const digestFromCursor = Math.min(derived.digest.cursor, digestTarget);
1799
- const digestSnapshot: TranscriptSnapshot = { ...snap, messages: snap.messages.slice(0, digestTarget) };
1800
- derived.digest.status = "running";
1801
- derived.digest.updatedAt = new Date().toISOString();
1802
- await updateLegacyAndPersist();
1803
- try {
1804
- const result = await conv.generateRollingDigest(session, digestSnapshot, digestFromCursor, derived.digest.text);
1805
- derived.digest.text = result.digest.trim();
1806
- derived.digest.title = result.title?.trim() || derived.digest.title;
1807
- derived.digest.cursor = digestTarget;
1808
- derived.digest.status = digestTarget < session.lastMirroredCount ? "pending" : "complete";
1809
- derived.digest.attempt = 0;
1810
- derived.digest.lastError = undefined;
1811
- derived.digest.updatedAt = new Date().toISOString();
1812
- if (result.title?.trim() && session.issueNumber) {
1813
- await client.updateIssue(session.issueNumber, { title: result.title.trim() });
1814
- session.issueTitle = result.title.trim();
1815
- session.titleSource = "digest";
1816
- }
1817
- } catch (error) {
1818
- derived.digest.status = "error";
1819
- derived.digest.attempt += 1;
1820
- derived.digest.lastError = String(error);
1821
- derived.digest.updatedAt = new Date().toISOString();
1822
- retryNeeded = true;
1823
- this.warn(`background digest sync for ${session.sessionId}`, error);
1824
- }
1825
- await updateLegacyAndPersist();
1826
- }
1827
-
1828
- if (this.needsFinalSummary(session) && derived.digest.cursor >= session.lastMirroredCount) {
1829
- const summaryTarget = Math.min(session.lastMirroredCount, snap.messages.length);
1830
- const summarySnapshot: TranscriptSnapshot = { ...snap, messages: snap.messages.slice(0, summaryTarget) };
1831
- derived.summary.status = "running";
1832
- derived.summary.updatedAt = new Date().toISOString();
1833
- await updateLegacyAndPersist();
1834
- try {
1835
- const result = await conv.generateFinalSummaryFromDigest(session, summarySnapshot, derived.digest.text ?? "");
1836
- await conv.syncLabels(session, summarySnapshot, true);
1837
- await conv.syncBody(session, summarySnapshot, result.summary, true, result.title);
1838
- derived.summary.text = result.summary;
1839
- derived.summary.status = summaryTarget < session.lastMirroredCount ? "pending" : "complete";
1840
- derived.summary.basedOnCursor = summaryTarget;
1841
- derived.summary.lastError = undefined;
1842
- derived.summary.updatedAt = new Date().toISOString();
1843
- if (result.title?.trim()) {
1844
- session.issueTitle = result.title.trim();
1845
- session.titleSource = "llm";
1846
- }
1847
- this.maybeAutoNameRepo(agentId, result.summary, result.title);
1848
- } catch (error) {
1849
- derived.summary.status = "error";
1850
- derived.summary.lastError = String(error);
1851
- derived.summary.updatedAt = new Date().toISOString();
1852
- retryNeeded = true;
1853
- this.warn(`background summary sync for ${session.sessionId}`, error);
1854
- }
1855
- await updateLegacyAndPersist();
1856
- }
1857
-
1858
- if (!canCombineDeltaDerivation && this.needsMemoryExtract(session)) {
1859
- const extractTarget = Math.min(session.lastMirroredCount, snap.messages.length);
1860
- const extractFromCursor = Math.min(derived.memory.extractCursor, extractTarget);
1861
- const extractSnapshot: TranscriptSnapshot = { ...snap, messages: snap.messages.slice(0, extractTarget) };
1862
- derived.memory.extractStatus = "running";
1863
- derived.memory.updatedAt = new Date().toISOString();
1864
- await updateLegacyAndPersist();
1865
- try {
1866
- const candidates = await mem.extractCandidates(session, extractSnapshot, extractFromCursor, derived.digest.text);
1867
- derived.memory.pendingCandidates = mergeMemoryCandidates(derived.memory.pendingCandidates, candidates);
1868
- derived.memory.extractCursor = extractTarget;
1869
- derived.memory.extractStatus = extractTarget < session.lastMirroredCount ? "pending" : "complete";
1870
- derived.memory.attempt = 0;
1871
- derived.memory.lastError = undefined;
1872
- derived.memory.updatedAt = new Date().toISOString();
1873
- if (derived.memory.pendingCandidates.length === 0) {
1874
- derived.memory.appliedCursor = Math.max(derived.memory.appliedCursor, extractTarget);
1875
- derived.memory.reconcileStatus = "complete";
1876
- } else {
1877
- derived.memory.reconcileStatus = "pending";
1878
- }
1879
- } catch (error) {
1880
- derived.memory.extractStatus = "error";
1881
- derived.memory.attempt += 1;
1882
- derived.memory.lastError = String(error);
1883
- derived.memory.updatedAt = new Date().toISOString();
1884
- retryNeeded = true;
1885
- this.warn(`background memory extract for ${session.sessionId}`, error);
1886
- }
1887
- await updateLegacyAndPersist();
1888
- }
1889
-
1890
- if (this.needsMemoryReconcile(session)) {
1891
- if (derived.memory.pendingCandidates.length === 0) {
1892
- derived.memory.appliedCursor = derived.memory.extractCursor;
1893
- derived.memory.reconcileStatus = "complete";
1894
- derived.memory.updatedAt = new Date().toISOString();
1895
- await updateLegacyAndPersist();
1896
- } else {
1897
- const candidates = mergeMemoryCandidates([], derived.memory.pendingCandidates);
1898
- derived.memory.reconcileStatus = "running";
1899
- derived.memory.updatedAt = new Date().toISOString();
1900
- await updateLegacyAndPersist();
1901
- try {
1902
- const decision = await mem.reconcileCandidates(session, candidates);
1903
- const { savedCount, staledCount } = await this.enqueueRepoWrite(
1904
- this.repoWriteKey(route),
1905
- () => mem.applyReconciledDecision(decision),
1906
- );
1907
- if (savedCount > 0 || staledCount > 0) {
1908
- this.api.logger.info?.(
1909
- `clawmem: synced memories for ${session.sessionId} (saved=${savedCount}, stale=${staledCount})`,
1910
- );
1911
- }
1912
- const consumed = new Set(candidates.map((candidate) => candidate.candidateId));
1913
- derived.memory.pendingCandidates = derived.memory.pendingCandidates.filter((candidate) => !consumed.has(candidate.candidateId));
1914
- derived.memory.appliedCursor = derived.memory.extractCursor;
1915
- derived.memory.reconcileStatus = derived.memory.pendingCandidates.length > 0 ? "pending" : "complete";
1916
- derived.memory.attempt = 0;
1917
- derived.memory.lastError = undefined;
1918
- derived.memory.updatedAt = new Date().toISOString();
1919
- } catch (error) {
1920
- derived.memory.reconcileStatus = "error";
1921
- derived.memory.attempt += 1;
1922
- derived.memory.lastError = String(error);
1923
- derived.memory.updatedAt = new Date().toISOString();
1924
- retryNeeded = true;
1925
- this.warn(`background memory reconcile for ${session.sessionId}`, error);
1926
- }
1927
- await updateLegacyAndPersist();
1928
- }
1929
- }
1930
-
1931
- if (retryNeeded && this.sessionNeedsDerivedWork(session)) {
1932
- const delayMs = DERIVED_WORK_RECOVERY_DELAYS_MS[Math.min(attempt, DERIVED_WORK_RECOVERY_DELAYS_MS.length - 1)] ?? 120000;
1933
- this.api.logger.warn?.(
1934
- `clawmem: derived work incomplete for ${session.sessionId}; retrying in ${Math.round(delayMs / 1000)}s (${reason})`,
1935
- );
1936
- this.scheduleDerivedRecovery(scopeKey, agentId, { delayMs, attempt: attempt + 1, reason: "retry" });
1937
- return;
1938
- }
1939
-
1940
- if (this.sessionNeedsDerivedWork(session)) {
1941
- this.kickDerivedWork(scopeKey, agentId, "follow-up");
1942
- }
1943
- }
1944
-
1945
- private sessionNeedsDerivedWork(session: SessionMirrorState): boolean {
1946
- return this.needsDigest(session)
1947
- || this.needsFinalSummary(session)
1948
- || this.needsMemoryExtract(session)
1949
- || this.needsMemoryReconcile(session);
1950
- }
1951
-
1952
2203
  private getServices(agentId?: string, repo?: string): { route: ClawMemResolvedRoute; conv: ConversationMirror; mem: MemoryStore; client: GitHubIssueClient } {
1953
2204
  const route = resolveAgentRoute(this.config, agentId, repo);
1954
2205
  const client = new GitHubIssueClient(route, this.api.logger);
@@ -1956,7 +2207,7 @@ class ClawMemService {
1956
2207
  route,
1957
2208
  client,
1958
2209
  conv: new ConversationMirror(client, this.api, this.config),
1959
- mem: new MemoryStore(client, this.api, this.config),
2210
+ mem: new MemoryStore(client),
1960
2211
  };
1961
2212
  }
1962
2213
  private resolveToolAgentId(agentId: unknown): string {
@@ -2040,28 +2291,6 @@ class ClawMemService {
2040
2291
  }
2041
2292
  return { value };
2042
2293
  }
2043
- /**
2044
- * After finalization, check if the repo still has an empty/default description.
2045
- * If so, use the conversation summary to suggest a meaningful name and update
2046
- * the repo description automatically. Best-effort, fire-and-forget.
2047
- */
2048
- private maybeAutoNameRepo(agentId: string, summary: string, title?: string): void {
2049
- if (!summary || summary.startsWith("failed:") || summary === "pending") return;
2050
- const snippet = title || summary.slice(0, 100);
2051
- void (async () => {
2052
- try {
2053
- const client = new GitHubIssueClient(resolveAgentRoute(this.config, agentId), this.api.logger);
2054
- const repo = await client.getRepoInfo();
2055
- // Only auto-name if description is still empty or a default placeholder.
2056
- if (repo.description && repo.description !== "My Memory Space" && repo.description !== "我的记忆空间" && repo.description !== "マイメモリースペース") return;
2057
- // Use the conversation title or summary as a lightweight description.
2058
- await client.updateRepoDescription(snippet);
2059
- this.api.logger.info?.(`clawmem: auto-named repo to "${snippet}"`);
2060
- } catch (e) {
2061
- this.api.logger.warn(`clawmem: auto-name repo failed: ${String(e)}`);
2062
- }
2063
- })();
2064
- }
2065
2294
  private warn(scope: string, error: unknown): void { this.api.logger.warn(`clawmem: ${scope} failed: ${String(error)}`); }
2066
2295
  }
2067
2296
 
@@ -2123,6 +2352,43 @@ export function buildAutoRecallContext(memories: Array<{
2123
2352
  ].join("\n");
2124
2353
  }
2125
2354
 
2355
+ export function buildClawMemPromptSection(params: MemoryPromptBuilderParams): string[] {
2356
+ const hasTool = (name: string) => params.availableTools.has(name);
2357
+ const retrievalTools = [
2358
+ hasTool("memory_recall") ? "`memory_recall`" : "",
2359
+ hasTool("memory_list") ? "`memory_list`" : "",
2360
+ hasTool("memory_get") ? "`memory_get`" : "",
2361
+ ].filter(Boolean);
2362
+ const routingTools = [hasTool("memory_repos") ? "`memory_repos`" : ""].filter(Boolean);
2363
+ const schemaTools = [hasTool("memory_labels") ? "`memory_labels`" : ""].filter(Boolean);
2364
+ const writeTools = [
2365
+ hasTool("memory_store") ? "`memory_store`" : "",
2366
+ hasTool("memory_update") ? "`memory_update`" : "",
2367
+ ].filter(Boolean);
2368
+ const hasForgetTool = hasTool("memory_forget");
2369
+
2370
+ const lines = [
2371
+ "## ClawMem",
2372
+ "ClawMem is the active long-term memory system for this OpenClaw installation.",
2373
+ "Core loop:",
2374
+ "- Before answering, ask whether prior memory could improve the answer. Default to yes for preferences, project history, decisions, lessons, workflows, conventions, recurring problems, and active tasks.",
2375
+ `- Treat auto-injected ClawMem context as a hint, not proof of absence.${retrievalTools.length > 0 ? ` If relevant memory may exist and the hint is weak or missing, retrieve explicitly with ${joinNaturalLanguageList(retrievalTools)}.` : ""}`,
2376
+ `${routingTools.length > 0 ? `- Before explicit memory work, choose the right repo. If unclear, inspect ${joinNaturalLanguageList(routingTools)} and then fall back to the agent's default repo.` : "- Before explicit memory work, choose the right repo instead of assuming every memory belongs in the default repo."}`,
2377
+ `${writeTools.length > 0 || hasForgetTool
2378
+ ? `- After answering, ask whether this turn created durable knowledge. If yes or unsure, write it now${writeTools.length > 0 ? ` with ${joinNaturalLanguageList(writeTools)}` : ""}${hasForgetTool ? `${writeTools.length > 0 ? "; " : " "}use \`memory_forget\` for stale or superseded memories` : ""} instead of waiting for background extraction.`
2379
+ : "- After answering, ask whether this turn created durable knowledge and save it immediately instead of waiting for background extraction."}`,
2380
+ "- Store one durable fact per memory. Skip temporary requests, tool chatter, startup boilerplate, and bundled summaries of unrelated facts.",
2381
+ "- Prefer an explicit short `title` plus a fuller `detail`. Write new human-readable memory text in the user's current language and keep structural labels machine-readable.",
2382
+ `${schemaTools.length > 0
2383
+ ? `- Reuse existing \`kind\` and \`topic\` labels by checking ${joinNaturalLanguageList(schemaTools)} first. If no current label fits, create one short stable machine-readable label instead of a translated or near-duplicate variant.`
2384
+ : "- Reuse existing `kind` and `topic` labels before inventing new ones. If no current label fits, create one short stable machine-readable label instead of a translated or near-duplicate variant."}`,
2385
+ "- Use the bundled `clawmem` skill for detailed routing, schema, collaboration, communication, and manual repo-backed workflows.",
2386
+ "",
2387
+ ];
2388
+
2389
+ return lines;
2390
+ }
2391
+
2126
2392
  export function extractPromptTextForRecall(event: unknown): string | undefined {
2127
2393
  const direct = normalizePromptText(event);
2128
2394
  if (direct) return direct;
@@ -2143,6 +2409,13 @@ export function extractPromptTextForRecall(event: unknown): string | undefined {
2143
2409
  ?? promptCandidates.find((candidate) => candidate.text)?.text;
2144
2410
  }
2145
2411
 
2412
+ function joinNaturalLanguageList(items: string[]): string {
2413
+ if (items.length === 0) return "";
2414
+ if (items.length === 1) return items[0]!;
2415
+ if (items.length === 2) return `${items[0]} and ${items[1]}`;
2416
+ return `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`;
2417
+ }
2418
+
2146
2419
  function extractPromptTextFromMessages(value: unknown): string | undefined {
2147
2420
  if (!Array.isArray(value)) return undefined;
2148
2421
  let fallback: string | undefined;
@@ -2207,6 +2480,23 @@ function candidatePromptText(value: unknown): { text?: string; changed: boolean
2207
2480
  return { changed: false };
2208
2481
  }
2209
2482
 
2483
+ function getCachedFinalArtifacts(
2484
+ session: SessionMirrorState,
2485
+ targetCursor: number,
2486
+ ): { summary: string; title?: string; candidates: MemoryCandidate[] } | null {
2487
+ const derived = session.derived;
2488
+ if (!derived) return null;
2489
+ const summary = derived.summary.text?.trim();
2490
+ if (!summary || derived.summary.basedOnCursor < targetCursor) return null;
2491
+ const hasCachedMemory = Array.isArray(derived.memory.candidates) || derived.memory.capturedCursor >= targetCursor;
2492
+ if (!hasCachedMemory) return null;
2493
+ return {
2494
+ summary,
2495
+ ...(derived.summary.title?.trim() ? { title: derived.summary.title.trim() } : {}),
2496
+ candidates: Array.isArray(derived.memory.candidates) ? derived.memory.candidates : [],
2497
+ };
2498
+ }
2499
+
2210
2500
  export function resolvePromptHookMode(api: Pick<OpenClawPluginApi, "runtime">): PromptHookMode {
2211
2501
  const hostVersion = resolveOpenClawHostVersion(api);
2212
2502
  if (!hostVersion) return "legacy";
@@ -2377,6 +2667,20 @@ function renderUserOrganizationInvitationLine(invitation: { id?: number; role?:
2377
2667
  return `${org} [role:${role}${idText}${created}${expires}${teamsText}${inviter}]`;
2378
2668
  }
2379
2669
 
2670
+ function renderOrganizationMembershipLine(membership: {
2671
+ state?: string;
2672
+ role?: string;
2673
+ organization?: { login?: string };
2674
+ user?: { login?: string; name?: string };
2675
+ }): string {
2676
+ const login = membership.user?.login?.trim() || membership.user?.name?.trim() || "unknown-user";
2677
+ const name = membership.user?.name?.trim() && membership.user?.name?.trim() !== login ? ` (${membership.user.name.trim()})` : "";
2678
+ const state = membership.state?.trim() || "unknown";
2679
+ const role = membership.role?.trim() || "unknown";
2680
+ const org = membership.organization?.login?.trim();
2681
+ return `${login}${name} [state:${state} role:${role}${org ? ` org:${org}` : ""}]`;
2682
+ }
2683
+
2380
2684
  function canonicalPermission(permissions?: Record<string, boolean | undefined>, explicit?: string): string {
2381
2685
  const direct = normalizePermissionAlias(explicit);
2382
2686
  if (direct) return direct;
@@ -2398,4 +2702,9 @@ function normalizePermissionAlias(value: unknown): "none" | CollaborationPermiss
2398
2702
  return undefined;
2399
2703
  }
2400
2704
 
2705
+ function isHttpStatusError(error: unknown, status: number): boolean {
2706
+ const value = String(error);
2707
+ return value.includes(`HTTP ${status}:`);
2708
+ }
2709
+
2401
2710
  export function createClawMemPlugin(api: OpenClawPluginApi): void { new ClawMemService(api).register(); }