import path from "node:path";
import { createId, normalizeId, nowIso, readJsonFile, writeJsonFile } from "../../shared/index.js";
import { listAgentThreadHelpers } from "../agent-thread/index.js";
import { listTeamInbox } from "./mailbox.js";
import { listTeamTasks } from "./task-board.js";
import { teamRoot } from "./store.js";
export function memberMemoryPath(store, runId, memberName) {
    return path.join(teamRoot(store, runId), "member-memory", `${normalizeId(memberName)}.json`);
}
export async function loadMemberMemory(store, runId, memberName) {
    return readJsonFile(memberMemoryPath(store, runId, memberName));
}
export async function writeMemberMemoryCheckpoint(store, runId, runtime, member, input) {
    const existing = await loadMemberMemory(store, runId, String(member.name));
    const [messages, tasks] = await Promise.all([
        listTeamInbox(store, runId, String(member.name), { includeAcknowledged: false }),
        listTeamTasks(store, runId),
    ]);
    const openTasks = tasks.filter((task) => task.owner_agent === member.name && task.status !== "completed" && task.status !== "cancelled");
    const helpers = await listAgentThreadHelpers(store, runId, String(member.name)).catch(() => []);
    const recentHelpers = helpers.slice(-5);
    const checkpoint = {
        checkpoint_id: createId("member_memory"),
        created_at: nowIso(),
        session_id: input.sessionId,
        summary: `${input.reason}: preserve ${member.name} contract, ${messages.length} unread message(s), ${openTasks.length} open assigned task(s), team ${runtime.team_name ?? runtime.team_id ?? runId}.`,
        semantic_summary: `${member.name} is ${member.status}; preserve role objective, ${openTasks.length} open task(s), ${messages.length} unread message(s), ${recentHelpers.length} recent helper record(s).`,
        known_outputs: [
            ...(member.expected_outputs ?? []),
            ...recentHelpers.flatMap((helper) => helper.result_ref ? [helper.result_ref] : []),
        ].slice(-12),
        open_questions: messages.slice(0, 5).map((message) => `${message.message_id} from ${message.from}: ${message.body.slice(0, 160)}`),
        next_local_actions: openTasks.slice(0, 6).map((task) => `${task.team_task_id}: ${task.title}`),
        helper_refs: recentHelpers.map((helper) => `${helper.helper_id}:${helper.status}${helper.background_id ? `:${helper.background_id}` : ""}`),
        last_result_refs: recentHelpers.flatMap((helper) => helper.result_ref ? [helper.result_ref] : []),
        unread_message_count: messages.length,
        open_task_ids: openTasks.map((task) => task.team_task_id),
        role_contract: {
            role_id: String(member.name),
            role_label: member.role_label ?? String(member.name),
            status: member.status,
            capability_profile: member.capability_profile ? String(member.capability_profile) : undefined,
            write_surface: member.write_surface,
            read_paths: member.read_paths ?? [],
            write_paths: member.write_paths ?? [],
            stop_condition: member.stop_condition,
        },
    };
    const memory = {
        version: 1,
        run_id: runId,
        member: String(member.name),
        updated_at: checkpoint.created_at,
        checkpoints: [...(existing?.checkpoints ?? []), checkpoint].slice(-12),
    };
    await writeJsonFile(memberMemoryPath(store, runId, String(member.name)), memory);
    return memory;
}
export function renderMemberMemoryContext(memory) {
    const latest = memory?.checkpoints.at(-1);
    if (!memory || !latest)
        return undefined;
    const knownOutputs = latest.known_outputs ?? [];
    const openQuestions = latest.open_questions ?? [];
    const nextLocalActions = latest.next_local_actions ?? [];
    const helperRefs = latest.helper_refs ?? [];
    const lastResultRefs = latest.last_result_refs ?? [];
    return `<system-reminder>
[SEED member memory]
Member: ${memory.member}
Updated: ${memory.updated_at}
Latest checkpoint: ${latest.summary}
Semantic summary: ${latest.semantic_summary ?? latest.summary}
Role: ${latest.role_contract.role_label} status:${latest.role_contract.status} capability:${latest.role_contract.capability_profile ?? "unspecified"} surface:${latest.role_contract.write_surface ?? "read_only_or_coordination_only"}
Read paths: ${latest.role_contract.read_paths.join(", ") || "none"}
Write paths: ${latest.role_contract.write_paths.join(", ") || "none"}
Open assigned tasks: ${latest.open_task_ids.join(", ") || "none"}
Unread messages at compaction: ${latest.unread_message_count}
Known outputs: ${knownOutputs.join(", ") || "none"}
Open questions: ${openQuestions.join(" | ") || "none"}
Next local actions: ${nextLocalActions.join(" | ") || "none"}
Helper refs: ${helperRefs.join(", ") || "none"}
Last result refs: ${lastResultRefs.join(", ") || "none"}

Continue from this memory. Do not restart completed work; ask Lab-Representative or read the roster/inbox when state is stale.
</system-reminder>`;
}
//# sourceMappingURL=member-memory.js.map