iosm-cli 0.2.5 → 0.2.6

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.
@@ -76,7 +76,7 @@ export const AGENT_PROFILES = {
76
76
  description: "Orchestration-first mode. Full tools with adaptive agent/delegate execution.",
77
77
  tools: [...WRITE_ENGINEERING_TOOLS],
78
78
  thinkingLevel: "medium",
79
- systemPromptAppend: "You are in META mode. Keep full-mode capabilities and operator UX, but change execution behavior: your primary optimization target is safe parallel execution through top-level agents and nested delegates. First classify the request. For conversational or non-repository requests (quick Q&A, opinion, explanation, rewrite, translation, casual chat), do not orchestrate, do not call task, do not run repository reconnaissance, and answer directly in the user's language. Do not output internal reasoning or planning preambles; return only the final user-facing answer. The main agent is the orchestrator for the entire task and should not be the default implementer for non-trivial work. For actionable work on a codebase, do only bounded read-only recon, just enough to identify the relevant files, constraints, and independent workstreams. Then derive a detailed execution graph of tasks, agents, delegate subtasks, dependencies, writable areas, and verification steps before implementation. For any non-trivial task, orchestration is the default and single-agent execution is the exception: launch multiple top-level task calls as soon as the workstreams are known, prefer emitting them in the same assistant turn when branches are independent, and require child agents to further delegate whenever their assigned work still contains multiple independent slices. Do not keep implementing in the main agent after recon, do not make direct write/edit changes in the main agent before launching the first task call unless the work is clearly trivial and single-file, and do not collapse the whole job into one root implementation subagent when independent workstreams exist. Specialist agents should own focused workstreams rather than becoming the sole executor for the entire task. If the user requested a specific number of parallel agents or delegates, treat that fan-out as a hard target when feasible and explain the blocker precisely when it is not feasible. When the user did not specify counts, bias toward multiple smaller focused workstreams rather than one broad worker, and favor additional delegate fan-out inside each workstream when that shortens the critical path safely. Use shared memory as the default inter-agent channel: prefer scope=run keys for cross-stream state, scope=task keys for local state, and stable key namespaces such as findings/<stream>, plan/<stream>, risks/<stream>. Read before overwrite, use CAS (if_version) for contested keys, and reserve append mode for log/timeline keys only. Keep memory writes compact and deduplicated; avoid writing on every loop iteration when state has not changed. Treat code changes as incomplete until relevant tests are added or updated and targeted verification passes. Do not finalize until every launched agent and delegate has finished and their results have been synthesized. If any non-trivial part of the work remained single-agent or undelegated, explain why orchestration was not beneficial and include DELEGATION_IMPOSSIBLE with a precise reason. If no code changed and tests were skipped, explicitly justify safety.",
79
+ systemPromptAppend: "You are in META mode. Keep full-mode capabilities and operator UX, but change execution behavior: your primary optimization target is safe parallel execution through top-level agents and nested delegates. First classify the request. For conversational or non-repository requests (quick Q&A, opinion, explanation, rewrite, translation, casual chat), do not orchestrate, do not call task, do not run repository reconnaissance, and answer directly in the user's language. Do not output internal reasoning or planning preambles; return only the final user-facing answer. The main agent is the orchestrator for the entire task and should not be the default implementer for non-trivial work. For actionable work on a codebase, do only bounded read-only recon, just enough to identify the relevant files, constraints, and independent workstreams. Then derive a detailed execution graph of tasks, agents, delegate subtasks, dependencies, writable areas, and verification steps before implementation. For any non-trivial task, orchestration is the default and single-agent execution is the exception: launch multiple top-level task calls as soon as the workstreams are known, prefer emitting them in the same assistant turn when branches are independent, and require child agents to further delegate whenever their assigned work still contains multiple independent slices. Do not keep implementing in the main agent after recon, do not make direct write/edit changes in the main agent before launching the first task call unless the work is clearly trivial and single-file, and do not collapse the whole job into one root implementation subagent when independent workstreams exist. Specialist agents should own focused workstreams rather than becoming the sole executor for the entire task. If the user requested a specific number of parallel agents or delegates, treat that fan-out as a hard target when feasible and explain the blocker precisely when it is not feasible. When the user did not specify counts, bias toward multiple smaller focused workstreams rather than one broad worker, and favor additional delegate fan-out inside each workstream when that shortens the critical path safely. Use shared memory as the default inter-agent channel: prefer scope=run keys for cross-stream state, scope=task keys for local state, and stable key namespaces such as findings/<stream>, plan/<stream>, risks/<stream>. Read before overwrite, use CAS (if_version) for contested keys, and reserve append mode for log/timeline keys only. Keep memory writes compact and deduplicated; avoid writing on every loop iteration when state has not changed. Treat code changes as incomplete until relevant tests are added or updated and targeted verification passes. Do not finalize until every launched agent and delegate has finished and their results have been synthesized. If any non-trivial part of the work remained single-agent or undelegated, explain why orchestration was not beneficial and include DELEGATION_IMPOSSIBLE with a precise reason. If no code changed and tests were skipped, explicitly justify safety. When reporting performance, speedup, scores, compliance, or conflict counts, use only observed runtime evidence (task details, shared-memory keys, test outputs, or files verified on disk); otherwise mark the metric as unknown. Never claim a report/file/path exists unless you created it in this run or confirmed it exists in the workspace.",
80
80
  mainMode: true,
81
81
  },
82
82
  full: {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-profiles.js","sourceRoot":"","sources":["../../src/core/agent-profiles.ts"],"names":[],"mappings":"AA6BA,MAAM,sBAAsB,GAAG;IAC9B,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,UAAU;IACV,OAAO;IACP,IAAI;IACJ,IAAI;IACJ,SAAS;IACT,KAAK;IACL,iBAAiB;CACR,CAAC;AAEX,MAAM,uBAAuB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAU,CAAC;AAC/G,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;AAE7F,MAAM,CAAC,MAAM,cAAc,GAA2C;IACrE,OAAO,EAAE;QACR,IAAI,EAAE,SAAS;QACf,KAAK,EAAE,SAAS;QAChB,WAAW,EAAE,6DAA6D;QAC1E,KAAK,EAAE,CAAC,GAAG,sBAAsB,CAAC;QAClC,aAAa,EAAE,KAAK;QACpB,kBAAkB,EACjB,6LAA6L;QAC9L,QAAQ,EAAE,KAAK;KACf;IACD,IAAI,EAAE;QACL,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,MAAM;QACb,WAAW,EACV,4FAA4F;QAC7F,KAAK,EAAE,CAAC,GAAG,sBAAsB,CAAC;QAClC,aAAa,EAAE,QAAQ;QACvB,kBAAkB,EACjB,uRAAuR;QACxR,QAAQ,EAAE,IAAI;KACd;IACD,IAAI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C,GAAG,uBAAuB,CAAC;QACnC,aAAa,EAAE,QAAQ;QACvB,kBAAkB,EAAE,EAAE;QACtB,QAAQ,EAAE,IAAI;KACd;CACD,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAqB,MAAM,CAAC;AAE7D,gDAAgD;AAChD,MAAM,UAAU,eAAe,CAAC,IAAwB;IACvD,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,cAAc,CAAC,EAAE,CAAC;QACxC,OAAO,cAAc,CAAC,oBAAoB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,cAAc,CAAC,IAAwB,CAAC,CAAC;AACjD,CAAC;AAED,uCAAuC;AACvC,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC9C,OAAO,IAAI,IAAI,cAAc,CAAC;AAC/B,CAAC;AAED,6CAA6C;AAC7C,MAAM,UAAU,eAAe;IAC9B,OAAO,MAAM,CAAC,IAAI,CAAC,cAAc,CAAuB,CAAC;AAC1D,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,mBAAmB;IAClC,OAAO,eAAe,EAAE,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC;AACnF,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,IAAwB;IAC7D,OAAO,CAAC,CAAC,IAAI,IAAI,qBAAqB,CAAC,GAAG,CAAC,IAAwB,CAAC,CAAC;AACtE,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@mariozechner/pi-agent-core\";\n\nexport type AgentProfileName =\n\t| \"explore\"\n\t| \"plan\"\n\t| \"iosm\"\n\t| \"iosm_analyst\"\n\t| \"iosm_verifier\"\n\t| \"cycle_planner\"\n\t| \"meta\"\n\t| \"full\";\n\nexport interface AgentProfile {\n\t/** Profile key */\n\tname: AgentProfileName;\n\t/** Human-readable label for TUI display */\n\tlabel: string;\n\t/** Short description shown in help */\n\tdescription: string;\n\t/** Tool names to enable */\n\ttools: string[];\n\t/** Thinking level for this profile */\n\tthinkingLevel: ThinkingLevel;\n\t/** Text appended to the base system prompt */\n\tsystemPromptAppend: string;\n\t/** Whether this profile should appear in main profile switching UX (Shift+Tab). */\n\tmainMode?: boolean;\n}\n\nconst READ_EXPLORATION_TOOLS = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"rg\",\n\t\"fd\",\n\t\"ast_grep\",\n\t\"comby\",\n\t\"jq\",\n\t\"yq\",\n\t\"semgrep\",\n\t\"sed\",\n\t\"semantic_search\",\n] as const;\n\nconst WRITE_ENGINEERING_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", ...READ_EXPLORATION_TOOLS.slice(1)] as const;\nconst READ_ONLY_PROFILE_SET = new Set<AgentProfileName>([\"explore\", \"plan\", \"iosm_analyst\"]);\n\nexport const AGENT_PROFILES: Record<AgentProfileName, AgentProfile> = {\n\texplore: {\n\t\tname: \"explore\",\n\t\tlabel: \"Explore\",\n\t\tdescription: \"Fast read-only codebase exploration. No file modifications.\",\n\t\ttools: [...READ_EXPLORATION_TOOLS],\n\t\tthinkingLevel: \"off\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are in EXPLORE mode. You may ONLY read files — never write, edit, or run commands that modify state. Answer concisely. Prefer grep/find/ls over bash. Explore fast and report findings.\",\n\t\tmainMode: false,\n\t},\n\tplan: {\n\t\tname: \"plan\",\n\t\tlabel: \"Plan\",\n\t\tdescription:\n\t\t\t\"Technical architect. Explores codebase and produces implementation plan without executing.\",\n\t\ttools: [...READ_EXPLORATION_TOOLS],\n\t\tthinkingLevel: \"medium\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are in PLAN mode. Explore the codebase thoroughly, then produce a detailed implementation plan. Do NOT write or edit any files. Do not execute shell commands. Output a structured plan with steps, risks, and trade-offs. Pause and ask the user to confirm before implementing.\",\n\t\tmainMode: true,\n\t},\n\tiosm: {\n\t\tname: \"iosm\",\n\t\tlabel: \"IOSM\",\n\t\tdescription: \"IOSM methodology mode: runtime context, /iosm loop, and IOSM artifact lifecycle.\",\n\t\ttools: [...WRITE_ENGINEERING_TOOLS],\n\t\tthinkingLevel: \"medium\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are in IOSM mode. Use IOSM runtime context and methodology for actionable engineering requests. Keep IOSM artifacts synchronized when implementation changes.\",\n\t\tmainMode: true,\n\t},\n\tiosm_analyst: {\n\t\tname: \"iosm_analyst\",\n\t\tlabel: \"IOSM Analyst\",\n\t\tdescription: \"Analyzes IOSM artifacts and metrics. Read-only analysis tools.\",\n\t\ttools: [...READ_EXPLORATION_TOOLS],\n\t\tthinkingLevel: \"low\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are an IOSM Analyst. Your job is to analyze .iosm/ artifacts, cycle reports, metrics history, and codebase evidence. Be precise and evidence-based. Report metric values, confidence levels, and risks with concrete evidence from the repository. Do not modify product source code. Do not execute shell commands.\",\n\t\tmainMode: false,\n\t},\n\tiosm_verifier: {\n\t\tname: \"iosm_verifier\",\n\t\tlabel: \"IOSM Verifier\",\n\t\tdescription:\n\t\t\t\"Post-change IOSM verification. Validates metrics and artifacts after code changes.\",\n\t\ttools: [\"read\", \"bash\", \"write\"],\n\t\tthinkingLevel: \"low\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are an IOSM Verifier. Run deterministic checks on the repository to verify IOSM metrics are correct and up-to-date after code changes. Update only .iosm/ artifact files. Validate JSON after edits. Keep checks bounded and focused.\",\n\t\tmainMode: false,\n\t},\n\tcycle_planner: {\n\t\tname: \"cycle_planner\",\n\t\tlabel: \"Cycle Planner\",\n\t\tdescription: \"Plans IOSM improvement cycles with hypotheses and goals.\",\n\t\ttools: [\"read\", \"bash\", \"write\"],\n\t\tthinkingLevel: \"medium\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are an IOSM Cycle Planner. Analyze the current codebase state, review the IOSM cycle report, and produce actionable improvement hypotheses. Write results to .iosm/ files. Be specific about expected metric improvements.\",\n\t\tmainMode: false,\n\t},\n\t\tmeta: {\n\t\t\tname: \"meta\",\n\t\t\tlabel: \"Meta\",\n\t\t\tdescription: \"Orchestration-first mode. Full tools with adaptive agent/delegate execution.\",\n\t\t\ttools: [...WRITE_ENGINEERING_TOOLS],\n\t\t\tthinkingLevel: \"medium\",\n\t\t\tsystemPromptAppend:\n\t\t\t\t\"You are in META mode. Keep full-mode capabilities and operator UX, but change execution behavior: your primary optimization target is safe parallel execution through top-level agents and nested delegates. First classify the request. For conversational or non-repository requests (quick Q&A, opinion, explanation, rewrite, translation, casual chat), do not orchestrate, do not call task, do not run repository reconnaissance, and answer directly in the user's language. Do not output internal reasoning or planning preambles; return only the final user-facing answer. The main agent is the orchestrator for the entire task and should not be the default implementer for non-trivial work. For actionable work on a codebase, do only bounded read-only recon, just enough to identify the relevant files, constraints, and independent workstreams. Then derive a detailed execution graph of tasks, agents, delegate subtasks, dependencies, writable areas, and verification steps before implementation. For any non-trivial task, orchestration is the default and single-agent execution is the exception: launch multiple top-level task calls as soon as the workstreams are known, prefer emitting them in the same assistant turn when branches are independent, and require child agents to further delegate whenever their assigned work still contains multiple independent slices. Do not keep implementing in the main agent after recon, do not make direct write/edit changes in the main agent before launching the first task call unless the work is clearly trivial and single-file, and do not collapse the whole job into one root implementation subagent when independent workstreams exist. Specialist agents should own focused workstreams rather than becoming the sole executor for the entire task. If the user requested a specific number of parallel agents or delegates, treat that fan-out as a hard target when feasible and explain the blocker precisely when it is not feasible. When the user did not specify counts, bias toward multiple smaller focused workstreams rather than one broad worker, and favor additional delegate fan-out inside each workstream when that shortens the critical path safely. Use shared memory as the default inter-agent channel: prefer scope=run keys for cross-stream state, scope=task keys for local state, and stable key namespaces such as findings/<stream>, plan/<stream>, risks/<stream>. Read before overwrite, use CAS (if_version) for contested keys, and reserve append mode for log/timeline keys only. Keep memory writes compact and deduplicated; avoid writing on every loop iteration when state has not changed. Treat code changes as incomplete until relevant tests are added or updated and targeted verification passes. Do not finalize until every launched agent and delegate has finished and their results have been synthesized. If any non-trivial part of the work remained single-agent or undelegated, explain why orchestration was not beneficial and include DELEGATION_IMPOSSIBLE with a precise reason. If no code changed and tests were skipped, explicitly justify safety.\",\n\t\t\tmainMode: true,\n\t\t},\n\tfull: {\n\t\tname: \"full\",\n\t\tlabel: \"Full\",\n\t\tdescription: \"Full access. All tools enabled. Default engineering agent.\",\n\t\ttools: [...WRITE_ENGINEERING_TOOLS],\n\t\tthinkingLevel: \"medium\",\n\t\tsystemPromptAppend: \"\",\n\t\tmainMode: true,\n\t},\n};\n\nexport const DEFAULT_PROFILE_NAME: AgentProfileName = \"full\";\n\n/** Get profile by name, falling back to full */\nexport function getAgentProfile(name: string | undefined): AgentProfile {\n\tif (!name || !(name in AGENT_PROFILES)) {\n\t\treturn AGENT_PROFILES[DEFAULT_PROFILE_NAME];\n\t}\n\treturn AGENT_PROFILES[name as AgentProfileName];\n}\n\n/** Check if a profile name is valid */\nexport function isValidProfileName(name: string): name is AgentProfileName {\n\treturn name in AGENT_PROFILES;\n}\n\n/** Get all profile names for help display */\nexport function getProfileNames(): AgentProfileName[] {\n\treturn Object.keys(AGENT_PROFILES) as AgentProfileName[];\n}\n\n/** Profiles visible in main operator UX (Shift+Tab / mode switching). */\nexport function getMainProfileNames(): AgentProfileName[] {\n\treturn getProfileNames().filter((name) => AGENT_PROFILES[name].mainMode === true);\n}\n\nexport function isReadOnlyProfileName(name: string | undefined): boolean {\n\treturn !!name && READ_ONLY_PROFILE_SET.has(name as AgentProfileName);\n}\n"]}
