claude-mem 13.26.1 → 13.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/dist/npx-cli/index.js +1 -1
  3. package/openclaw/openclaw.plugin.json +1 -1
  4. package/openclaw/skills/agent-cost-report/CHECKSUMS.txt +47 -0
  5. package/openclaw/skills/agent-cost-report/SKILL.md +240 -0
  6. package/openclaw/skills/agent-cost-report/scripts/acr/__init__.py +1 -0
  7. package/openclaw/skills/agent-cost-report/scripts/acr/behavior.py +313 -0
  8. package/openclaw/skills/agent-cost-report/scripts/acr/classify.py +83 -0
  9. package/openclaw/skills/agent-cost-report/scripts/acr/costs.py +121 -0
  10. package/openclaw/skills/agent-cost-report/scripts/acr/devices.py +88 -0
  11. package/openclaw/skills/agent-cost-report/scripts/acr/evidence.py +165 -0
  12. package/openclaw/skills/agent-cost-report/scripts/acr/labels.py +112 -0
  13. package/openclaw/skills/agent-cost-report/scripts/acr/measure.py +89 -0
  14. package/openclaw/skills/agent-cost-report/scripts/acr/mistakes.py +321 -0
  15. package/openclaw/skills/agent-cost-report/scripts/acr/patterns.py +394 -0
  16. package/openclaw/skills/agent-cost-report/scripts/acr/period.py +101 -0
  17. package/openclaw/skills/agent-cost-report/scripts/acr/prices.py +102 -0
  18. package/openclaw/skills/agent-cost-report/scripts/acr/render.py +516 -0
  19. package/openclaw/skills/agent-cost-report/scripts/acr/rollup.py +364 -0
  20. package/openclaw/skills/agent-cost-report/scripts/acr/rules.json +26 -0
  21. package/openclaw/skills/agent-cost-report/scripts/acr/rules.py +78 -0
  22. package/openclaw/skills/agent-cost-report/scripts/acr/sample.py +45 -0
  23. package/openclaw/skills/agent-cost-report/scripts/acr/snapshot.py +55 -0
  24. package/openclaw/skills/agent-cost-report/scripts/acr/sync.py +78 -0
  25. package/openclaw/skills/agent-cost-report/scripts/acr/transcripts.py +130 -0
  26. package/openclaw/skills/agent-cost-report/scripts/acr/wins.py +286 -0
  27. package/openclaw/skills/agent-cost-report/scripts/acr.py +206 -0
  28. package/openclaw/skills/agent-cost-report/scripts/tests/_db.py +49 -0
  29. package/openclaw/skills/agent-cost-report/scripts/tests/_paths.py +9 -0
  30. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/codex/sessions/2026/09/18/rollout-codex-1.jsonl +4 -0
  31. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/make_report_fixtures.py +46 -0
  32. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/prices_sample.json +6 -0
  33. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/projects/-workspace-proj-a/sess-aaaa.jsonl +8 -0
  34. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/projects/-workspace-proj-b/sess-bbbb.jsonl +1 -0
  35. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-1day.json +823 -0
  36. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-30day.json +2213 -0
  37. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-7day.json +1252 -0
  38. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-empty.json +536 -0
  39. package/openclaw/skills/agent-cost-report/scripts/tests/fixtures/report-session.json +662 -0
  40. package/openclaw/skills/agent-cost-report/scripts/tests/test_behavior.py +275 -0
  41. package/openclaw/skills/agent-cost-report/scripts/tests/test_devices.py +99 -0
  42. package/openclaw/skills/agent-cost-report/scripts/tests/test_labels.py +70 -0
  43. package/openclaw/skills/agent-cost-report/scripts/tests/test_measure.py +118 -0
  44. package/openclaw/skills/agent-cost-report/scripts/tests/test_period.py +91 -0
  45. package/openclaw/skills/agent-cost-report/scripts/tests/test_prices.py +126 -0
  46. package/openclaw/skills/agent-cost-report/scripts/tests/test_render.py +114 -0
  47. package/openclaw/skills/agent-cost-report/scripts/tests/test_rollup.py +264 -0
  48. package/openclaw/skills/agent-cost-report/scripts/tests/test_snapshot.py +64 -0
  49. package/openclaw/skills/agent-cost-report/scripts/tests/test_sync.py +52 -0
  50. package/openclaw/skills/agent-cost-report/scripts/tests/test_transcripts.py +154 -0
  51. package/openclaw/skills/agent-cost-report/scripts/tests/test_wins.py +181 -0
  52. package/package.json +1 -1
  53. package/plugin/.claude-plugin/plugin.json +1 -1
  54. package/plugin/.codex-plugin/plugin.json +1 -1
  55. package/plugin/package.json +1 -1
  56. package/plugin/scripts/mcp-server.cjs +1 -1
  57. package/plugin/scripts/server-service.cjs +2 -2
  58. package/plugin/scripts/transcript-watcher.cjs +2 -2
  59. package/plugin/scripts/transcript-watcher.cjs.map +1 -1
  60. package/plugin/scripts/worker-service.cjs +5 -5
  61. package/plugin/scripts/worker-service.cjs.map +1 -1
  62. package/plugin/skills/agent-cost-report/CHECKSUMS.txt +47 -0
  63. package/plugin/skills/agent-cost-report/SKILL.md +240 -0
  64. package/plugin/skills/agent-cost-report/VERIFICATION.md +106 -0
  65. package/plugin/skills/agent-cost-report/scripts/acr/__init__.py +1 -0
  66. package/plugin/skills/agent-cost-report/scripts/acr/behavior.py +313 -0
  67. package/plugin/skills/agent-cost-report/scripts/acr/classify.py +83 -0
  68. package/plugin/skills/agent-cost-report/scripts/acr/costs.py +121 -0
  69. package/plugin/skills/agent-cost-report/scripts/acr/devices.py +88 -0
  70. package/plugin/skills/agent-cost-report/scripts/acr/evidence.py +165 -0
  71. package/plugin/skills/agent-cost-report/scripts/acr/labels.py +112 -0
  72. package/plugin/skills/agent-cost-report/scripts/acr/measure.py +89 -0
  73. package/plugin/skills/agent-cost-report/scripts/acr/mistakes.py +321 -0
  74. package/plugin/skills/agent-cost-report/scripts/acr/patterns.py +394 -0
  75. package/plugin/skills/agent-cost-report/scripts/acr/period.py +101 -0
  76. package/plugin/skills/agent-cost-report/scripts/acr/prices.py +102 -0
  77. package/plugin/skills/agent-cost-report/scripts/acr/render.py +516 -0
  78. package/plugin/skills/agent-cost-report/scripts/acr/rollup.py +364 -0
  79. package/plugin/skills/agent-cost-report/scripts/acr/rules.json +26 -0
  80. package/plugin/skills/agent-cost-report/scripts/acr/rules.py +78 -0
  81. package/plugin/skills/agent-cost-report/scripts/acr/sample.py +45 -0
  82. package/plugin/skills/agent-cost-report/scripts/acr/snapshot.py +55 -0
  83. package/plugin/skills/agent-cost-report/scripts/acr/sync.py +78 -0
  84. package/plugin/skills/agent-cost-report/scripts/acr/transcripts.py +130 -0
  85. package/plugin/skills/agent-cost-report/scripts/acr/wins.py +286 -0
  86. package/plugin/skills/agent-cost-report/scripts/acr.py +206 -0
  87. package/plugin/skills/agent-cost-report/scripts/tests/_db.py +49 -0
  88. package/plugin/skills/agent-cost-report/scripts/tests/_paths.py +9 -0
  89. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/codex/sessions/2026/09/18/rollout-codex-1.jsonl +4 -0
  90. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/make_report_fixtures.py +46 -0
  91. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/prices_sample.json +6 -0
  92. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/projects/-workspace-proj-a/sess-aaaa.jsonl +8 -0
  93. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/projects/-workspace-proj-b/sess-bbbb.jsonl +1 -0
  94. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-1day.json +823 -0
  95. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-30day.json +2213 -0
  96. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-7day.json +1252 -0
  97. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-empty.json +536 -0
  98. package/plugin/skills/agent-cost-report/scripts/tests/fixtures/report-session.json +662 -0
  99. package/plugin/skills/agent-cost-report/scripts/tests/test_behavior.py +275 -0
  100. package/plugin/skills/agent-cost-report/scripts/tests/test_devices.py +99 -0
  101. package/plugin/skills/agent-cost-report/scripts/tests/test_labels.py +70 -0
  102. package/plugin/skills/agent-cost-report/scripts/tests/test_measure.py +118 -0
  103. package/plugin/skills/agent-cost-report/scripts/tests/test_period.py +91 -0
  104. package/plugin/skills/agent-cost-report/scripts/tests/test_prices.py +126 -0
  105. package/plugin/skills/agent-cost-report/scripts/tests/test_render.py +114 -0
  106. package/plugin/skills/agent-cost-report/scripts/tests/test_rollup.py +264 -0
  107. package/plugin/skills/agent-cost-report/scripts/tests/test_snapshot.py +64 -0
  108. package/plugin/skills/agent-cost-report/scripts/tests/test_sync.py +52 -0
  109. package/plugin/skills/agent-cost-report/scripts/tests/test_transcripts.py +154 -0
  110. package/plugin/skills/agent-cost-report/scripts/tests/test_wins.py +181 -0
  111. package/plugin/skills/agent-cost-report/verification/precision-2026-09-26.json +7 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.26.1",