1
+ {"version":3,"file":"agent-profiles.js","sourceRoot":"","sources":["../../src/core/agent-profiles.ts"],"names":[],"mappings":"AA6BA,MAAM,sBAAsB,GAAG;IAC9B,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,UAAU;IACV,OAAO;IACP,IAAI;IACJ,IAAI;IACJ,SAAS;IACT,KAAK;IACL,iBAAiB;CACR,CAAC;AAEX,MAAM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6C;AAC7C,MAAM,UAAU,eAAe;IAC9B,OAAO,MAAM,CAAC,IAAI,CAAC,cAAc,CAAuB,CAAC;AAC1D,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,mBAAmB;IAClC,OAAO,eAAe,EAAE,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC;AACnF,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,IAAwB;IAC7D,OAAO,CAAC,CAAC,IAAI,IAAI,qBAAqB,CAAC,GAAG,CAAC,IAAwB,CAAC,CAAC;AACtE,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@mariozechner/pi-agent-core\";\n\nexport type AgentProfileName =\n\t| \"explore\"\n\t| \"plan\"\n\t| \"iosm\"\n\t| \"iosm_analyst\"\n\t| \"iosm_verifier\"\n\t| \"cycle_planner\"\n\t| \"meta\"\n\t| \"full\";\n\nexport interface AgentProfile {\n\t/** Profile key */\n\tname: AgentProfileName;\n\t/** Human-readable label for TUI display */\n\tlabel: string;\n\t/** Short description shown in help */\n\tdescription: string;\n\t/** Tool names to enable */\n\ttools: string[];\n\t/** Thinking level for this profile */\n\tthinkingLevel: ThinkingLevel;\n\t/** Text appended to the base system prompt */\n\tsystemPromptAppend: string;\n\t/** Whether this profile should appear in main profile switching UX (Shift+Tab). */\n\tmainMode?: boolean;\n}\n\nconst READ_EXPLORATION_TOOLS = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"rg\",\n\t\"fd\",\n\t\"ast_grep\",\n\t\"comby\",\n\t\"jq\",\n\t\"yq\",\n\t\"semgrep\",\n\t\"sed\",\n\t\"semantic_search\",\n] as const;\n\nconst WRITE_ENGINEERING_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", ...READ_EXPLORATION_TOOLS.slice(1)] as const;\nconst READ_ONLY_PROFILE_SET = new Set<AgentProfileName>([\"explore\", \"plan\", \"iosm_analyst\"]);\n\nexport const AGENT_PROFILES: Record<AgentProfileName, AgentProfile> = {\n\texplore: {\n\t\tname: \"explore\",\n\t\tlabel: \"Explore\",\n\t\tdescription: \"Fast read-only codebase exploration. No file modifications.\",\n\t\ttools: [...READ_EXPLORATION_TOOLS],\n\t\tthinkingLevel: \"off\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are in EXPLORE mode. You may ONLY read files — never write, edit, or run commands that modify state. Answer concisely. Prefer grep/find/ls over bash. Explore fast and report findings.\",\n\t\tmainMode: false,\n\t},\n\tplan: {\n\t\tname: \"plan\",\n\t\tlabel: \"Plan\",\n\t\tdescription:\n\t\t\t\"Technical architect. Explores codebase and produces implementation plan without executing.\",\n\t\ttools: [...READ_EXPLORATION_TOOLS],\n\t\tthinkingLevel: \"medium\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are in PLAN mode. Explore the codebase thoroughly, then produce a detailed implementation plan. Do NOT write or edit any files. Do not execute shell commands. Output a structured plan with steps, risks, and trade-offs. Pause and ask the user to confirm before implementing.\",\n\t\tmainMode: true,\n\t},\n\tiosm: {\n\t\tname: \"iosm\",\n\t\tlabel: \"IOSM\",\n\t\tdescription: \"IOSM methodology mode: runtime context, /iosm loop, and IOSM artifact lifecycle.\",\n\t\ttools: [...WRITE_ENGINEERING_TOOLS],\n\t\tthinkingLevel: \"medium\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are in IOSM mode. Use IOSM runtime context and methodology for actionable engineering requests. Keep IOSM artifacts synchronized when implementation changes.\",\n\t\tmainMode: true,\n\t},\n\tiosm_analyst: {\n\t\tname: \"iosm_analyst\",\n\t\tlabel: \"IOSM Analyst\",\n\t\tdescription: \"Analyzes IOSM artifacts and metrics. Read-only analysis tools.\",\n\t\ttools: [...READ_EXPLORATION_TOOLS],\n\t\tthinkingLevel: \"low\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are an IOSM Analyst. Your job is to analyze .iosm/ artifacts, cycle reports, metrics history, and codebase evidence. Be precise and evidence-based. Report metric values, confidence levels, and risks with concrete evidence from the repository. Do not modify product source code. Do not execute shell commands.\",\n\t\tmainMode: false,\n\t},\n\tiosm_verifier: {\n\t\tname: \"iosm_verifier\",\n\t\tlabel: \"IOSM Verifier\",\n\t\tdescription:\n\t\t\t\"Post-change IOSM verification. Validates metrics and artifacts after code changes.\",\n\t\ttools: [\"read\", \"bash\", \"write\"],\n\t\tthinkingLevel: \"low\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are an IOSM Verifier. Run deterministic checks on the repository to verify IOSM metrics are correct and up-to-date after code changes. Update only .iosm/ artifact files. Validate JSON after edits. Keep checks bounded and focused.\",\n\t\tmainMode: false,\n\t},\n\tcycle_planner: {\n\t\tname: \"cycle_planner\",\n\t\tlabel: \"Cycle Planner\",\n\t\tdescription: \"Plans IOSM improvement cycles with hypotheses and goals.\",\n\t\ttools: [\"read\", \"bash\", \"write\"],\n\t\tthinkingLevel: \"medium\",\n\t\tsystemPromptAppend:\n\t\t\t\"You are an IOSM Cycle Planner. Analyze the current codebase state, review the IOSM cycle report, and produce actionable improvement hypotheses. Write results to .iosm/ files. Be specific about expected metric improvements.\",\n\t\tmainMode: false,\n\t},\n\t\tmeta: {\n\t\t\tname: \"meta\",\n\t\t\tlabel: \"Meta\",\n\t\t\tdescription: \"Orchestration-first mode. Full tools with adaptive agent/delegate execution.\",\n\t\t\ttools: [...WRITE_ENGINEERING_TOOLS],\n\t\t\tthinkingLevel: \"medium\",\n\t\t\tsystemPromptAppend:\n\t\t\t\t\"You are in META mode. Keep full-mode capabilities and operator UX, but change execution behavior: your primary optimization target is safe parallel execution through top-level agents and nested delegates. First classify the request. For conversational or non-repository requests (quick Q&A, opinion, explanation, rewrite, translation, casual chat), do not orchestrate, do not call task, do not run repository reconnaissance, and answer directly in the user's language. Do not output internal reasoning or planning preambles; return only the final user-facing answer. The main agent is the orchestrator for the entire task and should not be the default implementer for non-trivial work. For actionable work on a codebase, do only bounded read-only recon, just enough to identify the relevant files, constraints, and independent workstreams. Then derive a detailed execution graph of tasks, agents, delegate subtasks, dependencies, writable areas, and verification steps before implementation. For any non-trivial task, orchestration is the default and single-agent execution is the exception: launch multiple top-level task calls as soon as the workstreams are known, prefer emitting them in the same assistant turn when branches are independent, and require child agents to further delegate whenever their assigned work still contains multiple independent slices. Do not keep implementing in the main agent after recon, do not make direct write/edit changes in the main agent before launching the first task call unless the work is clearly trivial and single-file, and do not collapse the whole job into one root implementation subagent when independent workstreams exist. Specialist agents should own focused workstreams rather than becoming the sole executor for the entire task. If the user requested a specific number of parallel agents or delegates, treat that fan-out as a hard target when feasible and explain the blocker precisely when it is not feasible. When the user did not specify counts, bias toward multiple smaller focused workstreams rather than one broad worker, and favor additional delegate fan-out inside each workstream when that shortens the critical path safely. Use shared memory as the default inter-agent channel: prefer scope=run keys for cross-stream state, scope=task keys for local state, and stable key namespaces such as findings/<stream>, plan/<stream>, risks/<stream>. Read before overwrite, use CAS (if_version) for contested keys, and reserve append mode for log/timeline keys only. Keep memory writes compact and deduplicated; avoid writing on every loop iteration when state has not changed. Treat code changes as incomplete until relevant tests are added or updated and targeted verification passes. Do not finalize until every launched agent and delegate has finished and their results have been synthesized. If any non-trivial part of the work remained single-agent or undelegated, explain why orchestration was not beneficial and include DELEGATION_IMPOSSIBLE with a precise reason. If no code changed and tests were skipped, explicitly justify safety. When reporting performance, speedup, scores, compliance, or conflict counts, use only observed runtime evidence (task details, shared-memory keys, test outputs, or files verified on disk); otherwise mark the metric as unknown. Never claim a report/file/path exists unless you created it in this run or confirmed it exists in the workspace.\",\n\t\t\tmainMode: true,\n\t\t},\n\tfull: {\n\t\tname: \"full\",\n\t\tlabel: \"Full\",\n\t\tdescription: \"Full access. All tools enabled. Default engineering agent.\",\n\t\ttools: [...WRITE_ENGINEERING_TOOLS],\n\t\tthinkingLevel: \"medium\",\n\t\tsystemPromptAppend: \"\",\n\t\tmainMode: true,\n\t},\n};\n\nexport const DEFAULT_PROFILE_NAME: AgentProfileName = \"full\";\n\n/** Get profile by name, falling back to full */\nexport function getAgentProfile(name: string | undefined): AgentProfile {\n\tif (!name || !(name in AGENT_PROFILES)) {\n\t\treturn AGENT_PROFILES[DEFAULT_PROFILE_NAME];\n\t}\n\treturn AGENT_PROFILES[name as AgentProfileName];\n}\n\n/** Check if a profile name is valid */\nexport function isValidProfileName(name: string): name is AgentProfileName {\n\treturn name in AGENT_PROFILES;\n}\n\n/** Get all profile names for help display */\nexport function getProfileNames(): AgentProfileName[] {\n\treturn Object.keys(AGENT_PROFILES) as AgentProfileName[];\n}\n\n/** Profiles visible in main operator UX (Shift+Tab / mode switching). */\nexport function getMainProfileNames(): AgentProfileName[] {\n\treturn getProfileNames().filter((name) => AGENT_PROFILES[name].mainMode === true);\n}\n\nexport function isReadOnlyProfileName(name: string | undefined): boolean {\n\treturn !!name && READ_ONLY_PROFILE_SET.has(name as AgentProfileName);\n}\n"]}
@@ -26,6 +26,19 @@ export interface SharedMemoryReadResult {
26
26
  items: SharedMemoryReadItem[];
27
27
  totalMatched: number;
28
28
  }