3
+ "version": "13.27.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -100,7 +100,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
100
100
  ${m.stack??""}
101
101
  `)}else $n(f+`
102
102
  `)}debug(e,r,i,n){this.log(0,e,r,i,n)}info(e,r,i,n){this.log(1,e,r,i,n)}warn(e,r,i,n){this.log(2,e,r,i,n)}setErrorSink(e){qS=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!qS||!(i instanceof Error))return;qS(i)}catch{}}dataIn(e,r,i,n){this.info(e,`\u2192 ${r}`,i,n)}dataOut(e,r,i,n){this.info(e,`\u2190 ${r}`,i,n)}success(e,r,i,n){this.info(e,`\u2713 ${r}`,i,n)}failure(e,r,i,n){this.error(e,`\u2717 ${r}`,i,n)}},w=new BS});import{join as UP}from"path";import{mkdirSync as N8,writeFileSync as L8}from"fs";import{randomUUID as $8}from"crypto";function U8(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function VS(t,e){if(U8(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function JP(t,e){return VS(t,e).enabled}function eu(){return UP(Un(),FP)}function po(){let t;try{t=lr(eu(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return w.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}function Fa(t){let e=Un();N8(e,{recursive:!0}),L8(UP(e,FP),JSON.stringify(t,null,2)+`
103
- `)}function tf(){let t=po();if(t?.installId)return t.installId;let e=$8();return Fa({installId:e,decidedAt:""}),e}var FP,rf=E(()=>{"use strict";He();ls();Oe();FP="telemetry.json"});import F8 from"os";function J8(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let i=r instanceof Error?r:new Error(String(r));return w.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,i),""}}let e=t;return e.length>zP?e.slice(0,zP):e}catch{return""}}function z8(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=F8.homedir()||""}catch(i){let n=i instanceof Error?i:new Error(String(i));w.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,n),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(i){let n=i instanceof Error?i:new Error(String(i));return w.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,n),t.split(e).join("~")}}function q8(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function G8(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(e)?e.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${mn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${mn}@`))}function B8(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function V8(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${mn}`})}function W8(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,mn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,mn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,mn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,mn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,mn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,mn),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,mn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,mn),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,mn),e}function qP(t){let e=J8(t);return e.length===0?"":(e=z8(e),e=G8(e),e=q8(e),e=B8(e),e=V8(e),e=W8(e),e)}var zP,mn,GP=E(()=>{"use strict";Oe();zP=8192,mn="[REDACTED]"});function Z8(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!H8.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>BP?i.slice(0,BP):i;e[r]=qP(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function VP(t){let e={};try{Z8(t,e)}catch{}return e}var H8,BP,WP=E(()=>{"use strict";GP();H8=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),BP=200});import HP from"os";function ZP(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||X8}function YP(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Q8}function XP(t){let e={};for(let r of eX)t[r]!==void 0&&(e[r]=t[r]);return e}function tX(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||HP.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return w.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function QP(){return{version:Y8,os:process.platform,os_version:HP.release(),is_wsl:tX(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Y8,X8,Q8,eX,eM=E(()=>{"use strict";Oe();Y8="13.26.1",X8="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Q8="https://us.i.posthog.com";eX=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"]});async function oi(t,e,r){try{if(!JP(process.env,po()))return;let i=VP({...QP(),...e??{}});if(r?.person?i.$set=XP(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
103
+ `)}function tf(){let t=po();if(t?.installId)return t.installId;let e=$8();return Fa({installId:e,decidedAt:""}),e}var FP,rf=E(()=>{"use strict";He();ls();Oe();FP="telemetry.json"});import F8 from"os";function J8(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let i=r instanceof Error?r:new Error(String(r));return w.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,i),""}}let e=t;return e.length>zP?e.slice(0,zP):e}catch{return""}}function z8(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=F8.homedir()||""}catch(i){let n=i instanceof Error?i:new Error(String(i));w.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,n),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(i){let n=i instanceof Error?i:new Error(String(i));return w.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,n),t.split(e).join("~")}}function q8(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function G8(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(e)?e.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${mn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${mn}@`))}function B8(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function V8(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${mn}`})}function W8(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,mn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,mn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,mn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,mn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,mn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,mn),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,mn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,mn),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,mn),e}function qP(t){let e=J8(t);return e.length===0?"":(e=z8(e),e=G8(e),e=q8(e),e=B8(e),e=V8(e),e=W8(e),e)}var zP,mn,GP=E(()=>{"use strict";Oe();zP=8192,mn="[REDACTED]"});function Z8(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!H8.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>BP?i.slice(0,BP):i;e[r]=qP(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function VP(t){let e={};try{Z8(t,e)}catch{}return e}var H8,BP,WP=E(()=>{"use strict";GP();H8=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),BP=200});import HP from"os";function ZP(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||X8}function YP(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Q8}function XP(t){let e={};for(let r of eX)t[r]!==void 0&&(e[r]=t[r]);return e}function tX(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||HP.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return w.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function QP(){return{version:Y8,os:process.platform,os_version:HP.release(),is_wsl:tX(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Y8,X8,Q8,eX,eM=E(()=>{"use strict";Oe();Y8="13.27.0",X8="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Q8="https://us.i.posthog.com";eX=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"]});async function oi(t,e,r){try{if(!JP(process.env,po()))return;let i=VP({...QP(),...e??{}});if(r?.person?i.$set=XP(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
104
104
  `);return}let n=ZP(),o=new AbortController,s=setTimeout(()=>o.abort(),rX);try{await nX(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function nX(t,e,r,i){await fetch(`${YP()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:tf(),properties:r}),signal:i})}var rX,nf=E(()=>{"use strict";rf();WP();eM();rX=2e3});import{spawn as iX,spawnSync as tM}from"node:child_process";import{dirname as oX,extname as tu,join as sX}from"node:path";function si(t,e,r){return iX(t,e??[],{windowsHide:!0,...r})}function lX(t){return`"${t.replace(/"/g,'""')}"`}function ZS(t){if(process.platform!=="win32")return[];try{let e=tM("where",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return e.status!==0||!e.stdout.trim()?[]:e.stdout.split(/\r?\n/).map(r=>r.trim()).filter(Boolean)}catch{return[]}}function dX(t,e){let r=t.find(n=>WS.has(tu(n).toLowerCase()));if(r)return r;let i=t.find(n=>HS.has(tu(n).toLowerCase()));if(i&&e){let n=e(i);if(n&&WS.has(tu(n).toLowerCase()))return n}return i??t.find(n=>aX.has(tu(n).toLowerCase()))??t[0]??null}function pX(t,e,r=uX){if(!/[\\/]volta[\\/]bin[\\/]/i.test(e))return null;try{let i=r(sX(oX(e),"volta.exe"),["which",t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:cX,windowsHide:!0});return i.status!==0||!i.stdout.trim()?null:i.stdout.split(/\r?\n/).map(n=>n.trim()).find(Boolean)??null}catch{return null}}function Ja(t){return dX(ZS(t),e=>pX(t,e))}function za(t,e,r,i=process.platform){let n={...i==="win32"?{windowsHide:!0}:{},...r};if(i==="win32"&&HS.has(tu(t).toLowerCase())){let o=[t,...e].map(lX).join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${o}"`],options:{...n,windowsVerbatimArguments:!0}}}return{command:t,args:[...e],options:n}}var HS,WS,aX,cX,uX,ai=E(()=>{"use strict";HS=new Set([".cmd",".bat"]),WS=new Set([".exe",".com"]),aX=new Set([...WS,...HS]);cX=5e3,uX=(t,e,r)=>tM(t,e,r)});function qa(t){return process.platform==="win32"?Math.round(t*qr.WINDOWS_MULTIPLIER):t}var qr,of=E(()=>{"use strict";qr={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});var iM={};De(iM,{SettingsDefaultsManager:()=>Le});import{readFileSync as fX,existsSync as mX}from"fs";import{join as rM}from"path";import{homedir as nM,hostname as hX}from"os";function vX(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{if(new URL(e).hostname===gX)return bX}catch{return null}return null}var yX,gX,bX,Le,Dr=E(()=>{"use strict";of();Rr();yX="security_alert",gX="sync-hub.black-pond-afbb.workers.dev",bX="https://sync.cmem.ai";Le=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(qa(qr.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:rM(nM(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:rM(nM(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:hX(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_LLM_TIMEOUT_MS:"30000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let i=r?this.applyEnvOverrides(e):e;return i.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(i.CLAUDE_MEM_WORKER_HOST),i}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let i of Object.keys(this.DEFAULTS))process.env[i]!==void 0&&(r[i]=process.env[i]);return r}static loadFromFile(e,r=!0){try{if(!mX(e)){let u=this.getAllDefaults();try{lt(e,u),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(d){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,d instanceof Error?d.message:String(d))}return this.finalizeSettings(u,r)}let i=fX(e,"utf-8"),n=Et(i),o=n,s=n.env&&typeof n.env=="object"&&!Array.isArray(n.env),a=s&&Object.keys(n).some(u=>u!=="env");if(s&&(o=n.env,!a))try{lt(e,o),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(u){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,u instanceof Error?u.message:String(u))}if(o.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===yX){o={...o,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{lt(e,a?{...n,env:o}:o),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(u){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,u instanceof Error?u.message:String(u))}}let l=vX(o.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(l!==null){o={...o,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:l};try{lt(e,a?{...n,env:o}:o),console.warn("[SETTINGS] Migrated cloud sync hub URL off the legacy workers.dev host:",e)}catch(u){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,u instanceof Error?u.message:String(u))}}let c={...this.DEFAULTS};for(let u of Object.keys(this.DEFAULTS))o[u]!==void 0&&(c[u]=o[u]);return this.finalizeSettings(c,r)}catch(i){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,i instanceof Error?i.message:String(i));let n=this.getAllDefaults();return this.finalizeSettings(n,r)}}}});import{execFile as SX}from"child_process";import{promisify as EX}from"util";import{createHash as LIe}from"crypto";import{existsSync as UIe,readFileSync as FIe,writeFileSync as JIe,mkdirSync as zIe,unlinkSync as qIe}from"fs";import{userInfo as BIe}from"os";import{join as WIe}from"path";var XIe,oM=E(()=>{"use strict";He();Dr();Oe();XIe=EX(SX)});import{existsSync as YS,readFileSync as aM,writeFileSync as wX,mkdirSync as _X,chmodSync as sM}from"fs";import{parseEnv as kX}from"util";import{basename as axe}from"path";function lM(){return process.env.CLAUDE_MEM_ENV_FILE??Be.envFile()}function uM(t){return kX(t)}function IX(t){let e=["# claude-mem credentials","# This file stores keys and gateway settings for the claude-mem memory agent","# Edit this file or use claude-mem settings to configure",""];for(let[r,i]of Object.entries(t))if(i){let n=/[\s#=]/.test(i);e.push(`${r}=${n?`"${i}"`:i}`)}return e.join(`
105
105
  `)+`
106
106
  `}function dM(){let t=lM();if(!YS(t))return{};try{let e=aM(t,"utf-8"),r=uM(e),i={};for(let n of cM)r[n]&&(i[n]=r[n]);return i}catch(e){return w.warn("ENV","Failed to load .env file",{path:t},e instanceof Error?e:new Error(String(e))),{}}}function pM(t){let e=lM(),r={};try{YS(Be.dataDir())||_X(Be.dataDir(),{recursive:!0,mode:448}),sM(Be.dataDir(),448),r=YS(e)?uM(aM(e,"utf-8")):{}}catch(n){let o=n instanceof Error?n:new Error(String(n));throw w.error("ENV","Failed to set up env directory or read existing env",{},o),o}let i={...r};for(let n of cM){let o=t[n];o!==void 0&&(o?i[n]=o:delete i[n])}try{wX(e,IX(i),{encoding:"utf-8",mode:384}),sM(e,384)}catch(n){throw w.error("ENV","Failed to save .env file",{path:e},n instanceof Error?n:new Error(String(n))),n}}var cM,fM=E(()=>{"use strict";Oe();He();Dr();oM();cM=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","GEMINI_API_KEY","OPENROUTER_API_KEY"]});function Fn(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(AX.has(r)){e[r]=i;continue}TX.has(r)||xX.some(n=>r.startsWith(n))||(e[r]=i)}return e}var xX,TX,CX,AX,ru=E(()=>{"use strict";xX=["CLAUDECODE_","CLAUDE_CODE_"],TX=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),CX=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),AX=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...CX])});import{spawnSync as hM}from"child_process";import{readFileSync as OX}from"fs";function DX(t){XS+=1;let e=hM("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Fn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function PX(t,e=!1){if(!e){let i=mM.get(t);if(i&&Date.now()-i.capturedAtMs<RX)return i.token}let r=null;try{r=DX(t)}catch(i){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:i instanceof Error?i.message:String(i)}),r=null}return mM.set(t,{token:r,capturedAtMs:Date.now()}),r}function yM(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){XS+=1;try{let r=OX(`/proc/${t}/stat`,"utf-8"),i=r.lastIndexOf(") ");if(i<0)return null;let o=r.slice(i+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(r){return w.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return PX(t,e);XS+=1;try{let r=hM("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Fn(process.env),LC_ALL:"C",LANG:"C"}});if(r.status!==0)return null;let i=r.stdout.trim();return i.length>0?i:null}catch(r){return w.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function fo(t){return yM(t,!1)}function Di(t,e){if(e===null)return!0;let r=yM(t,!0);return r===null?!0:r===e}var RX,mM,XS,QS=E(()=>{"use strict";Oe();ru();RX=5e3,mM=new Map,XS=0});import{execFile as MX}from"child_process";import{readdirSync as KX,readFileSync as jX}from"fs";import{promisify as NX}from"util";async function Jn(t,e={}){let r=e.signalMode==="immediate",i=e.expectedStartToken!==void 0?e.expectedStartToken:fo(t),n=()=>Di(t,i);if(!n()){w.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(w.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await eE("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(o){let s=o.code,a=String(o.stderr??""),l=o instanceof Error?o.message:String(o);if(s===LX||$X.test(`${a} ${l}`)){w.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new sf(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||l}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",s=await af(t);for(let c of s){if(!Di(c.pid,c.startToken)){w.debug("PROCESS",`Skipping ${o}: descendant PID was reused since enumeration`,{pid:c.pid,rootPid:t});continue}try{process.kill(c.pid,o)}catch{}}if(n())try{process.kill(t,o)}catch(c){let u=c instanceof Error?c:new Error(String(c)),d=u.code;d!=="ESRCH"&&w.debug("PROCESS",`Failed to ${o} PID ${t}`,{code:d},u)}else w.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:o});r||await new Promise(c=>setTimeout(c,500));let a=n()?await af(t):[],l=new Map;for(let c of s)l.set(c.pid,c.startToken);for(let c of a)l.set(c.pid,c.startToken);for(let[c,u]of l){if(!Di(c,u)){w.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:c,rootPid:t});continue}try{process.kill(c,"SIGKILL")}catch{}}if(!r&&n())try{process.kill(t,"SIGKILL")}catch{}}catch(o){throw new sf(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function UX(){return process.platform==="win32"?zX():process.platform==="linux"?FX():JX()}function FX(){let t=[],e;try{e=KX("/proc")}catch(r){return w.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let i;try{i=jX(`/proc/${r}/stat`,"utf-8")}catch{continue}let n=i.lastIndexOf(") ");if(n<0)continue;let o=i.slice(n+2).split(" "),s=Number.parseInt(o[1]??"",10),a=o[19];Number.isFinite(s)&&t.push({pid:Number.parseInt(r,10),ppid:s,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function JX(){let t;try{t=(await eE("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return w.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
@@ -3,7 +3,7 @@
3
3
  "name": "Claude-Mem (Persistent Memory)",
4
4
  "description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
5
5
  "kind": "memory",
6
- "version": "13.26.1",
6
+ "version": "13.27.0",
7
7
  "license": "Apache-2.0",
8
8
  "author": "thedotmack",
9
9
  "homepage": "https://claude-mem.ai",
@@ -0,0 +1,47 @@
1
+ 8f7afa104e956d318696610358d0b55c032397ed5232cbac1b064ed43429f09e SKILL.md
2
+ a0bc9b77b1895208cd63587b1524f16e203a5824b27786cb6ff18a2a260f234c scripts/acr.py
3
+ bc4fc2a17a1b2bd38422000c907ec07bf1deb1008c7b1bfcf45b2e41364da3e4 scripts/acr/__init__.py
4
+ a5a3394119fca6a376843826c29cec40e6edbd3085f22024bfdad27601ff8b85 scripts/acr/behavior.py
5
+ f72d82461e2c02584bcc3f4d7a05fd18165e5b3d255c0333c7763599daa5adaa scripts/acr/classify.py
6
+ 15ff8f31e778d80c0436876f7c28a0bfd25660dec44ab8dbeaa334ec8ecb41b2 scripts/acr/costs.py
7
+ 75322a8ba32ec58a2649755b5dff481f7a0f69806325667cf1ce7597b165cb32 scripts/acr/devices.py
8
+ 8240ac9f6444ef0ab5e83e5533b8aa641922bde6ca82ce4de7b19c1ca2622ea3 scripts/acr/evidence.py
9
+ 162f0eab3d5ced5a14fac4c194f5ad997a0d9cf3df93b4e90637d156556dec8a scripts/acr/labels.py
10
+ 24796160a02f578fd6ddc9613b3f5052c611c2e8fbeff5d90397ecf1119a74ad scripts/acr/measure.py
11
+ f617e2c75cd65f4415a7ae6107d03681bc85365684ebf777b594f074c87e231c scripts/acr/mistakes.py
12
+ 3ae9141248b97d27a87c7ac9526db0a663f90924448126e4b2cab5c090a4f3a3 scripts/acr/patterns.py
13
+ 9bc988081b4e48f252a9b47ddd6f26bf05766bd5e41495736d1f29c3db833b6f scripts/acr/period.py
14
+ 5235c50c24012738321cf441d61dd8987be398b5939af8c9fd038f49417c261b scripts/acr/prices.py
15
+ 53dc7888ba105e67e58b719c25f0a7b96402d4ae9dbc9a29362745064105590d scripts/acr/render.py
16
+ a96306368d051a24be5bbfa516ae7f7448b10a01176548671de142068bf444be scripts/acr/rollup.py
17
+ 6637b40b8171127a9d76cf9a971412f6e0ee351246e1944070cd63d36d2bd3fb scripts/acr/rules.json
18
+ 2c57f2e41221be84ce08d5146cdff6d5016119c120fc43505afe7274a18d0012 scripts/acr/rules.py
19
+ 6328e919ab8e09535129b4f3845fc2e0d0ab50d0beafbc3042f57bee07ba9db2 scripts/acr/sample.py
20
+ d329883df29e52e66312ef0829a17521adb832c4d267a69957aba10235b34679 scripts/acr/snapshot.py
21
+ 0d03c8ed1c8076ec59dc8f6c1241ca52f5d2ecf83f47792d8dfb20a1c8737a81 scripts/acr/sync.py
22
+ 05155c3c9d0f061484d933839189a7b14d2b56bab603ef41a0e0e141be4c8848 scripts/acr/transcripts.py
23
+ a2ce04c2409982bf38427bcf8f4fa40cf119d289159d67dea5d2c5966066b6c1 scripts/acr/wins.py
24
+ 34f188a792da085d50a0fd608836ca03395a01978229aad90fb7901be753e655 scripts/tests/_db.py
25
+ 1baa143bea04326b7096a0654f91c22255d1f131ed23af454395b9d3c959f78d scripts/tests/_paths.py
26
+ a2cc21046a1e79c3977e5bf22ca75f67c0c77d4e725ef33663ac62b289688e7e scripts/tests/test_behavior.py
27
+ ccbb9887b02d145359a42cfb3919850d4e4b7b538b9017caa7cc4312a94b85cd scripts/tests/test_devices.py
28
+ 5041df7b137161be717d7356bbf6472875e02e48bbd0a1de7453dede78e31d30 scripts/tests/test_labels.py
29
+ 7aa398f4d51dbbba314c1886e54df0f96c34af401c1e747f939a9e695cd58395 scripts/tests/test_measure.py
30
+ 2d2c8dad098d8165e11293456777526b35b3caba41c8b7fedaf92365e2b419e1 scripts/tests/test_period.py
31
+ 77a16deda2df742acb5c5405fb014584d270b686fc3d2e38e5e1d7e25eb3f3a7 scripts/tests/test_prices.py
32
+ 96f38b7fe379e89e28b71ee6ade91b1591200fb27477280739624d919b8a3cdc scripts/tests/test_render.py
33
+ 9ca3e43df448955189e686eac7229c6e5de59458fb30278b3d923ca160c67b6d scripts/tests/test_rollup.py
34
+ 323379622ffc8984d3bf2d3710fb1cc8284fd7174ed7e6725dbf5613bea5cdd4 scripts/tests/test_snapshot.py
35
+ ca1b30d767ddf668bf9ace78e76aa4592eb299a09c1f5f9049e089f610d1ba11 scripts/tests/test_sync.py
36
+ 2c39ce509e7293e95ffa81f766f46792c76a0497f491806d797e9ec76a822d52 scripts/tests/test_transcripts.py
37
+ 96acc8b6531383951b347a816ef511765fa24564425ad0bd9ee0ad27b18d7e9d scripts/tests/test_wins.py
38
+ e18dd87adc7439dbc3485328eb39bdf8c72231713412a7d34f095007e939576f scripts/tests/fixtures/make_report_fixtures.py
39
+ f89b3a779a195670f381c40ec2fcda56b049e14c3cefa0483d583fc11209ab06 scripts/tests/fixtures/prices_sample.json
40
+ 2763df8beaebc33e037f0c618b3e1d0e95747f277fa41f139cd5630cf9901226 scripts/tests/fixtures/report-1day.json
41
+ 2191f096c71c5f5144bd831503114a8f8cc889b5b60e1243a704b9335032aed1 scripts/tests/fixtures/report-30day.json
42
+ 5f2079b73c4474d36bf2d369ee783220dac786ce702a68ca4748d0f95133f6a2 scripts/tests/fixtures/report-7day.json
43
+ 38568fd8b682b168187f404843af2ac95290bfec8ac27e24ad0a770f689bcd82 scripts/tests/fixtures/report-empty.json
44
+ af27b7684dfa734437c9922e1c8a81172f278a7560b232c2ead3fc16629823ae scripts/tests/fixtures/report-session.json
45
+ 9ed8ae28c7bb8dd86be98617819abfc8b4557af7c8efa4ee36a339efd0cb62b5 scripts/tests/fixtures/codex/sessions/2026/09/18/rollout-codex-1.jsonl
46
+ d3285c6a012ff622f104fd0ab8452e0d586233aec1f4562a0f0655cbadf004b9 scripts/tests/fixtures/projects/-workspace-proj-a/sess-aaaa.jsonl
47
+ cd0219f1b8e202d04c7c07ce7c2dd52fc5ec78f30ae8254defe4cae2880bb000 scripts/tests/fixtures/projects/-workspace-proj-b/sess-bbbb.jsonl
@@ -0,0 +1,240 @@
1
+ ---
2
+ name: Agent Cost Report
3
+ description: >-
4
+ Believable agent cost report for any period, default the last 7 full days PT, not counting today.
5
+ Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured
6
+ provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus
7
+ report.json, line-items.csv, evidence.json.
8
+ allowed-tools:
9
+ - Bash
10
+ - Read
11
+ - Write
12
+ - AskUserQuestion
13
+ - mcp__plugin_claude-mem_mcp-search__search
14
+ - mcp__plugin_claude-mem_mcp-search__timeline
15
+ - mcp__plugin_claude-mem_mcp-search__get_observations
16
+ ---
17
+
18
+ # Agent Cost Report
19
+
20
+ **Claude-Mem / Claude Code skill.** Runtime is the `scripts/` pipeline (transcripts → tokens → dollars → Timing-style report) plus a progressive Mem Search review pass that confirms the drafted labels. The Notion draft is SPEC history only — never the product, never the runtime, never the ship vehicle.
21
+
22
+ Resolve the absolute directory containing this `SKILL.md`; all helper paths are relative to that directory. `${CLAUDE_SKILL_DIR}` is the shortcut: `python3 "${CLAUDE_SKILL_DIR}/scripts/acr.py" …`. Python 3.9+ standard library only; no pip installs. The look lives in `scripts/acr/render.py`, never here.
23
+
24
+ ## Purpose
25
+
26
+ Turn Claude-Mem activity into a **manager-readable cost and failure report**.
27
+
28
+ Product idea: a reusable skill that searches Claude-Mem via Mem Search, reconstructs real units of work, assigns cost and failure categories, and renders a printable report.
29
+
30
+ ## Insight north star
31
+
32
+ The headline is dollars, to two decimals, labeled. The dollars come from Claude Code transcripts (exact per-reply token usage) priced at OpenRouter public list prices, so they are **ESTIMATED**. Measured provider spend appears only when a sanctioned source gives it. Directly under the dollars: what the mistakes cost, what shipped, and both on one time axis.
33
+
34
+ ## Questions the report must answer
35
+
36
+ 1. What work was completed?
37
+ 2. What did each outcome cost?
38
+ 3. What was wasted through looping, hedging, wrong turns, rework, or poor routing?
39
+ 4. Were any unauthorized actions attempted?
40
+ 5. What should the manager change next?
41
+
42
+ **Primary unit = cost per completed outcome** (not cost per observation).
43
+
44
+ ## When to use
45
+
46
+ - "Agent cost report" / "cost per outcome" / "failure economics" / "was this session worth it" / "what did the agents cost this week"
47
+ - After a real Mem session dig when leadership needs outcome economics
48
+ - Sample / ship packs that need self-contained HTML + JSON + CSV + evidence
49
+
50
+ Memory dig mechanics: the claude-mem `mem-search` skill (progressive recall).
51
+
52
+ ## Default scope (ALWAYS)
53
+
54
+ - Unless the user names a **specific session / range / project**, the window is the **last 7 full days in PT, not counting today**: `end` = the PT midnight that started today (exclusive), `start` = `end − 7 days`. The default window never contains a partial day (G3, Alex 2026-09-25).
55
+ - Explicit windows: `--start YYYY-MM-DD --end YYYY-MM-DD` (PT calendar days, end exclusive). An explicit `--end` later than today marks the last day "partial, generated HH:MM PT".
56
+ - One session: `--session <content_session_id>`. One project plus a period: `--project <name> --start … --end …` (worktrees of the project are included).
57
+ - The report **Scope** strip shows the PT range, and Details list every session id in scope.
58
+
59
+ ## Progressive Mem Search (ALWAYS)
60
+
61
+ Follow the claude-mem `mem-search` three layers. Keep spend light.
62
+
63
+ 1. **Search** — get an index of IDs (titles, types, token hints).
64
+ 2. **Timeline** — only around anchors you care about.
65
+ 3. **Observations** — `get_observations` for the filtered IDs you will cite as evidence.
66
+
67
+ Recipe:
68
+
69
+ 1. Resolve scope (default: the last 7 full PT days).
70
+ 2. Search → collect IDs.
71
+ 3. Timeline for thin context only.
72
+ 4. Observations for intended / actual / outcome / waste / rework / blocked / unauthorized / status.
73
+ 5. Group into named work items + failure events.
74
+ 6. Calculate line-item costs.
75
+ 7. Render HTML + optional PDF (+ json/csv/evidence).
76
+ 8. Keep evidence IDs in the appendix — do not dump entire timelines into the main report.
77
+
78
+ ADHD process bullets:
79
+
80
+ - Search first → pick IDs → timeline only if context is thin → fetch only needed obs.
81
+ - Work-item titles are invented for managers ("Restore search after Chroma crash-loop"); observation titles stay evidence-only.
82
+ - Evidence appendix lists obs IDs + short titles; main sections stay outcome-first.
83
+
84
+ In this skill the search pass is the **review step** (see Recipe step 4): the pipeline drafts categories and failure types from keywords (`label_source: keyword`); the orchestrator confirms or changes each line item's `category` and `failure_type` from its cited evidence IDs and applies the result with `review --apply`. Items left unreviewed keep the "draft label" mark and the footer counts them.
85
+
86
+ ## Work categories (ALWAYS)
87
+
88
+ `Feature` · `Bug fix` · `Incident` · `Maintenance` · `Investigation` · `Experiment`
89
+
90
+ ## Failure / waste types (ALWAYS)
91
+
92
+ `Looping` · `Hedging` · `Wrong turn` · `Rework` · `Regression` · `Premature completion` · `Unauthorized action` · `Suboptimal path` · `Duplicate work` · `Blocked work` · `Missed requirement` · `Unnecessary escalation` · `Context re-read` · `Model thrash` · `Fan-out waste` · `Recovery after miss`
93
+
94
+ **Rework lock (ALWAYS):** Rework lives **only** under `failure_type` — never as a work category. Keep category as the intended job type; set `failure_type: Rework` when rework occurred.
95
+
96
+ A line item can have a work category **and** a failure_type (e.g. Maintenance + Looping).
97
+
98
+ ## Cost model
99
+
100
+ Measured tokens come from Claude Code transcripts (`~/.claude/projects/**/*.jsonl`, assistant replies deduped on `(message.id, requestId)`); Codex transcripts are read the same way. Prices are OpenRouter public list prices per million tokens, fetched at run time and saved with the report.
101
+
102
+ ```
103
+ agent_cost_i (per reply, micro-dollars) =
104
+ input × price.input + output × price.output
105
+ + cache_write_5m × price.cache_write + cache_write_1h × price.cache_write_1h
106
+ + cache_read × price.cache_read # cache_write_1h = listed rate, else 2 × input
107
+
108
+ agent_estimated_usd = Σ agent_cost_i over every reply in the window (matched or not) # ESTIMATED, the headline
109
+ extrapolated_unmeasured = observer tokens of sessions with no transcript here × (measured $ per observer token)
110
+ # EXTRAPOLATED (low confidence); "all sessions measured" when nothing remains
111
+ observer_note_taker_est = note-taker (observer) tokens, deduped per reply, × its input list price
112
+ # priced separately, never agent cost, never in the headline
113
+ mistakes_estimated_usd = Σ agent_cost_i over the same-session union of wasted turns, each turn once # low figure
114
+ cost_per_completed_outcome = Σ attributed $ for status ∈ {shipped, completed} / count(those work items)
115
+ waste_rate = Σ wasted_cost / Σ attributed $ recovery_share = Σ recovery_cost / Σ attributed $
116
+ ```
117
+
118
+ Line items are sessions: `attributed_usd` = estimated (transcript on this box) or extrapolated (no transcript). `wasted_cost` and `recovery_cost` come from the behavior pass (below), one union set for the ribbon, the line items and the mistakes line. The upper bound (redo windows plus project-wide fallback) stays in Details.
119
+
120
+ **Unauthorized blocked:** `direct_cost` $0, `risk_exposure` high, `action_status` blocked. Always keep risk_exposure non-dollar unless real cash/remediation is at stake — never invent risk dollars.
121
+
122
+ `confidence` — `high` when tokens + model + outcome are clear; `medium` when allocation across obs is judgmental; `low` when evidence is thin.
123
+
124
+ Unpriced models (not in the price list, or a negative "variable" price) are listed by name with their tokens and add nothing; they are never priced at zero silently.
125
+
126
+ ## Behavior metrics (heuristic until reviewed)
127
+
128
+ A second pass over the same transcripts tags every user turn human / bot / unknown (relayed agent prompts are never Alex's words), finds frustration episodes, and runs the pattern detectors from the Frustration Arc study: invented human gates, broke working things, wrong or expensive model, over-engineering, did something not asked, fake output, false "done", wrong tool or contact, bad outbound (incidents × recipients, never dollars), memory or rule loss, jargon, unclear cause, plus tool errors and hedging (Alex's definition: a caveat given when the answer was already available). Four summary tiles; everything else in Details. Every count is labeled `heuristic` until reviewed or classified. The optional classifier (`--classify`) is off by default, capped at $2.00 per run, uses only a regular inference `OPENROUTER_API_KEY`, and its spend is shown separately.
129
+
130
+ ## Money labeling (ALWAYS)
131
+
132
+ | Label | Meaning |
133
+ |-------|---------|
134
+ | **Measured** | Provider-reported spend from a sanctioned source (today: the OpenRouter per-key snapshot, shown with its UTC bucket label) |
135
+ | **Estimated** | Measured transcript tokens × OpenRouter list price per MTok (the formula above) |
136
+ | **Extrapolated** | Sessions with no transcript on this machine, from the observer-token ratio; always "low confidence" |
137
+ | **Unavailable** | No measured value — write `measured spend unavailable`, never `$0 spent` for unknown |
138
+ | **risk_exposure** | Severity / qualitative unless real cash is at stake (seats, refunds, SLA) |
139
+
140
+ `cost_basis` on each line item: `estimated_usage`, `measured_provider`, or `extrapolated`. Dollars are shown to two decimals everywhere (`$109.25`); every figure carries its label and basis.
141
+
142
+ ## Line-item schema
143
+
144
+ Each row in `line-items.csv` / `report.json.line_items`:
145
+
146
+ | Field | Notes |
147
+ |-------|-------|
148
+ | `work_item_id` | Stable id (`WI-1` …) |
149
+ | `title` | Human work-item title (ALWAYS invent at review; drafts use the session's first prompt) |
150
+ | `scope` / `project` / `worktree` | Period, session or project; primary project; worktree when relevant |
151
+ | `session_ids` / `content_session_id` | Mem session id(s) and the transcript join key |
152
+ | `status` | `shipped` / `completed` / `in_progress` / `abandoned` / `blocked` |
153
+ | `category` / `work_category` | One of the six work categories |
154
+ | `failure_type` / `failure_signals` | Empty or failure types (Rework lives here) |
155
+ | `cost_measured` | Number or `unavailable` |
156
+ | `cost_estimated` / `cost_extrapolated` / `attributed_usd` | List-price estimate; extrapolation for sessions with no transcript; the one used |
157
+ | `wasted_cost` / `recovery_cost` / `productive_cost` | USD from the behavior union (0 if none) |
158
+ | `risk_exposure` | `none` / `low` / `medium` / `high` (non-dollar unless real cash) |
159
+ | `evidence_ids` / `summary_ids` | Observation and summary IDs |
160
+ | `agent_tokens` | `{input, output, cache_write_5m, cache_write_1h, cache_read}` |
161
+ | `observer_tokens` | Note-taker tokens, Details only |
162
+ | `model` / `model_prices_usd_per_mtok` | Dominant model and the prices used |
163
+ | `cost_basis` | `estimated_usage` / `measured_provider` / `extrapolated` |
164
+ | `label_source` | `keyword` (draft) / `llm` / `human`, with `reviewed_by` and `reviewed_at_pt` |
165
+ | `device` | `local`, `remote-N`, or an export label such as `mac` |
166
+ | `behavior_counts` | Pattern hits in this session |
167
+ | `recommended_action` / `confidence` / `date_pt` / `notes` | One lever; high/medium/low; PT day; one plain sentence |
168
+
169
+ ## Deliverables (ALWAYS)
170
+
171
+ `acr.py` writes one directory containing:
172
+
173
+ 1. **`report.html`** — self-contained (inline CSS, no script, no external resources), Timing-style
174
+ 2. **`report.pdf`** — from `report.print.html` with headless `google-chrome`; when Chrome is missing the run says "PDF skipped, HTML is canonical"
175
+ 3. **`report.json`** — window, scope, spend, totals, by_day, by_model, by_device, line_items, wins, behavior, timeline
176
+ 4. **`line-items.csv`** — one row per work item
177
+ 5. **`evidence.json`** — observation IDs cited, short titles, observer tokens, model, session ids
178
+ 6. **`labels.review.json`** — the drafted labels for the review pass
179
+
180
+ ### Manager-facing HTML sections (required order)
181
+
182
+ 1. **Hero** — dollars with its tag (ESTIMATE / MEASURED), the basis sentence, "N things finished, about $X each", the extrapolated line, "Measured provider spend: unavailable" when it is, and the story sentence (computed, never hand-written)
183
+ 2. **Wins vs mistakes** — the cost-of-mistakes line (low figure), wins shipped (merged PRs, published versions, praise; cost "unmeasured" until sessions are linked to PRs), and two timelines on one PT-day axis
184
+ 3. **Cost ribbon** — every piece of work as a block sized by cost, waste hatched, in-progress striped
185
+ 4. **Where the money went** (donut by kind of work) · **Day by day** (stacked bars, empty days say "no agent work") · **How much was useful** (the ring, the behavior strip with at most four tiles)
186
+ 5. **What got done** — one folded row per work item, most expensive first, draft labels marked
187
+ 6. **Worth your attention** — at most three, computed
188
+ 7. **Details & evidence** (folded; open in the PDF) — wins, mistakes by day, behavior pattern table with the upper bound, rule effectiveness, spend and pricing, models, failure accounting, line items, devices, unmatched transcripts, unpriced models, label counts, the honesty rules, links to the CSV and JSON
189
+
190
+ ## Truthfulness ALWAYS rules
191
+
192
+ Positive truth rules only:
193
+
194
+ 1. Always label estimate vs measured (`cost_basis` = `estimated_usage` or `measured_provider`).
195
+ 2. Always say **measured spend unavailable** when unmatched — never "$0 spent" for unknown.
196
+ 3. Always use **completed outcomes** as the unit (cost per completed outcome).
197
+ 4. Always keep `risk_exposure` non-dollar unless real cash/remediation is at stake.
198
+ 5. Always invent human work-item titles; observation titles are evidence-only.
199
+ 6. Always progressive Mem Search; evidence IDs live in the appendix.
200
+ 7. Always put Rework under `failure_type` only.
201
+ 8. Always default scope to most recent sessions unless the user names another.
202
+
203
+ Added by the rebuild, same spirit: the note-taker's cost is separate and never in the headline; keyword labels are drafts until reviewed; Grok Bot and Mac figures are "unavailable" or "extrapolated (low confidence)", never $0 and never guessed; the live database is only ever opened read-only (every run works on a snapshot).
204
+
205
+ ## Recipe (orchestrator)
206
+
207
+ All commands from the skill directory; `OUT` is one run directory (for example `/tmp/acr-weekly/run`). Every step is idempotent.
208
+
209
+ 1. **Prices** — `python3 scripts/acr.py prices --out $OUT` (OpenRouter list prices; `--prices <saved prices.json>` to run offline; no key needed).
210
+ 2. **Collect** — `python3 scripts/acr.py collect --out $OUT` (default window) or `… --start YYYY-MM-DD --end YYYY-MM-DD`, `… --session <id>`, `… --project <name> --start … --end …`.
211
+ 3. **Rollup** — `python3 scripts/acr.py rollup --out $OUT` with the same period flags. Writes report.json, line-items.csv, evidence.json, labels.review.json. Options: `--no-gh` (skip the read-only `gh pr view` confirmation of merged PRs), `--classify` (see above), `--rules-dir <house rules>` (rule effectiveness).
212
+ 4. **Review** — for each line item in `labels.review.json`, `get_observations` on its `evidence_ids` (not whole timelines), confirm or change `category`, `failure_type`, `status`, and the title; write the reviewed file with `reviewed_by` (model id or `Alex`); apply with `python3 scripts/acr.py review --apply <reviewed.json> --out $OUT`. Items left unreviewed stay marked "draft label".
213
+ 5. **Render** — `python3 scripts/acr.py render --in $OUT/report.json --out $OUT --print`.
214
+ 6. **PDF** — `python3 scripts/acr.py pdf --out $OUT` (skipped with a message when Chrome is missing).
215
+ 7. **Optional, needs Alex's go — measured OpenRouter spend**: with a regular inference key in the environment, `OPENROUTER_API_KEY=… python3 scripts/acr.py measure-openrouter --out $OUT` before step 3. Without the key the file says `unavailable` and nothing else changes.
216
+ 8. **Optional, needs Alex's go — Mac export merge**: `python3 scripts/acr.py rollup … --device-usage <device-usage-mac.json>` (see Gaps and gates).
217
+ 9. Return absolute paths, the skill slug `agent-cost-report`, the headline dollars with their label, the mistakes line, the wins, PDF yes/no, and how the report answers the five product questions.
218
+
219
+ ## Gaps and gates
220
+
221
+ Each of these needs Alex's explicit go; the report shows the honest fallback until then.
222
+
223
+ - **OpenRouter key (needs Alex)** — a regular inference `OPENROUTER_API_KEY` supplied as an environment variable through the house's secure secret flow; never a management or provisioning key, never read from a settings file, never printed or written to any output. The per-key endpoint gives UTC day/week/month snapshots, so the figure is shown with its bucket label and switches the hero to MEASURED only when the bucket fully covers the report window. A range-by-day source (`/api/v1/activity`) exists but needs a management key, so it is not implemented (G5).
224
+ - **Mac transcripts (needs Alex)** — sessions from Alex's Mac have no transcript on the box, so their cost is EXTRAPOLATED (low confidence) until a device export is merged. Either Alex runs, on the Mac, from a plain checkout of this skill (system `python3` 3.9+): `python3 scripts/acr.py collect --export-device mac --start YYYY-MM-DD --end YYYY-MM-DD --out ~/acr-export` and shares `~/acr-export/device-usage-mac.json` (ids, timestamps, token counts, model names; no prompt or observation text, no settings, no paths); or, only after Alex's explicit go for that specific run (window, machine, destination named), an orchestrating agent runs the same command on the registered Mac through the house's registered-machine tooling and copies only `device-usage-mac.json` to the box. A go for one run is not a go for the next (G6 covered Sep 18–26 only). Merge with `--device-usage`; joined sessions flip to `estimated_usage` with `device: mac`.
225
+ - **Grok Bot (ALWAYS unavailable, no seat count)** — Grok Bot is Cursor's cloud agent. Cursor shows its weekly usage only on the plan screen; there is no API or export, and the house has no xAI key for it. The report says exactly "Grok Bot usage: unavailable" (G4): no dollars, no guessed per-seat price, no seat count. A figure Alex supplies by hand would be entered as `measured_manual` with `entered_by: Alex` and the date, never inferred; that would be a new decision.
226
+ - **Win cost (unmeasured until R4)** — sessions are not linked to PRs today, so every win reads "unmeasured (session not linked to PR)". Once commits carry a `Claude-Session: <content_session_id>` trailer (G13: trailer only, bare id), PR and publish wins get `ESTIMATED · session-linked` costs. There is no fallback estimate (G11).
227
+ - **Merge to main, npm publish, `/version-bump`** — each needs Alex's separate go. Pushing the work branch and opening the PR are routine.
228
+
229
+ ## Keeping copies in sync
230
+
231
+ The plugin directory is the source of truth. `python3 scripts/acr.py sync-check` compares `SKILL.md`, `CHECKSUMS.txt` and `scripts/**` against the house copy (`~/agent-data/workflows/agent-cost-report/`) and the four mirror plugins (`claude-mem-cursor`, `claude-mem-grok-bot`, `cowork`, `openclaw`, each under `skills/agent-cost-report/`) and exits 1 on drift; `--write` copies plugin → destinations and re-checks (G2). `CHECKSUMS.txt` is `sha256sum -c` compatible.
232
+
233
+ ## Related
234
+
235
+ - claude-mem `mem-search` skill — progressive recall
236
+ - `plans/2026-09-25-agent-cost-report-weekly.md` — the rebuild plan, decisions G1–G16, and the verification targets
237
+
238
+ ## Creed
239
+
240
+ **Claude-Mem skill · outcomes first · estimates labeled · most recent by default · rework under failure_type · progressive recall · HTML is canonical · humans see what the agent did and why it cost money.**
@@ -0,0 +1 @@
1
+ """agent-cost-report helpers (stdlib only). See plans/2026-09-25-agent-cost-report-weekly.md Phase 1."""