29
+ export interface SharedMemoryUsageSummary {
30
+ runId: string;
31
+ totalEntries: number;
32
+ totalWrites: number;
33
+ runScopeWrites: number;
34
+ taskScopeWrites: number;
35
+ currentTaskWrites: number;
36
+ currentTaskRunScopeWrites: number;
37
+ currentTaskTaskScopeWrites: number;
38
+ currentTaskDelegateWrites: number;
39
+ uniqueWriters: number;
40
+ uniqueKeys: number;
41
+ }
29
42
  export interface SharedMemoryWriteInput {
30
43
  key: string;
31
44
  value: string;
@@ -43,4 +56,5 @@ export interface SharedMemoryReadInput {
43
56
  export declare function getSharedMemoryPath(rootCwd: string, runId: string): string;
44
57
  export declare function writeSharedMemory(context: SharedMemoryContext, input: SharedMemoryWriteInput, signal?: AbortSignal): Promise<SharedMemoryReadItem>;
45
58
  export declare function readSharedMemory(context: SharedMemoryContext, input: SharedMemoryReadInput, signal?: AbortSignal): Promise<SharedMemoryReadResult>;
59
+ export declare function summarizeSharedMemoryUsage(context: Pick<SharedMemoryContext, "rootCwd" | "runId" | "taskId">, signal?: AbortSignal): Promise<SharedMemoryUsageSummary>;
46
60
  //# sourceMappingURL=shared-memory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-memory.d.ts","sourceRoot":"","sources":["../../src/core/shared-memory.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,iBAAiB,GAAG,KAAK,GAAG,MAAM,CAAC;AAC/C,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,QAAQ,CAAC;AAErD,MAAM,WAAW,kBAAkB;IAClC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AA0BD,MAAM,WAAW,oBAAoB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,iBAAiB,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,kBAAkB,CAAC;CAC3B;AAED,MAAM,WAAW,sBAAsB;IACtC,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,iBAAiB,CAAC;IACzB,KAAK,EAAE,oBAAoB,EAAE,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,sBAAsB;IACtC,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,iBAAiB,CAAC;IACzB,IAAI,EAAE,qBAAqB,CAAC;IAC5B,SAAS,CAAC,EAAE,MAAM,CAA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B,EAC7B,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,oBAAoB,CAAC,CAwD/B;AAyBD,wBAAsB,gBAAgB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,KAAK,EAAE,qBAAqB,EAC5B,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,sBAAsB,CAAC,CAkCjC;AAED,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,GAAG,OAAO,GAAG,QAAQ,CAAC,EAClE,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,wBAAwB,CAAC,CAkEnC"}
@@ -379,4 +379,67 @@ export async function readSharedMemory(context, input, signal) {
379
379
  normalizeLockError(error);
380
380
  }
381
381
  }
382
+ export async function summarizeSharedMemoryUsage(context, signal) {
383
+ try {
384
+ return await withSnapshotStore({
385
+ rootCwd: context.rootCwd,
386
+ runId: context.runId,
387
+ taskId: context.taskId,
388
+ }, (store) => {
389
+ const currentTaskId = context.taskId?.trim() || undefined;
390
+ let runScopeWrites = 0;
391
+ let taskScopeWrites = 0;
392
+ let currentTaskWrites = 0;
393
+ let currentTaskRunScopeWrites = 0;
394
+ let currentTaskTaskScopeWrites = 0;
395
+ let currentTaskDelegateWrites = 0;
396
+ const writerSet = new Set();
397
+ const keySet = new Set();
398
+ for (const item of store.history) {
399
+ const scope = item.scope === "task" ? "task" : "run";
400
+ if (scope === "run") {
401
+ runScopeWrites += 1;
402
+ }
403
+ else {
404
+ taskScopeWrites += 1;
405
+ }
406
+ keySet.add(`${scope}:${item.key}`);
407
+ const writerToken = [
408
+ item.writer.taskId?.trim() || "-",
409
+ item.writer.delegateId?.trim() || "-",
410
+ item.writer.profile?.trim() || "-",
411
+ ].join("|");
412
+ writerSet.add(writerToken);
413
+ if (currentTaskId && item.writer.taskId?.trim() === currentTaskId) {
414
+ currentTaskWrites += 1;
415
+ if (scope === "run") {
416
+ currentTaskRunScopeWrites += 1;
417
+ }
418
+ else {
419
+ currentTaskTaskScopeWrites += 1;
420
+ }
421
+ if (item.writer.delegateId?.trim()) {
422
+ currentTaskDelegateWrites += 1;
423
+ }
424
+ }
425
+ }
426
+ return {
427
+ runId: store.runId,
428
+ totalEntries: Object.keys(store.entries).length,
429
+ totalWrites: store.history.length,
430
+ runScopeWrites,
431
+ taskScopeWrites,
432
+ currentTaskWrites,
433
+ currentTaskRunScopeWrites,
434
+ currentTaskTaskScopeWrites,
435
+ currentTaskDelegateWrites,
436
+ uniqueWriters: writerSet.size,
437
+ uniqueKeys: keySet.size,
438
+ };
439
+ }, signal);
440
+ }
441
+ catch (error) {
442
+ normalizeLockError(error);
443
+ }
444
+ }
382
445
  //# sourceMappingURL=shared-memory.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-memory.js","sourceRoot":"","sources":["../../src/core/shared-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AA2EvC,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAClC,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAChC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,MAAM,aAAa,GAAG,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,2CAA2C,EAAE,oBAAoB,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;AAChI,MAAM,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,oCAAoC,EAAE,cAAc,EA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GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO;gBACN,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,KAAK,EAAE,MAAM;gBACb,YAAY,EAAE,YAAY,CAAC,MAAM;aACjC,CAAC;QACF,CAAC,EAAE,MAAM,CAAC,CAAC;IACZ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;AACF,CAAC","sourcesContent":["import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\n\nexport type SharedMemoryScope = \"run\" | \"task\";\nexport type SharedMemoryWriteMode = \"set\" | \"append\";\n\nexport interface SharedMemoryWriter {\n\ttaskId?: string;\n\tdelegateId?: string;\n\tprofile?: string;\n}\n\nexport interface SharedMemoryContext {\n\trootCwd: string;\n\trunId: string;\n\ttaskId?: string;\n\tdelegateId?: string;\n\tprofile?: string;\n}\n\ninterface SharedMemoryEntry {\n\tvalue: string;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\ninterface SharedMemoryHistoryItem {\n\tkey: string;\n\tscope: SharedMemoryScope;\n\tmode: SharedMemoryWriteMode;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\ninterface SharedMemoryStore {\n\trunId: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tentries: Record<string, SharedMemoryEntry>;\n\thistory: SharedMemoryHistoryItem[];\n}\n\nexport interface SharedMemoryReadItem {\n\tkey: string;\n\tscope: SharedMemoryScope;\n\tvalue?: string;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\nexport interface SharedMemoryReadResult {\n\trunId: string;\n\tscope: SharedMemoryScope;\n\titems: SharedMemoryReadItem[];\n\ttotalMatched: number;\n}\n\nexport interface SharedMemoryWriteInput {\n\tkey: string;\n\tvalue: string;\n\tscope: SharedMemoryScope;\n\tmode: SharedMemoryWriteMode;\n\tifVersion?: number;\n}\n\nexport interface SharedMemoryReadInput {\n\tscope: SharedMemoryScope;\n\tkey?: string;\n\tprefix?: string;\n\tlimit?: number;\n\tincludeValues?: boolean;\n}\n\nconst maxEntryCharsDefault = 4000;\nconst maxKeysDefault = 500;\nconst historySizeDefault = 1000;\nconst lockRetryAttempts = 12;\nconst lockRetryDelayMs = 20;\nconst snapshotRetryAttempts = 4;\nconst snapshotRetryDelayMs = 8;\n\nconst maxEntryChars = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_MAX_ENTRY_CHARS, maxEntryCharsDefault, 64, 20_000);\nconst maxKeys = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_MAX_KEYS, maxKeysDefault, 10, 20_000);\nconst historySize = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_HISTORY_SIZE, historySizeDefault, 10, 50_000);\n\nfunction readBoundedInt(raw: string | undefined, fallback: number, min: number, max: number): number {\n\tconst parsed = raw ? Number.parseInt(raw, 10) : fallback;\n\tif (!Number.isInteger(parsed)) return fallback;\n\treturn Math.max(min, Math.min(max, parsed));\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n\tif (!signal) {\n\t\treturn new Promise((resolve) => setTimeout(resolve, ms));\n\t}\n\tif (signal.aborted) {\n\t\treturn Promise.reject(new Error(\"Operation aborted\"));\n\t}\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nclass Mutex {\n\tprivate locked = false;\n\tprivate readonly waiters: Array<() => void> = [];\n\n\tasync acquire(): Promise<() => void> {\n\t\tif (!this.locked) {\n\t\t\tthis.locked = true;\n\t\t\treturn () => this.release();\n\t\t}\n\t\tawait new Promise<void>((resolve) => this.waiters.push(resolve));\n\t\tthis.locked = true;\n\t\treturn () => this.release();\n\t}\n\n\tprivate release(): void {\n\t\tthis.locked = false;\n\t\tconst next = this.waiters.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t}\n\t}\n\n\tisIdle(): boolean {\n\t\treturn !this.locked && this.waiters.length === 0;\n\t}\n}\n\nconst localWriteMutexes = new Map<string, Mutex>();\n\nfunction getOrCreateLocalWriteMutex(filePath: string): Mutex {\n\tconst existing = localWriteMutexes.get(filePath);\n\tif (existing) return existing;\n\tconst created = new Mutex();\n\tlocalWriteMutexes.set(filePath, created);\n\treturn created;\n}\n\nfunction cleanupLocalWriteMutex(filePath: string): void {\n\tconst existing = localWriteMutexes.get(filePath);\n\tif (!existing || !existing.isIdle()) return;\n\tlocalWriteMutexes.delete(filePath);\n}\n\nfunction normalizeRunId(runId: string): string {\n\tconst trimmed = runId.trim();\n\tif (!trimmed) throw new Error(\"shared memory requires non-empty run_id context\");\n\treturn trimmed;\n}\n\nfunction normalizeKey(key: string): string {\n\tconst normalized = key.trim().replace(/\\s+/g, \" \");\n\tif (!normalized) throw new Error(\"shared memory key must be non-empty\");\n\tif (normalized.length > 240) {\n\t\tthrow new Error(\"shared memory key too long (max 240 chars)\");\n\t}\n\treturn normalized;\n}\n\nfunction resolveScopedKey(context: SharedMemoryContext, scope: SharedMemoryScope, key: string): string {\n\tconst normalizedKey = normalizeKey(key);\n\tif (scope === \"task\") {\n\t\tif (!context.taskId || !context.taskId.trim()) {\n\t\t\tthrow new Error(\"task-scoped shared memory requires task_id context\");\n\t\t}\n\t\treturn `task:${context.taskId.trim()}:${normalizedKey}`;\n\t}\n\treturn `run:${normalizedKey}`;\n}\n\nfunction parseScopedKey(scopedKey: string): { scope: SharedMemoryScope; key: string; taskId?: string } {\n\tif (scopedKey.startsWith(\"task:\")) {\n\t\tconst rest = scopedKey.slice(\"task:\".length);\n\t\tconst split = rest.indexOf(\":\");\n\t\tif (split <= 0) {\n\t\t\treturn { scope: \"task\", key: rest };\n\t\t}\n\t\treturn {\n\t\t\tscope: \"task\",\n\t\t\ttaskId: rest.slice(0, split),\n\t\t\tkey: rest.slice(split + 1),\n\t\t};\n\t}\n\tif (scopedKey.startsWith(\"run:\")) {\n\t\treturn { scope: \"run\", key: scopedKey.slice(\"run:\".length) };\n\t}\n\treturn { scope: \"run\", key: scopedKey };\n}\n\nfunction getSharedMemoryDir(rootCwd: string): string {\n\treturn join(rootCwd, \".iosm\", \"subagents\", \"shared-memory\");\n}\n\nexport function getSharedMemoryPath(rootCwd: string, runId: string): string {\n\treturn join(getSharedMemoryDir(rootCwd), `${normalizeRunId(runId)}.json`);\n}\n\nfunction createInitialStore(runId: string): SharedMemoryStore {\n\tconst now = new Date().toISOString();\n\treturn {\n\t\trunId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tentries: {},\n\t\thistory: [],\n\t};\n}\n\nfunction normalizeParsedStore(runId: string, parsed: unknown): SharedMemoryStore {\n\tif (!parsed || typeof parsed !== \"object\") return createInitialStore(runId);\n\tconst cast = parsed as SharedMemoryStore;\n\tif (cast.runId !== runId) return createInitialStore(runId);\n\tif (!cast.entries || typeof cast.entries !== \"object\") cast.entries = {};\n\tif (!Array.isArray(cast.history)) cast.history = [];\n\tif (!cast.createdAt || typeof cast.createdAt !== \"string\") cast.createdAt = new Date().toISOString();\n\tif (!cast.updatedAt || typeof cast.updatedAt !== \"string\") cast.updatedAt = cast.createdAt;\n\treturn cast;\n}\n\nfunction readStore(filePath: string, runId: string): SharedMemoryStore {\n\tif (!existsSync(filePath)) {\n\t\treturn createInitialStore(runId);\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(filePath, \"utf8\"));\n\t\treturn normalizeParsedStore(runId, parsed);\n\t} catch {\n\t\treturn createInitialStore(runId);\n\t}\n}\n\nasync function readStoreSnapshot(filePath: string, runId: string, signal?: AbortSignal): Promise<SharedMemoryStore> {\n\tif (!existsSync(filePath)) {\n\t\treturn createInitialStore(runId);\n\t}\n\tfor (let attempt = 1; attempt <= snapshotRetryAttempts; attempt += 1) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(readFileSync(filePath, \"utf8\"));\n\t\t\treturn normalizeParsedStore(runId, parsed);\n\t\t} catch {\n\t\t\tif (attempt >= snapshotRetryAttempts) break;\n\t\t\tawait delay(snapshotRetryDelayMs * attempt, signal);\n\t\t}\n\t}\n\treturn createInitialStore(runId);\n}\n\nfunction writeStore(filePath: string, store: SharedMemoryStore): void {\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tconst tempPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;\n\ttry {\n\t\twriteFileSync(tempPath, `${JSON.stringify(store, null, 2)}\\n`, \"utf8\");\n\t\trenameSync(tempPath, filePath);\n\t} finally {\n\t\tif (existsSync(tempPath)) {\n\t\t\trmSync(tempPath, { force: true });\n\t\t}\n\t}\n}\n\nasync function acquireFileLock(filePath: string, signal?: AbortSignal): Promise<() => Promise<void>> {\n\tfor (let attempt = 1; attempt <= lockRetryAttempts; attempt += 1) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\ttry {\n\t\t\treturn await lockfile.lock(filePath, { realpath: false });\n\t\t} catch (error) {\n\t\t\tconst code = error && typeof error === \"object\" && \"code\" in error ? String(error.code) : \"\";\n\t\t\tif (code !== \"ELOCKED\" || attempt >= lockRetryAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait delay(lockRetryDelayMs * attempt, signal);\n\t\t}\n\t}\n\tthrow new Error(\"failed to acquire shared memory lock\");\n}\n\nasync function withLockedStore<T>(\n\tcontext: SharedMemoryContext,\n\tfn: (store: SharedMemoryStore, filePath: string) => T,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst runId = normalizeRunId(context.runId);\n\tconst filePath = getSharedMemoryPath(context.rootCwd, runId);\n\tconst releaseLocalMutex = await getOrCreateLocalWriteMutex(filePath).acquire();\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tif (!existsSync(filePath)) {\n\t\twriteStore(filePath, createInitialStore(runId));\n\t}\n\tconst release = await acquireFileLock(filePath, signal);\n\ttry {\n\t\tconst store = readStore(filePath, runId);\n\t\tconst value = fn(store, filePath);\n\t\twriteStore(filePath, store);\n\t\treturn value;\n\t} finally {\n\t\ttry {\n\t\t\tawait release();\n\t\t} finally {\n\t\t\treleaseLocalMutex();\n\t\t\tcleanupLocalWriteMutex(filePath);\n\t\t}\n\t}\n}\n\nasync function withSnapshotStore<T>(\n\tcontext: SharedMemoryContext,\n\tfn: (store: SharedMemoryStore, filePath: string) => T,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst runId = normalizeRunId(context.runId);\n\tconst filePath = getSharedMemoryPath(context.rootCwd, runId);\n\tconst store = await readStoreSnapshot(filePath, runId, signal);\n\treturn fn(store, filePath);\n}\n\nfunction isAbortError(error: unknown): boolean {\n\tif (error instanceof Error) return /aborted/i.test(error.message);\n\tif (typeof error === \"string\") return /aborted/i.test(error);\n\treturn false;\n}\n\nfunction normalizeLockError(error: unknown): never {\n\tif (isAbortError(error)) {\n\t\tthrow new Error(\"Operation aborted\");\n\t}\n\tthrow error;\n}\n\nfunction trimHistory(store: SharedMemoryStore): void {\n\tif (store.history.length <= historySize) return;\n\tstore.history = store.history.slice(store.history.length - historySize);\n}\n\nfunction writerFromContext(context: SharedMemoryContext): SharedMemoryWriter {\n\treturn {\n\t\ttaskId: context.taskId?.trim() || undefined,\n\t\tdelegateId: context.delegateId?.trim() || undefined,\n\t\tprofile: context.profile?.trim() || undefined,\n\t};\n}\n\nexport async function writeSharedMemory(\n\tcontext: SharedMemoryContext,\n\tinput: SharedMemoryWriteInput,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryReadItem> {\n\tconst normalizedValue = input.value;\n\tif (normalizedValue.length > maxEntryChars) {\n\t\tthrow new Error(`shared memory value exceeds ${maxEntryChars} chars`);\n\t}\n\tconst scopedKey = resolveScopedKey(context, input.scope, input.key);\n\ttry {\n\t\treturn await withLockedStore(context, (store) => {\n\t\tconst now = new Date().toISOString();\n\t\tconst entriesCount = Object.keys(store.entries).length;\n\t\tconst previous = store.entries[scopedKey];\n\t\tif (!previous && entriesCount >= maxKeys) {\n\t\t\tthrow new Error(`shared memory key limit reached (${maxKeys})`);\n\t\t}\n\t\tif (input.ifVersion !== undefined && previous && previous.version !== input.ifVersion) {\n\t\t\tthrow new Error(`shared memory CAS mismatch for key \"${input.key}\" (expected ${input.ifVersion}, got ${previous.version})`);\n\t\t}\n\t\tif (input.ifVersion !== undefined && !previous) {\n\t\t\tthrow new Error(`shared memory CAS mismatch for key \"${input.key}\" (expected ${input.ifVersion}, got 0)`);\n\t\t}\n\n\t\tconst nextValue = input.mode === \"append\" ? `${previous?.value ?? \"\"}${normalizedValue}` : normalizedValue;\n\t\tif (nextValue.length > maxEntryChars) {\n\t\t\tthrow new Error(`shared memory value exceeds ${maxEntryChars} chars after ${input.mode}`);\n\t\t}\n\t\tconst nextVersion = (previous?.version ?? 0) + 1;\n\t\tconst writer = writerFromContext(context);\n\t\tstore.entries[scopedKey] = {\n\t\t\tvalue: nextValue,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t};\n\t\tstore.updatedAt = now;\n\t\tstore.history.push({\n\t\t\tkey: normalizeKey(input.key),\n\t\t\tscope: input.scope,\n\t\t\tmode: input.mode,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t});\n\t\ttrimHistory(store);\n\n\t\treturn {\n\t\t\tkey: normalizeKey(input.key),\n\t\t\tscope: input.scope,\n\t\t\tvalue: nextValue,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t};\n\t\t}, signal);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n\nfunction matchesScopeAndPrefix(\n\tcontext: SharedMemoryContext,\n\tscopedKey: string,\n\tscope: SharedMemoryScope,\n\tkey: string | undefined,\n\tprefix: string | undefined,\n): { matched: boolean; parsed: ReturnType<typeof parseScopedKey> } {\n\tconst parsed = parseScopedKey(scopedKey);\n\tif (parsed.scope !== scope) return { matched: false, parsed };\n\tif (scope === \"task\") {\n\t\tconst taskId = context.taskId?.trim();\n\t\tif (!taskId) return { matched: false, parsed };\n\t\tif (parsed.taskId !== taskId) return { matched: false, parsed };\n\t}\n\tif (key) {\n\t\treturn { matched: parsed.key === key, parsed };\n\t}\n\tif (prefix) {\n\t\treturn { matched: parsed.key.startsWith(prefix), parsed };\n\t}\n\treturn { matched: true, parsed };\n}\n\nexport async function readSharedMemory(\n\tcontext: SharedMemoryContext,\n\tinput: SharedMemoryReadInput,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryReadResult> {\n\tconst normalizedKey = input.key ? normalizeKey(input.key) : undefined;\n\tconst normalizedPrefix = input.prefix ? normalizeKey(input.prefix) : undefined;\n\tconst limit = Math.max(1, Math.min(100, input.limit ?? 20));\n\tconst includeValues = input.includeValues !== false;\n\n\ttry {\n\t\treturn await withSnapshotStore(context, (store) => {\n\t\tconst matchedItems: SharedMemoryReadItem[] = [];\n\t\tfor (const [scopedKey, entry] of Object.entries(store.entries)) {\n\t\t\tconst matched = matchesScopeAndPrefix(context, scopedKey, input.scope, normalizedKey, normalizedPrefix);\n\t\t\tif (!matched.matched) continue;\n\t\t\tmatchedItems.push({\n\t\t\t\tkey: matched.parsed.key,\n\t\t\t\tscope: input.scope,\n\t\t\t\tvalue: includeValues ? entry.value : undefined,\n\t\t\t\tversion: entry.version,\n\t\t\t\tupdatedAt: entry.updatedAt,\n\t\t\t\twriter: entry.writer ?? {},\n\t\t\t});\n\t\t}\n\n\t\tmatchedItems.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n\t\tconst sliced = matchedItems.slice(0, limit);\n\t\treturn {\n\t\t\trunId: store.runId,\n\t\t\tscope: input.scope,\n\t\t\titems: sliced,\n\t\t\ttotalMatched: matchedItems.length,\n\t\t};\n\t\t}, signal);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n"]}
1
+ {"version":3,"file":"shared-memory.js","sourceRoot":"","sources":["../../src/core/shared-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AAyFvC,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAClC,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAChC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,MAAM,aAAa,GAAG,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,2CAA2C,EAAE,oBAAoB,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;AAChI,MAAM,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,oCAAoC,EAAE,cAAc,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;AAC7G,MAAM,WAAW,GAAG,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,wCAAwC,EAAE,kBAAkB,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;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AAC,CAAC;IAC3B,CAAC;AACF,CAAC","sourcesContent":["import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\n\nexport type SharedMemoryScope = \"run\" | \"task\";\nexport type SharedMemoryWriteMode = \"set\" | \"append\";\n\nexport interface SharedMemoryWriter {\n\ttaskId?: string;\n\tdelegateId?: string;\n\tprofile?: string;\n}\n\nexport interface SharedMemoryContext {\n\trootCwd: string;\n\trunId: string;\n\ttaskId?: string;\n\tdelegateId?: string;\n\tprofile?: string;\n}\n\ninterface SharedMemoryEntry {\n\tvalue: string;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\ninterface SharedMemoryHistoryItem {\n\tkey: string;\n\tscope: SharedMemoryScope;\n\tmode: SharedMemoryWriteMode;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\ninterface SharedMemoryStore {\n\trunId: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tentries: Record<string, SharedMemoryEntry>;\n\thistory: SharedMemoryHistoryItem[];\n}\n\nexport interface SharedMemoryReadItem {\n\tkey: string;\n\tscope: SharedMemoryScope;\n\tvalue?: string;\n\tversion: number;\n\tupdatedAt: string;\n\twriter: SharedMemoryWriter;\n}\n\nexport interface SharedMemoryReadResult {\n\trunId: string;\n\tscope: SharedMemoryScope;\n\titems: SharedMemoryReadItem[];\n\ttotalMatched: number;\n}\n\nexport interface SharedMemoryUsageSummary {\n\trunId: string;\n\ttotalEntries: number;\n\ttotalWrites: number;\n\trunScopeWrites: number;\n\ttaskScopeWrites: number;\n\tcurrentTaskWrites: number;\n\tcurrentTaskRunScopeWrites: number;\n\tcurrentTaskTaskScopeWrites: number;\n\tcurrentTaskDelegateWrites: number;\n\tuniqueWriters: number;\n\tuniqueKeys: number;\n}\n\nexport interface SharedMemoryWriteInput {\n\tkey: string;\n\tvalue: string;\n\tscope: SharedMemoryScope;\n\tmode: SharedMemoryWriteMode;\n\tifVersion?: number;\n}\n\nexport interface SharedMemoryReadInput {\n\tscope: SharedMemoryScope;\n\tkey?: string;\n\tprefix?: string;\n\tlimit?: number;\n\tincludeValues?: boolean;\n}\n\nconst maxEntryCharsDefault = 4000;\nconst maxKeysDefault = 500;\nconst historySizeDefault = 1000;\nconst lockRetryAttempts = 12;\nconst lockRetryDelayMs = 20;\nconst snapshotRetryAttempts = 4;\nconst snapshotRetryDelayMs = 8;\n\nconst maxEntryChars = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_MAX_ENTRY_CHARS, maxEntryCharsDefault, 64, 20_000);\nconst maxKeys = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_MAX_KEYS, maxKeysDefault, 10, 20_000);\nconst historySize = readBoundedInt(process.env.IOSM_SUBAGENT_SHARED_MEMORY_HISTORY_SIZE, historySizeDefault, 10, 50_000);\n\nfunction readBoundedInt(raw: string | undefined, fallback: number, min: number, max: number): number {\n\tconst parsed = raw ? Number.parseInt(raw, 10) : fallback;\n\tif (!Number.isInteger(parsed)) return fallback;\n\treturn Math.max(min, Math.min(max, parsed));\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n\tif (!signal) {\n\t\treturn new Promise((resolve) => setTimeout(resolve, ms));\n\t}\n\tif (signal.aborted) {\n\t\treturn Promise.reject(new Error(\"Operation aborted\"));\n\t}\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\treject(new Error(\"Operation aborted\"));\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nclass Mutex {\n\tprivate locked = false;\n\tprivate readonly waiters: Array<() => void> = [];\n\n\tasync acquire(): Promise<() => void> {\n\t\tif (!this.locked) {\n\t\t\tthis.locked = true;\n\t\t\treturn () => this.release();\n\t\t}\n\t\tawait new Promise<void>((resolve) => this.waiters.push(resolve));\n\t\tthis.locked = true;\n\t\treturn () => this.release();\n\t}\n\n\tprivate release(): void {\n\t\tthis.locked = false;\n\t\tconst next = this.waiters.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t}\n\t}\n\n\tisIdle(): boolean {\n\t\treturn !this.locked && this.waiters.length === 0;\n\t}\n}\n\nconst localWriteMutexes = new Map<string, Mutex>();\n\nfunction getOrCreateLocalWriteMutex(filePath: string): Mutex {\n\tconst existing = localWriteMutexes.get(filePath);\n\tif (existing) return existing;\n\tconst created = new Mutex();\n\tlocalWriteMutexes.set(filePath, created);\n\treturn created;\n}\n\nfunction cleanupLocalWriteMutex(filePath: string): void {\n\tconst existing = localWriteMutexes.get(filePath);\n\tif (!existing || !existing.isIdle()) return;\n\tlocalWriteMutexes.delete(filePath);\n}\n\nfunction normalizeRunId(runId: string): string {\n\tconst trimmed = runId.trim();\n\tif (!trimmed) throw new Error(\"shared memory requires non-empty run_id context\");\n\treturn trimmed;\n}\n\nfunction normalizeKey(key: string): string {\n\tconst normalized = key.trim().replace(/\\s+/g, \" \");\n\tif (!normalized) throw new Error(\"shared memory key must be non-empty\");\n\tif (normalized.length > 240) {\n\t\tthrow new Error(\"shared memory key too long (max 240 chars)\");\n\t}\n\treturn normalized;\n}\n\nfunction resolveScopedKey(context: SharedMemoryContext, scope: SharedMemoryScope, key: string): string {\n\tconst normalizedKey = normalizeKey(key);\n\tif (scope === \"task\") {\n\t\tif (!context.taskId || !context.taskId.trim()) {\n\t\t\tthrow new Error(\"task-scoped shared memory requires task_id context\");\n\t\t}\n\t\treturn `task:${context.taskId.trim()}:${normalizedKey}`;\n\t}\n\treturn `run:${normalizedKey}`;\n}\n\nfunction parseScopedKey(scopedKey: string): { scope: SharedMemoryScope; key: string; taskId?: string } {\n\tif (scopedKey.startsWith(\"task:\")) {\n\t\tconst rest = scopedKey.slice(\"task:\".length);\n\t\tconst split = rest.indexOf(\":\");\n\t\tif (split <= 0) {\n\t\t\treturn { scope: \"task\", key: rest };\n\t\t}\n\t\treturn {\n\t\t\tscope: \"task\",\n\t\t\ttaskId: rest.slice(0, split),\n\t\t\tkey: rest.slice(split + 1),\n\t\t};\n\t}\n\tif (scopedKey.startsWith(\"run:\")) {\n\t\treturn { scope: \"run\", key: scopedKey.slice(\"run:\".length) };\n\t}\n\treturn { scope: \"run\", key: scopedKey };\n}\n\nfunction getSharedMemoryDir(rootCwd: string): string {\n\treturn join(rootCwd, \".iosm\", \"subagents\", \"shared-memory\");\n}\n\nexport function getSharedMemoryPath(rootCwd: string, runId: string): string {\n\treturn join(getSharedMemoryDir(rootCwd), `${normalizeRunId(runId)}.json`);\n}\n\nfunction createInitialStore(runId: string): SharedMemoryStore {\n\tconst now = new Date().toISOString();\n\treturn {\n\t\trunId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tentries: {},\n\t\thistory: [],\n\t};\n}\n\nfunction normalizeParsedStore(runId: string, parsed: unknown): SharedMemoryStore {\n\tif (!parsed || typeof parsed !== \"object\") return createInitialStore(runId);\n\tconst cast = parsed as SharedMemoryStore;\n\tif (cast.runId !== runId) return createInitialStore(runId);\n\tif (!cast.entries || typeof cast.entries !== \"object\") cast.entries = {};\n\tif (!Array.isArray(cast.history)) cast.history = [];\n\tif (!cast.createdAt || typeof cast.createdAt !== \"string\") cast.createdAt = new Date().toISOString();\n\tif (!cast.updatedAt || typeof cast.updatedAt !== \"string\") cast.updatedAt = cast.createdAt;\n\treturn cast;\n}\n\nfunction readStore(filePath: string, runId: string): SharedMemoryStore {\n\tif (!existsSync(filePath)) {\n\t\treturn createInitialStore(runId);\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(filePath, \"utf8\"));\n\t\treturn normalizeParsedStore(runId, parsed);\n\t} catch {\n\t\treturn createInitialStore(runId);\n\t}\n}\n\nasync function readStoreSnapshot(filePath: string, runId: string, signal?: AbortSignal): Promise<SharedMemoryStore> {\n\tif (!existsSync(filePath)) {\n\t\treturn createInitialStore(runId);\n\t}\n\tfor (let attempt = 1; attempt <= snapshotRetryAttempts; attempt += 1) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(readFileSync(filePath, \"utf8\"));\n\t\t\treturn normalizeParsedStore(runId, parsed);\n\t\t} catch {\n\t\t\tif (attempt >= snapshotRetryAttempts) break;\n\t\t\tawait delay(snapshotRetryDelayMs * attempt, signal);\n\t\t}\n\t}\n\treturn createInitialStore(runId);\n}\n\nfunction writeStore(filePath: string, store: SharedMemoryStore): void {\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tconst tempPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;\n\ttry {\n\t\twriteFileSync(tempPath, `${JSON.stringify(store, null, 2)}\\n`, \"utf8\");\n\t\trenameSync(tempPath, filePath);\n\t} finally {\n\t\tif (existsSync(tempPath)) {\n\t\t\trmSync(tempPath, { force: true });\n\t\t}\n\t}\n}\n\nasync function acquireFileLock(filePath: string, signal?: AbortSignal): Promise<() => Promise<void>> {\n\tfor (let attempt = 1; attempt <= lockRetryAttempts; attempt += 1) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\ttry {\n\t\t\treturn await lockfile.lock(filePath, { realpath: false });\n\t\t} catch (error) {\n\t\t\tconst code = error && typeof error === \"object\" && \"code\" in error ? String(error.code) : \"\";\n\t\t\tif (code !== \"ELOCKED\" || attempt >= lockRetryAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait delay(lockRetryDelayMs * attempt, signal);\n\t\t}\n\t}\n\tthrow new Error(\"failed to acquire shared memory lock\");\n}\n\nasync function withLockedStore<T>(\n\tcontext: SharedMemoryContext,\n\tfn: (store: SharedMemoryStore, filePath: string) => T,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst runId = normalizeRunId(context.runId);\n\tconst filePath = getSharedMemoryPath(context.rootCwd, runId);\n\tconst releaseLocalMutex = await getOrCreateLocalWriteMutex(filePath).acquire();\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tif (!existsSync(filePath)) {\n\t\twriteStore(filePath, createInitialStore(runId));\n\t}\n\tconst release = await acquireFileLock(filePath, signal);\n\ttry {\n\t\tconst store = readStore(filePath, runId);\n\t\tconst value = fn(store, filePath);\n\t\twriteStore(filePath, store);\n\t\treturn value;\n\t} finally {\n\t\ttry {\n\t\t\tawait release();\n\t\t} finally {\n\t\t\treleaseLocalMutex();\n\t\t\tcleanupLocalWriteMutex(filePath);\n\t\t}\n\t}\n}\n\nasync function withSnapshotStore<T>(\n\tcontext: SharedMemoryContext,\n\tfn: (store: SharedMemoryStore, filePath: string) => T,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst runId = normalizeRunId(context.runId);\n\tconst filePath = getSharedMemoryPath(context.rootCwd, runId);\n\tconst store = await readStoreSnapshot(filePath, runId, signal);\n\treturn fn(store, filePath);\n}\n\nfunction isAbortError(error: unknown): boolean {\n\tif (error instanceof Error) return /aborted/i.test(error.message);\n\tif (typeof error === \"string\") return /aborted/i.test(error);\n\treturn false;\n}\n\nfunction normalizeLockError(error: unknown): never {\n\tif (isAbortError(error)) {\n\t\tthrow new Error(\"Operation aborted\");\n\t}\n\tthrow error;\n}\n\nfunction trimHistory(store: SharedMemoryStore): void {\n\tif (store.history.length <= historySize) return;\n\tstore.history = store.history.slice(store.history.length - historySize);\n}\n\nfunction writerFromContext(context: SharedMemoryContext): SharedMemoryWriter {\n\treturn {\n\t\ttaskId: context.taskId?.trim() || undefined,\n\t\tdelegateId: context.delegateId?.trim() || undefined,\n\t\tprofile: context.profile?.trim() || undefined,\n\t};\n}\n\nexport async function writeSharedMemory(\n\tcontext: SharedMemoryContext,\n\tinput: SharedMemoryWriteInput,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryReadItem> {\n\tconst normalizedValue = input.value;\n\tif (normalizedValue.length > maxEntryChars) {\n\t\tthrow new Error(`shared memory value exceeds ${maxEntryChars} chars`);\n\t}\n\tconst scopedKey = resolveScopedKey(context, input.scope, input.key);\n\ttry {\n\t\treturn await withLockedStore(context, (store) => {\n\t\tconst now = new Date().toISOString();\n\t\tconst entriesCount = Object.keys(store.entries).length;\n\t\tconst previous = store.entries[scopedKey];\n\t\tif (!previous && entriesCount >= maxKeys) {\n\t\t\tthrow new Error(`shared memory key limit reached (${maxKeys})`);\n\t\t}\n\t\tif (input.ifVersion !== undefined && previous && previous.version !== input.ifVersion) {\n\t\t\tthrow new Error(`shared memory CAS mismatch for key \"${input.key}\" (expected ${input.ifVersion}, got ${previous.version})`);\n\t\t}\n\t\tif (input.ifVersion !== undefined && !previous) {\n\t\t\tthrow new Error(`shared memory CAS mismatch for key \"${input.key}\" (expected ${input.ifVersion}, got 0)`);\n\t\t}\n\n\t\tconst nextValue = input.mode === \"append\" ? `${previous?.value ?? \"\"}${normalizedValue}` : normalizedValue;\n\t\tif (nextValue.length > maxEntryChars) {\n\t\t\tthrow new Error(`shared memory value exceeds ${maxEntryChars} chars after ${input.mode}`);\n\t\t}\n\t\tconst nextVersion = (previous?.version ?? 0) + 1;\n\t\tconst writer = writerFromContext(context);\n\t\tstore.entries[scopedKey] = {\n\t\t\tvalue: nextValue,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t};\n\t\tstore.updatedAt = now;\n\t\tstore.history.push({\n\t\t\tkey: normalizeKey(input.key),\n\t\t\tscope: input.scope,\n\t\t\tmode: input.mode,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t});\n\t\ttrimHistory(store);\n\n\t\treturn {\n\t\t\tkey: normalizeKey(input.key),\n\t\t\tscope: input.scope,\n\t\t\tvalue: nextValue,\n\t\t\tversion: nextVersion,\n\t\t\tupdatedAt: now,\n\t\t\twriter,\n\t\t};\n\t\t}, signal);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n\nfunction matchesScopeAndPrefix(\n\tcontext: SharedMemoryContext,\n\tscopedKey: string,\n\tscope: SharedMemoryScope,\n\tkey: string | undefined,\n\tprefix: string | undefined,\n): { matched: boolean; parsed: ReturnType<typeof parseScopedKey> } {\n\tconst parsed = parseScopedKey(scopedKey);\n\tif (parsed.scope !== scope) return { matched: false, parsed };\n\tif (scope === \"task\") {\n\t\tconst taskId = context.taskId?.trim();\n\t\tif (!taskId) return { matched: false, parsed };\n\t\tif (parsed.taskId !== taskId) return { matched: false, parsed };\n\t}\n\tif (key) {\n\t\treturn { matched: parsed.key === key, parsed };\n\t}\n\tif (prefix) {\n\t\treturn { matched: parsed.key.startsWith(prefix), parsed };\n\t}\n\treturn { matched: true, parsed };\n}\n\nexport async function readSharedMemory(\n\tcontext: SharedMemoryContext,\n\tinput: SharedMemoryReadInput,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryReadResult> {\n\tconst normalizedKey = input.key ? normalizeKey(input.key) : undefined;\n\tconst normalizedPrefix = input.prefix ? normalizeKey(input.prefix) : undefined;\n\tconst limit = Math.max(1, Math.min(100, input.limit ?? 20));\n\tconst includeValues = input.includeValues !== false;\n\n\ttry {\n\t\treturn await withSnapshotStore(context, (store) => {\n\t\tconst matchedItems: SharedMemoryReadItem[] = [];\n\t\tfor (const [scopedKey, entry] of Object.entries(store.entries)) {\n\t\t\tconst matched = matchesScopeAndPrefix(context, scopedKey, input.scope, normalizedKey, normalizedPrefix);\n\t\t\tif (!matched.matched) continue;\n\t\t\tmatchedItems.push({\n\t\t\t\tkey: matched.parsed.key,\n\t\t\t\tscope: input.scope,\n\t\t\t\tvalue: includeValues ? entry.value : undefined,\n\t\t\t\tversion: entry.version,\n\t\t\t\tupdatedAt: entry.updatedAt,\n\t\t\t\twriter: entry.writer ?? {},\n\t\t\t});\n\t\t}\n\n\t\tmatchedItems.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n\t\tconst sliced = matchedItems.slice(0, limit);\n\t\treturn {\n\t\t\trunId: store.runId,\n\t\t\tscope: input.scope,\n\t\t\titems: sliced,\n\t\t\ttotalMatched: matchedItems.length,\n\t\t};\n\t\t}, signal);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n\nexport async function summarizeSharedMemoryUsage(\n\tcontext: Pick<SharedMemoryContext, \"rootCwd\" | \"runId\" | \"taskId\">,\n\tsignal?: AbortSignal,\n): Promise<SharedMemoryUsageSummary> {\n\ttry {\n\t\treturn await withSnapshotStore(\n\t\t\t{\n\t\t\t\trootCwd: context.rootCwd,\n\t\t\t\trunId: context.runId,\n\t\t\t\ttaskId: context.taskId,\n\t\t\t},\n\t\t\t(store) => {\n\t\t\t\tconst currentTaskId = context.taskId?.trim() || undefined;\n\t\t\t\tlet runScopeWrites = 0;\n\t\t\t\tlet taskScopeWrites = 0;\n\t\t\t\tlet currentTaskWrites = 0;\n\t\t\t\tlet currentTaskRunScopeWrites = 0;\n\t\t\t\tlet currentTaskTaskScopeWrites = 0;\n\t\t\t\tlet currentTaskDelegateWrites = 0;\n\t\t\t\tconst writerSet = new Set<string>();\n\t\t\t\tconst keySet = new Set<string>();\n\n\t\t\t\tfor (const item of store.history) {\n\t\t\t\t\tconst scope = item.scope === \"task\" ? \"task\" : \"run\";\n\t\t\t\t\tif (scope === \"run\") {\n\t\t\t\t\t\trunScopeWrites += 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttaskScopeWrites += 1;\n\t\t\t\t\t}\n\t\t\t\t\tkeySet.add(`${scope}:${item.key}`);\n\t\t\t\t\tconst writerToken = [\n\t\t\t\t\t\titem.writer.taskId?.trim() || \"-\",\n\t\t\t\t\t\titem.writer.delegateId?.trim() || \"-\",\n\t\t\t\t\t\titem.writer.profile?.trim() || \"-\",\n\t\t\t\t\t].join(\"|\");\n\t\t\t\t\twriterSet.add(writerToken);\n\n\t\t\t\t\tif (currentTaskId && item.writer.taskId?.trim() === currentTaskId) {\n\t\t\t\t\t\tcurrentTaskWrites += 1;\n\t\t\t\t\t\tif (scope === \"run\") {\n\t\t\t\t\t\t\tcurrentTaskRunScopeWrites += 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcurrentTaskTaskScopeWrites += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (item.writer.delegateId?.trim()) {\n\t\t\t\t\t\t\tcurrentTaskDelegateWrites += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\trunId: store.runId,\n\t\t\t\t\ttotalEntries: Object.keys(store.entries).length,\n\t\t\t\t\ttotalWrites: store.history.length,\n\t\t\t\t\trunScopeWrites,\n\t\t\t\t\ttaskScopeWrites,\n\t\t\t\t\tcurrentTaskWrites,\n\t\t\t\t\tcurrentTaskRunScopeWrites,\n\t\t\t\t\tcurrentTaskTaskScopeWrites,\n\t\t\t\t\tcurrentTaskDelegateWrites,\n\t\t\t\t\tuniqueWriters: writerSet.size,\n\t\t\t\t\tuniqueKeys: keySet.size,\n\t\t\t\t};\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tnormalizeLockError(error);\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"shared-memory.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shared-memory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,KAAK,MAAM,EAAQ,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAEN,KAAK,mBAAmB,EAIxB,MAAM,qBAAqB,CAAC;AAE7B,QAAA,MAAM,uBAAuB;;;;;;EAwB3B,CAAC;AAEH,QAAA,MAAM,sBAAsB;;;;;;EA8B1B,CAAC;AAEH,MAAM,MAAM,sBAAsB,GAAG,MAAM,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAC5E,MAAM,MAAM,qBAAqB,GAAG,MAAM,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAyD1E,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,mBAAmB,GAAG,SAAS,CAAC,OAAO,uBAAuB,CAAC,CA+BnH;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,mBAAmB,GAAG,SAAS,CAAC,OAAO,sBAAsB,CAAC,CAiDjH"}
1
+ {"version":3,"file":"shared-memory.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shared-memory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,KAAK,MAAM,EAAQ,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAEN,KAAK,mBAAmB,EAIxB,MAAM,qBAAqB,CAAC;AAa7B,QAAA,MAAM,uBAAuB;;;;;;EAwB3B,CAAC;AAEH,QAAA,MAAM,sBAAsB;;;;;;EA8B1B,CAAC;AAEH,MAAM,MAAM,sBAAsB,GAAG,MAAM,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAC5E,MAAM,MAAM,qBAAqB,GAAG,MAAM,CAAC,OAAO,sBAAsB,CAAC,CAAC;AA2E1E,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,mBAAmB,GAAG,SAAS,CAAC,OAAO,uBAAuB,CAAC,CAuCnH;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,mBAAmB,GAAG,SAAS,CAAC,OAAO,sBAAsB,CAAC,CA2DjH"}
@@ -1,5 +1,14 @@
1
1
  import { Type } from "@sinclair/typebox";
2
2
  import { readSharedMemory, writeSharedMemory, } from "../shared-memory.js";
3
+ function resolveSharedMemoryScopePolicy(raw) {
4
+ const normalized = (raw ?? "").trim().toLowerCase();
5
+ if (normalized === "warn")
6
+ return "warn";
7
+ if (normalized === "enforce")
8
+ return "enforce";
9
+ return "legacy";
10
+ }
11
+ const sharedMemoryScopePolicy = resolveSharedMemoryScopePolicy(process.env.IOSM_SHARED_MEMORY_SCOPE_POLICY);
3
12
  const sharedMemoryWriteSchema = Type.Object({
4
13
  key: Type.String({
5
14
  minLength: 1,
@@ -75,8 +84,21 @@ function summarizeWriter(context) {
75
84
  .join(" ");
76
85
  return parts.length > 0 ? parts : "root";
77
86
  }
78
- function normalizeScope(scope) {
79
- return scope ?? "task";
87
+ function resolveScope(input) {
88
+ if (input.scope)
89
+ return { scope: input.scope };
90
+ if (sharedMemoryScopePolicy === "enforce") {
91
+ throw new Error(`shared_memory_${input.operation} requires explicit scope ("run" or "task"). ` +
92
+ `Set IOSM_SHARED_MEMORY_SCOPE_POLICY=legacy to restore implicit defaults.`);
93
+ }
94
+ const shouldWarn = sharedMemoryScopePolicy === "warn" || input.context.profile === "meta";
95
+ if (!shouldWarn) {
96
+ return { scope: "task" };
97
+ }
98
+ return {
99
+ scope: "task",
100
+ warning: `scope omitted -> defaulted to "task" for shared_memory_${input.operation}. Pass explicit scope to avoid ambiguity.`,
101
+ };
80
102
  }
81
103
  function normalizeMode(mode) {
82
104
  return mode ?? "set";
@@ -90,23 +112,31 @@ export function createSharedMemoryWriteTool(context) {
90
112
  execute: async (_toolCallId, params, _signal) => {
91
113
  const input = params;
92
114
  const ensured = ensureContext(context);
115
+ const scopeResolution = resolveScope({
116
+ scope: input.scope,
117
+ context: ensured,
118
+ operation: "write",
119
+ });
93
120
  const result = await writeSharedMemory(ensured, {
94
121
  key: input.key,
95
122
  value: input.value,
96
- scope: normalizeScope(input.scope),
123
+ scope: scopeResolution.scope,
97
124
  mode: normalizeMode(input.mode),
98
125
  ifVersion: input.if_version,
99
126
  }, _signal);
127
+ const warningLine = scopeResolution.warning ? `\nwarning: ${scopeResolution.warning}` : "";
100
128
  return {
101
129
  content: [
102
130
  {
103
131
  type: "text",
104
- text: `shared memory updated (${result.scope}:${result.key} v${result.version} by ${summarizeWriter(ensured)})`,
132
+ text: `shared memory updated (${result.scope}:${result.key} v${result.version} by ${summarizeWriter(ensured)})${warningLine}`,
105
133
  },
106
134
  ],
107
135
  details: {
108
136
  runId: ensured.runId,
109
137
  item: summarizeSharedMemoryItemForDetails(result, false),
138
+ scopePolicy: sharedMemoryScopePolicy,
139
+ scopeWarning: scopeResolution.warning,
110
140
  },
111
141
  };
112
142
  },
@@ -124,8 +154,13 @@ export function createSharedMemoryReadTool(context) {
124
154
  throw new Error("shared_memory_read accepts either key or prefix, not both");
125
155
  }
126
156
  const ensured = ensureContext(context);
157
+ const scopeResolution = resolveScope({
158
+ scope: input.scope,
159
+ context: ensured,
160
+ operation: "read",
161
+ });
127
162
  const result = await readSharedMemory(ensured, {
128
- scope: normalizeScope(input.scope),
163
+ scope: scopeResolution.scope,
129
164
  key: input.key,
130
165
  prefix: input.prefix,
131
166
  limit: input.limit,
@@ -147,6 +182,9 @@ export function createSharedMemoryReadTool(context) {
147
182
  : ` value=${item.value.length > 80 ? `${item.value.slice(0, 77)}...` : item.value}`;
148
183
  return `- ${item.key} v${item.version}${writer ? ` (${writer})` : ""}${valuePart}`;
149
184
  });
185
+ if (scopeResolution.warning) {
186
+ lines.unshift(`warning: ${scopeResolution.warning}`);
187
+ }
150
188
  return {
151
189
  content: [{ type: "text", text: [header, ...lines].join("\n") }],
152
190
  details: {
@@ -154,6 +192,8 @@ export function createSharedMemoryReadTool(context) {
154
192
  scope: result.scope,
155
193
  totalMatched: result.totalMatched,
156
194
  items: result.items.map((item) => summarizeSharedMemoryItemForDetails(item, input.include_values === true)),
195
+ scopePolicy: sharedMemoryScopePolicy,
196
+ scopeWarning: scopeResolution.warning,
157
197
  },
158
198
  };
159
199
  },
@@ -1 +1 @@
1
- {"version":3,"file":"shared-memory.js","sourceRoot":"","sources":["../../../src/core/tools/shared-memory.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EACN,gBAAgB,EAIhB,iBAAiB,GACjB,MAAM,qBAAqB,CAAC;AAE7B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C,CAAC,CAAC,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,CAAC;gBACpF,CAAC,CAAC,CAAC;YACN,OAAO;gBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBACzE,OAAO,EAAE;oBACR,KAAK,EAAE,MAAM,CAAC,KAAK;oBACnB,KAAK,EAAE,MAAM,CAAC,KAAK;oBACnB,YAAY,EAAE,MAAM,CAAC,YAAY;oBACjC,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,mCAAmC,CAAC,IAAI,EAAE,KAAK,CAAC,cAAc,KAAK,IAAI,CAAC,CAAC;iBAC3G;aACD,CAAC;QACH,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { AgentTool } from \"@mariozechner/pi-agent-core\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport {\n\treadSharedMemory,\n\ttype SharedMemoryContext,\n\ttype SharedMemoryScope,\n\ttype SharedMemoryWriteMode,\n\twriteSharedMemory,\n} from \"../shared-memory.js\";\n\nconst sharedMemoryWriteSchema = Type.Object({\n\tkey: Type.String({\n\t\tminLength: 1,\n\t\tdescription: \"Logical key for shared data within the current run (for example: findings/auth).\",\n\t}),\n\tvalue: Type.String({\n\t\tdescription: \"Text payload to store.\",\n\t}),\n\tscope: Type.Optional(\n\t\tType.Union([Type.Literal(\"run\"), Type.Literal(\"task\")], {\n\t\t\tdescription: \"run = visible to all tasks in run_id; task = isolated to current task_id.\",\n\t\t}),\n\t),\n\tmode: Type.Optional(\n\t\tType.Union([Type.Literal(\"set\"), Type.Literal(\"append\")], {\n\t\t\tdescription: \"set replaces value; append concatenates to existing value.\",\n\t\t}),\n\t),\n\tif_version: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1,\n\t\t\tdescription: \"Optional CAS guard. Write succeeds only when current version matches this value.\",\n\t\t}),\n\t),\n});\n\nconst sharedMemoryReadSchema = Type.Object({\n\tkey: Type.Optional(\n\t\tType.String({\n\t\t\tminLength: 1,\n\t\t\tdescription: \"Exact key to read. Mutually exclusive with prefix.\",\n\t\t}),\n\t),\n\tprefix: Type.Optional(\n\t\tType.String({\n\t\t\tminLength: 1,\n\t\t\tdescription: \"Prefix filter for keys (for example: findings/).\",\n\t\t}),\n\t),\n\tscope: Type.Optional(\n\t\tType.Union([Type.Literal(\"run\"), Type.Literal(\"task\")], {\n\t\t\tdescription: \"run = visible to all tasks in run_id; task = isolated to current task_id.\",\n\t\t}),\n\t),\n\tlimit: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1,\n\t\t\tmaximum: 100,\n\t\t\tdescription: \"Maximum entries to return (default 20).\",\n\t\t}),\n\t),\n\tinclude_values: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription: \"When false (default), returns only metadata (key/version/writer).\",\n\t\t}),\n\t),\n});\n\nexport type SharedMemoryWriteInput = Static<typeof sharedMemoryWriteSchema>;\nexport type SharedMemoryReadInput = Static<typeof sharedMemoryReadSchema>;\n\nfunction summarizeSharedMemoryItemForDetails(\n\titem: {\n\t\tkey: string;\n\t\tscope: SharedMemoryScope;\n\t\tversion: number;\n\t\tupdatedAt: string;\n\t\twriter: { taskId?: string; delegateId?: string; profile?: string };\n\t\tvalue?: string;\n\t},\n\tincludeValuePreview: boolean,\n): Record<string, unknown> {\n\tconst base: Record<string, unknown> = {\n\t\tkey: item.key,\n\t\tscope: item.scope,\n\t\tversion: item.version,\n\t\tupdatedAt: item.updatedAt,\n\t\twriter: item.writer,\n\t};\n\tif (typeof item.value !== \"string\") return base;\n\tconst valueLength = item.value.length;\n\tif (!includeValuePreview) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tvalueLength,\n\t\t};\n\t}\n\treturn {\n\t\t...base,\n\t\tvalueLength,\n\t\tvaluePreview: item.value.length > 200 ? `${item.value.slice(0, 197)}...` : item.value,\n\t};\n}\n\nfunction ensureContext(context: SharedMemoryContext): SharedMemoryContext {\n\tif (!context.runId || !context.runId.trim()) {\n\t\tthrow new Error(\"shared memory is unavailable: missing run_id context\");\n\t}\n\treturn context;\n}\n\nfunction summarizeWriter(context: SharedMemoryContext): string {\n\tconst parts = [context.taskId ? `task=${context.taskId}` : undefined, context.delegateId ? `delegate=${context.delegateId}` : undefined]\n\t\t.filter((item): item is string => Boolean(item))\n\t\t.join(\" \");\n\treturn parts.length > 0 ? parts : \"root\";\n}\n\nfunction normalizeScope(scope: SharedMemoryScope | undefined): SharedMemoryScope {\n\treturn scope ?? \"task\";\n}\n\nfunction normalizeMode(mode: SharedMemoryWriteMode | undefined): SharedMemoryWriteMode {\n\treturn mode ?? \"set\";\n}\n\nexport function createSharedMemoryWriteTool(context: SharedMemoryContext): AgentTool<typeof sharedMemoryWriteSchema> {\n\treturn {\n\t\tname: \"shared_memory_write\",\n\t\tlabel: \"shared_memory_write\",\n\t\tdescription:\n\t\t\t\"Write intermediate data into run-scoped shared memory so parallel agents/delegates can exchange state.\",\n\t\tparameters: sharedMemoryWriteSchema,\n\t\texecute: async (_toolCallId: string, params: unknown, _signal?: AbortSignal) => {\n\t\t\tconst input = params as SharedMemoryWriteInput;\n\t\t\tconst ensured = ensureContext(context);\n\t\t\tconst result = await writeSharedMemory(ensured, {\n\t\t\t\tkey: input.key,\n\t\t\t\tvalue: input.value,\n\t\t\t\tscope: normalizeScope(input.scope),\n\t\t\t\tmode: normalizeMode(input.mode),\n\t\t\t\tifVersion: input.if_version,\n\t\t\t}, _signal);\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: `shared memory updated (${result.scope}:${result.key} v${result.version} by ${summarizeWriter(ensured)})`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: {\n\t\t\t\t\trunId: ensured.runId,\n\t\t\t\t\titem: summarizeSharedMemoryItemForDetails(result, false),\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport function createSharedMemoryReadTool(context: SharedMemoryContext): AgentTool<typeof sharedMemoryReadSchema> {\n\treturn {\n\t\tname: \"shared_memory_read\",\n\t\tlabel: \"shared_memory_read\",\n\t\tdescription:\n\t\t\t\"Read intermediate data from run-scoped shared memory (task-local or run-global view).\",\n\t\tparameters: sharedMemoryReadSchema,\n\t\texecute: async (_toolCallId: string, params: unknown, _signal?: AbortSignal) => {\n\t\t\tconst input = params as SharedMemoryReadInput;\n\t\t\tif (input.key && input.prefix) {\n\t\t\t\tthrow new Error(\"shared_memory_read accepts either key or prefix, not both\");\n\t\t\t}\n\t\t\tconst ensured = ensureContext(context);\n\t\t\tconst result = await readSharedMemory(ensured, {\n\t\t\t\tscope: normalizeScope(input.scope),\n\t\t\t\tkey: input.key,\n\t\t\t\tprefix: input.prefix,\n\t\t\t\tlimit: input.limit,\n\t\t\t\tincludeValues: input.include_values ?? false,\n\t\t\t}, _signal);\n\t\t\tconst header = `shared memory ${result.scope}: ${result.items.length}/${result.totalMatched}`;\n\t\t\tconst lines =\n\t\t\t\tresult.items.length === 0\n\t\t\t\t\t? [\"(no entries)\"]\n\t\t\t\t\t: result.items.map((item) => {\n\t\t\t\t\t\t\tconst writer = [\n\t\t\t\t\t\t\t\titem.writer.taskId ? `task=${item.writer.taskId}` : undefined,\n\t\t\t\t\t\t\t\titem.writer.delegateId ? `delegate=${item.writer.delegateId}` : undefined,\n\t\t\t\t\t\t\t\titem.writer.profile ? `profile=${item.writer.profile}` : undefined,\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t\t\t\t\t.join(\" \");\n\t\t\t\t\t\t\tconst valuePart =\n\t\t\t\t\t\t\t\titem.value === undefined\n\t\t\t\t\t\t\t\t\t? \"\"\n\t\t\t\t\t\t\t\t\t: ` value=${item.value.length > 80 ? `${item.value.slice(0, 77)}...` : item.value}`;\n\t\t\t\t\t\t\treturn `- ${item.key} v${item.version}${writer ? ` (${writer})` : \"\"}${valuePart}`;\n\t\t\t\t\t\t});\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\" as const, text: [header, ...lines].join(\"\\n\") }],\n\t\t\t\tdetails: {\n\t\t\t\t\trunId: result.runId,\n\t\t\t\t\tscope: result.scope,\n\t\t\t\t\ttotalMatched: result.totalMatched,\n\t\t\t\t\titems: result.items.map((item) => summarizeSharedMemoryItemForDetails(item, input.include_values === true)),\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"shared-memory.js","sourceRoot":"","sources":["../../../src/core/tools/shared-memory.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EACN,gBAAgB,EAIhB,iBAAiB,GACjB,MAAM,qBAAqB,CAAC;AAI7B,SAAS,8BAA8B,CAAC,GAAuB;IAC9D,MAAM,UAAU,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACpD,IAAI,UAAU,KAAK,MAAM;QAAE,OAAO,MAAM,CAAC;IACzC,IAAI,UAAU,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC/C,OAAO,QAAQ,CAAC;AACjB,CAAC;AAED,MAAM,uBAAuB,GAAG,8BAA8B,CAAC,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;AAE5G,MAAM,uBAAuB,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3C,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC;QAChB,SAAS,EAAE,CAAC;QACZ,WAAW,EAAE,kFAAkF;KAC/F,CAAC;IACF,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC;QAClB,WAAW,EAAE,wBAAwB;KACrC,CAAC;IACF,KA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K,EAAE,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,mCAAmC,CAAC,IAAI,EAAE,KAAK,CAAC,cAAc,KAAK,IAAI,CAAC,CAAC;oBAC3G,WAAW,EAAE,uBAAuB;oBACpC,YAAY,EAAE,eAAe,CAAC,OAAO;iBACrC;aACD,CAAC;QACH,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { AgentTool } from \"@mariozechner/pi-agent-core\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport {\n\treadSharedMemory,\n\ttype SharedMemoryContext,\n\ttype SharedMemoryScope,\n\ttype SharedMemoryWriteMode,\n\twriteSharedMemory,\n} from \"../shared-memory.js\";\n\ntype SharedMemoryScopePolicy = \"legacy\" | \"warn\" | \"enforce\";\n\nfunction resolveSharedMemoryScopePolicy(raw: string | undefined): SharedMemoryScopePolicy {\n\tconst normalized = (raw ?? \"\").trim().toLowerCase();\n\tif (normalized === \"warn\") return \"warn\";\n\tif (normalized === \"enforce\") return \"enforce\";\n\treturn \"legacy\";\n}\n\nconst sharedMemoryScopePolicy = resolveSharedMemoryScopePolicy(process.env.IOSM_SHARED_MEMORY_SCOPE_POLICY);\n\nconst sharedMemoryWriteSchema = Type.Object({\n\tkey: Type.String({\n\t\tminLength: 1,\n\t\tdescription: \"Logical key for shared data within the current run (for example: findings/auth).\",\n\t}),\n\tvalue: Type.String({\n\t\tdescription: \"Text payload to store.\",\n\t}),\n\tscope: Type.Optional(\n\t\tType.Union([Type.Literal(\"run\"), Type.Literal(\"task\")], {\n\t\t\tdescription: \"run = visible to all tasks in run_id; task = isolated to current task_id.\",\n\t\t}),\n\t),\n\tmode: Type.Optional(\n\t\tType.Union([Type.Literal(\"set\"), Type.Literal(\"append\")], {\n\t\t\tdescription: \"set replaces value; append concatenates to existing value.\",\n\t\t}),\n\t),\n\tif_version: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1,\n\t\t\tdescription: \"Optional CAS guard. Write succeeds only when current version matches this value.\",\n\t\t}),\n\t),\n});\n\nconst sharedMemoryReadSchema = Type.Object({\n\tkey: Type.Optional(\n\t\tType.String({\n\t\t\tminLength: 1,\n\t\t\tdescription: \"Exact key to read. Mutually exclusive with prefix.\",\n\t\t}),\n\t),\n\tprefix: Type.Optional(\n\t\tType.String({\n\t\t\tminLength: 1,\n\t\t\tdescription: \"Prefix filter for keys (for example: findings/).\",\n\t\t}),\n\t),\n\tscope: Type.Optional(\n\t\tType.Union([Type.Literal(\"run\"), Type.Literal(\"task\")], {\n\t\t\tdescription: \"run = visible to all tasks in run_id; task = isolated to current task_id.\",\n\t\t}),\n\t),\n\tlimit: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1,\n\t\t\tmaximum: 100,\n\t\t\tdescription: \"Maximum entries to return (default 20).\",\n\t\t}),\n\t),\n\tinclude_values: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription: \"When false (default), returns only metadata (key/version/writer).\",\n\t\t}),\n\t),\n});\n\nexport type SharedMemoryWriteInput = Static<typeof sharedMemoryWriteSchema>;\nexport type SharedMemoryReadInput = Static<typeof sharedMemoryReadSchema>;\n\nfunction summarizeSharedMemoryItemForDetails(\n\titem: {\n\t\tkey: string;\n\t\tscope: SharedMemoryScope;\n\t\tversion: number;\n\t\tupdatedAt: string;\n\t\twriter: { taskId?: string; delegateId?: string; profile?: string };\n\t\tvalue?: string;\n\t},\n\tincludeValuePreview: boolean,\n): Record<string, unknown> {\n\tconst base: Record<string, unknown> = {\n\t\tkey: item.key,\n\t\tscope: item.scope,\n\t\tversion: item.version,\n\t\tupdatedAt: item.updatedAt,\n\t\twriter: item.writer,\n\t};\n\tif (typeof item.value !== \"string\") return base;\n\tconst valueLength = item.value.length;\n\tif (!includeValuePreview) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tvalueLength,\n\t\t};\n\t}\n\treturn {\n\t\t...base,\n\t\tvalueLength,\n\t\tvaluePreview: item.value.length > 200 ? `${item.value.slice(0, 197)}...` : item.value,\n\t};\n}\n\nfunction ensureContext(context: SharedMemoryContext): SharedMemoryContext {\n\tif (!context.runId || !context.runId.trim()) {\n\t\tthrow new Error(\"shared memory is unavailable: missing run_id context\");\n\t}\n\treturn context;\n}\n\nfunction summarizeWriter(context: SharedMemoryContext): string {\n\tconst parts = [context.taskId ? `task=${context.taskId}` : undefined, context.delegateId ? `delegate=${context.delegateId}` : undefined]\n\t\t.filter((item): item is string => Boolean(item))\n\t\t.join(\" \");\n\treturn parts.length > 0 ? parts : \"root\";\n}\n\nfunction resolveScope(input: {\n\tscope: SharedMemoryScope | undefined;\n\tcontext: SharedMemoryContext;\n\toperation: \"read\" | \"write\";\n}): { scope: SharedMemoryScope; warning?: string } {\n\tif (input.scope) return { scope: input.scope };\n\tif (sharedMemoryScopePolicy === \"enforce\") {\n\t\tthrow new Error(\n\t\t\t`shared_memory_${input.operation} requires explicit scope (\"run\" or \"task\"). ` +\n\t\t\t\t`Set IOSM_SHARED_MEMORY_SCOPE_POLICY=legacy to restore implicit defaults.`,\n\t\t);\n\t}\n\tconst shouldWarn = sharedMemoryScopePolicy === \"warn\" || input.context.profile === \"meta\";\n\tif (!shouldWarn) {\n\t\treturn { scope: \"task\" };\n\t}\n\treturn {\n\t\tscope: \"task\",\n\t\twarning: `scope omitted -> defaulted to \"task\" for shared_memory_${input.operation}. Pass explicit scope to avoid ambiguity.`,\n\t};\n}\n\nfunction normalizeMode(mode: SharedMemoryWriteMode | undefined): SharedMemoryWriteMode {\n\treturn mode ?? \"set\";\n}\n\nexport function createSharedMemoryWriteTool(context: SharedMemoryContext): AgentTool<typeof sharedMemoryWriteSchema> {\n\treturn {\n\t\tname: \"shared_memory_write\",\n\t\tlabel: \"shared_memory_write\",\n\t\tdescription:\n\t\t\t\"Write intermediate data into run-scoped shared memory so parallel agents/delegates can exchange state.\",\n\t\tparameters: sharedMemoryWriteSchema,\n\t\texecute: async (_toolCallId: string, params: unknown, _signal?: AbortSignal) => {\n\t\t\tconst input = params as SharedMemoryWriteInput;\n\t\t\tconst ensured = ensureContext(context);\n\t\t\tconst scopeResolution = resolveScope({\n\t\t\t\tscope: input.scope,\n\t\t\t\tcontext: ensured,\n\t\t\t\toperation: \"write\",\n\t\t\t});\n\t\t\tconst result = await writeSharedMemory(ensured, {\n\t\t\t\tkey: input.key,\n\t\t\t\tvalue: input.value,\n\t\t\t\tscope: scopeResolution.scope,\n\t\t\t\tmode: normalizeMode(input.mode),\n\t\t\t\tifVersion: input.if_version,\n\t\t\t}, _signal);\n\t\t\tconst warningLine = scopeResolution.warning ? `\\nwarning: ${scopeResolution.warning}` : \"\";\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: `shared memory updated (${result.scope}:${result.key} v${result.version} by ${summarizeWriter(ensured)})${warningLine}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: {\n\t\t\t\t\trunId: ensured.runId,\n\t\t\t\t\titem: summarizeSharedMemoryItemForDetails(result, false),\n\t\t\t\t\tscopePolicy: sharedMemoryScopePolicy,\n\t\t\t\t\tscopeWarning: scopeResolution.warning,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport function createSharedMemoryReadTool(context: SharedMemoryContext): AgentTool<typeof sharedMemoryReadSchema> {\n\treturn {\n\t\tname: \"shared_memory_read\",\n\t\tlabel: \"shared_memory_read\",\n\t\tdescription:\n\t\t\t\"Read intermediate data from run-scoped shared memory (task-local or run-global view).\",\n\t\tparameters: sharedMemoryReadSchema,\n\t\texecute: async (_toolCallId: string, params: unknown, _signal?: AbortSignal) => {\n\t\t\tconst input = params as SharedMemoryReadInput;\n\t\t\tif (input.key && input.prefix) {\n\t\t\t\tthrow new Error(\"shared_memory_read accepts either key or prefix, not both\");\n\t\t\t}\n\t\t\tconst ensured = ensureContext(context);\n\t\t\tconst scopeResolution = resolveScope({\n\t\t\t\tscope: input.scope,\n\t\t\t\tcontext: ensured,\n\t\t\t\toperation: \"read\",\n\t\t\t});\n\t\t\tconst result = await readSharedMemory(ensured, {\n\t\t\t\tscope: scopeResolution.scope,\n\t\t\t\tkey: input.key,\n\t\t\t\tprefix: input.prefix,\n\t\t\t\tlimit: input.limit,\n\t\t\t\tincludeValues: input.include_values ?? false,\n\t\t\t}, _signal);\n\t\t\tconst header = `shared memory ${result.scope}: ${result.items.length}/${result.totalMatched}`;\n\t\t\tconst lines =\n\t\t\t\tresult.items.length === 0\n\t\t\t\t\t? [\"(no entries)\"]\n\t\t\t\t\t: result.items.map((item) => {\n\t\t\t\t\t\t\tconst writer = [\n\t\t\t\t\t\t\t\titem.writer.taskId ? `task=${item.writer.taskId}` : undefined,\n\t\t\t\t\t\t\t\titem.writer.delegateId ? `delegate=${item.writer.delegateId}` : undefined,\n\t\t\t\t\t\t\t\titem.writer.profile ? `profile=${item.writer.profile}` : undefined,\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t\t\t\t\t.join(\" \");\n\t\t\t\t\t\t\tconst valuePart =\n\t\t\t\t\t\t\t\titem.value === undefined\n\t\t\t\t\t\t\t\t\t? \"\"\n\t\t\t\t\t\t\t\t\t: ` value=${item.value.length > 80 ? `${item.value.slice(0, 77)}...` : item.value}`;\n\t\t\t\t\t\t\treturn `- ${item.key} v${item.version}${writer ? ` (${writer})` : \"\"}${valuePart}`;\n\t\t\t\t\t\t});\n\t\t\tif (scopeResolution.warning) {\n\t\t\t\tlines.unshift(`warning: ${scopeResolution.warning}`);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\" as const, text: [header, ...lines].join(\"\\n\") }],\n\t\t\t\tdetails: {\n\t\t\t\t\trunId: result.runId,\n\t\t\t\t\tscope: result.scope,\n\t\t\t\t\ttotalMatched: result.totalMatched,\n\t\t\t\t\titems: result.items.map((item) => summarizeSharedMemoryItemForDetails(item, input.include_values === true)),\n\t\t\t\t\tscopePolicy: sharedMemoryScopePolicy,\n\t\t\t\t\tscopeWarning: scopeResolution.warning,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { AgentTool } from "@mariozechner/pi-agent-core";
2
2
  import { type Static } from "@sinclair/typebox";
3
3
  import { type FailureCause } from "../failure-retrospective.js";
4
- import type { SharedMemoryContext } from "../shared-memory.js";
4
+ import { type SharedMemoryContext } from "../shared-memory.js";
5
5
  import type { CustomSubagentDefinition } from "../subagents.js";
6
6
  /**
7
7
  * Callback type passed in from sdk.ts to avoid circular imports.
@@ -94,6 +94,17 @@ export interface TaskToolDetails {
94
94
  retrospectiveAttempts?: number;
95
95
  retrospectiveRecovered?: number;
96
96
  failureCauses?: Partial<Record<FailureCause, number>>;
97
+ coordination?: {
98
+ sharedMemoryWrites?: number;
99
+ currentTaskWrites?: number;
100
+ currentTaskDelegateWrites?: number;
101
+ runScopeWrites?: number;
102
+ taskScopeWrites?: number;
103
+ duplicatesDetected?: number;
104
+ claimKeysMatched?: number;
105
+ claimCollisions?: number;
106
+ };
107
+ sharedMemorySummaryKey?: string;
97
108
  }
98
109
  export interface TaskToolOptions {
99
110
  resolveCustomSubagent?: (name: string) => CustomSubagentDefinition | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"task.d.ts","sourceRoot":"","sources":["../../../src/core/tools/task.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,KAAK,MAAM,EAAQ,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAKN,KAAK,YAAY,EACjB,MAAM,6BAA6B,CAAC;AAcrC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEhE;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG;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