Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
v0.8.0: Pay Memory β audit layer for paid agent actions
Sol Aitkenbbe51830ae81
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 8524a508..87521468 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.7.0",+ "version": "0.8.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex f1fb96bd..3a52c089 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.7.0",+ "version": "0.8.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d3c93b1c..3e8322f9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,92 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.8.0] - 2026-05-10++Pay Memory: a memory and audit layer for paid agent actions. Hermes (or any+other supported runtime) makes a paid API call through `pay.sh`; Open Second+Brain saves the reason, the policy check, the receipt, the generated asset,+the spending policy decision, the human-approval state, and a per-task+report β all as plain Markdown inside the configured vault.++This release does not execute payments and does not hold wallet keys. The+payment still happens through the agent's local `pay` CLI; Open Second Brain+records what happened.++### Added++- **Core Pay Memory module** (`src/core/pay-memory/`):+ - filesystem helpers (`paymentsDateDir`, `receiptPath`, `assetPath`,+ `reportPath`) and `validateSlug` (defense-in-depth against path+ traversal in user-supplied slugs);+ - best-effort raw-output redactor for `api_key` / `token` / `secret` /+ `bearer` / `authorization` / `private_key` / `password` / `passwd` /+ `pwd` / `credential` / `session_token` in env, YAML, JSON, and+ HTTP-header shapes;+ - deterministic Markdown receipt / asset / report writers with+ frontmatter; bracket and backtick sanitisation in wikilinks /+ inline-code spans;+ - spending policy template renderer (`spending.md`) plus a separate,+ optional **machine-readable policy** (`spending.json`) with+ allowlist, single-call cap, daily budget cap, per-category receipt+ quotas, and "require approval above" threshold;+ - daily payment digest (`buildPaymentDigest` ++ `renderPaymentDigestTelegram`) for cron-friendly 4-line summaries;+ - **approval workflow** (`pending-payment-request` artifact under+ `AI Wiki/payments/_pending/`) with `pending β approved/rejected β+ consumed` state machine.+- **Path-safety helpers** (`src/core/path-safety.ts`): `ensureInsideVault`+ and `vaultRelative` use `path.sep` so the prefix check works on Windows+ too; replaces the duplicated POSIX-only versions previously inlined in+ `src/mcp/tools.ts` and `src/core/pay-memory/paths.ts`.+- **Atomic / race-safe writers** (`atomicCreateFileSyncExclusive`,+ `writeFrontmatterAtomic`): Pay Memory artifacts are written via+ `link(2)` semantics so "refuse to overwrite" is enforced atomically+ even with concurrent CLI + MCP server processes.+- **CLI commands** (eleven new in this version):+ - `init-pay-memory` β bootstrap `AI Wiki/{policies,payments,assets,drafts,reports}/`+ and write `policies/spending.md`.+ - `append-payment-receipt` β save a Markdown receipt; `--raw-output-file`+ is redacted before persisting.+ - `capture-asset` β save a Markdown note for a generated asset.+ - `payment-report` β aggregate a date's receipts into a Markdown report.+ - `check-payment-policy` β evaluate a prospective paid call against+ `spending.json`; exit 0 / 1 / 3 = allowed / denied / approval_required.+ - `request-payment-approval` β create a pending request the user must+ sign off on before the agent runs `pay`.+ - `approve-payment-request`, `reject-payment-request`,+ `consume-payment-request`, `list-pending-payments` β human / agent+ sides of the approval workflow.+ - `payment-digest` β render a Telegram-friendly 4-line summary for a+ date (with `--empty-mode silent|empty|summary`).+- **MCP tools** (eight new in this version): `payment_memory_init`,+ `payment_receipt_append`, `asset_capture`, `payment_report_generate`,+ `payment_policy_check`, `payment_request_approval`,+ `payment_request_status`, `payment_request_consume`. Server+ `initialize.instructions` describes the suggested call chain.+- **Documentation**: `docs/hermes-cron.md` (wiring `payment-digest` into a+ Hermes cron `--script --no-agent` job for daily Telegram delivery),+ `examples/hermes-payment-digest.sh` reference wrapper,+ `docs/plans/2026-05-10-pay-memory.md` (implementation plan), and+ `tests/e2e/pay-memory-sandbox.sh` (manual end-to-end smoke test against+ the real `pay --sandbox` CLI).++### Changed++- The MCP tool server now advertises **thirteen** tools (the previous five+ plus eight Pay Memory tools).+- `core/vault.ts` exposes `formatFrontmatter` (pure renderer) and+ `writeFrontmatterAtomic` (race-safe writer used by Pay Memory). The+ legacy `writeFrontmatter` keeps its non-atomic semantics for non-critical+ callers (`init.ts`, the `o2b index` command, etc.).++### Out of scope++- On-chain anchoring of vault hashes (Solana memo, web3 RPC) is+ intentionally excluded from this project. Pay Memory continues to record+ `payment_proof` strings opaquely for whatever upstream system produced+ them; the audit trail lives in the vault, not on a blockchain.+## [0.7.0] - 2026-05-09Single TypeScript source of truth on the [Bun](https://bun.sh) runtime.diff --git a/README.md b/README.mdindex 409aa9c1..6d9dedda 100644--- a/README.md+++ b/README.md@@ -120,16 +120,27 @@ scripts/o2b index --vault /path/to/vault## CLI commands```text-o2b status Show config/vault status-o2b init Bootstrap the vault profile-o2b install-cli Symlink o2b and vault-log into ~/.local/bin-o2b doctor Run vault and adapter checks-o2b append-event Append one daily event-log entry-o2b index Rebuild the Markdown page index-o2b export-config Write a redacted config snapshot-o2b mcp Run the optional MCP tool server (stdio)-o2b uninstall Print an uninstall plan; --apply-local removes config; --remove-cli removes symlinks-vault-log Compatibility wrapper around append-event+o2b status Show config/vault status+o2b init Bootstrap the vault profile+o2b install-cli Symlink o2b and vault-log into ~/.local/bin+o2b doctor Run vault and adapter checks+o2b append-event Append one daily event-log entry+o2b index Rebuild the Markdown page index+o2b export-config Write a redacted config snapshot+o2b mcp Run the optional MCP tool server (stdio)+o2b uninstall Print an uninstall plan; --apply-local removes config; --remove-cli removes symlinks+o2b init-pay-memory Bootstrap AI Wiki/{policies,payments,assets,drafts,reports}/+o2b append-payment-receipt Save a Markdown receipt for a paid API call+o2b capture-asset Save a Markdown note for a generated asset+o2b payment-report Aggregate a date's receipts into a Markdown report+o2b check-payment-policy Evaluate a paid call against policies/spending.json+o2b request-payment-approval Create a pending payment request (human must approve)+o2b approve-payment-request Mark a pending request as approved (human action)+o2b reject-payment-request Mark a pending request as rejected (human action)+o2b consume-payment-request Link an approved request to its resulting receipt+o2b list-pending-payments List pending/approved/etc. requests+o2b payment-digest Render a 4-line digest for a date (Hermes cron-friendly)+vault-log Compatibility wrapper around append-event```After running `o2b install-cli`, the bare `o2b` and `vault-log` commands are available on PATH. The local checkout can also be used without installing the Python package β run commands through `scripts/o2b` and `scripts/vault-log`, or set `PYTHONPATH=src` for module execution.@@ -151,7 +162,151 @@ mcp_servers:args: ["mcp", "--vault", "/path/to/vault"]```-Tools: `second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`. See `docs/mcp.md` for full setup, tool schemas, and Claude Code/Codex notes. The CLI remains the supported baseline; the MCP server is opt-in.+Tools: `second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`, plus the eight Pay Memory tools (`payment_memory_init`, `payment_receipt_append`, `asset_capture`, `payment_report_generate`, `payment_policy_check`, `payment_request_approval`, `payment_request_status`, `payment_request_consume`). See `docs/mcp.md` for full setup, tool schemas, and Claude Code/Codex notes. The CLI remains the supported baseline; the MCP server is opt-in.++## Pay Memory++Pay Memory is an audit layer for paid agent actions. The agent makes the+paid API call itself (typically through `pay` from+[solana-foundation/pay](https://github.com/solana-foundation/pay)); Open+Second Brain records the reason, the policy check, the receipt, and any+generated asset as plain Markdown inside the vault.++```bash+o2b init-pay-memory --vault /path/to/vault+# β AI Wiki/{policies,payments,assets,drafts,reports}/ and policies/spending.md++# After running `pay --sandbox curl β¦` and capturing the output:+o2b append-payment-receipt \+ --vault /path/to/vault \+ --service paysponge/fal \+ --status success \+ --reason "Generate one original blog header image" \+ --actual-amount 0.05 --currency USDC \+ --result-ref https://fal-cdn.example/img.png \+ --result-note "AI Wiki/assets/blog-header.md" \+ --raw-output-file /tmp/pay-output.txt++o2b capture-asset \+ --vault /path/to/vault \+ --title "Blog Header: Pay Memory" \+ --service paysponge/fal \+ --result-url https://fal-cdn.example/img.png \+ --source-receipt "AI Wiki/payments/2026-05-10/<receipt-slug>.md"++o2b payment-report --vault /path/to/vault --date 2026-05-10+```++Open Second Brain never executes payments and never holds wallet keys. The+spending policy at `AI Wiki/policies/spending.md` is read by the agent+before each paid call; this MVP does not enforce policy at runtime.++`--raw-output-file` is run through a redactor that masks values for+`api_key` / `token` / `secret` / `bearer` / `authorization` / `private_key` /+`password` / `passwd` / `pwd` / `credential` / `session_token` in env, YAML,+JSON, and HTTP-header shapes. Best-effort only β verify the saved receipt+before sharing it externally.++### Optional: machine-readable spending policy++Pay Memory's default policy is the Markdown document at+`AI Wiki/policies/spending.md` β read by the agent before each paid call,+enforced by convention. To enable runtime enforcement, drop a JSON+companion at `AI Wiki/policies/spending.json`:++```json+{+ "schema_version": 1,+ "currency": "USDC",+ "max_total_per_day": 0.10,+ "max_single_call": 0.07,+ "allowed_services": ["paysponge/fal"],+ "max_per_category": { "media_generation": 1 },+ "require_approval_above": 0.05+}+```++Then have the agent (or the user) run:++```bash+o2b check-payment-policy --service paysponge/fal --expected-amount 0.05+```++Exit codes are `0` (allowed), `1` (denied), `3` (approval required) so a+shell script can branch. The MCP tool `payment_policy_check` returns the+same structured decision.++If `spending.json` is absent, the check fails open (`has_policy: false`)+β existing flows that rely on the Markdown-only policy keep working.++### Optional: approval workflow++For paid calls that should not happen until a human signs off, Pay Memory+ships a pending-payment-request artifact under `AI Wiki/payments/_pending/`+with a `pending β approved/rejected β consumed` state machine.++Agent side:++```bash+o2b request-payment-approval \+ --service paysponge/fal \+ --reason "Generate one blog header image" \+ --expected-amount 0.05 --currency USDC+# β AI Wiki/payments/_pending/req-2026-05-10-1000-fal-...md+```++Human side, after reviewing the request file in Obsidian:++```bash+o2b approve-payment-request --id <id> --approved-by <name>+# or+o2b reject-payment-request --id <id> --rejected-by <name> --reason "..."+```++Agent side, after the approved paid call succeeded and the receipt was+saved:++```bash+o2b consume-payment-request --id <id> \+ --receipt "AI Wiki/payments/2026-05-10/<receipt-slug>.md"+```++The MCP-server side mirrors `payment_request_approval`,+`payment_request_status` (poll for approval), and `payment_request_consume`.++### Optional: daily Telegram digest via Hermes cron++`o2b payment-digest --vault <vault> --date <YYYY-MM-DD>` renders a 4-line+Russian summary suitable for delivery via Hermes cron `--script --no-agent`+jobs. See [`docs/hermes-cron.md`](docs/hermes-cron.md) for the+ready-to-paste `hermes cron create` command.++### Installing the `pay` CLI on a Linux VPS++`pay` is the Solana-Foundation payment wrapper that turns a regular HTTP+client into one that handles HTTP 402 payment challenges. It is published+as a prebuilt static binary on GitHub Releases β no Rust toolchain or+Node.js is needed on the host:++```bash+TAG=pay-v0.16.0 # pin a specific release+gh release download "$TAG" -R solana-foundation/pay \+ -p 'pay-x86_64-unknown-linux-gnu.tar.gz' -p 'sha256sums.txt' -D /tmp+cd /tmp && sha256sum -c --ignore-missing sha256sums.txt+tar -xzf pay-x86_64-unknown-linux-gnu.tar.gz+sudo install -m 0755 pay /usr/local/bin/pay+pay --version+```++Sandbox mode (`pay --sandbox curl <url>`) does **not** require running+`pay setup` first β it generates an ephemeral Solana keypair and funds it+locally via the Surfpool sandbox RPC. That makes it safe to wire into a+CI / e2e test that exercises the full Pay Memory pipeline without spending+real funds. See `tests/e2e/pay-memory-sandbox.sh` for a reference run.++For non-sandbox use the local secure storage helper (macOS Keychain, GNOME+Keyring, Windows Hello, 1Password) is configured by `pay setup`. Open+Second Brain itself never holds wallet keys.## Updatingdiff --git a/docs/hermes-cron.md b/docs/hermes-cron.mdnew file mode 100644index 00000000..db0e45c9--- /dev/null+++ b/docs/hermes-cron.md@@ -0,0 +1,66 @@+# Hermes cron β daily Pay Memory digest++This guide wires `o2b payment-digest` into [Hermes](https://github.com/NousResearch/hermes-agent)'s built-in cron scheduler so a short daily summary of the previous day's paid actions is delivered to a Telegram topic.++The digest is produced by `o2b payment-digest` itself β pure TypeScript, no LLM in the loop. That gives a deterministic 4-line message regardless of the orchestrator model's mood and avoids the "lazy single-sentence" output mode the gateway default (`combo-orchestrator`) sometimes falls into when the prompt has too many conditionals.++## Prerequisites++- Hermes is installed and the gateway is running (`hermes gateway status`).+- The Open Second Brain plugin is enabled in Hermes (`hermes plugins list | grep open-second-brain`).+- `o2b` is on `PATH` for the user that runs the gateway. If not, run `o2b install-cli` once.+- Your vault is at `/path/to/vault` (the same one the gateway is configured to use).+- You have a Telegram supergroup `chat_id` and a thread/topic id to post to.++## Register the cron job++Hermes cron uses 5-field cron syntax in **UTC**. The example below runs at 06:00 Belgrade summer (= 04:00 UTC):++```bash+hermes cron create \+ --name "pay-memory-daily-digest" \+ --deliver "telegram:<chat_id>:<topic_id>" \+ --workdir "/" \+ --no-agent --script \+ '0 4 * * *' \+ 'o2b payment-digest --vault /path/to/vault --date "$(date -u -d yesterday +%F)" --empty-mode silent'+```++Notes:++- `--no-agent --script` makes Hermes shell out to the prompt instead of routing it through the LLM. The prompt's stdout becomes the delivered Telegram message verbatim (because `cron.wrap_response: false` is set in the default Hermes config).+- `--empty-mode silent` makes the command emit `[SILENT]` when no receipts exist for that date. Use `--empty-mode empty` if you'd rather have no output at all (Hermes will then send an empty message β most clients suppress it). Use `--empty-mode summary` to always send a one-liner.+- `--workdir /` is fine; the script doesn't read relative paths.++After creation, verify:++```bash+hermes cron list+hermes cron run pay-memory-daily-digest # one-shot dry run+```++The first scheduled run will populate `~/.hermes/cron/output/<job_id>/<timestamp>.md` with the prompt + the response (the digest text) Hermes delivered.++## Edit / pause / remove++```bash+hermes cron edit pay-memory-daily-digest --schedule '0 5 * * *'+hermes cron pause pay-memory-daily-digest+hermes cron resume pay-memory-daily-digest+hermes cron remove pay-memory-daily-digest+```++## What the digest looks like++```text+π³ ΠΠΏΠ»Π°ΡΠ΅Π½ΠΎ ΡΠ΅ΡΠ²ΠΈΡΠΎΠ²: **2**+π° Π‘ΡΠΌΠΌΠ°: **0.07 USDC**+π Π€Π°ΠΉΠ»Ρ ΡΠ΅ΠΊΠΎΠ²: **2**+π ΠΡΡΡΡ: `/root/vault/AI Wiki/reports/payment-report-2026-05-09.md`+```++When there were no receipts the day before, the literal token `[SILENT]` is emitted (or empty / a one-line summary, per `--empty-mode`).++## Standalone shell wrapper (optional)++If you'd rather invoke this from systemd, GitHub Actions, or any non-Hermes scheduler, see [`examples/hermes-payment-digest.sh`](../examples/hermes-payment-digest.sh) β a thin Bash wrapper around `o2b payment-digest` that takes the vault path as `$1`.diff --git a/docs/mcp.md b/docs/mcp.mdindex d02bca5c..0d44daee 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -25,12 +25,55 @@ in Open Second Brain depends on the MCP server being running.| `second_brain_capture` | Write a Markdown note under `AI Wiki/notes/` with frontmatter. | `title`, `content` || `event_log_append` | Append a single-line event to the daily Markdown event log. | `message` || `vault_health` | Run vault, config, and plugin manifest health checks. | β |+| `payment_memory_init` | Bootstrap `AI Wiki/{policies,payments,assets,drafts,reports}/` and write the spending policy template. | β |+| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |+| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |+| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `AI Wiki/reports/`. | `date` |+| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json` (allowed / approval_required / denied). | `service` |+| `payment_request_approval` | Create a pending-payment-request the user must approve before the agent runs `pay`. | `service`, `reason` |+| `payment_request_status` | Look up a pending request by id; agent uses this to poll for approval. | `id` |+| `payment_request_consume` | Mark an `approved` request as `consumed` and link the resulting receipt. | `id`, `receipt` |`second_brain_query` accepts `pattern` (string) and `limit` (1β500, default 50).`second_brain_capture` also accepts `tags` (array of strings) and `overwrite`(boolean). `event_log_append` accepts `agent`, `date` (YYYY.MM.DD), and `time`(HH:MM). `vault_health` accepts `repo` (string) for plugin manifest validation.+`payment_memory_init` accepts `agent` (string) and `overwrite` (boolean β to+refresh the policy template). `payment_receipt_append` accepts the same+optional fields as the CLI: `agent`, `category`, `endpoint`, `expected_cost`,+`actual_amount`, `currency`, `payment_proof`, `result_ref`, `result_note`,+`raw_output`, `slug`, `date` (`YYYY-MM-DD`), `time` (`HH:MM`), `overwrite`.+`asset_capture` accepts `source_receipt`, `prompt`, `used_in`, `slug`,+`overwrite`. `payment_report_generate` accepts `title`, `task`, `slug`,+`overwrite`.++> **Date format note.** `event_log_append` uses `YYYY.MM.DD` to match the+> `Daily/<date>.md` filename convention; Pay Memory tools (`payment_receipt_append`,+> `payment_report_generate`, `payment_policy_check`, `payment_request_approval`)+> use ISO 8601 `YYYY-MM-DD` because the `AI Wiki/payments/<date>/`+> subdirectory layout is independent of `Daily/`. Both accept the matching+> `--date` form on the CLI.++`payment_policy_check` accepts `expected_amount` (number or numeric+string), `currency`, `category`, and `date`. `payment_request_approval`+mirrors `payment_receipt_append` for the descriptive fields plus+`expected_output`, `vault_files` (array of strings), and `enforce_policy`+(boolean β refuses to create the request when the policy denies the call+outright). `payment_request_status` returns the named request's `status`+plus a curated subset of frontmatter fields (`service`, `reason`,+`expected_amount`, `currency`, `created`, `approved_by`, `approved_at`,+`rejected_by`, `rejected_at`, `rejection_reason`, `receipt`,+`policy_status`, `policy_rule`) β agents poll this to see whether their+request has moved from `pending` to `approved`. Fields that were not+captured at request time (e.g. `vault_files`, `endpoint`) are not+re-derived; read the underlying Markdown file via the path returned in+the response if you need them.++The Pay Memory tools never execute payments themselves β the agent makes the+paid call through its own `pay` CLI and passes the resulting metadata into+these tools, which only persist it as Markdown.+All tool results contain both an unstructured `content` text block (a JSONserialization of the structured payload) and a `structuredContent` object soclients that prefer typed results can use it directly.@@ -83,6 +126,17 @@ mcp_servers:- second_brain_capture- event_log_append- vault_health+ # Pay Memory tools (v0.8.0+); drop any line below to disable a+ # specific tool, or remove the whole `tools.include` block to+ # expose every advertised tool.+ - payment_memory_init+ - payment_receipt_append+ - asset_capture+ - payment_report_generate+ - payment_policy_check+ - payment_request_approval+ - payment_request_status+ - payment_request_consume```If you run Open Second Brain from a checkout instead of an installed package,diff --git a/docs/plans/2026-05-10-pay-memory.md b/docs/plans/2026-05-10-pay-memory.mdnew file mode 100644index 00000000..39033f2a--- /dev/null+++ b/docs/plans/2026-05-10-pay-memory.md@@ -0,0 +1,398 @@+# Pay Memory Implementation Plan++> **Status (2026-05-10):** the work landed in v0.8.0 with an expanded+> scope. The plan below describes the original 4 CLI + 4 MCP MVP; the+> shipped release added `check-payment-policy`, the approval workflow+> (`request-/approve-/reject-/consume-payment-request`,+> `list-pending-payments`), and `payment-digest` β totalling 11 CLI+> commands and 8 MCP tools, plus an OpenClaw native-plugin parity pass.+> See `CHANGELOG [0.8.0]` for the final inventory.++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Add a memory/audit layer for paid agent actions to OpenSecondBrain. The agent (Hermes / Claude Code / Codex / OpenClaw) makes paid API calls through `pay.sh`; OpenSecondBrain records the reason, the policy check, the receipt, the generated asset, and a per-task report β all as plain Markdown inside the configured vault.++**Non-goals (MVP):** OpenSecondBrain never executes payments, never holds wallet keys, never enforces budgets at runtime. The spending policy is a Markdown document that the agent reads before paying. Reference: `Projects/open-second-brain/pay-memory.md` in the planning vault.++**Tech stack:** TypeScript on Bun, no new runtime dependencies. Reuses `core/vault.ts` (`writeFrontmatter`, `slugify`), `core/fs-atomic.ts` (`atomicWriteFileSync`), `core/config.ts` (vault/agent/timezone resolution), `cli/argparse.ts`, `mcp/tools.ts` (`ToolDefinition`, `coerceStr`, `ensureInsideVault`).++**Release:** Single PR on `feature/v0.8.0-pay-memory` β `main`. Version bump to `v0.8.0`. Hermetic Bun tests only β no real `pay --sandbox curl` in CI.++---++## Architecture summary++Three layers, in order of dependency:++1. **`src/core/pay-memory/`** β pure helpers: dated paths, slug generation, frontmatter writer wrappers, redactor for `raw_output`, policy template renderer, report aggregator. No I/O concerns leak into CLI/MCP.+2. **`src/cli/main.ts`** β four new subcommands wired into the existing dispatcher: `init-pay-memory`, `append-payment-receipt`, `capture-asset`, `payment-report`.+3. **`src/mcp/tools.ts`** β four new tools mirroring the CLI: `payment_memory_init`, `payment_receipt_append`, `asset_capture`, `payment_report_generate`. Same `ServerContext`, same `coerceStr` validation, same handler shape.++The vault layout this feature creates (relative to `<vault>`):++```text+AI Wiki/+ policies/+ spending.md+ payments/+ YYYY-MM-DD/+ <receipt-slug>.md+ assets/+ <asset-slug>.md+ drafts/ # written by the agent via existing tools+ reports/+ <report-slug>.md+```++`drafts/` is mentioned for completeness β the agent writes blog drafts through the existing `second_brain_capture` tool (or directly), so this feature does not need a dedicated command for it.++**Date format note:** payment subdirectories use `YYYY-MM-DD` (hyphenated, ISO-style), matching the spec. This intentionally differs from `Daily/YYYY.MM.DD.md` used by the event log β the two layouts are independent.++---++## File structure++- Create `src/core/pay-memory/index.ts` β re-exports the public API of the package.+- Create `src/core/pay-memory/paths.ts` β `payMemoryDirs(vault)`, `receiptPath(vault, date, slug)`, `assetPath(vault, slug)`, `reportPath(vault, slug)`.+- Create `src/core/pay-memory/policy.ts` β `DEFAULT_POLICY_TEMPLATE` constant, `writePolicyIfMissing(vault, opts)`.+- Create `src/core/pay-memory/redactor.ts` β `redactRawOutput(text)` regex-based replacer.+- Create `src/core/pay-memory/receipt.ts` β `RECEIPT_FRONTMATTER_TYPE`, `writeReceipt(vault, input)`, returns `{ path, slug, date }`.+- Create `src/core/pay-memory/asset.ts` β `writeAsset(vault, input)`, returns `{ path, slug }`.+- Create `src/core/pay-memory/report.ts` β `aggregateReceipts(vault, date)`, `writeReport(vault, input)`, returns `{ path, slug, receipts_used }`.+- Create `src/core/pay-memory/types.ts` β shared input/output interfaces (`ReceiptInput`, `AssetInput`, `ReportInput`, `PaymentReceiptSummary`).+- Modify `src/cli/main.ts` β add `cmdInitPayMemory`, `cmdAppendPaymentReceipt`, `cmdCaptureAsset`, `cmdPaymentReport`; extend the `switch` and `HELP` text.+- Modify `src/mcp/tools.ts` β add four tool definitions to `buildToolTable()`.+- Modify `src/mcp/instructions.ts` β append a short paragraph describing the new tools so the LLM discovers them on `initialize`.+- Create `tests/core/pay-memory.paths.test.ts`.+- Create `tests/core/pay-memory.redactor.test.ts`.+- Create `tests/core/pay-memory.policy.test.ts`.+- Create `tests/core/pay-memory.receipt.test.ts`.+- Create `tests/core/pay-memory.asset.test.ts`.+- Create `tests/core/pay-memory.report.test.ts`.+- Create `tests/cli/pay-memory.test.ts` β exercises all four subcommands end-to-end via `main(argv)`.+- Create `tests/mcp/pay-memory.test.ts` β exercises all four MCP tools via `MCPServer.callTool`.+- Modify `README.md` β add a `## Pay Memory` section with the same usage block.+- Modify `docs/mcp.md` β list the four new tools and their input schemas.+- Modify `CHANGELOG.md` β add a `## [0.8.0] - 2026-05-10` section (no `Unreleased`).+- Modify `package.json`, `plugin.yaml`, `pyproject.toml`, `openclaw.plugin.json` β version bump to `0.8.0` (sync via `bun run sync-version`).++---++## Public API of `core/pay-memory`++### `paths.ts`++```ts+export interface PayMemoryDirs {+ readonly policies: string; // <vault>/AI Wiki/policies+ readonly payments: string; // <vault>/AI Wiki/payments+ readonly assets: string; // <vault>/AI Wiki/assets+ readonly drafts: string; // <vault>/AI Wiki/drafts+ readonly reports: string; // <vault>/AI Wiki/reports+}++export function payMemoryDirs(vault: string): PayMemoryDirs;+export function policyPath(vault: string): string; // policies/spending.md+export function paymentsDateDir(vault: string, date: string): string;+export function receiptPath(vault: string, date: string, slug: string): string;+export function assetPath(vault: string, slug: string): string;+export function reportPath(vault: string, slug: string): string;++/** Validate `YYYY-MM-DD`. Throws on bad input. */+export function validateIsoDate(value: string): string;+```++### `policy.ts`++`DEFAULT_POLICY_TEMPLATE` is a generic placeholder per the user's existing memory rule (don't ship templates that pin specific services). The body lists the structure the agent must satisfy, lists `# allowed_services:` and `# max_*` placeholders, and includes one commented-out `paysponge/fal` example so demo users know how to fill it in.++```ts+export const DEFAULT_POLICY_TEMPLATE: string;++export interface WritePolicyResult {+ readonly path: string;+ readonly created: boolean; // false when file existed and overwrite=false+ readonly overwritten: boolean;+}++export function writePolicyIfMissing(+ vault: string,+ opts?: { readonly overwrite?: boolean }+): WritePolicyResult;+```++### `redactor.ts`++Six case-insensitive patterns matched in `key=value`, `key: value`, and JSON `"key": "value"` shapes. Each match keeps the key and replaces the value with `***REDACTED***`.++```ts+export const SECRET_KEYS: ReadonlyArray<string>; // api_key, token, secret, bearer, authorization, private_key+export function redactRawOutput(text: string): string;+```++### `receipt.ts`++```ts+export const RECEIPT_FRONTMATTER_TYPE = "agent-payment-receipt";++export interface ReceiptInput {+ readonly agent: string;+ readonly service: string; // e.g. "paysponge/fal"+ readonly status: string; // "success" | "failed" | ...+ readonly reason: string;+ readonly category?: string;+ readonly endpoint?: string;+ readonly expectedCost?: string;+ readonly actualAmount?: string;+ readonly currency?: string;+ readonly paymentProof?: string;+ readonly resultRef?: string;+ readonly resultNote?: string; // wikilink target+ readonly rawOutput?: string; // run through redactRawOutput before write+ readonly slug?: string; // optional override+ readonly date?: string; // YYYY-MM-DD; default = today (vault tz)+ readonly time?: string; // HH:MM (24h); default = now (vault tz)+ readonly overwrite?: boolean;+}++export interface ReceiptOutput {+ readonly path: string; // absolute+ readonly relativePath: string; // vault-relative+ readonly slug: string;+ readonly date: string;+ readonly created: string; // ISO Z timestamp written into frontmatter+}++export function writeReceipt(vault: string, input: ReceiptInput): ReceiptOutput;+```++Frontmatter example (matches spec Β§6.2):++```yaml+type: agent-payment-receipt+agent: hermes-main+payment_layer: pay.sh+network: solana+service: paysponge/fal+category: media_generation+status: success+created: 2026-05-10T17:20:00Z+```++The body is a deterministic Markdown template with the same section headings as the spec (`## Why this paid call was made`, `## Spending policy check`, `## Expected cost`, `## Request`, `## Payment`, `## Result`, `## Raw pay.sh output`). Optional fields render as `_(not provided)_` rather than being skipped, so the receipt is uniformly searchable.++Slug generation: `slug = input.slug ?? slugify(`${service.replace("/", "-")}-${reason}`)`. Reuses `core/vault.ts:slugify`.++### `asset.ts`++Same shape as receipt but for `AI Wiki/assets/<slug>.md`. Frontmatter: `type: generated-asset`, `source`, `source_receipt` (wikilink), `created`. Body has `## Purpose`, `## Prompt`, `## Result`, `## Notes`.++### `report.ts`++```ts+export interface PaymentReceiptSummary {+ readonly path: string; // vault-relative+ readonly service: string;+ readonly status: string;+ readonly actualAmount?: string;+ readonly currency?: string;+ readonly resultRef?: string;+ readonly resultNote?: string;+}++export function aggregateReceipts(vault: string, date: string): PaymentReceiptSummary[];++export interface ReportInput {+ readonly date: string;+ readonly title?: string;+ readonly task?: string;+ readonly slug?: string;+ readonly overwrite?: boolean;+}++export interface ReportOutput {+ readonly path: string;+ readonly relativePath: string;+ readonly slug: string;+ readonly receiptsUsed: number;+}++export function writeReport(vault: string, input: ReportInput): ReportOutput;+```++`aggregateReceipts` reads every `.md` file under `AI Wiki/payments/<date>/`, parses frontmatter via `core/vault.ts:parseFrontmatter`, extracts the documented fields (best-effort β fields missing from frontmatter are inferred from the body via simple regex on the section headings the receipt writer just emitted). Tests pin both happy path and missing-field shapes.++---++## CLI commands++Each command lives in `src/cli/main.ts` next to existing handlers. They follow the same pattern: `parseFlags(rest, schema)` β core helper β human-readable stdout (or `--json`) β exit code. All commands accept `--vault` and fall back to `requireVault(flags.vault, defaultConfigPath())`.++### `o2b init-pay-memory`++Flags: `--vault`, `--agent` (default = `resolveAgentName(config)`), `--overwrite`.++Behavior:+- Creates `AI Wiki/{policies,payments,assets,drafts,reports}` (idempotent).+- Writes `AI Wiki/policies/spending.md` from `DEFAULT_POLICY_TEMPLATE` only if missing or `--overwrite`.+- Returns JSON to stdout when `--json` is set; otherwise human summary listing created/skipped paths.++### `o2b append-payment-receipt`++Required: `--service`, `--status`, `--reason`. Optional: `--vault`, `--agent`, `--category`, `--endpoint`, `--expected-cost`, `--actual-amount`, `--currency`, `--payment-proof`, `--result-ref`, `--result-note`, `--raw-output-file`, `--slug`, `--date`, `--time`, `--overwrite`, `--json`.++Behavior:+- Reads `--raw-output-file` if provided (UTF-8); pipes through `redactRawOutput` before passing to `writeReceipt`.+- Refuses to overwrite without `--overwrite`; matches existing `init` command exit conventions.+- Stdout: `created: <relative-path>` (or JSON with `{ path, slug, date, created }`).+- **Does not** write to `Daily/`. The agent calls `event_log_append` separately.++### `o2b capture-asset`++Required: `--title`, `--service`, `--result-url`. Optional: `--source-receipt`, `--prompt-file`, `--used-in`, `--slug`, `--overwrite`, `--json`.++Behavior: identical pattern to `append-payment-receipt`, calls `writeAsset`.++### `o2b payment-report`++Required: `--date`. Optional: `--title`, `--task`, `--slug`, `--overwrite`, `--json`.++Behavior: aggregates receipts for `--date`, renders the report Markdown, writes to `AI Wiki/reports/<slug>.md`.++### Help text++`HELP` constant in `src/cli/main.ts` gains a `Pay Memory` group:++```text+Pay Memory:+ init-pay-memory Bootstrap policies/, payments/, assets/, drafts/, reports/+ append-payment-receipt Save a Markdown receipt for a paid API call+ capture-asset Save a Markdown note for a generated asset+ payment-report Generate a daily payment report from existing receipts+```++---++## MCP tools++Added to `buildToolTable()` in `src/mcp/tools.ts`. Each tool reuses `coerceStr`, `coerceStrList`, `ensureInsideVault`, and the same `ServerContext` resolved at server startup. JSON Schema mirrors the CLI flags exactly, so an agent can move between CLI and MCP without rebuilding its mental model.++| Tool | Required args | Optional args |+| --- | --- | --- |+| `payment_memory_init` | β | `agent`, `overwrite` |+| `payment_receipt_append` | `service`, `status`, `reason` | `agent`, `category`, `endpoint`, `expected_cost`, `actual_amount`, `currency`, `payment_proof`, `result_ref`, `result_note`, `raw_output`, `slug`, `date`, `time`, `overwrite` |+| `asset_capture` | `title`, `service`, `result_url` | `source_receipt`, `prompt`, `used_in`, `slug`, `overwrite` |+| `payment_report_generate` | `date` | `title`, `task`, `slug`, `overwrite` |++`raw_output` arrives as a string (CLI uses `--raw-output-file`; MCP receives the content directly). The redactor runs in the core helper, not the tool layer β that keeps both surfaces consistent.++`src/mcp/instructions.ts` gains one paragraph after the existing tool list:++> **Pay Memory tools.** When the agent makes a paid API call through pay.sh (or any other payment layer), call `payment_memory_init` once per vault to bootstrap the layout, `payment_receipt_append` to record the call, `asset_capture` for generated outputs, and `payment_report_generate` to produce a daily report. These tools never execute payments β they only persist memory. After a successful paid call, also append a daily event with `event_log_append` so the receipt is discoverable from `Daily/`.++---++## Redaction++`redactRawOutput` runs over the raw payment output before it lands on disk, replacing values for these keys (case-insensitive):++- `api_key`, `apikey`, `api-key`+- `token`, `access_token`, `refresh_token`, `bearer`+- `secret`, `client_secret`+- `authorization` (HTTP header)+- `private_key`++Recognised shapes:++- `key=value` (env-style)+- `key: value` (YAML / log lines)+- `"key": "value"` (JSON)+- `Authorization: Bearer <token>` (HTTP header)++The replacement is the literal string `***REDACTED***`. Tests pin all four shapes plus a "no false positive" case (`description: secret recipe` is not matched because the value is not a credential pattern β we only replace within the recognized assignment forms).++This is best-effort. The receipt body keeps the disclaimer that the agent must visually inspect raw output before sharing externally.++---++## Tests++All Bun-native (`bun test`), hermetic β each test creates a tmp vault under `Bun.tempDir()` (or `mkdtempSync`) and asserts on filesystem state. Test naming mirrors the existing `tests/core/`, `tests/cli/`, `tests/mcp/` layout.++Coverage targets:++- `pay-memory.paths.test.ts` β `payMemoryDirs`, `receiptPath`, `validateIsoDate` (good and bad inputs).+- `pay-memory.redactor.test.ts` β all four shapes, no-false-positive case, multi-line input.+- `pay-memory.policy.test.ts` β first-run creation, idempotent re-run, `--overwrite` behavior.+- `pay-memory.receipt.test.ts` β happy path, slug auto-generation, overwrite refusal, raw_output redaction, `--date` override.+- `pay-memory.asset.test.ts` β happy path, source_receipt wikilink rendering, overwrite refusal.+- `pay-memory.report.test.ts` β aggregates two receipts under a date, ignores non-`.md` files, missing-frontmatter graceful handling.+- `pay-memory.test.ts` (CLI) β full flow: `init-pay-memory` β `append-payment-receipt` β `capture-asset` β `payment-report`, asserts file paths and exit codes for each.+- `pay-memory.test.ts` (MCP) β same flow via `server.callTool(name, args)`, asserts `structuredContent` and `isError`.++CI matrix: `bun run typecheck && bun test`. Existing CI workflow already runs both β no workflow change.++---++## Step-by-step task list++### Task 1: Core helpers++**Files:**+- Create: `src/core/pay-memory/index.ts`, `paths.ts`, `policy.ts`, `redactor.ts`, `receipt.ts`, `asset.ts`, `report.ts`, `types.ts`+- Create: `tests/core/pay-memory.paths.test.ts`, `pay-memory.redactor.test.ts`, `pay-memory.policy.test.ts`, `pay-memory.receipt.test.ts`, `pay-memory.asset.test.ts`, `pay-memory.report.test.ts`++- [ ] **Step 1: scaffold `core/pay-memory/` modules and types.**+- [ ] **Step 2: implement `paths.ts` and pin behavior with tests.**+- [ ] **Step 3: implement `redactor.ts` and pin all shapes with tests.**+- [ ] **Step 4: implement `policy.ts` (template + `writePolicyIfMissing`) with tests.**+- [ ] **Step 5: implement `receipt.ts` with deterministic body renderer; tests cover slug, frontmatter, overwrite, redaction integration.**+- [ ] **Step 6: implement `asset.ts`; tests cover wikilink rendering and overwrite.**+- [ ] **Step 7: implement `report.ts` (`aggregateReceipts` + `writeReport`); tests cover multi-receipt aggregation and missing-field tolerance.**++### Task 2: CLI commands++**Files:**+- Modify: `src/cli/main.ts`+- Create: `tests/cli/pay-memory.test.ts`++- [ ] **Step 8: extend `HELP` with the Pay Memory group; wire dispatcher cases.**+- [ ] **Step 9: implement `cmdInitPayMemory`; assert via CLI test.**+- [ ] **Step 10: implement `cmdAppendPaymentReceipt`; CLI test covers `--raw-output-file` redaction path.**+- [ ] **Step 11: implement `cmdCaptureAsset`; CLI test covers `--prompt-file` and overwrite refusal.**+- [ ] **Step 12: implement `cmdPaymentReport`; CLI test covers `--date` aggregation across two receipts.**++### Task 3: MCP tools++**Files:**+- Modify: `src/mcp/tools.ts`, `src/mcp/instructions.ts`+- Create: `tests/mcp/pay-memory.test.ts`++- [ ] **Step 13: add four `ToolDefinition` entries to `buildToolTable()` mirroring the CLI inputs.**+- [ ] **Step 14: extend `instructions.ts` with the Pay Memory paragraph.**+- [ ] **Step 15: MCP test runs end-to-end: `payment_memory_init` β `payment_receipt_append` β `asset_capture` β `payment_report_generate`.**++### Task 4: Docs and release++**Files:**+- Modify: `README.md`, `docs/mcp.md`, `CHANGELOG.md`, `package.json`, `plugin.yaml`, `pyproject.toml`, `openclaw.plugin.json`++- [ ] **Step 16: README β add `## Pay Memory` section with CLI usage block, link to spec, and security note.**+- [ ] **Step 17: `docs/mcp.md` β append the four new tools with their input schemas.**+- [ ] **Step 18: `CHANGELOG.md` β add `## [0.8.0] - 2026-05-10` with concrete bullets (no `Unreleased`).**+- [ ] **Step 19: bump version to `0.8.0`; run `bun run sync-version` to propagate to `plugin.yaml`, `pyproject.toml`, `openclaw.plugin.json`.**+- [ ] **Step 20: run `bun run typecheck && bun test` end-to-end and confirm green.**++### Task 5: PR++- [ ] **Step 21: create branch `feature/v0.8.0-pay-memory`, commit, push, open PR against `main` titled `feat: pay-memory layer (v0.8.0)`.**++---++## Open questions deferred to future work (not in this PR)++- _All listed deferred items have since landed in v0.8.0 except those+ explicitly excluded below; see CHANGELOG.md for the final scope._+- Out of scope for this project: on-chain anchoring of vault hashes+ (Solana memo, web3 RPC). Pay Memory records `payment_proof` strings+ opaquely; the audit trail is the vault itself.diff --git a/examples/hermes-payment-digest.sh b/examples/hermes-payment-digest.shnew file mode 100755index 00000000..c51e601c--- /dev/null+++ b/examples/hermes-payment-digest.sh@@ -0,0 +1,28 @@+#!/usr/bin/env bash+#+# Pay Memory daily digest wrapper for Hermes cron `--script --no-agent` jobs+# (or any scheduler that captures stdout). Prints a 4-line Telegram-friendly+# summary of yesterday's receipts, or `[SILENT]` when there are none.+#+# Usage:+# hermes-payment-digest.sh [vault] [date]+#+# `vault` defaults to /root/vault. `date` defaults to yesterday in UTC and is+# accepted in `YYYY-MM-DD` form β useful for backfilling the digest after a+# cron miss.+#+# This script is deliberately thin. All formatting lives inside `o2b+# payment-digest` so the rendered output stays consistent between+# interactive and scheduled invocations.++set -euo pipefail++VAULT=${1:-/root/vault}+DATE=${2:-$(date -u -d 'yesterday' +%F)}++if ! command -v o2b >/dev/null 2>&1; then+ echo "[SILENT]"+ exit 0+fi++o2b payment-digest --vault "$VAULT" --date "$DATE" --empty-mode silentdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex cdcfa0cc..99cc1d85 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "0.7.0",+ "version": "0.8.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex c1f40d38..bbae069d 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1554,8 +1554,8 @@ var require_proper_lockfile = __commonJS((exports, module) => {// src/openclaw/index.tsimport { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";-import { existsSync as existsSync5 } from "node:fs";-import { join as join6 } from "node:path";+import { existsSync as existsSync7 } from "node:fs";+import { join as join10, resolve as resolvePath } from "node:path";// src/core/config.tsimport { existsSync, readFileSync, statSync } from "node:fs";@@ -1563,14 +1563,40 @@ import { homedir } from "node:os";import { join as join2 } from "node:path";// src/core/fs-atomic.ts-import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from "node:fs";+import {+ closeSync,+ fsyncSync,+ linkSync,+ mkdirSync,+ openSync,+ renameSync,+ unlinkSync,+ writeSync+} from "node:fs";import { basename, dirname, join } from "node:path";function atomicWriteFileSync(target, contents) {+ withTempFile(target, contents, (tmpPath) => {+ renameSync(tmpPath, target);+ });+}+function atomicCreateFileSyncExclusive(target, contents) {+ withTempFile(target, contents, (tmpPath) => {+ try {+ linkSync(tmpPath, target);+ } finally {+ try {+ unlinkSync(tmpPath);+ } catch {}+ }+ });+}+function withTempFile(target, contents, commit) {const dir = dirname(target);mkdirSync(dir, { recursive: true });const tmpName = `.${basename(target)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;const tmpPath = join(dir, tmpName);let fd = null;+ let committed = false;try {fd = openSync(tmpPath, "wx", 420);const buf = Buffer.from(contents, "utf8");@@ -1581,7 +1607,8 @@ function atomicWriteFileSync(target, contents) {fsyncSync(fd);closeSync(fd);fd = null;- renameSync(tmpPath, target);+ commit(tmpPath);+ committed = true;try {const dfd = openSync(dir, "r");try {@@ -1596,9 +1623,11 @@ function atomicWriteFileSync(target, contents) {closeSync(fd);} catch {}}- try {- unlinkSync(tmpPath);- } catch {}+ if (!committed) {+ try {+ unlinkSync(tmpPath);+ } catch {}+ }throw err;}}@@ -2141,9 +2170,318 @@ function buildReminder(agent) {return loadReminderTemplate().replace(/\{agent\}/g, agent);}+// src/core/pay-memory/paths.ts+import { join as join5 } from "node:path";++// src/core/path-safety.ts+import { existsSync as existsSync4, realpathSync } from "node:fs";+import { dirname as dirname4, posix, relative, resolve as resolve2, sep } from "node:path";+function ensureInsideVault(target, vault) {+ const resolvedTarget = resolve2(target);+ const resolvedVault = resolve2(vault);+ if (!isLexicallyInside(resolvedTarget, resolvedVault)) {+ throw new Error(`path escapes vault: ${target}`);+ }+ if (existsSync4(resolvedVault)) {+ const realVault = safeRealpath(resolvedVault);+ const realAncestor = safeRealpath(deepestExistingAncestor(resolvedTarget));+ if (!isLexicallyInside(realAncestor, realVault)) {+ throw new Error(`path escapes vault via symlink: ${target}`);+ }+ }+ return resolvedTarget;+}+function isLexicallyInside(target, root) {+ const t = process.platform === "win32" ? target.toLowerCase() : target;+ const r = process.platform === "win32" ? root.toLowerCase() : root;+ return t === r || t.startsWith(r + sep);+}+function deepestExistingAncestor(target) {+ let cur = target;+ while (!existsSync4(cur)) {+ const parent = dirname4(cur);+ if (parent === cur)+ return cur;+ cur = parent;+ }+ return cur;+}+function safeRealpath(p) {+ try {+ return realpathSync(p);+ } catch (err) {+ if (err?.code === "ENOENT")+ return p;+ throw err;+ }+}+function vaultRelative(target, vault) {+ const rel = relative(resolve2(vault), resolve2(target));+ return rel.split(/[\\/]/).filter((p) => p.length > 0).join(posix.sep);+}++// src/core/pay-memory/paths.ts+var ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;+var HHMM_RE = /^(\d{2}):(\d{2})$/;+function payMemoryDirs(vault) {+ const root = join5(vault, "AI Wiki");+ return {+ policies: join5(root, "policies"),+ payments: join5(root, "payments"),+ assets: join5(root, "assets"),+ drafts: join5(root, "drafts"),+ reports: join5(root, "reports")+ };+}+function policyPath(vault) {+ return join5(payMemoryDirs(vault).policies, "spending.md");+}+function paymentsDateDir(vault, date) {+ return join5(payMemoryDirs(vault).payments, validateIsoDate(date));+}+function receiptPath(vault, date, slug) {+ return join5(paymentsDateDir(vault, date), `${validateSlug(slug)}.md`);+}+function assetPath(vault, slug) {+ return join5(payMemoryDirs(vault).assets, `${validateSlug(slug)}.md`);+}+function reportPath(vault, slug) {+ return join5(payMemoryDirs(vault).reports, `${validateSlug(slug)}.md`);+}+var WINDOWS_RESERVED_BASENAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;+function validateSlug(slug) {+ const trimmed = slug.trim();+ if (!trimmed)+ throw new Error("slug must not be empty");+ if (trimmed.includes("/") || trimmed.includes("\\")) {+ throw new Error(`slug must not contain path separators: ${slug}`);+ }+ if (trimmed === ".." || trimmed === "." || /(?:^|[^\w])\.\.(?:$|[^\w])/.test(trimmed)) {+ throw new Error(`slug must not contain '..' traversal: ${slug}`);+ }+ if (/[. ]$/.test(trimmed)) {+ throw new Error(`slug must not end with '.' or whitespace (Windows-incompatible): ${slug}`);+ }+ if (WINDOWS_RESERVED_BASENAME_RE.test(trimmed)) {+ throw new Error(`slug uses a Windows-reserved filename: ${slug}`);+ }+ return trimmed;+}+function validateIsoDate(value) {+ const m = ISO_DATE_RE.exec(value);+ if (!m) {+ throw new Error("payment date must use YYYY-MM-DD format");+ }+ const year = parseInt(m[1], 10);+ const month = parseInt(m[2], 10);+ const day = parseInt(m[3], 10);+ const utc = new Date(Date.UTC(year, month - 1, day));+ if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {+ throw new Error(`payment date is not a valid calendar date: ${value}`);+ }+ return value;+}+function validateIsoTime(value) {+ const m = HHMM_RE.exec(value);+ if (!m) {+ throw new Error("payment time must use HH:MM 24-hour format");+ }+ const hour = parseInt(m[1], 10);+ const minute = parseInt(m[2], 10);+ if (hour > 23 || minute > 59) {+ throw new Error(`payment time out of range: ${value} (hour must be 0-23, minute 0-59)`);+ }+ return value;+}+function isoDateNow(tz) {+ const fmt = new Intl.DateTimeFormat("en-CA", {+ timeZone: tz ?? undefined,+ year: "numeric",+ month: "2-digit",+ day: "2-digit"+ });+ return fmt.format(new Date);+}+function isoTimeNow(tz) {+ const parts = new Intl.DateTimeFormat("en-US", {+ timeZone: tz ?? undefined,+ hour: "2-digit",+ minute: "2-digit",+ hourCycle: "h23"+ }).formatToParts(new Date);+ const get = (type) => parts.find((p) => p.type === type).value;+ return `${get("hour")}:${get("minute")}`;+}+function isoTimestampZ(date, time, tz) {+ validateIsoDate(date);+ validateIsoTime(time);+ if (!tz) {+ return `${date}T${time}:00Z`;+ }+ const utcMillis = utcMillisForLocalWallClock(date, time, tz);+ return new Date(utcMillis).toISOString().replace(/\.\d{3}Z$/, "Z");+}+function utcMillisForLocalWallClock(date, time, tz) {+ const naiveUtc = Date.parse(`${date}T${time}:00Z`);+ const offsetMinutes = tzOffsetMinutes(naiveUtc, tz);+ return naiveUtc - offsetMinutes * 60000;+}+function tzOffsetMinutes(instantMs, tz) {+ const fmt = new Intl.DateTimeFormat("en-US", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ hourCycle: "h23"+ });+ const parts = fmt.formatToParts(new Date(instantMs));+ const get = (type) => Number(parts.find((p) => p.type === type)?.value ?? "0");+ const localUtcMs = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));+ return Math.round((localUtcMs - instantMs) / 60000);+}+// src/core/pay-memory/redactor.ts+var PLACEHOLDER = "***REDACTED***";+var MAX_REDACTOR_INPUT = 256 * 1024;+var TRUNCATION_MARKER = `++[β¦truncated for size; original exceeded 256 KB. Inspect \`pay\` raw output before sharing.]+`;+var SECRET_KEYS = [+ "api_key",+ "token",+ "access_token",+ "refresh_token",+ "bearer",+ "secret",+ "client_secret",+ "authorization",+ "private_key",+ "password",+ "passwd",+ "pwd",+ "credential",+ "credentials",+ "session_token"+];+var KEY_PATTERN = SECRET_KEYS.map((k) => k.replace(/[-_]/g, "[-_]?")).join("|");+var ENV_RE = new RegExp(`\\b(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`, "gi");+var COLON_VALUE_RE = new RegExp(`(?<!")\\b(${KEY_PATTERN})(\\s*:\\s*)("[^"]*"|'[^']*'|[^\\r\\n]+)`, "gi");+var JSON_ENTRY_RE = new RegExp(`("(?:${KEY_PATTERN})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"|true|false|null|-?\\d+(?:\\.\\d+)?)`, "gi");+var BEARER_RE = /\b(Bearer\s+)([A-Za-z0-9._\-+/=]+)/gi;+function redactRawOutput(text) {+ if (!text)+ return text;+ let out = text.length > MAX_REDACTOR_INPUT ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER : text;+ out = out.replace(JSON_ENTRY_RE, (_match, keyPart, value) => {+ if (value.startsWith('"'))+ return `${keyPart}"${PLACEHOLDER}"`;+ return `${keyPart}${PLACEHOLDER}`;+ });+ out = out.replace(ENV_RE, (_match, key, sep2) => {+ return `${key}${sep2}${PLACEHOLDER}`;+ });+ out = out.replace(BEARER_RE, (_match, prefix) => `${prefix}${PLACEHOLDER}`);+ out = out.replace(COLON_VALUE_RE, (match, key, sep2, value) => {+ if (value.includes(PLACEHOLDER))+ return match;+ if (value.startsWith('"') && value.endsWith('"')) {+ return `${key}${sep2}"${PLACEHOLDER}"`;+ }+ if (value.startsWith("'") && value.endsWith("'")) {+ return `${key}${sep2}'${PLACEHOLDER}'`;+ }+ return `${key}${sep2}${PLACEHOLDER}`;+ });+ return out;+}+// src/core/pay-memory/policy.ts+import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5 } from "node:fs";+import { dirname as dirname5 } from "node:path";+var DEFAULT_POLICY_TEMPLATE = `# Agent Spending Policy++This file is read by the agent before any paid action. The agent MUST cite+this policy in the resulting payment receipt.++This MVP does not enforce limits at the payment layer. The policy exists so+that a human reviewer can see, after the fact, which rules the agent agreed+to follow.++## Budget++- Max total spend for the current task: TODO (e.g. $0.10)+- Max single paid call: TODO (e.g. $0.07)+- Max paid generations per task: TODO (e.g. 1)+- Approve repeats: false+- Approve dynamic pricing: false++## Allowed services++List the services the agent is allowed to call. One per line. Edit before+running a paid task.++- TODO++<!--+Example for the OpenSecondBrain hackathon demo:++- paysponge/fal+-->++## Required before each paid call++The agent must state:++- service name+- expected price range+- reason for payment+- expected output+- which vault files will be created or updated++## Required after each paid call++The agent must save:++- raw payment-tool output (after redaction)+- payment amount, if available+- service endpoint, if available+- generated asset URL or response identifier+- payment receipt note in \`AI Wiki/payments/<date>/\`+- daily event log entry referencing the receipt+`;+function writePolicyIfMissing(vault, opts = {}) {+ const target = policyPath(vault);+ const overwrite = opts.overwrite ?? false;+ mkdirSync4(dirname5(target), { recursive: true });+ if (overwrite) {+ const existed = existsSync5(target);+ atomicWriteFileSync(target, DEFAULT_POLICY_TEMPLATE);+ return existed ? buildPolicyResult(target, "overwritten") : buildPolicyResult(target, "created");+ }+ try {+ atomicCreateFileSyncExclusive(target, DEFAULT_POLICY_TEMPLATE);+ return buildPolicyResult(target, "created");+ } catch (err) {+ if (err?.code === "EEXIST") {+ return buildPolicyResult(target, "skipped");+ }+ throw err;+ }+}+function buildPolicyResult(path, status) {+ return {+ path,+ status,+ created: status === "created",+ overwritten: status === "overwritten",+ skipped: status === "skipped"+ };+}// src/core/vault.ts-import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync, statSync as statSync3, writeFileSync } from "node:fs";-import { dirname as dirname4, join as join5, relative } from "node:path";+import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, readdirSync, statSync as statSync3, writeFileSync } from "node:fs";+import { dirname as dirname6, join as join6, relative as relative2 } from "node:path";var FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;var KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;var PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$/;@@ -2177,7 +2515,7 @@ var DEFAULT_SKIP_FILES = ["index.md", "log.md"];function parseFrontmatter(path) {let text;try {- text = readFileSync5(path, "utf8");+ text = readFileSync6(path, "utf8");} catch {return [{}, ""];}@@ -2207,8 +2545,7 @@ function parseFrontmatter(path) {}return [metadata, body];}-function writeFrontmatter(path, metadata, body) {- mkdirSync4(dirname4(path), { recursive: true });+function formatFrontmatter(metadata, body) {const lines = ["---"];for (const [key, value] of Object.entries(metadata)) {lines.push(`${key}: ${formatYamlValue(value)}`);@@ -2218,9 +2555,29 @@ function writeFrontmatter(path, metadata, body) {lines.push("");lines.push(body);}- writeFileSync(path, lines.join(`+ return lines.join(``) + `-`, "utf8");+`;+}+function writeFrontmatter(path, metadata, body) {+ mkdirSync5(dirname6(path), { recursive: true });+ writeFileSync(path, formatFrontmatter(metadata, body), "utf8");+}+function writeFrontmatterAtomic(path, metadata, body, opts = {}) {+ const contents = formatFrontmatter(metadata, body);+ if (opts.overwrite) {+ atomicWriteFileSync(path, contents);+ return;+ }+ try {+ atomicCreateFileSyncExclusive(path, contents);+ } catch (err) {+ if (opts.existsErrorKind && err?.code === "EEXIST") {+ const rel = opts.vaultForRelativePath ? path.startsWith(opts.vaultForRelativePath + "/") ? path.slice(opts.vaultForRelativePath.length + 1) : path : path;+ throw new Error(`${opts.existsErrorKind} already exists: ${rel}`);+ }+ throw err;+ }}function slugify(value) {const lowered = value.trim().toLowerCase();@@ -2246,7 +2603,7 @@ function walk(root, dir, skipDirs, skipFiles, out) {return;}for (const entry of entries) {- const full = join5(dir, entry.name);+ const full = join6(dir, entry.name);if (entry.isDirectory()) {if (skipDirs.has(entry.name))continue;@@ -2259,7 +2616,7 @@ function walk(root, dir, skipDirs, skipFiles, out) {continue;if (skipFiles.has(entry.name.toLowerCase()))continue;- const rel = relative(root, full);+ const rel = relative2(root, full);const parts = rel.split(/[\\/]/);if (parts.some((p) => skipDirs.has(p)))continue;@@ -2331,63 +2688,797 @@ function formatYamlValue(value) {}return formatYamlScalar(value);}-// package.json-var package_default = {- name: "open-second-brain",- version: "0.7.0",- type: "module",- private: false,- description: "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",- license: "MIT",- homepage: "https://github.com/itechmeat/open-second-brain",- repository: {- type: "git",- url: "https://github.com/itechmeat/open-second-brain.git"- },- keywords: ["second-brain", "obsidian", "agents", "openclaw-plugin", "mcp"],- engines: {- bun: ">=1.1.0"- },- bin: {- o2b: "./scripts/o2b",- "vault-log": "./scripts/vault-log"- },- scripts: {- "build:openclaw": "bun build src/openclaw/index.ts --outfile openclaw/index.js --target=node --format=esm --external openclaw/plugin-sdk/plugin-entry",- test: "bun test",- typecheck: "tsc --noEmit",- "sync-version": "bun run scripts/sync-version.ts",- "sync-version:check": "bun run scripts/sync-version.ts --check"- },- files: [- "openclaw/",- "src/",- "skills/",- "scripts/",- "plugins/",- "openclaw.plugin.json",- "README.md",- "LICENSE",- "pyproject.toml"- ],- dependencies: {- "proper-lockfile": "^4.1.2"- },- devDependencies: {- "@types/bun": "^1.1.0",- "@types/node": "^22.0.0",- "@types/proper-lockfile": "^4.1.4",- typescript: "^5.5.0"- },- openclaw: {- extensions: ["./openclaw/index.js"]- }-};-// src/mcp/protocol.ts-var SERVER_VERSION = package_default.version;+// src/core/pay-memory/_md.ts+var NOT_PROVIDED = "_(not provided)_";+function stripMarkdownExt(target) {+ return target.replace(/\.md$/i, "");+}+function sanitizeWikilinkTarget(target) {+ return target.replace(/[[\]]/g, "");+}+function wikiLink(target) {+ return `[[${stripMarkdownExt(sanitizeWikilinkTarget(target.trim()))}]]`;+}+function formatCode(value) {+ const trimmed = (value ?? "").trim();+ if (!trimmed)+ return NOT_PROVIDED;+ return `\`${trimmed.replace(/`/g, "Λ")}\``;+}+function nowIsoZ() {+ return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");+}+function putIfPresent(meta, key, value) {+ if (value === null || value === undefined)+ return;+ const trimmed = String(value).trim();+ if (!trimmed)+ return;+ meta[key] = trimmed;+}+function frontmatterStr(value) {+ if (value === undefined || value === null)+ return "";+ if (Array.isArray(value))+ return value.join(", ");+ return String(value);+}-// src/mcp/tools.ts+// src/core/pay-memory/receipt.ts+var RECEIPT_FRONTMATTER_TYPE = "agent-payment-receipt";+function writeReceipt(vault, input) {+ if (!input.service?.trim())+ throw new Error("receipt requires a service");+ if (!input.status?.trim())+ throw new Error("receipt requires a status");+ if (!input.reason?.trim())+ throw new Error("receipt requires a reason");+ if (!input.agent?.trim())+ throw new Error("receipt requires an agent");+ const tz = input.tz ?? null;+ const date = validateIsoDate(input.date ?? isoDateNow(tz));+ const time = validateIsoTime(input.time ?? isoTimeNow(tz));+ const slug = input.slug && input.slug.trim() || defaultReceiptSlug(input.service, input.reason);+ const target = receiptPath(vault, date, slug);+ ensureInsideVault(target, vault);+ const created = isoTimestampZ(date, time, tz);+ const paymentLayer = input.paymentLayer?.trim() || "pay.sh";+ const network = input.network?.trim() || "solana";+ const metadata = {+ type: RECEIPT_FRONTMATTER_TYPE,+ agent: input.agent.trim(),+ payment_layer: paymentLayer,+ network,+ service: input.service.trim(),+ status: input.status.trim(),+ reason: input.reason.trim(),+ created+ };+ if (tz)+ metadata["timezone"] = tz;+ putIfPresent(metadata, "category", input.category);+ putIfPresent(metadata, "endpoint", input.endpoint);+ putIfPresent(metadata, "expected_cost", input.expectedCost);+ putIfPresent(metadata, "actual_amount", input.actualAmount);+ putIfPresent(metadata, "currency", input.currency);+ putIfPresent(metadata, "payment_proof", input.paymentProof);+ putIfPresent(metadata, "result_ref", input.resultRef);+ putIfPresent(metadata, "result_note", input.resultNote);+ metadata["policy_status"] = input.policyStatus ?? "not_checked";+ putIfPresent(metadata, "policy_rule", input.policyRule);+ if (input.policyReasons && input.policyReasons.length > 0) {+ metadata["policy_reasons"] = [...input.policyReasons];+ }+ putIfPresent(metadata, "policy_checked_at", input.policyCheckedAt);+ putIfPresent(metadata, "approval_request", input.approvalRequestId);+ putIfPresent(metadata, "approval_status", input.approvalStatus);+ putIfPresent(metadata, "approved_by", input.approvedBy);+ putIfPresent(metadata, "approved_at", input.approvedAt);+ const body = renderReceiptBody(input);+ writeFrontmatterAtomic(target, metadata, body, {+ overwrite: input.overwrite,+ existsErrorKind: "receipt",+ vaultForRelativePath: vault+ });+ return {+ path: target,+ relativePath: vaultRelative(target, vault),+ slug,+ date,+ created+ };+}+function defaultReceiptSlug(service, reason) {+ const tail = service.split("/").pop() ?? service;+ return slugify(`${tail}-${reason}`);+}+function renderPolicySection(input) {+ const status = input.policyStatus ?? "not_checked";+ const out = ["Decision:", ""];+ switch (status) {+ case "allowed":+ out.push("Allowed by the configured spending policy. The agent ran a policy", "check before initiating this paid call.");+ break;+ case "approval_required":+ out.push("Policy returned `approval_required` β a human approval was needed", "before initiating this paid call.");+ break;+ case "denied":+ out.push("Policy returned `denied` β this receipt records a paid call that", "the policy did not approve. If the call still proceeded, a human", "explicitly waved the policy aside; check the approval section", "below for who and why.");+ break;+ case "not_checked":+ default:+ out.push("Not checked. The receipt was created without a policy decision β", "either no `AI Wiki/policies/spending.json` is configured, or the", "caller chose not to evaluate the policy. This is *not* a claim", "that the call was allowed.");+ break;+ }+ if (input.policyRule?.trim()) {+ out.push("", `Rule fired: \`${input.policyRule.trim()}\``);+ }+ if (input.policyReasons && input.policyReasons.length > 0) {+ out.push("", "Reasons:", "");+ for (const r of input.policyReasons)+ out.push(`- ${r}`);+ }+ if (input.policyCheckedAt?.trim()) {+ out.push("", `Policy checked at: \`${input.policyCheckedAt.trim()}\``);+ }+ if (input.approvalRequestId?.trim() || input.approvalStatus?.trim() || input.approvedBy?.trim()) {+ out.push("", "Approval:");+ if (input.approvalRequestId?.trim()) {+ out.push("", `Request: [[AI Wiki/payments/_pending/${input.approvalRequestId.trim()}]]`);+ }+ if (input.approvalStatus?.trim()) {+ out.push(`Status: \`${input.approvalStatus.trim()}\``);+ }+ if (input.approvedBy?.trim()) {+ out.push(`Approved by: ${input.approvedBy.trim()}`);+ }+ if (input.approvedAt?.trim()) {+ out.push(`Approved at: \`${input.approvedAt.trim()}\``);+ }+ }+ out.push("");+ return out;+}+function fieldOrPlaceholder(value) {+ if (value === null || value === undefined)+ return NOT_PROVIDED;+ const trimmed = String(value).trim();+ return trimmed || NOT_PROVIDED;+}+function renderReceiptBody(input) {+ const reason = input.reason.trim();+ const title = `Payment Receipt: ${reason}`;+ const resultNote = input.resultNote?.trim();+ const resultNoteLine = resultNote ? `[[${stripMarkdownExt(sanitizeWikilinkTarget(resultNote))}]]` : NOT_PROVIDED;+ const rawOutput = input.rawOutput ? redactRawOutput(input.rawOutput) : null;+ const lines = [+ `# ${title}`,+ "",+ "## Why this paid call was made",+ "",+ reason,+ "",+ "## Spending policy check",+ "",+ "Policy file:",+ "",+ "[[AI Wiki/policies/spending]]",+ "",+ ...renderPolicySection(input),+ "## Expected cost",+ "",+ fieldOrPlaceholder(input.expectedCost),+ "",+ "## Request",+ "",+ "Service:",+ "",+ formatCode(input.service),+ "",+ "Endpoint:",+ "",+ formatCode(input.endpoint),+ "",+ "Reason:",+ "",+ reason,+ "",+ "## Payment",+ "",+ "Amount:",+ "",+ formatCode(input.actualAmount),+ "",+ "Currency:",+ "",+ formatCode(input.currency),+ "",+ "Payment proof / transaction / receipt:",+ "",+ formatCode(input.paymentProof),+ "",+ "## Result",+ "",+ "Generated asset:",+ "",+ formatCode(input.resultRef),+ "",+ "Asset note:",+ "",+ resultNoteLine,+ "",+ "## Raw pay.sh output",+ ""+ ];+ if (rawOutput) {+ lines.push("```text", rawOutput.replace(/\r\n?/g, `+`).replace(/\s+$/g, ""), "```");+ } else {+ lines.push(NOT_PROVIDED);+ }+ lines.push("", "> Verify raw output above does not contain credentials before sharing this", "> receipt outside the vault. Best-effort redaction has been applied.");+ return lines.join(`+`);+}+// src/core/pay-memory/asset.ts+var ASSET_FRONTMATTER_TYPE = "generated-asset";+function writeAsset(vault, input) {+ if (!input.title?.trim())+ throw new Error("asset requires a title");+ if (!input.service?.trim())+ throw new Error("asset requires a service");+ if (!input.resultUrl?.trim())+ throw new Error("asset requires a result_url");+ const slug = input.slug && input.slug.trim() || slugify(input.title);+ const target = assetPath(vault, slug);+ ensureInsideVault(target, vault);+ const created = nowIsoZ();+ const metadata = {+ type: ASSET_FRONTMATTER_TYPE,+ title: input.title.trim(),+ source: input.service.trim(),+ result_url: input.resultUrl.trim(),+ created+ };+ if (input.sourceReceipt?.trim()) {+ metadata["source_receipt"] = wikiLink(input.sourceReceipt);+ }+ if (input.usedIn?.trim()) {+ metadata["used_in"] = wikiLink(input.usedIn);+ }+ writeFrontmatterAtomic(target, metadata, renderAssetBody(input), {+ overwrite: input.overwrite,+ existsErrorKind: "asset",+ vaultForRelativePath: vault+ });+ return {+ path: target,+ relativePath: vaultRelative(target, vault),+ slug,+ created+ };+}+function renderAssetBody(input) {+ const title = input.title.trim();+ const usedIn = input.usedIn?.trim();+ const sourceReceipt = input.sourceReceipt?.trim();+ const prompt = input.prompt?.trim();+ const lines = [`# ${title}`, ""];+ lines.push("## Purpose", "");+ if (usedIn) {+ lines.push(`Used in: ${wikiLink(usedIn)}`);+ } else {+ lines.push(NOT_PROVIDED);+ }+ lines.push("");+ lines.push("## Prompt", "");+ if (prompt) {+ lines.push(...prompt.split(/\r?\n/).map((line) => line ? `> ${line}` : ">"));+ } else {+ lines.push(NOT_PROVIDED);+ }+ lines.push("");+ lines.push("## Result", "", `${input.resultUrl.trim()}`, "");+ lines.push("## Source", "");+ lines.push(`Service: \`${input.service.trim().replace(/`/g, "Λ")}\``);+ if (sourceReceipt) {+ lines.push(`Receipt: ${wikiLink(sourceReceipt)}`);+ } else {+ lines.push(`Receipt: ${NOT_PROVIDED}`);+ }+ lines.push("");+ lines.push("## Notes", "", "Generated through a paid API call recorded in the linked receipt.");+ return lines.join(`+`);+}+// src/core/pay-memory/report.ts+import { readdirSync as readdirSync2 } from "node:fs";+import { join as join7 } from "node:path";+var REPORT_FRONTMATTER_TYPE = "payment-report";+function aggregateReceipts(vault, date) {+ const dir = paymentsDateDir(vault, date);+ let entries;+ try {+ entries = readdirSync2(dir, { withFileTypes: true });+ } catch (err) {+ if (err?.code === "ENOENT")+ return [];+ throw err;+ }+ const summaries = [];+ for (const entry of entries) {+ if (!entry.isFile())+ continue;+ if (!entry.name.toLowerCase().endsWith(".md"))+ continue;+ const full = join7(dir, entry.name);+ let meta;+ try {+ [meta] = parseFrontmatter(full);+ } catch {+ continue;+ }+ if (frontmatterStr(meta["type"]) !== RECEIPT_FRONTMATTER_TYPE)+ continue;+ const service = frontmatterStr(meta["service"]);+ const status = frontmatterStr(meta["status"]);+ if (!service || !status)+ continue;+ summaries.push({+ path: vaultRelative(full, vault),+ service,+ status,+ category: frontmatterStr(meta["category"]) || null,+ actualAmount: frontmatterStr(meta["actual_amount"]) || null,+ currency: frontmatterStr(meta["currency"]) || null,+ resultRef: frontmatterStr(meta["result_ref"]) || null,+ resultNote: frontmatterStr(meta["result_note"]) || null,+ reason: frontmatterStr(meta["reason"]) || null+ });+ }+ summaries.sort((a, b) => {+ const s = a.service.localeCompare(b.service);+ return s !== 0 ? s : a.path.localeCompare(b.path);+ });+ return summaries;+}+function writeReport(vault, input) {+ const date = validateIsoDate(input.date);+ const title = input.title && input.title.trim() || `Payment Report ${date}`;+ const slug = input.slug && input.slug.trim() || slugify(`payment-report-${date}`);+ const target = reportPath(vault, slug);+ ensureInsideVault(target, vault);+ const summaries = aggregateReceipts(vault, date);+ const created = nowIsoZ();+ const metadata = {+ type: REPORT_FRONTMATTER_TYPE,+ title,+ date,+ created,+ receipts_used: summaries.length+ };+ if (input.task?.trim())+ metadata["task"] = input.task.trim();+ writeFrontmatterAtomic(target, metadata, renderReportBody(date, title, input.task ?? null, summaries), {+ overwrite: input.overwrite,+ existsErrorKind: "report",+ vaultForRelativePath: vault+ });+ return {+ path: target,+ relativePath: vaultRelative(target, vault),+ slug,+ receiptsUsed: summaries.length+ };+}+function renderReportBody(date, title, task, summaries) {+ const lines = [`# ${title}`, "", `Date: ${date}`, ""];+ lines.push("## Task", "");+ lines.push(task && task.trim() ? task.trim() : NOT_PROVIDED);+ lines.push("");+ lines.push("## Paid services used", "");+ if (summaries.length === 0) {+ lines.push("No receipts found for this date.");+ } else {+ for (const s of summaries) {+ lines.push(`### ${s.service}`, "");+ lines.push(`Status: \`${s.status}\``);+ if (s.reason)+ lines.push(`Reason: ${s.reason}`);+ lines.push(`Receipt: [[${stripMarkdownExt(s.path)}]]`);+ if (s.actualAmount) {+ const amount = s.currency ? `${s.actualAmount} ${s.currency}` : s.actualAmount;+ lines.push(`Amount: \`${amount}\``);+ }+ if (s.resultRef)+ lines.push(`Result: \`${s.resultRef}\``);+ if (s.resultNote)+ lines.push(`Asset: [[${stripMarkdownExt(s.resultNote)}]]`);+ lines.push("");+ }+ }+ lines.push("## Files", "");+ if (summaries.length === 0) {+ lines.push(NOT_PROVIDED);+ } else {+ for (const s of summaries) {+ lines.push(`- [[${stripMarkdownExt(s.path)}]]`);+ if (s.resultNote)+ lines.push(`- [[${stripMarkdownExt(s.resultNote)}]]`);+ }+ }+ return lines.join(`+`);+}+// src/core/pay-memory/policy-rules.ts+import { readFileSync as readFileSync7 } from "node:fs";+import { join as join8 } from "node:path";+var POLICY_SCHEMA_VERSION = 1;+function policyJsonPath(vault) {+ return join8(payMemoryDirs(vault).policies, "spending.json");+}+function loadPolicyRules(vault) {+ const target = policyJsonPath(vault);+ let text;+ try {+ text = readFileSync7(target, "utf8");+ } catch (err) {+ if (err?.code === "ENOENT")+ return null;+ throw new Error(`failed to read ${target}: ${err.message ?? String(err)}`);+ }+ let parsed;+ try {+ parsed = JSON.parse(text);+ } catch (err) {+ throw new Error(`${target} is not valid JSON: ${err.message ?? String(err)}`);+ }+ return validatePolicyRules(parsed, target);+}+function validatePolicyRules(value, source) {+ if (typeof value !== "object" || value === null || Array.isArray(value)) {+ throw new Error(`${source} must be a JSON object at the root`);+ }+ const obj = value;+ const out = {};+ if ("schema_version" in obj) {+ const v = obj["schema_version"];+ if (typeof v !== "number") {+ throw new Error(`${source}: schema_version must be a number`);+ }+ if (v !== POLICY_SCHEMA_VERSION) {+ throw new Error(`${source}: unsupported schema_version ${v}; expected ${POLICY_SCHEMA_VERSION}. ` + "Upgrade Open Second Brain or roll the policy back to the matching schema.");+ }+ out["schema_version"] = v;+ }+ if ("currency" in obj) {+ if (typeof obj["currency"] !== "string") {+ throw new Error(`${source}: currency must be a string`);+ }+ out["currency"] = obj["currency"];+ }+ for (const k of ["max_total_per_day", "max_single_call", "require_approval_above"]) {+ if (k in obj) {+ const v = obj[k];+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {+ throw new Error(`${source}: ${k} must be a non-negative finite number`);+ }+ out[k] = v;+ }+ }+ if ("allowed_services" in obj) {+ const v = obj["allowed_services"];+ if (!Array.isArray(v) || !v.every((s) => typeof s === "string")) {+ throw new Error(`${source}: allowed_services must be an array of strings`);+ }+ out["allowed_services"] = [...v];+ }+ if ("max_per_category" in obj) {+ const v = obj["max_per_category"];+ if (typeof v !== "object" || v === null || Array.isArray(v)) {+ throw new Error(`${source}: max_per_category must be an object`);+ }+ const map = {};+ for (const [k, n] of Object.entries(v)) {+ if (typeof n !== "number" || !Number.isInteger(n) || n < 0) {+ throw new Error(`${source}: max_per_category.${k} must be a non-negative integer`);+ }+ map[k] = n;+ }+ out["max_per_category"] = map;+ }+ return out;+}+function evaluatePolicy(rules, request, context) {+ if (!rules) {+ return {+ status: "allowed",+ allowed: true,+ approvalRequired: false,+ reasons: [],+ rule: null,+ hasPolicy: false,+ policyPath: null,+ currency: null+ };+ }+ const reasons = [];+ let denyRule = null;+ let approvalRule = null;+ const policyCurrency = rules.currency ?? "USDC";+ if (rules.allowed_services && rules.allowed_services.length > 0) {+ if (!rules.allowed_services.includes(request.service)) {+ reasons.push(`service ${JSON.stringify(request.service)} is not in allowed_services`);+ denyRule ??= "allowed_services";+ }+ }+ const reqCurrency = request.currency ?? policyCurrency;+ if (request.currency && request.currency !== policyCurrency) {+ reasons.push(`request currency ${request.currency} differs from policy ${policyCurrency} β ` + "amount-based limits cannot be evaluated; please normalize before checking");+ denyRule ??= "currency_mismatch";+ }+ const amount = typeof request.expectedAmount === "number" ? request.expectedAmount : null;+ if (amount === null && (rules.max_single_call !== undefined || rules.max_total_per_day !== undefined || rules.require_approval_above !== undefined)) {+ reasons.push("expected_amount is required to evaluate amount-based policy rules; " + "request human approval explicitly");+ approvalRule ??= "missing_expected_amount";+ }+ if (rules.max_single_call !== undefined && amount !== null && amount > rules.max_single_call) {+ reasons.push(`expected amount ${amount} ${reqCurrency} exceeds max_single_call ` + `${rules.max_single_call} ${policyCurrency}`);+ denyRule ??= "max_single_call";+ }+ if (rules.max_total_per_day !== undefined && amount !== null && context.daySpend + amount > rules.max_total_per_day) {+ reasons.push(`daily spend ${context.daySpend} + ${amount} = ${context.daySpend + amount} ` + `exceeds max_total_per_day ${rules.max_total_per_day} ${policyCurrency}`);+ denyRule ??= "max_total_per_day";+ }+ if (request.category && rules.max_per_category) {+ const cap = rules.max_per_category[request.category];+ if (cap !== undefined && context.dayCategoryCount >= cap) {+ reasons.push(`category '${request.category}' already has ${context.dayCategoryCount} ` + `receipt(s) today; cap is ${cap}`);+ denyRule ??= "max_per_category";+ }+ }+ if (rules.require_approval_above !== undefined && amount !== null && amount > rules.require_approval_above) {+ approvalRule = "require_approval_above";+ reasons.push(`expected amount ${amount} ${reqCurrency} exceeds approval threshold ` + `${rules.require_approval_above} ${policyCurrency}`);+ }+ const status = denyRule ? "denied" : approvalRule ? "approval_required" : "allowed";+ return {+ status,+ allowed: status === "allowed",+ approvalRequired: status === "approval_required",+ reasons,+ rule: denyRule ?? approvalRule,+ hasPolicy: true,+ policyPath: null,+ currency: policyCurrency+ };+}+function checkPolicy(vault, request) {+ const rules = loadPolicyRules(vault);+ const date = validateIsoDate(request.date ?? isoDateNow(request.tz));+ const summaries = aggregateReceipts(vault, date);+ const policyCurrency = rules?.currency ?? "USDC";+ let daySpend = 0;+ for (const s of summaries) {+ if (!s.actualAmount)+ continue;+ if (s.currency && s.currency !== policyCurrency)+ continue;+ const n = parseFloat(s.actualAmount);+ if (Number.isFinite(n))+ daySpend += n;+ }+ const dayCategoryCount = request.category ? summaries.filter((s) => s.category === request.category).length : 0;+ const decision = evaluatePolicy(rules, request, { daySpend, dayCategoryCount });+ return {+ ...decision,+ policyPath: rules ? policyJsonPath(vault) : null+ };+}+// src/core/pay-memory/approval.ts+var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);+import { join as join9 } from "node:path";+var PENDING_REQUEST_FRONTMATTER_TYPE = "pending-payment-request";+function pendingDir(vault) {+ return join9(payMemoryDirs(vault).payments, "_pending");+}+function pendingRequestPath(vault, id) {+ return join9(pendingDir(vault), `${validateSlug(id)}.md`);+}+function writePendingRequest(vault, input) {+ if (!input.service?.trim())+ throw new Error("pending request requires a service");+ if (!input.reason?.trim())+ throw new Error("pending request requires a reason");+ if (!input.agent?.trim())+ throw new Error("pending request requires an agent");+ const tz = input.tz ?? null;+ const date = validateIsoDate(input.date ?? isoDateNow(tz));+ const time = validateIsoTime(input.time ?? isoTimeNow(tz));+ const id = input.slug && input.slug.trim() || defaultRequestSlug(input, date, time);+ const target = pendingRequestPath(vault, id);+ ensureInsideVault(target, vault);+ const decision = checkPolicy(vault, {+ service: input.service.trim(),+ expectedAmount: input.expectedAmount ?? null,+ currency: input.currency ?? null,+ category: input.category ?? null,+ date,+ tz+ });+ if (input.enforcePolicy && !decision.allowed && !decision.approvalRequired) {+ throw new Error(`policy denied: ${decision.reasons.join("; ") || decision.rule || "no reason given"}`);+ }+ const created = isoTimestampZ(date, time, tz);+ const metadata = {+ type: PENDING_REQUEST_FRONTMATTER_TYPE,+ id,+ agent: input.agent.trim(),+ service: input.service.trim(),+ reason: input.reason.trim(),+ status: "pending",+ created,+ policy_status: decision.status+ };+ if (tz)+ metadata["timezone"] = tz;+ if (decision.rule)+ metadata["policy_rule"] = decision.rule;+ putIfPresent(metadata, "category", input.category);+ putIfPresent(metadata, "endpoint", input.endpoint);+ putIfPresent(metadata, "currency", input.currency);+ if (typeof input.expectedAmount === "number") {+ metadata["expected_amount"] = String(input.expectedAmount);+ }+ writeFrontmatterAtomic(target, metadata, renderRequestBody(input, decision), {+ overwrite: false,+ existsErrorKind: "pending request",+ vaultForRelativePath: vault+ });+ return {+ path: target,+ relativePath: vaultRelative(target, vault),+ id,+ status: "pending",+ created,+ policyDecision: decision+ };+}+function loadPendingRequest(vault, id) {+ const target = pendingRequestPath(vault, id);+ const [metadata, body] = parseFrontmatter(target);+ if (frontmatterStr(metadata["type"]) !== PENDING_REQUEST_FRONTMATTER_TYPE)+ return null;+ const status = parseStatus(frontmatterStr(metadata["status"]));+ return {+ metadata,+ body,+ path: target,+ relativePath: vaultRelative(target, vault),+ id,+ status+ };+}+async function consumePendingRequest(vault, id, opts) {+ const receiptPath2 = opts.receiptPath?.trim();+ if (!receiptPath2) {+ throw new Error("consume-payment-request requires a non-empty receiptPath");+ }+ return transitionRequest(vault, id, "approved", "consumed", (meta) => {+ meta["receipt"] = receiptPath2;+ meta["consumed_at"] = nowIsoZ();+ });+}+async function transitionRequest(vault, id, expectedFrom, newStatus, patch) {+ const lockTarget = pendingRequestPath(vault, id);+ const initial = loadPendingRequest(vault, id);+ if (!initial) {+ throw new Error(`pending request not found: ${id}`);+ }+ const release = await import_proper_lockfile2.default.lock(lockTarget, {+ retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },+ stale: 1e4,+ realpath: false+ });+ try {+ const loaded = loadPendingRequest(vault, id);+ if (!loaded) {+ throw new Error(`pending request not found: ${id}`);+ }+ if (loaded.status !== expectedFrom) {+ throw new Error(`cannot transition request ${id} from ${loaded.status} to ${newStatus} ` + `(expected ${expectedFrom})`);+ }+ const newMeta = { ...loaded.metadata };+ newMeta["status"] = newStatus;+ patch(newMeta);+ writeFrontmatterAtomic(loaded.path, newMeta, loaded.body, { overwrite: true });+ return {+ path: loaded.path,+ relativePath: loaded.relativePath,+ id,+ status: newStatus,+ created: frontmatterStr(loaded.metadata["created"]),+ policyDecision: {+ status: parseDecisionStatus(frontmatterStr(loaded.metadata["policy_status"])),+ allowed: frontmatterStr(loaded.metadata["policy_status"]) === "allowed",+ approvalRequired: frontmatterStr(loaded.metadata["policy_status"]) === "approval_required",+ reasons: [],+ rule: frontmatterStr(loaded.metadata["policy_rule"]) || null,+ hasPolicy: Boolean(frontmatterStr(loaded.metadata["policy_status"])),+ policyPath: null,+ currency: frontmatterStr(loaded.metadata["currency"]) || null+ }+ };+ } finally {+ await release();+ }+}+function defaultRequestSlug(input, date, time) {+ const tail = input.service.split("/").pop() ?? input.service;+ return slugify(`req-${date}-${time.replace(":", "")}-${tail}-${input.reason}`);+}+function renderRequestBody(input, decision) {+ const reason = input.reason.trim();+ const lines = [+ `# Pending Payment Request: ${reason}`,+ "",+ "## Service",+ "",+ formatCode(input.service),+ "",+ "## Reason",+ "",+ reason,+ "",+ "## Expected cost",+ "",+ typeof input.expectedAmount === "number" ? `\`${input.expectedAmount}\`${input.currency ? ` ${input.currency}` : ""}` : NOT_PROVIDED,+ "",+ "## Endpoint",+ "",+ formatCode(input.endpoint),+ "",+ "## Expected output",+ "",+ input.expectedOutput?.trim() ?? NOT_PROVIDED,+ "",+ "## Vault files that will change",+ ""+ ];+ if (input.vaultFiles && input.vaultFiles.length > 0) {+ for (const f of input.vaultFiles)+ lines.push(`- \`${f}\``);+ } else {+ lines.push(NOT_PROVIDED);+ }+ lines.push("", "## Policy check", "", `Status: \`${decision.status}\``);+ if (decision.rule)+ lines.push(`Rule fired: \`${decision.rule}\``);+ if (decision.reasons.length > 0) {+ lines.push("", "Reasons:", "");+ for (const r of decision.reasons)+ lines.push(`- ${r}`);+ }+ lines.push("", "## How to approve / reject", "", "Use the `o2b` CLI:", "", "```bash", `o2b approve-payment-request --vault <vault> --id <id> --approved-by <name>`, `o2b reject-payment-request --vault <vault> --id <id> --rejected-by <name> [--reason "..."]`, "```", "", "Once approved, the agent will execute the paid call and call", "`o2b consume-payment-request` to link the resulting receipt back here.");+ return lines.join(`+`);+}+function parseStatus(raw) {+ if (raw === "pending" || raw === "approved" || raw === "rejected" || raw === "consumed") {+ return raw;+ }+ throw new Error(`invalid payment-request status: ${JSON.stringify(raw)}`);+}+function parseDecisionStatus(raw) {+ if (raw === "denied" || raw === "approval_required")+ return raw;+ return "allowed";+}+// src/openclaw/index.ts+import { mkdirSync as mkdirSync6 } from "node:fs";++// src/core/agent-identity.tsvar PLACEHOLDER_AGENT_VALUES = new Set(["agent","assistant",@@ -2412,6 +3503,17 @@ var PLACEHOLDER_AGENT_VALUES = new Set(["openclaw","user"]);+function normalizeAgentArgument(value) {+ if (value === null || value === undefined)+ return null;+ const cleaned = String(value).trim().replace(/^@+/, "").trim();+ if (!cleaned)+ return null;+ const canonical = cleaned.toLowerCase().replace(/_/g, "-");+ if (PLACEHOLDER_AGENT_VALUES.has(canonical))+ return null;+ return cleaned;+}// src/openclaw/index.tsfunction resolveVaultPath(api) {@@ -2431,32 +3533,51 @@ function resolveOpenclawTimezone(api) {}}function resolveOpenclawAgent(api, argAgent) {- const normalized = normalizeAgentArg(argAgent);+ const normalized = normalizeAgentArgument(argAgent);if (normalized)return normalized;const cfg = api.pluginConfig ?? {};return cfg.agentName ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();}-function normalizeAgentArg(value) {- if (value === null || value === undefined)+function coerceExpectedAmount(value) {+ if (value === undefined || value === null)return null;- const cleaned = String(value).trim().replace(/^@+/, "").trim();- if (!cleaned)+ if (typeof value === "number") {+ if (!Number.isFinite(value)) {+ throw new Error("expected_amount must be a finite number");+ }+ return value;+ }+ if (typeof value === "string") {+ const trimmed = value.trim();+ if (trimmed === "")+ return null;+ const parsed = Number(trimmed);+ if (!Number.isFinite(parsed)) {+ throw new Error("expected_amount must be a number or numeric string");+ }+ return parsed;+ }+ throw new Error("expected_amount must be a number or numeric string");+}+function strOrNull(value) {+ if (value === undefined || value === null)return null;- if (PLACEHOLDER_AGENT_VALUES.has(cleaned.toLowerCase()))+ if (typeof value !== "string")return null;- return cleaned;+ const trimmed = value.trim();+ return trimmed ? trimmed : null;}-function vaultRel(target, vault) {- if (target.startsWith(vault + "/"))- return target.slice(vault.length + 1);- return target;+function asJson(payload) {+ return {+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]+ };}var openclaw_default = definePluginEntry({register(api) {api.on("before_prompt_build", () => {const cfg = api.pluginConfig ?? {};- const agent = normalizeAgentArg(cfg.agentName ?? null) ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();+ const agent = normalizeAgentArgument(cfg.agentName ?? null) ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();if (agent === "agent")return;return { prependContext: buildReminder(agent) };@@ -2474,7 +3595,7 @@ var openclaw_default = definePluginEntry({config_keys: Object.keys(discovery.data).sort(),config: redactMapping(discovery.data),vault_path: vault,- vault_exists: existsSync5(vault)+ vault_exists: existsSync7(vault)};return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };}@@ -2500,7 +3621,7 @@ var openclaw_default = definePluginEntry({},async execute(_id, params) {const vault = resolveVaultPath(api);- if (!existsSync5(vault))+ if (!existsSync7(vault))throw new Error(`vault directory missing: ${vault}`);const pattern = params["pattern"] ?? null;const limit = typeof params["limit"] === "number" ? params["limit"] : 50;@@ -2508,7 +3629,7 @@ var openclaw_default = definePluginEntry({throw new Error("argument 'limit' must be between 1 and 500");const pages = listVaultPages(vault);const needle = pattern ? pattern.toLowerCase() : null;- const matched = (needle === null ? pages : pages.filter((p) => p.title.toLowerCase().includes(needle))).slice(0, limit).map((p) => ({ title: p.title, path: vaultRel(p.path, vault), metadata: p.metadata }));+ const matched = (needle === null ? pages : pages.filter((p) => p.title.toLowerCase().includes(needle))).slice(0, limit).map((p) => ({ title: p.title, path: vaultRelative(p.path, vault), metadata: p.metadata }));const result = {vault_path: vault,total_pages: pages.length,@@ -2543,7 +3664,7 @@ var openclaw_default = definePluginEntry({},async execute(_id, params) {const vault = resolveVaultPath(api);- if (!existsSync5(vault))+ if (!existsSync7(vault))throw new Error(`vault directory missing: ${vault}`);const title = params["title"] ?? "";const content = params["content"] ?? "";@@ -2553,12 +3674,12 @@ var openclaw_default = definePluginEntry({throw new Error("title must not be empty");if (!content.trim())throw new Error("content must not be empty");- const notesDir = join6(vault, "AI Wiki", "notes");+ const notesDir = join10(vault, "AI Wiki", "notes");const slug = slugify(title);- const target = join6(notesDir, `${slug}.md`);- const noteExisted = existsSync5(target);+ const target = join10(notesDir, `${slug}.md`);+ const noteExisted = existsSync7(target);if (noteExisted && !overwrite) {- throw new Error(`note already exists: ${vaultRel(target, vault)}`);+ throw new Error(`note already exists: ${vaultRelative(target, vault)}`);}const metadata = {title,@@ -2569,7 +3690,7 @@ var openclaw_default = definePluginEntry({metadata["tags"] = tags;writeFrontmatter(target, metadata, content.trim());const result = {- path: vaultRel(target, vault),+ path: vaultRelative(target, vault),absolute_path: target,slug,overwritten: noteExisted && overwrite@@ -2606,7 +3727,7 @@ var openclaw_default = definePluginEntry({const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();const path = await appendEvent(vault, agent, message, { date, time, tz });const result = {- path: vaultRel(path, vault),+ path: vaultRelative(path, vault),absolute_path: path,agent,date,@@ -2640,6 +3761,399 @@ var openclaw_default = definePluginEntry({return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };}});+ api.registerTool({+ name: "payment_memory_init",+ description: "Bootstrap the Pay Memory layout (policies/, payments/, assets/, drafts/, reports/) and write the spending policy template.",+ parameters: {+ type: "object",+ properties: {+ agent: { type: "string" },+ overwrite: { type: "boolean" }+ },+ additionalProperties: false+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const overwrite = Boolean(params["overwrite"] ?? false);+ const agent = resolveOpenclawAgent(api, params["agent"] ?? null);+ const dirs = payMemoryDirs(vault);+ const created = [];+ const skipped = [];+ for (const dir of [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports]) {+ const existed = existsSync7(dir);+ mkdirSync6(dir, { recursive: true });+ (existed ? skipped : created).push(vaultRelative(dir, vault));+ }+ const policy = writePolicyIfMissing(vault, { overwrite });+ return asJson({+ vault_path: vault,+ agent,+ created,+ skipped,+ policy_path: vaultRelative(policy.path, vault),+ policy_status: policy.status+ });+ }+ });+ api.registerTool({+ name: "payment_receipt_append",+ description: "Save a Markdown receipt for one paid API call. raw_output is run through a redactor before persisting.",+ parameters: {+ type: "object",+ properties: {+ agent: { type: "string" },+ service: { type: "string" },+ status: { type: "string" },+ reason: { type: "string" },+ category: { type: "string" },+ endpoint: { type: "string" },+ expected_cost: { type: "string" },+ actual_amount: { type: "string" },+ currency: { type: "string" },+ payment_proof: { type: "string" },+ result_ref: { type: "string" },+ result_note: { type: "string" },+ raw_output: { type: "string" },+ slug: { type: "string" },+ date: { type: "string" },+ time: { type: "string" },+ overwrite: { type: "boolean" },+ policy_status: {+ type: "string",+ enum: ["allowed", "approval_required", "denied", "not_checked"]+ },+ policy_rule: { type: "string" },+ policy_reasons: { type: "array", items: { type: "string" } },+ policy_checked_at: { type: "string" },+ from_request: { type: "string" },+ payment_layer: { type: "string" },+ network: { type: "string" }+ },+ required: ["service", "status", "reason"],+ additionalProperties: false+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();+ const agent = resolveOpenclawAgent(api, params["agent"] ?? null);+ let policyStatus = strOrNull(params["policy_status"]);+ let policyRule = strOrNull(params["policy_rule"]);+ const policyReasonsRaw = params["policy_reasons"];+ let policyReasons = null;+ if (policyReasonsRaw !== undefined && policyReasonsRaw !== null) {+ if (!Array.isArray(policyReasonsRaw) || !policyReasonsRaw.every((s) => typeof s === "string")) {+ throw new Error("policy_reasons must be an array of strings");+ }+ policyReasons = [...policyReasonsRaw];+ }+ let policyCheckedAt = strOrNull(params["policy_checked_at"]);+ let approvalStatus = null;+ let approvedBy = null;+ let approvedAt = null;+ const fromRequest = strOrNull(params["from_request"]);+ if (fromRequest) {+ const loaded = loadPendingRequest(vault, fromRequest);+ if (!loaded)+ throw new Error(`pending request not found: ${fromRequest}`);+ const meta = loaded.metadata;+ const get = (k) => {+ const v = meta[k];+ if (v === undefined || v === null)+ return null;+ return Array.isArray(v) ? v.join(", ") : String(v);+ };+ policyStatus ??= get("policy_status") ?? null;+ policyRule ??= get("policy_rule");+ approvalStatus = loaded.status;+ approvedBy = get("approved_by");+ approvedAt = get("approved_at");+ }+ if (policyStatus !== null) {+ const allowed = [+ "allowed",+ "approval_required",+ "denied",+ "not_checked"+ ];+ if (!allowed.includes(policyStatus)) {+ throw new Error(`policy_status must be one of: ${allowed.join(", ")}`);+ }+ }+ const result = writeReceipt(vault, {+ agent,+ service: String(params["service"]),+ status: String(params["status"]),+ reason: String(params["reason"]),+ paymentLayer: strOrNull(params["payment_layer"]),+ network: strOrNull(params["network"]),+ category: strOrNull(params["category"]),+ endpoint: strOrNull(params["endpoint"]),+ expectedCost: strOrNull(params["expected_cost"]),+ actualAmount: strOrNull(params["actual_amount"]),+ currency: strOrNull(params["currency"]),+ paymentProof: strOrNull(params["payment_proof"]),+ resultRef: strOrNull(params["result_ref"]),+ resultNote: strOrNull(params["result_note"]),+ rawOutput: strOrNull(params["raw_output"]),+ slug: strOrNull(params["slug"]),+ date: strOrNull(params["date"]),+ time: strOrNull(params["time"]),+ overwrite: Boolean(params["overwrite"] ?? false),+ tz,+ policyStatus,+ policyRule,+ policyReasons,+ policyCheckedAt,+ approvalRequestId: fromRequest,+ approvalStatus,+ approvedBy,+ approvedAt+ });+ return asJson({+ path: result.relativePath,+ absolute_path: resolvePath(result.path),+ slug: result.slug,+ date: result.date,+ created: result.created+ });+ }+ });+ api.registerTool({+ name: "asset_capture",+ description: "Save a Markdown note for an asset produced by a paid call, linked to its receipt.",+ parameters: {+ type: "object",+ properties: {+ title: { type: "string" },+ service: { type: "string" },+ result_url: { type: "string" },+ source_receipt: { type: "string" },+ prompt: { type: "string" },+ used_in: { type: "string" },+ slug: { type: "string" },+ overwrite: { type: "boolean" }+ },+ required: ["title", "service", "result_url"],+ additionalProperties: false+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const result = writeAsset(vault, {+ title: String(params["title"]),+ service: String(params["service"]),+ resultUrl: String(params["result_url"]),+ sourceReceipt: strOrNull(params["source_receipt"]),+ prompt: strOrNull(params["prompt"]),+ usedIn: strOrNull(params["used_in"]),+ slug: strOrNull(params["slug"]),+ overwrite: Boolean(params["overwrite"] ?? false)+ });+ return asJson({+ path: result.relativePath,+ absolute_path: resolvePath(result.path),+ slug: result.slug,+ created: result.created+ });+ }+ });+ api.registerTool({+ name: "payment_report_generate",+ description: "Aggregate a date's payment receipts into a Markdown report under AI Wiki/reports/.",+ parameters: {+ type: "object",+ properties: {+ date: { type: "string" },+ title: { type: "string" },+ task: { type: "string" },+ slug: { type: "string" },+ overwrite: { type: "boolean" }+ },+ required: ["date"],+ additionalProperties: false+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const result = writeReport(vault, {+ date: String(params["date"]),+ title: strOrNull(params["title"]),+ task: strOrNull(params["task"]),+ slug: strOrNull(params["slug"]),+ overwrite: Boolean(params["overwrite"] ?? false)+ });+ return asJson({+ path: result.relativePath,+ absolute_path: resolvePath(result.path),+ slug: result.slug,+ receipts_used: result.receiptsUsed+ });+ }+ });+ api.registerTool({+ name: "payment_policy_check",+ description: "Evaluate a prospective paid call against AI Wiki/policies/spending.json. Returns allowed / approval_required / denied + the rule that fired.",+ parameters: {+ type: "object",+ properties: {+ service: { type: "string" },+ expected_amount: { type: ["number", "string"] },+ currency: { type: "string" },+ category: { type: "string" },+ date: { type: "string" }+ },+ required: ["service"],+ additionalProperties: false+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();+ const decision = checkPolicy(vault, {+ service: String(params["service"]),+ expectedAmount: coerceExpectedAmount(params["expected_amount"]),+ currency: strOrNull(params["currency"]),+ category: strOrNull(params["category"]),+ date: strOrNull(params["date"]),+ tz+ });+ return asJson({+ status: decision.status,+ allowed: decision.allowed,+ approval_required: decision.approvalRequired,+ rule: decision.rule,+ reasons: decision.reasons,+ has_policy: decision.hasPolicy,+ policy_path: decision.policyPath !== null ? vaultRelative(decision.policyPath, vault) : null,+ currency: decision.currency+ });+ }+ });+ api.registerTool({+ name: "payment_request_approval",+ description: "Create a pending-payment-request that the user must approve before the agent runs `pay`. Records the policy check at request time.",+ parameters: {+ type: "object",+ properties: {+ agent: { type: "string" },+ service: { type: "string" },+ reason: { type: "string" },+ expected_amount: { type: ["number", "string"] },+ currency: { type: "string" },+ category: { type: "string" },+ endpoint: { type: "string" },+ expected_output: { type: "string" },+ vault_files: { type: "array", items: { type: "string" } },+ slug: { type: "string" },+ date: { type: "string" },+ time: { type: "string" },+ enforce_policy: { type: "boolean" }+ },+ required: ["service", "reason"],+ additionalProperties: false+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();+ const agent = resolveOpenclawAgent(api, params["agent"] ?? null);+ const vaultFilesRaw = params["vault_files"];+ let vaultFiles = null;+ if (vaultFilesRaw !== undefined && vaultFilesRaw !== null) {+ if (!Array.isArray(vaultFilesRaw) || !vaultFilesRaw.every((s) => typeof s === "string")) {+ throw new Error("vault_files must be an array of strings");+ }+ vaultFiles = [...vaultFilesRaw];+ }+ const result = writePendingRequest(vault, {+ agent,+ service: String(params["service"]),+ reason: String(params["reason"]),+ expectedAmount: coerceExpectedAmount(params["expected_amount"]),+ currency: strOrNull(params["currency"]),+ category: strOrNull(params["category"]),+ endpoint: strOrNull(params["endpoint"]),+ expectedOutput: strOrNull(params["expected_output"]),+ vaultFiles,+ slug: strOrNull(params["slug"]),+ date: strOrNull(params["date"]),+ time: strOrNull(params["time"]),+ enforcePolicy: Boolean(params["enforce_policy"] ?? false),+ tz+ });+ return asJson({+ id: result.id,+ path: result.relativePath,+ absolute_path: resolvePath(result.path),+ status: result.status,+ created: result.created,+ policy_status: result.policyDecision.status,+ policy_rule: result.policyDecision.rule+ });+ }+ });+ api.registerTool({+ name: "payment_request_status",+ description: "Look up a pending-payment-request by id and return its current status and metadata. The agent uses this to poll for human approval.",+ parameters: {+ type: "object",+ properties: { id: { type: "string" } },+ required: ["id"],+ additionalProperties: false+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const id = String(params["id"]);+ const loaded = loadPendingRequest(vault, id);+ if (!loaded)+ throw new Error(`pending request not found: ${id}`);+ const meta = loaded.metadata;+ const get = (k) => {+ const v = meta[k];+ if (v === undefined || v === null)+ return null;+ return Array.isArray(v) ? v.join(", ") : String(v);+ };+ return asJson({+ id,+ path: loaded.relativePath,+ status: loaded.status,+ service: get("service"),+ reason: get("reason"),+ expected_amount: get("expected_amount"),+ currency: get("currency"),+ created: get("created"),+ approved_by: get("approved_by"),+ approved_at: get("approved_at"),+ rejected_by: get("rejected_by"),+ rejected_at: get("rejected_at"),+ rejection_reason: get("rejection_reason"),+ receipt: get("receipt"),+ policy_status: get("policy_status"),+ policy_rule: get("policy_rule")+ });+ }+ });+ api.registerTool({+ name: "payment_request_consume",+ description: "Mark an `approved` request as `consumed` and link the resulting receipt path. Called by the agent after the paid call succeeded.",+ parameters: {+ type: "object",+ properties: {+ id: { type: "string" },+ receipt: { type: "string" }+ },+ required: ["id", "receipt"],+ additionalProperties: false+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const result = await consumePendingRequest(vault, String(params["id"]), {+ receiptPath: String(params["receipt"])+ });+ return asJson({+ id: result.id,+ path: result.relativePath,+ status: result.status+ });+ }+ });}});export {diff --git a/package.json b/package.jsonindex be9901d1..68707325 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.7.0",+ "version": "0.8.0","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",diff --git a/plugin.yaml b/plugin.yamlindex f5128296..65d0b4a3 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.7.0"+version: "0.8.0"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 3c80f1b4..03456a63 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.7.0"+version: "0.8.0"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex 04206414..788dbc47 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "0.7.0"+version = "0.8.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/main.ts b/src/cli/main.tsindex ce0dc6d3..312bd80e 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -8,13 +8,14 @@* statement, not a registry β keeps the control flow obvious.*/-import { mkdirSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { resolve } from "node:path";import {defaultConfigPath,discoverConfig,redactMapping,+ resolveAgentName,resolveTimezone,resolveVault,setConfigValue,@@ -22,6 +23,24 @@ import {import { doctor } from "../core/doctor.ts";import { appendEvent } from "../core/event-log.ts";import { bootstrapVault } from "../core/init.ts";+import {+ approvePendingRequest,+ buildPaymentDigest,+ checkPolicy,+ consumePendingRequest,+ listPendingRequests,+ loadPendingRequest,+ payMemoryDirs,+ rejectPendingRequest,+ renderPaymentDigestTelegram,+ vaultRelativePath,+ writeAsset,+ writePendingRequest,+ writePolicyIfMissing,+ writeReceipt,+ writeReport,+} from "../core/pay-memory/index.ts";+import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";import { listVaultPages, writeFrontmatter } from "../core/vault.ts";import { CliError, parseFlags } from "./argparse.ts";import {@@ -58,6 +77,52 @@ function requireVault(flagVal: string | undefined, configPath: string | null): sreturn vault;}+/**+ * Emit `payload` as pretty-printed JSON with sorted keys, plus a trailing+ * newline. Centralises the format so the eleven Pay Memory subcommands+ * don't each repeat the same `JSON.stringify(...) + "\n"` boilerplate.+ */+function writeJson(payload: unknown): void {+ process.stdout.write(JSON.stringify(payload, sortedReplacer, 2) + "\n");+}++/**+ * Render a uniform `error: failed to <action>: <reason>\n` message on+ * stderr and return exit-code 1. Use as the `return failWith(...)` last+ * expression of a catch arm so the subcommand keeps its single-exit+ * shape.+ */+function failWith(action: string, exc: unknown): number {+ const reason = (exc as Error)?.message ?? String(exc);+ process.stderr.write(`error: failed to ${action}: ${reason}\n`);+ return 1;+}++/**+ * Parse an optional `--<name>` flag whose value should be a finite number.+ * Returns `{ value: number | null, error: string | null }`. The caller is+ * expected to bail with exit 2 + the error string when `error` is set.+ *+ * Trim before testing for emptiness β `Number(" ")` evaluates to `0` in+ * JS, and without this whitespace-only flags would silently bypass the+ * missing-amount guard in `check-payment-policy` and+ * `request-payment-approval`.+ */+function parseOptionalNumberFlag(+ flags: Record<string, string | boolean | string[] | undefined>,+ name: string,+): { value: number | null; error: string | null } {+ const raw = flags[name] as string | undefined;+ if (raw === undefined) return { value: null, error: null };+ const trimmed = raw.trim();+ if (trimmed === "") return { value: null, error: null };+ const parsed = Number(trimmed);+ if (!Number.isFinite(parsed)) {+ return { value: null, error: `--${name} must be a number, got: ${raw}` };+ }+ return { value: parsed, error: null };+}+// ββ Subcommands βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync function cmdStatus(argv: string[]): Promise<number> {@@ -272,6 +337,738 @@ async function cmdIndex(argv: string[]): Promise<number> {return 0;}+// ββ Pay Memory subcommands ββββββββββββββββββββββββββββββββββββββββββββββββββ++async function cmdInitPayMemory(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ agent: { type: "string" },+ overwrite: { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);+ const agent =+ (flags["agent"] as string | undefined) ?? resolveAgentName(config);++ const dirs = payMemoryDirs(vault);+ const dirList = [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports];+ const created: string[] = [];+ const skipped: string[] = [];+ for (const dir of dirList) {+ const existed = existsSync(dir);+ try {+ mkdirSync(dir, { recursive: true });+ } catch (exc) {+ process.stderr.write(+ `error: failed to create ${dir}: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }+ (existed ? skipped : created).push(vaultRelativePath(dir, vault));+ }++ let policy;+ try {+ policy = writePolicyIfMissing(vault, { overwrite: Boolean(flags["overwrite"]) });+ } catch (exc) {+ process.stderr.write(+ `error: failed to write policy: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }+ const policyRel = vaultRelativePath(policy.path, vault);+ const policyStatus = policy.status;++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ {+ vault_path: vault,+ agent,+ created,+ skipped,+ policy_path: policyRel,+ policy_status: policyStatus,+ },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ return 0;+ }++ process.stdout.write(`pay-memory layout initialized: ${vault}\n`);+ for (const rel of created) process.stdout.write(` created: ${rel}\n`);+ for (const rel of skipped) process.stdout.write(` exists: ${rel}\n`);+ process.stdout.write(` ${policyStatus}: ${policyRel}\n`);+ process.stdout.write(`agent: ${agent}\n`);+ return 0;+}++async function cmdAppendPaymentReceipt(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ agent: { type: "string" },+ service: { type: "string", required: true },+ status: { type: "string", required: true },+ reason: { type: "string", required: true },+ category: { type: "string" },+ endpoint: { type: "string" },+ "expected-cost": { type: "string" },+ "actual-amount": { type: "string" },+ currency: { type: "string" },+ "payment-proof": { type: "string" },+ "result-ref": { type: "string" },+ "result-note": { type: "string" },+ "raw-output-file": { type: "string" },+ slug: { type: "string" },+ date: { type: "string" },+ time: { type: "string" },+ overwrite: { type: "boolean" },+ json: { type: "boolean" },+ "policy-status": { type: "string" },+ "policy-rule": { type: "string" },+ "policy-reasons": { type: "string-array" },+ "policy-checked-at": { type: "string" },+ "from-request": { type: "string" },+ "payment-layer": { type: "string" },+ network: { type: "string" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);+ const agent =+ (flags["agent"] as string | undefined) ?? resolveAgentName(config);+ const tz = resolveTimezone(config);++ let rawOutput: string | undefined;+ const rawOutputFile = flags["raw-output-file"] as string | undefined;+ if (rawOutputFile) {+ try {+ rawOutput = readFileSync(rawOutputFile, "utf8");+ } catch (exc) {+ process.stderr.write(+ `error: cannot read raw-output-file: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }+ }++ // --policy-status / --from-request audit context. `--from-request`+ // pulls policy + approval state from the named pending-payment-request+ // so the agent doesn't have to repeat it on the command line. Explicit+ // flags win over `--from-request` so a caller can override individual+ // fields.+ let policyStatus = (flags["policy-status"] as string | undefined) ?? null;+ let policyRule = (flags["policy-rule"] as string | undefined) ?? null;+ let policyReasons = (flags["policy-reasons"] as string[] | undefined) ?? null;+ let policyCheckedAt =+ (flags["policy-checked-at"] as string | undefined) ?? null;+ let approvalStatus: string | null = null;+ let approvedBy: string | null = null;+ let approvedAt: string | null = null;+ const fromRequest = (flags["from-request"] as string | undefined) ?? null;+ if (fromRequest) {+ const loaded = loadPendingRequest(vault, fromRequest);+ if (!loaded) {+ process.stderr.write(`error: pending request not found: ${fromRequest}\n`);+ return 1;+ }+ const meta = loaded.metadata;+ const get = (k: string): string | null => {+ const v = meta[k];+ if (v === undefined || v === null) return null;+ return Array.isArray(v) ? v.join(", ") : String(v);+ };+ policyStatus ??= get("policy_status");+ policyRule ??= get("policy_rule");+ approvalStatus ??= loaded.status;+ approvedBy ??= get("approved_by");+ approvedAt ??= get("approved_at");+ }+ if (policyStatus !== null) {+ const allowed: ReadonlyArray<ReceiptPolicyStatus> = [+ "allowed",+ "approval_required",+ "denied",+ "not_checked",+ ];+ if (!allowed.includes(policyStatus as ReceiptPolicyStatus)) {+ process.stderr.write(+ `error: --policy-status must be one of: ${allowed.join(", ")}\n`,+ );+ return 2;+ }+ }++ let result;+ try {+ result = writeReceipt(vault, {+ agent,+ service: String(flags["service"]),+ status: String(flags["status"]),+ reason: String(flags["reason"]),+ paymentLayer: (flags["payment-layer"] as string | undefined) ?? null,+ network: (flags["network"] as string | undefined) ?? null,+ category: (flags["category"] as string | undefined) ?? null,+ endpoint: (flags["endpoint"] as string | undefined) ?? null,+ expectedCost: (flags["expected-cost"] as string | undefined) ?? null,+ actualAmount: (flags["actual-amount"] as string | undefined) ?? null,+ currency: (flags["currency"] as string | undefined) ?? null,+ paymentProof: (flags["payment-proof"] as string | undefined) ?? null,+ resultRef: (flags["result-ref"] as string | undefined) ?? null,+ resultNote: (flags["result-note"] as string | undefined) ?? null,+ rawOutput: rawOutput ?? null,+ slug: (flags["slug"] as string | undefined) ?? null,+ date: (flags["date"] as string | undefined) ?? null,+ time: (flags["time"] as string | undefined) ?? null,+ overwrite: Boolean(flags["overwrite"]),+ tz,+ policyStatus: policyStatus as ReceiptPolicyStatus | null,+ policyRule,+ policyReasons,+ policyCheckedAt,+ approvalRequestId: fromRequest,+ approvalStatus: approvalStatus as+ | "pending"+ | "approved"+ | "rejected"+ | "consumed"+ | null,+ approvedBy,+ approvedAt,+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to write receipt: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ {+ path: result.relativePath,+ absolute_path: result.path,+ slug: result.slug,+ date: result.date,+ created: result.created,+ },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ process.stdout.write(`receipt: ${result.relativePath}\n`);+ process.stdout.write(`slug: ${result.slug}\n`);+ process.stdout.write(`date: ${result.date}\n`);+ }+ return 0;+}++async function cmdCaptureAsset(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ title: { type: "string", required: true },+ service: { type: "string", required: true },+ "result-url": { type: "string", required: true },+ "source-receipt": { type: "string" },+ "prompt-file": { type: "string" },+ "used-in": { type: "string" },+ slug: { type: "string" },+ overwrite: { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);++ let prompt: string | undefined;+ const promptFile = flags["prompt-file"] as string | undefined;+ if (promptFile) {+ try {+ prompt = readFileSync(promptFile, "utf8");+ } catch (exc) {+ process.stderr.write(+ `error: cannot read prompt-file: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }+ }++ let result;+ try {+ result = writeAsset(vault, {+ title: String(flags["title"]),+ service: String(flags["service"]),+ resultUrl: String(flags["result-url"]),+ sourceReceipt: (flags["source-receipt"] as string | undefined) ?? null,+ prompt: prompt ?? null,+ usedIn: (flags["used-in"] as string | undefined) ?? null,+ slug: (flags["slug"] as string | undefined) ?? null,+ overwrite: Boolean(flags["overwrite"]),+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to write asset: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ {+ path: result.relativePath,+ absolute_path: result.path,+ slug: result.slug,+ created: result.created,+ },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ process.stdout.write(`asset: ${result.relativePath}\n`);+ process.stdout.write(`slug: ${result.slug}\n`);+ }+ return 0;+}++async function cmdPaymentDigest(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ date: { type: "string" },+ "empty-mode": { type: "string", default: "silent" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);+ const tz = resolveTimezone(config);++ const emptyMode = String(flags["empty-mode"]);+ if (!["silent", "empty", "summary"].includes(emptyMode)) {+ process.stderr.write(`error: --empty-mode must be silent|empty|summary\n`);+ return 2;+ }++ let digest;+ try {+ digest = buildPaymentDigest(vault, {+ date: (flags["date"] as string | undefined) ?? null,+ tz,+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to build digest: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ {+ date: digest.date,+ services: digest.services,+ receipts: digest.receipts,+ total_amount: digest.totalAmount,+ currency: digest.currency,+ },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ const text = renderPaymentDigestTelegram(digest, {+ emptyMode: emptyMode as "silent" | "empty" | "summary",+ });+ if (text) process.stdout.write(text + "\n");+ }+ return 0;+}++async function cmdRequestPaymentApproval(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ agent: { type: "string" },+ service: { type: "string", required: true },+ reason: { type: "string", required: true },+ "expected-amount": { type: "string" },+ currency: { type: "string" },+ category: { type: "string" },+ endpoint: { type: "string" },+ "expected-output": { type: "string" },+ "vault-files": { type: "string-array" },+ slug: { type: "string" },+ date: { type: "string" },+ time: { type: "string" },+ "enforce-policy": { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);+ const agent =+ (flags["agent"] as string | undefined) ?? resolveAgentName(config);+ const tz = resolveTimezone(config);++ const { value: expectedAmount, error: expectedErr } = parseOptionalNumberFlag(+ flags,+ "expected-amount",+ );+ if (expectedErr) {+ process.stderr.write(`error: ${expectedErr}\n`);+ return 2;+ }++ let result;+ try {+ result = writePendingRequest(vault, {+ agent,+ service: String(flags["service"]),+ reason: String(flags["reason"]),+ expectedAmount,+ currency: (flags["currency"] as string | undefined) ?? null,+ category: (flags["category"] as string | undefined) ?? null,+ endpoint: (flags["endpoint"] as string | undefined) ?? null,+ expectedOutput: (flags["expected-output"] as string | undefined) ?? null,+ vaultFiles: (flags["vault-files"] as string[] | undefined) ?? null,+ slug: (flags["slug"] as string | undefined) ?? null,+ date: (flags["date"] as string | undefined) ?? null,+ time: (flags["time"] as string | undefined) ?? null,+ tz,+ enforcePolicy: Boolean(flags["enforce-policy"]),+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to create pending request: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ {+ id: result.id,+ path: result.relativePath,+ status: result.status,+ created: result.created,+ policy_status: result.policyDecision.status,+ policy_rule: result.policyDecision.rule,+ },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ process.stdout.write(`pending: ${result.relativePath}\n`);+ process.stdout.write(`id: ${result.id}\n`);+ process.stdout.write(`policy: ${result.policyDecision.status}\n`);+ }+ return 0;+}++async function cmdApprovePaymentRequest(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ id: { type: "string", required: true },+ "approved-by": { type: "string", required: true },+ note: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);++ let result;+ try {+ result = await approvePendingRequest(vault, String(flags["id"]), {+ approvedBy: String(flags["approved-by"]),+ note: (flags["note"] as string | undefined) ?? null,+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to approve request: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }+ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ { id: result.id, status: result.status, path: result.relativePath },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ process.stdout.write(`approved: ${result.relativePath}\n`);+ process.stdout.write(`status: ${result.status}\n`);+ }+ return 0;+}++async function cmdRejectPaymentRequest(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ id: { type: "string", required: true },+ "rejected-by": { type: "string", required: true },+ reason: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);++ let result;+ try {+ result = await rejectPendingRequest(vault, String(flags["id"]), {+ rejectedBy: String(flags["rejected-by"]),+ reason: (flags["reason"] as string | undefined) ?? null,+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to reject request: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }+ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ { id: result.id, status: result.status, path: result.relativePath },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ process.stdout.write(`rejected: ${result.relativePath}\n`);+ process.stdout.write(`status: ${result.status}\n`);+ }+ return 0;+}++async function cmdConsumePaymentRequest(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ id: { type: "string", required: true },+ receipt: { type: "string", required: true },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);++ let result;+ try {+ result = await consumePendingRequest(vault, String(flags["id"]), {+ receiptPath: String(flags["receipt"]),+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to consume request: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }+ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ { id: result.id, status: result.status, path: result.relativePath },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ process.stdout.write(`consumed: ${result.relativePath}\n`);+ process.stdout.write(`status: ${result.status}\n`);+ }+ return 0;+}++async function cmdListPendingPayments(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ status: { type: "string", default: "pending" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);+ const status = String(flags["status"]);+ const valid = ["pending", "approved", "rejected", "consumed", "all"];+ if (!valid.includes(status)) {+ process.stderr.write(+ `error: --status must be one of: ${valid.join(", ")}\n`,+ );+ return 2;+ }++ let summaries;+ try {+ summaries = listPendingRequests(vault, {+ status: status as "pending" | "approved" | "rejected" | "consumed" | "all",+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to list requests: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ summaries.map((s) => ({+ id: s.id,+ path: s.relativePath,+ status: s.status,+ service: s.service,+ reason: s.reason,+ expected_amount: s.expectedAmount,+ currency: s.currency,+ created: s.created,+ policy_status: s.policyStatus,+ })),+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else if (summaries.length === 0) {+ process.stdout.write(`no requests with status: ${status}\n`);+ } else {+ for (const s of summaries) {+ // Use an explicit null check; a truthy check would hide an actual+ // `expected_amount: "0"` (legitimate for free-tier sandbox calls)+ // because `Boolean("0") === true` only happens for *strings* β once+ // any future change starts storing the field as a number, `0`+ // would silently disappear from the list output.+ const cost =+ s.expectedAmount !== null && s.expectedAmount !== ""+ ? ` (${s.expectedAmount}${s.currency ? " " + s.currency : ""})`+ : "";+ process.stdout.write(`${s.status}\t${s.id}\t${s.service}${cost}\t${s.reason}\n`);+ }+ }+ return 0;+}++async function cmdCheckPaymentPolicy(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ service: { type: "string", required: true },+ "expected-amount": { type: "string" },+ currency: { type: "string" },+ category: { type: "string" },+ date: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);+ const tz = resolveTimezone(config);++ const { value: expectedAmount, error: expectedErr } = parseOptionalNumberFlag(+ flags,+ "expected-amount",+ );+ if (expectedErr) {+ process.stderr.write(`error: ${expectedErr}\n`);+ return 2;+ }++ let decision;+ try {+ decision = checkPolicy(vault, {+ service: String(flags["service"]),+ expectedAmount,+ currency: (flags["currency"] as string | undefined) ?? null,+ category: (flags["category"] as string | undefined) ?? null,+ date: (flags["date"] as string | undefined) ?? null,+ tz,+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to evaluate policy: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ {+ status: decision.status,+ allowed: decision.allowed,+ approval_required: decision.approvalRequired,+ rule: decision.rule,+ reasons: decision.reasons,+ has_policy: decision.hasPolicy,+ policy_path:+ decision.policyPath !== null+ ? vaultRelativePath(decision.policyPath, vault)+ : null,+ currency: decision.currency,+ },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ process.stdout.write(`status: ${decision.status}\n`);+ process.stdout.write(`has_policy: ${decision.hasPolicy}\n`);+ if (decision.rule) process.stdout.write(`rule: ${decision.rule}\n`);+ for (const r of decision.reasons) process.stdout.write(` - ${r}\n`);+ }+ // Exit 0 when allowed; 1 when denied; 3 when approval is required (the+ // shell distinguishes the three so a calling script can branch).+ if (decision.allowed) return 0;+ if (decision.approvalRequired) return 3;+ return 1;+}++async function cmdPaymentReport(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ date: { type: "string", required: true },+ title: { type: "string" },+ task: { type: "string" },+ slug: { type: "string" },+ overwrite: { type: "boolean" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);++ let result;+ try {+ result = writeReport(vault, {+ date: String(flags["date"]),+ title: (flags["title"] as string | undefined) ?? null,+ task: (flags["task"] as string | undefined) ?? null,+ slug: (flags["slug"] as string | undefined) ?? null,+ overwrite: Boolean(flags["overwrite"]),+ });+ } catch (exc) {+ process.stderr.write(+ `error: failed to write report: ${(exc as Error).message ?? exc}\n`,+ );+ return 1;+ }++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify(+ {+ path: result.relativePath,+ absolute_path: result.path,+ slug: result.slug,+ receipts_used: result.receiptsUsed,+ },+ sortedReplacer,+ 2,+ ) + "\n",+ );+ } else {+ process.stdout.write(`report: ${result.relativePath}\n`);+ process.stdout.write(`receipts: ${result.receiptsUsed}\n`);+ }+ return 0;+}+async function cmdMcp(argv: string[]): Promise<number> {const { flags } = parseFlags(argv, {vault: { type: "string" },@@ -359,16 +1156,29 @@ async function cmdToolCall(argv: string[]): Promise<number> {const HELP = `usage: o2b <command> [args...]Commands:- status Show Open Second Brain configuration status- init Initialize a vault profile with required files- doctor Run health checks on vault, config, and plugins- append-event Append an event to the configured event log backend- export-config Write a redacted config snapshot- index Regenerate the vault index from discovered pages- mcp Run the optional MCP tool server (stdio JSON-RPC)- install-cli Create symlinks for o2b and vault-log in ~/.local/bin- uninstall Print an uninstall plan and (optionally) clean local config and CLI symlinks- tool-call Invoke an MCP tool handler from the CLI and print JSON to stdout+ status Show Open Second Brain configuration status+ init Initialize a vault profile with required files+ doctor Run health checks on vault, config, and plugins+ append-event Append an event to the configured event log backend+ export-config Write a redacted config snapshot+ index Regenerate the vault index from discovered pages+ mcp Run the optional MCP tool server (stdio JSON-RPC)+ install-cli Create symlinks for o2b and vault-log in ~/.local/bin+ uninstall Print an uninstall plan and (optionally) clean local config and CLI symlinks+ tool-call Invoke an MCP tool handler from the CLI and print JSON to stdout++Pay Memory:+ init-pay-memory Bootstrap policies/, payments/, assets/, drafts/, reports/+ append-payment-receipt Save a Markdown receipt for a paid API call+ capture-asset Save a Markdown note for an asset produced by a paid call+ payment-report Aggregate a date's receipts into a Markdown report+ check-payment-policy Evaluate a prospective paid call against policies/spending.json+ request-payment-approval Create a pending payment request the user must approve+ approve-payment-request Mark a pending request as approved (human action)+ reject-payment-request Mark a pending request as rejected (human action)+ consume-payment-request Link an approved request to its resulting receipt+ list-pending-payments List pending/approved/etc. requests+ payment-digest Render a Telegram-friendly 4-line summary for a date (Hermes cron-friendly)`;function sortedReplacer(_key: string, value: unknown): unknown {@@ -424,6 +1234,28 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {return await cmdUninstall(rest);case "tool-call":return await cmdToolCall(rest);+ case "init-pay-memory":+ return await cmdInitPayMemory(rest);+ case "append-payment-receipt":+ return await cmdAppendPaymentReceipt(rest);+ case "capture-asset":+ return await cmdCaptureAsset(rest);+ case "payment-report":+ return await cmdPaymentReport(rest);+ case "check-payment-policy":+ return await cmdCheckPaymentPolicy(rest);+ case "request-payment-approval":+ return await cmdRequestPaymentApproval(rest);+ case "approve-payment-request":+ return await cmdApprovePaymentRequest(rest);+ case "reject-payment-request":+ return await cmdRejectPaymentRequest(rest);+ case "consume-payment-request":+ return await cmdConsumePaymentRequest(rest);+ case "list-pending-payments":+ return await cmdListPendingPayments(rest);+ case "payment-digest":+ return await cmdPaymentDigest(rest);default:process.stderr.write(`error: unknown command: ${command}\n`);process.stderr.write(HELP);diff --git a/src/core/agent-identity.ts b/src/core/agent-identity.tsnew file mode 100644index 00000000..11a80330--- /dev/null+++ b/src/core/agent-identity.ts@@ -0,0 +1,55 @@+/**+ * Shared agent-identity helpers used by every runtime adapter.+ *+ * Centralises the two pieces of logic that need to stay in sync between+ * the MCP server (`src/mcp/tools.ts`) and the OpenClaw native plugin+ * (`src/openclaw/index.ts`) β and historically have drifted when one was+ * updated without the other:+ *+ * - `PLACEHOLDER_AGENT_VALUES`: the strings the LLM is most likely to+ * guess for the `agent` argument when it doesn't actually know its+ * identity. None of these are useful as a real `@<name>` in the daily+ * event log.+ * - `normalizeAgentArgument`: strip a leading `@`, trim whitespace, and+ * filter against `PLACEHOLDER_AGENT_VALUES` (case-insensitive).+ * Returns `null` for empty / placeholder inputs so the caller can+ * fall back to the server-resolved default.+ */++export const PLACEHOLDER_AGENT_VALUES: ReadonlySet<string> = new Set([+ "agent",+ "assistant",+ "ai",+ "ai-assistant",+ "bot",+ "chatbot",+ "claude",+ "claude-code",+ "codex",+ "codex-cli",+ "codex-exec",+ "copilot",+ "gemini",+ "gpt",+ "gpt-4",+ "gpt-5",+ "hermes",+ "llm",+ "model",+ "openai",+ "openclaw",+ "user",+]);++export function normalizeAgentArgument(value: string | null | undefined): string | null {+ if (value === null || value === undefined) return null;+ const cleaned = String(value).trim().replace(/^@+/, "").trim();+ if (!cleaned) return null;+ // Normalize hyphens / underscores to a single canonical form before the+ // set lookup. The placeholder list stores the hyphenated spelling+ // (`claude-code`, `gpt-4`, β¦) but agents emit either form interchangeably+ // β without this, `claude_code` or `gpt_4` would slip past the filter.+ const canonical = cleaned.toLowerCase().replace(/_/g, "-");+ if (PLACEHOLDER_AGENT_VALUES.has(canonical)) return null;+ return cleaned;+}diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.tsindex 78178c86..a7b5021a 100644--- a/src/core/fs-atomic.ts+++ b/src/core/fs-atomic.ts@@ -11,10 +11,68 @@* directory entry to durably persist the rename).*/-import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from "node:fs";+import {+ closeSync,+ fsyncSync,+ linkSync,+ mkdirSync,+ openSync,+ renameSync,+ unlinkSync,+ writeSync,+} from "node:fs";import { basename, dirname, join } from "node:path";export function atomicWriteFileSync(target: string, contents: string): void {+ withTempFile(target, contents, (tmpPath) => {+ // POSIX `rename(2)` is atomic and clobbers an existing target β that's+ // exactly the "overwrite" semantic we want. No exclusivity guarantee.+ renameSync(tmpPath, target);+ });+}++/**+ * Like {@link atomicWriteFileSync} but fails with `EEXIST` if `target`+ * already exists, atomically. Implemented via `link(2)` instead of+ * `rename(2)` because POSIX `link` returns EEXIST when the destination+ * inode is taken β there is no `rename`-with-no-clobber primitive that's+ * portable.+ *+ * Use this where the caller's "refuse to overwrite" guarantee must be+ * race-free: a plain `existsSync(target) || writeFileSync(...)` is+ * vulnerable to TOCTOU when two processes (CLI + MCP server, concurrent+ * agents) target the same path in parallel.+ *+ * Requires `tmpPath` and `target` to live on the same filesystem, which+ * is guaranteed because the temp file is placed alongside the target.+ */+export function atomicCreateFileSyncExclusive(target: string, contents: string): void {+ withTempFile(target, contents, (tmpPath) => {+ try {+ linkSync(tmpPath, target);+ } finally {+ // Always remove the temp inode regardless of whether linkSync+ // succeeded β the temp is an implementation detail.+ try {+ unlinkSync(tmpPath);+ } catch {+ // already gone; ignore+ }+ }+ });+}++/**+ * Internal helper: write `contents` to a sibling temp file (atomic + fsynced),+ * then call `commit` to attach the temp inode to the final path. The temp+ * file is unlinked on any failure; durability fsync of the parent directory+ * is best-effort after a successful commit.+ */+function withTempFile(+ target: string,+ contents: string,+ commit: (tmpPath: string) => void,+): void {const dir = dirname(target);mkdirSync(dir, { recursive: true });@@ -28,6 +86,7 @@ export function atomicWriteFileSync(target: string, contents: string): void {const tmpPath = join(dir, tmpName);let fd: number | null = null;+ let committed = false;try {fd = openSync(tmpPath, "wx", 0o644);const buf = Buffer.from(contents, "utf8");@@ -38,9 +97,10 @@ export function atomicWriteFileSync(target: string, contents: string): void {fsyncSync(fd);closeSync(fd);fd = null;- renameSync(tmpPath, target);+ commit(tmpPath);+ committed = true;- // Durably persist the rename by fsyncing the parent directory.+ // Durably persist the new directory entry by fsyncing the parent dir.// Node has no portable directory fsync; on Linux the open-O_RDONLY trick works.try {const dfd = openSync(dir, "r");@@ -52,7 +112,7 @@ export function atomicWriteFileSync(target: string, contents: string): void {} catch {// Directory fsync is a best-effort durability optimization.// Failure on platforms that don't support it (rare) is not fatal β- // the rename itself is already atomic at the inode level.+ // the rename/link itself is already atomic at the inode level.}} catch (err) {if (fd !== null) {@@ -62,10 +122,12 @@ export function atomicWriteFileSync(target: string, contents: string): void {// ignore}}- try {- unlinkSync(tmpPath);- } catch {- // tmp file may not exist if openSync failed+ if (!committed) {+ try {+ unlinkSync(tmpPath);+ } catch {+ // tmp file may not exist if openSync failed+ }}throw err;}diff --git a/src/core/path-safety.ts b/src/core/path-safety.tsnew file mode 100644index 00000000..58bcd2a3--- /dev/null+++ b/src/core/path-safety.ts@@ -0,0 +1,110 @@+/**+ * Path-safety helpers shared by every module that writes into the vault.+ *+ * Centralises the "is this path inside the vault?" check and a reusable+ * vault-relative path renderer. Every module that constructs a path to+ * write must funnel through `ensureInsideVault` so a malicious or buggy+ * input (e.g. a slug with `..`, an absolute symlink target) cannot land a+ * file outside the vault root.+ */++import { existsSync, realpathSync } from "node:fs";+import { dirname, posix, relative, resolve, sep } from "node:path";++/**+ * Throw if `target` is not the vault root or a descendant of it.+ *+ * The check is twofold:+ *+ * 1. `path.resolve` normalises `..` so a slug like `../etc/passwd`+ * cannot pretend to be inside the vault. The platform path+ * separator (`/` or `\`) is used for the prefix check so siblings+ * that share a name prefix (`/v` vs `/v-evil`) are rejected.+ * 2. `fs.realpathSync` follows symlinks for the deepest existing+ * ancestor of the target, then re-runs the prefix check on the+ * resolved real paths. This blocks the case where a directory+ * *inside* the vault is itself a symlink to somewhere outside it+ * (`<vault>/AI Wiki/payments/escape -> /tmp/outside`) β without+ * realpath, the lexical check would happily admit the path.+ *+ * Returns the resolved (lexical) absolute path of `target`. Callers that+ * need the realpath should call `realpathSync` themselves on the result;+ * we deliberately return the lexical form so wikilinks rendered from it+ * keep matching what the user sees in Obsidian.+ */+export function ensureInsideVault(target: string, vault: string): string {+ const resolvedTarget = resolve(target);+ const resolvedVault = resolve(vault);++ if (!isLexicallyInside(resolvedTarget, resolvedVault)) {+ throw new Error(`path escapes vault: ${target}`);+ }++ // Realpath protection only matters when the vault actually exists on+ // disk β otherwise there is no symlink to follow. Pure-lexical inputs+ // (used by unit tests) skip this branch and rely on step 1 above.+ if (existsSync(resolvedVault)) {+ const realVault = safeRealpath(resolvedVault);+ const realAncestor = safeRealpath(deepestExistingAncestor(resolvedTarget));+ if (!isLexicallyInside(realAncestor, realVault)) {+ throw new Error(`path escapes vault via symlink: ${target}`);+ }+ }++ return resolvedTarget;+}++function isLexicallyInside(target: string, root: string): boolean {+ // Windows file paths are case-insensitive at the filesystem level β+ // `C:\Vault\x.md` and `c:\vault\x.md` resolve to the same inode. Doing+ // a case-sensitive string compare on Windows would falsely reject a+ // user's lower-cased argument against a vault stored with the canonical+ // capitalisation. POSIX stays case-sensitive.+ const t = process.platform === "win32" ? target.toLowerCase() : target;+ const r = process.platform === "win32" ? root.toLowerCase() : root;+ return t === r || t.startsWith(r + sep);+}++function deepestExistingAncestor(target: string): string {+ let cur = target;+ // Walk up until we hit a path that exists. `dirname` of a top-level+ // path returns itself; the loop terminates either at the first existing+ // ancestor (the common case β vault root exists) or at the root.+ while (!existsSync(cur)) {+ const parent = dirname(cur);+ if (parent === cur) return cur;+ cur = parent;+ }+ return cur;+}++function safeRealpath(p: string): string {+ // realpath throws on non-existent paths and on permission failure.+ // For non-existent we fall back to the lexical form (the+ // `deepestExistingAncestor` walk above tries to avoid this case);+ // for permission failure we surface the error so the caller learns+ // about it instead of silently disabling symlink protection.+ try {+ return realpathSync(p);+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return p;+ throw err;+ }+}++/**+ * Vault-relative path with forward slashes.+ *+ * Markdown rendering and Obsidian wikilinks both want forward slashes+ * regardless of host OS, so we collapse Windows-style backslashes to+ * `/`. Returns the input unchanged if it is not inside the vault β that+ * guards `ensureInsideVault` callers that want to display the rejected+ * path back to the user without crashing.+ */+export function vaultRelative(target: string, vault: string): string {+ const rel = relative(resolve(vault), resolve(target));+ return rel+ .split(/[\\/]/)+ .filter((p) => p.length > 0)+ .join(posix.sep);+}diff --git a/src/core/pay-memory/_md.ts b/src/core/pay-memory/_md.tsnew file mode 100644index 00000000..bdbad50e--- /dev/null+++ b/src/core/pay-memory/_md.ts@@ -0,0 +1,80 @@+/**+ * Shared Markdown / frontmatter rendering helpers used by every Pay Memory+ * artifact writer (receipt, asset, report, approval). Internal to the+ * `pay-memory/` directory β not re-exported from the package barrel.+ *+ * Centralises:+ * - the `_(not provided)_` placeholder string used in body templates,+ * - inline-code rendering with backtick sanitisation,+ * - wikilink construction with bracket sanitisation,+ * - ISO-Z timestamp emission for `created` / `approved_at` / etc.,+ * - `FrontmatterMap` accessors (`putIfPresent`, `frontmatterStr`).+ */++import type { FrontmatterMap, FrontmatterValue } from "../types.ts";++export const NOT_PROVIDED = "_(not provided)_";++/** Strip a trailing `.md` (case-insensitive) from a wikilink target. */+export function stripMarkdownExt(target: string): string {+ return target.replace(/\.md$/i, "");+}++/**+ * Drop `[`/`]` from a wikilink target so they cannot prematurely close+ * the surrounding `[[ ... ]]`. These characters are never legal in vault+ * paths anyway.+ */+export function sanitizeWikilinkTarget(target: string): string {+ return target.replace(/[[\]]/g, "");+}++/**+ * Render an Obsidian wikilink for `target`, stripping `.md` and any bare+ * `[`/`]`. Idempotent on already-sanitised inputs.+ */+export function wikiLink(target: string): string {+ return `[[${stripMarkdownExt(sanitizeWikilinkTarget(target.trim()))}]]`;+}++/**+ * Wrap `value` in inline-code backticks, replacing embedded backticks with+ * the visually similar grave-accent placeholder so the surrounding span+ * stays balanced.+ */+export function formatCode(value: string | null | undefined): string {+ const trimmed = (value ?? "").trim();+ if (!trimmed) return NOT_PROVIDED;+ return `\`${trimmed.replace(/`/g, "Λ")}\``;+}++/** Current wall-clock time as `YYYY-MM-DDTHH:MM:SSZ`. */+export function nowIsoZ(): string {+ return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");+}++/**+ * Set `meta[key] = value.trim()` only when `value` is a non-empty string.+ * Used by writers that emit optional frontmatter fields conditionally so+ * the report aggregator can rely on "key present β relevant".+ */+export function putIfPresent(+ meta: FrontmatterMap,+ key: string,+ value: string | null | undefined,+): void {+ if (value === null || value === undefined) return;+ const trimmed = String(value).trim();+ if (!trimmed) return;+ meta[key] = trimmed as FrontmatterValue;+}++/**+ * Read a frontmatter field as a string. Arrays are joined with `, `;+ * `null` / `undefined` collapse to `""`.+ */+export function frontmatterStr(value: FrontmatterValue | undefined): string {+ if (value === undefined || value === null) return "";+ if (Array.isArray(value)) return value.join(", ");+ return String(value);+}diff --git a/src/core/pay-memory/approval.ts b/src/core/pay-memory/approval.tsnew file mode 100644index 00000000..e946ab8f--- /dev/null+++ b/src/core/pay-memory/approval.ts@@ -0,0 +1,519 @@+/**+ * Approval workflow for paid agent actions (spec Β§17.6).+ *+ * Adds a `pending-payment-request` artifact under `AI Wiki/payments/_pending/`.+ * The flow is:+ *+ * 1. Agent creates a pending request (`writePendingRequest`).+ * 2. User reviews and approves/rejects (`approvePendingRequest` /+ * `rejectPendingRequest`).+ * 3. Agent polls status (`loadPendingRequest`); on `approved`, executes+ * the paid call via `pay`, then calls `consumePendingRequest` to mark+ * the request as `consumed` and link the resulting receipt.+ *+ * State transitions (rejected/consumed are terminal):+ *+ * pending βapproveβ approved βconsumeβ consumed+ * β+ * ββββrejectβ rejected+ *+ * Policy is automatically checked at request time and the decision is+ * recorded in the frontmatter. A `denied` policy result still creates the+ * request β the user can see *why* the agent wanted to spend and override+ * the policy by approving anyway. (If you don't want this affordance,+ * pass `enforcePolicy: true` and the helper will throw before writing.)+ */++import lockfile from "proper-lockfile";+import { readdirSync } from "node:fs";+import { join } from "node:path";++import type { FrontmatterMap } from "../types.ts";+import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../vault.ts";+import {+ formatCode,+ frontmatterStr,+ nowIsoZ,+ NOT_PROVIDED,+ putIfPresent,+} from "./_md.ts";+import {+ ensureInsideVault,+ isoDateNow,+ isoTimeNow,+ isoTimestampZ,+ payMemoryDirs,+ validateIsoDate,+ validateIsoTime,+ validateSlug,+ vaultRelative,+} from "./paths.ts";+import { checkPolicy, type PolicyDecision } from "./policy-rules.ts";++export const PENDING_REQUEST_FRONTMATTER_TYPE = "pending-payment-request";++export type RequestStatus = "pending" | "approved" | "rejected" | "consumed";++export const REQUEST_STATUSES: ReadonlyArray<RequestStatus> = [+ "pending",+ "approved",+ "rejected",+ "consumed",+] as const;++export interface PendingRequestInput {+ readonly agent: string;+ readonly service: string;+ readonly reason: string;+ readonly expectedAmount?: number | null;+ readonly currency?: string | null;+ readonly category?: string | null;+ readonly endpoint?: string | null;+ readonly expectedOutput?: string | null;+ readonly vaultFiles?: ReadonlyArray<string> | null;+ readonly slug?: string | null;+ readonly date?: string | null;+ readonly time?: string | null;+ readonly tz?: string | null;+ readonly enforcePolicy?: boolean;+}++export interface PendingRequestOutput {+ readonly path: string;+ readonly relativePath: string;+ readonly id: string;+ readonly status: RequestStatus;+ readonly created: string;+ readonly policyDecision: PolicyDecision;+}++export interface PendingRequestSummary {+ readonly id: string;+ readonly path: string;+ readonly relativePath: string;+ readonly agent: string;+ readonly service: string;+ readonly reason: string;+ readonly expectedAmount: string | null;+ readonly currency: string | null;+ readonly category: string | null;+ readonly status: RequestStatus;+ readonly created: string | null;+ readonly approvedBy: string | null;+ readonly approvedAt: string | null;+ readonly rejectedBy: string | null;+ readonly rejectedAt: string | null;+ readonly rejectionReason: string | null;+ readonly receipt: string | null;+ readonly policyStatus: string | null;+}++export function pendingDir(vault: string): string {+ return join(payMemoryDirs(vault).payments, "_pending");+}++export function pendingRequestPath(vault: string, id: string): string {+ return join(pendingDir(vault), `${validateSlug(id)}.md`);+}++export function writePendingRequest(+ vault: string,+ input: PendingRequestInput,+): PendingRequestOutput {+ if (!input.service?.trim()) throw new Error("pending request requires a service");+ if (!input.reason?.trim()) throw new Error("pending request requires a reason");+ if (!input.agent?.trim()) throw new Error("pending request requires an agent");++ const tz = input.tz ?? null;+ const date = validateIsoDate(input.date ?? isoDateNow(tz));+ const time = validateIsoTime(input.time ?? isoTimeNow(tz));++ const id = (input.slug && input.slug.trim()) || defaultRequestSlug(input, date, time);+ const target = pendingRequestPath(vault, id);+ ensureInsideVault(target, vault);++ // Run the policy check up-front so the request frontmatter records+ // *why* the user is being asked to approve. If `enforcePolicy` is set,+ // a `denied` outcome blocks the request from being created at all.+ const decision = checkPolicy(vault, {+ service: input.service.trim(),+ expectedAmount: input.expectedAmount ?? null,+ currency: input.currency ?? null,+ category: input.category ?? null,+ date,+ tz,+ });+ if (input.enforcePolicy && !decision.allowed && !decision.approvalRequired) {+ throw new Error(+ `policy denied: ${decision.reasons.join("; ") || decision.rule || "no reason given"}`,+ );+ }++ const created = isoTimestampZ(date, time, tz);+ const metadata: FrontmatterMap = {+ type: PENDING_REQUEST_FRONTMATTER_TYPE,+ id,+ agent: input.agent.trim(),+ service: input.service.trim(),+ reason: input.reason.trim(),+ status: "pending",+ created,+ policy_status: decision.status,+ };+ if (tz) metadata["timezone"] = tz;+ if (decision.rule) metadata["policy_rule"] = decision.rule;+ putIfPresent(metadata, "category", input.category);+ putIfPresent(metadata, "endpoint", input.endpoint);+ putIfPresent(metadata, "currency", input.currency);+ if (typeof input.expectedAmount === "number") {+ metadata["expected_amount"] = String(input.expectedAmount);+ }++ writeFrontmatterAtomic(target, metadata, renderRequestBody(input, decision), {+ overwrite: false,+ existsErrorKind: "pending request",+ vaultForRelativePath: vault,+ });++ return {+ path: target,+ relativePath: vaultRelative(target, vault),+ id,+ status: "pending",+ created,+ policyDecision: decision,+ };+}++export interface LoadedPendingRequest {+ readonly metadata: FrontmatterMap;+ readonly body: string;+ readonly path: string;+ readonly relativePath: string;+ readonly id: string;+ readonly status: RequestStatus;+}++export function loadPendingRequest(vault: string, id: string): LoadedPendingRequest | null {+ const target = pendingRequestPath(vault, id);+ // parseFrontmatter swallows ENOENT (returns [{}, ""]) so the absent-file+ // case is naturally indistinguishable from a present-but-malformed file.+ // We disambiguate on the frontmatter `type` field below: only a real+ // pending-payment-request returns non-null.+ const [metadata, body] = parseFrontmatter(target);+ if (frontmatterStr(metadata["type"]) !== PENDING_REQUEST_FRONTMATTER_TYPE) return null;+ // parseStatus throws on malformed status β propagate, since transitions+ // need a known starting state. Listing walks catch the throw.+ const status = parseStatus(frontmatterStr(metadata["status"]));+ return {+ metadata,+ body,+ path: target,+ relativePath: vaultRelative(target, vault),+ id,+ status,+ };+}++export interface ListPendingRequestsOptions {+ /** Filter by status; "all" returns every request. Default "pending". */+ readonly status?: RequestStatus | "all";+}++export function listPendingRequests(+ vault: string,+ opts: ListPendingRequestsOptions = {},+): PendingRequestSummary[] {+ const dir = pendingDir(vault);+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return [];+ throw err;+ }+ const filter = opts.status ?? "pending";+ const out: PendingRequestSummary[] = [];+ for (const entry of entries) {+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;+ const full = join(dir, entry.name);+ let metadata: FrontmatterMap;+ try {+ [metadata] = parseFrontmatter(full);+ } catch {+ continue;+ }+ if (frontmatterStr(metadata["type"]) !== PENDING_REQUEST_FRONTMATTER_TYPE) continue;+ let status: RequestStatus;+ try {+ status = parseStatus(frontmatterStr(metadata["status"]));+ } catch {+ // The walker is best-effort: a corrupted entry shouldn't crash a+ // user-facing list. We skip it instead of throwing β the strict+ // validation in `loadPendingRequest` still surfaces the failure+ // when an actual transition is attempted on the offending file.+ continue;+ }+ if (filter !== "all" && status !== filter) continue;+ out.push({+ id: frontmatterStr(metadata["id"]) || stem(entry.name),+ path: full,+ relativePath: vaultRelative(full, vault),+ agent: frontmatterStr(metadata["agent"]),+ service: frontmatterStr(metadata["service"]),+ reason: frontmatterStr(metadata["reason"]),+ expectedAmount: frontmatterStr(metadata["expected_amount"]) || null,+ currency: frontmatterStr(metadata["currency"]) || null,+ category: frontmatterStr(metadata["category"]) || null,+ status,+ created: frontmatterStr(metadata["created"]) || null,+ approvedBy: frontmatterStr(metadata["approved_by"]) || null,+ approvedAt: frontmatterStr(metadata["approved_at"]) || null,+ rejectedBy: frontmatterStr(metadata["rejected_by"]) || null,+ rejectedAt: frontmatterStr(metadata["rejected_at"]) || null,+ rejectionReason: frontmatterStr(metadata["rejection_reason"]) || null,+ receipt: frontmatterStr(metadata["receipt"]) || null,+ policyStatus: frontmatterStr(metadata["policy_status"]) || null,+ });+ }+ out.sort((a, b) => (a.created ?? "").localeCompare(b.created ?? ""));+ return out;+}++export interface ApproveOptions {+ readonly approvedBy: string;+ readonly note?: string | null;+}++export async function approvePendingRequest(+ vault: string,+ id: string,+ opts: ApproveOptions,+): Promise<PendingRequestOutput> {+ const approvedBy = opts.approvedBy?.trim();+ if (!approvedBy) {+ throw new Error("approve-payment-request requires a non-empty approvedBy");+ }+ return transitionRequest(vault, id, "pending", "approved", (meta) => {+ meta["approved_by"] = approvedBy;+ meta["approved_at"] = nowIsoZ();+ if (opts.note?.trim()) meta["approval_note"] = opts.note.trim();+ });+}++export interface RejectOptions {+ readonly rejectedBy: string;+ readonly reason?: string | null;+}++export async function rejectPendingRequest(+ vault: string,+ id: string,+ opts: RejectOptions,+): Promise<PendingRequestOutput> {+ const rejectedBy = opts.rejectedBy?.trim();+ if (!rejectedBy) {+ throw new Error("reject-payment-request requires a non-empty rejectedBy");+ }+ return transitionRequest(vault, id, "pending", "rejected", (meta) => {+ meta["rejected_by"] = rejectedBy;+ meta["rejected_at"] = nowIsoZ();+ if (opts.reason?.trim()) meta["rejection_reason"] = opts.reason.trim();+ });+}++export interface ConsumeOptions {+ readonly receiptPath: string;+}++export async function consumePendingRequest(+ vault: string,+ id: string,+ opts: ConsumeOptions,+): Promise<PendingRequestOutput> {+ const receiptPath = opts.receiptPath?.trim();+ if (!receiptPath) {+ throw new Error("consume-payment-request requires a non-empty receiptPath");+ }+ return transitionRequest(vault, id, "approved", "consumed", (meta) => {+ meta["receipt"] = receiptPath;+ meta["consumed_at"] = nowIsoZ();+ });+}++// ββ helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Atomic state-machine transition for a pending-payment-request.+ *+ * The naive shape β loadPendingRequest β validate β patch β write β is+ * vulnerable to a textbook lost-update race: two CLI/MCP processes can+ * both read `pending`, both pass the validation, then both write β last+ * writer wins. For an approval workflow that changes financial decisions,+ * that's a correctness bug.+ *+ * `proper-lockfile` (already used by `event-log.ts`) gives us a portable+ * per-file mutex. We hold it across the entire read-modify-write so two+ * concurrent transitions on the same id are serialised: the second one+ * sees the first one's `approved`/`rejected` state and fails the+ * "expectedFrom" check instead of clobbering it.+ */+async function transitionRequest(+ vault: string,+ id: string,+ expectedFrom: RequestStatus,+ newStatus: RequestStatus,+ patch: (meta: FrontmatterMap) => void,+): Promise<PendingRequestOutput> {+ const lockTarget = pendingRequestPath(vault, id);+ // The lock target must exist; if the request file is missing the+ // transition would fail anyway with "not found" β so resolve that+ // first with a cheap pre-check, then take the lock and re-validate.+ const initial = loadPendingRequest(vault, id);+ if (!initial) {+ throw new Error(`pending request not found: ${id}`);+ }++ const release = await lockfile.lock(lockTarget, {+ retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },+ stale: 10_000,+ realpath: false,+ });+ try {+ // Re-load inside the lock β the artefact may have been rewritten+ // between the pre-check and the lock acquisition.+ const loaded = loadPendingRequest(vault, id);+ if (!loaded) {+ throw new Error(`pending request not found: ${id}`);+ }+ if (loaded.status !== expectedFrom) {+ throw new Error(+ `cannot transition request ${id} from ${loaded.status} to ${newStatus} ` ++ `(expected ${expectedFrom})`,+ );+ }+ const newMeta: FrontmatterMap = { ...loaded.metadata };+ newMeta["status"] = newStatus;+ patch(newMeta);+ writeFrontmatterAtomic(loaded.path, newMeta, loaded.body, { overwrite: true });+ return {+ path: loaded.path,+ relativePath: loaded.relativePath,+ id,+ status: newStatus,+ created: frontmatterStr(loaded.metadata["created"]),+ policyDecision: {+ status: parseDecisionStatus(frontmatterStr(loaded.metadata["policy_status"])),+ allowed: frontmatterStr(loaded.metadata["policy_status"]) === "allowed",+ approvalRequired:+ frontmatterStr(loaded.metadata["policy_status"]) === "approval_required",+ reasons: [],+ rule: frontmatterStr(loaded.metadata["policy_rule"]) || null,+ hasPolicy: Boolean(frontmatterStr(loaded.metadata["policy_status"])),+ policyPath: null,+ currency: frontmatterStr(loaded.metadata["currency"]) || null,+ },+ };+ } finally {+ await release();+ }+}++function defaultRequestSlug(+ input: PendingRequestInput,+ date: string,+ time: string,+): string {+ const tail = input.service.split("/").pop() ?? input.service;+ return slugify(`req-${date}-${time.replace(":", "")}-${tail}-${input.reason}`);+}++function renderRequestBody(input: PendingRequestInput, decision: PolicyDecision): string {+ const reason = input.reason.trim();+ const lines: string[] = [+ `# Pending Payment Request: ${reason}`,+ "",+ "## Service",+ "",+ formatCode(input.service),+ "",+ "## Reason",+ "",+ reason,+ "",+ "## Expected cost",+ "",+ typeof input.expectedAmount === "number"+ ? `\`${input.expectedAmount}\`${input.currency ? ` ${input.currency}` : ""}`+ : NOT_PROVIDED,+ "",+ "## Endpoint",+ "",+ formatCode(input.endpoint),+ "",+ "## Expected output",+ "",+ input.expectedOutput?.trim() ?? NOT_PROVIDED,+ "",+ "## Vault files that will change",+ "",+ ];+ if (input.vaultFiles && input.vaultFiles.length > 0) {+ for (const f of input.vaultFiles) lines.push(`- \`${f}\``);+ } else {+ lines.push(NOT_PROVIDED);+ }+ lines.push(+ "",+ "## Policy check",+ "",+ `Status: \`${decision.status}\``,+ );+ if (decision.rule) lines.push(`Rule fired: \`${decision.rule}\``);+ if (decision.reasons.length > 0) {+ lines.push("", "Reasons:", "");+ for (const r of decision.reasons) lines.push(`- ${r}`);+ }+ lines.push(+ "",+ "## How to approve / reject",+ "",+ "Use the `o2b` CLI:",+ "",+ "```bash",+ `o2b approve-payment-request --vault <vault> --id <id> --approved-by <name>`,+ `o2b reject-payment-request --vault <vault> --id <id> --rejected-by <name> [--reason "..."]`,+ "```",+ "",+ "Once approved, the agent will execute the paid call and call",+ "`o2b consume-payment-request` to link the resulting receipt back here.",+ );+ return lines.join("\n");+}++function parseStatus(raw: string): RequestStatus {+ if (+ raw === "pending" ||+ raw === "approved" ||+ raw === "rejected" ||+ raw === "consumed"+ ) {+ return raw;+ }+ // Reject malformed / hand-edited status values rather than silently+ // collapsing to "pending". A receipt that's been manually scrubbed to+ // `status: closed` or whatever should not become actionable as a fresh+ // pending approval. Callers that need to be lenient (e.g. the listing+ // walker) catch this and skip the entry.+ throw new Error(`invalid payment-request status: ${JSON.stringify(raw)}`);+}++function parseDecisionStatus(raw: string): PolicyDecision["status"] {+ if (raw === "denied" || raw === "approval_required") return raw;+ return "allowed";+}++function stem(filename: string): string {+ const dot = filename.lastIndexOf(".");+ return dot > 0 ? filename.slice(0, dot) : filename;+}diff --git a/src/core/pay-memory/asset.ts b/src/core/pay-memory/asset.tsnew file mode 100644index 00000000..8534d777--- /dev/null+++ b/src/core/pay-memory/asset.ts@@ -0,0 +1,104 @@+/**+ * Generated-asset note writer.+ *+ * Saves a Markdown note for an asset (image, file, transcript, ...) produced+ * by a paid API call. Frontmatter links the note back to the originating+ * receipt; the body keeps the prompt and generated URL human-readable.+ */++import type { FrontmatterMap } from "../types.ts";+import { slugify, writeFrontmatterAtomic } from "../vault.ts";+import {+ nowIsoZ,+ NOT_PROVIDED,+ wikiLink,+} from "./_md.ts";+import { assetPath, ensureInsideVault, vaultRelative } from "./paths.ts";+import type { AssetInput, AssetOutput } from "./types.ts";++export const ASSET_FRONTMATTER_TYPE = "generated-asset";++export function writeAsset(vault: string, input: AssetInput): AssetOutput {+ if (!input.title?.trim()) throw new Error("asset requires a title");+ if (!input.service?.trim()) throw new Error("asset requires a service");+ if (!input.resultUrl?.trim()) throw new Error("asset requires a result_url");++ const slug = (input.slug && input.slug.trim()) || slugify(input.title);+ const target = assetPath(vault, slug);+ ensureInsideVault(target, vault);++ const created = nowIsoZ();+ const metadata: FrontmatterMap = {+ type: ASSET_FRONTMATTER_TYPE,+ title: input.title.trim(),+ source: input.service.trim(),+ result_url: input.resultUrl.trim(),+ created,+ };+ if (input.sourceReceipt?.trim()) {+ metadata["source_receipt"] = wikiLink(input.sourceReceipt);+ }+ if (input.usedIn?.trim()) {+ metadata["used_in"] = wikiLink(input.usedIn);+ }++ writeFrontmatterAtomic(target, metadata, renderAssetBody(input), {+ overwrite: input.overwrite,+ existsErrorKind: "asset",+ vaultForRelativePath: vault,+ });++ return {+ path: target,+ relativePath: vaultRelative(target, vault),+ slug,+ created,+ };+}++function renderAssetBody(input: AssetInput): string {+ const title = input.title.trim();+ const usedIn = input.usedIn?.trim();+ const sourceReceipt = input.sourceReceipt?.trim();+ const prompt = input.prompt?.trim();++ const lines: string[] = [`# ${title}`, ""];++ lines.push("## Purpose", "");+ if (usedIn) {+ // Run every wikilink target through the same sanitizer/extension stripper+ // β `usedIn`, `sourceReceipt`, and `resultNote` (in receipts) all become+ // `[[...]]` and a stray `[`/`]` would prematurely close the link.+ lines.push(`Used in: ${wikiLink(usedIn)}`);+ } else {+ lines.push(NOT_PROVIDED);+ }+ lines.push("");++ lines.push("## Prompt", "");+ if (prompt) {+ lines.push(...prompt.split(/\r?\n/).map((line) => (line ? `> ${line}` : ">")));+ } else {+ lines.push(NOT_PROVIDED);+ }+ lines.push("");++ lines.push("## Result", "", `${input.resultUrl.trim()}`, "");++ lines.push("## Source", "");+ lines.push(`Service: \`${input.service.trim().replace(/`/g, "Λ")}\``);+ if (sourceReceipt) {+ lines.push(`Receipt: ${wikiLink(sourceReceipt)}`);+ } else {+ lines.push(`Receipt: ${NOT_PROVIDED}`);+ }+ lines.push("");++ lines.push(+ "## Notes",+ "",+ "Generated through a paid API call recorded in the linked receipt.",+ );+ return lines.join("\n");+}+diff --git a/src/core/pay-memory/digest.ts b/src/core/pay-memory/digest.tsnew file mode 100644index 00000000..4eccb38c--- /dev/null+++ b/src/core/pay-memory/digest.ts@@ -0,0 +1,132 @@+/**+ * Payment digest builder β a small structured summary of a date's receipts+ * suitable for Telegram / Slack delivery via Hermes cron `--script` jobs.+ *+ * Pure functions only: the CLI command and the standalone digest helper+ * both consume `buildPaymentDigest` and `renderPaymentDigestTelegram` so+ * the formatting stays consistent between scripted (cron) and interactive+ * (`o2b payment-digest`) use.+ */++import { aggregateReceipts } from "./report.ts";+import { isoDateNow, validateIsoDate } from "./paths.ts";++export interface PaymentDigest {+ readonly date: string;+ /** Distinct `service` field values across the day's receipts. */+ readonly services: number;+ /** Total receipt count (one per `<slug>.md`). */+ readonly receipts: number;+ /** Sum of `actual_amount` across receipts that share a single currency. */+ readonly totalAmount: number | null;+ /**+ * Currency string when all receipts agree; `null` when there are no+ * receipts with `actual_amount` or when currencies are mixed.+ */+ readonly currency: string | null;+ /** Optional vault-relative path to the report referenced in the digest. */+ readonly reportPath?: string | null;+}++export interface BuildPaymentDigestOptions {+ /** YYYY-MM-DD; defaults to today in `tz`. */+ readonly date?: string | null;+ readonly tz?: string | null;+ /** Optional vault-relative path to attach in the rendered digest. */+ readonly reportPath?: string | null;+}++export function buildPaymentDigest(+ vault: string,+ opts: BuildPaymentDigestOptions = {},+): PaymentDigest {+ const date = validateIsoDate(opts.date ?? isoDateNow(opts.tz));+ const summaries = aggregateReceipts(vault, date);++ const services = new Set(summaries.map((s) => s.service)).size;++ let totalAmount: number | null = null;+ let currency: string | null = null;+ let consistentCurrency: string | null | undefined = undefined;+ let mixedCurrency = false;+ let sum = 0;+ let counted = 0;+ for (const s of summaries) {+ if (!s.actualAmount) continue;+ const n = parseFloat(s.actualAmount);+ if (!Number.isFinite(n)) continue;+ sum += n;+ counted += 1;+ if (consistentCurrency === undefined) {+ consistentCurrency = s.currency;+ } else if (consistentCurrency !== s.currency) {+ consistentCurrency = null;+ mixedCurrency = true;+ }+ }+ if (counted > 0 && !mixedCurrency) {+ // Only emit a numeric total when every receipt shares a single+ // currency. Summing values across different currencies and reporting+ // the sum without a unit is misleading β the renderer will fall back+ // to the "β" placeholder so the user knows the day was mixed.+ totalAmount = sum;+ currency = consistentCurrency ?? null;+ }++ return {+ date,+ services,+ receipts: summaries.length,+ totalAmount,+ currency,+ reportPath: opts.reportPath ?? null,+ };+}++const SILENT_TOKEN = "[SILENT]";++export interface RenderDigestOptions {+ /**+ * What to emit when the digest has zero receipts. `"silent"` (default)+ * returns the literal `[SILENT]` token so a Hermes cron deliverer that+ * recognises it can suppress the message. `"empty"` returns an empty+ * string. `"summary"` returns a single-line "no receipts" notice.+ */+ readonly emptyMode?: "silent" | "empty" | "summary";+}++export function renderPaymentDigestTelegram(+ digest: PaymentDigest,+ opts: RenderDigestOptions = {},+): string {+ const emptyMode = opts.emptyMode ?? "silent";+ if (digest.receipts === 0) {+ if (emptyMode === "empty") return "";+ if (emptyMode === "summary") return `π Pay Memory: Π½Π΅Ρ ΡΠ΅ΠΊΠΎΠ² Π·Π° ${digest.date}.`;+ return SILENT_TOKEN;+ }++ const lines: string[] = [+ `π³ ΠΠΏΠ»Π°ΡΠ΅Π½ΠΎ ΡΠ΅ΡΠ²ΠΈΡΠΎΠ²: **${digest.services}**`,+ ];+ if (digest.totalAmount !== null) {+ const amount = formatAmount(digest.totalAmount);+ const cur = digest.currency ?? "?";+ lines.push(`π° Π‘ΡΠΌΠΌΠ°: **${amount}${cur === "?" ? "" : " " + cur}**`);+ } else {+ lines.push(`π° Π‘ΡΠΌΠΌΠ°: **β**`);+ }+ lines.push(`π Π€Π°ΠΉΠ»Ρ ΡΠ΅ΠΊΠΎΠ²: **${digest.receipts}**`);+ if (digest.reportPath) {+ lines.push(`π ΠΡΡΡΡ: \`${digest.reportPath}\``);+ }+ return lines.join("\n");+}++function formatAmount(n: number): string {+ // Trim trailing zeros after the decimal but keep meaningful precision.+ const fixed = n.toFixed(6);+ return fixed.replace(/\.?0+$/, "") || "0";+}++export const DIGEST_SILENT_TOKEN = SILENT_TOKEN;diff --git a/src/core/pay-memory/index.ts b/src/core/pay-memory/index.tsnew file mode 100644index 00000000..f62fe758--- /dev/null+++ b/src/core/pay-memory/index.ts@@ -0,0 +1,90 @@+/**+ * Public surface of the Pay Memory layer. CLI and MCP entry points import+ * from this barrel; the underlying modules stay internal so we can move+ * private helpers around without breaking call sites.+ */++// Public path helpers used by CLI / MCP / OpenClaw runtime adapters. The+// internal-only path constructors (`paymentsDateDir`, `receiptPath`,+// `assetPath`, `reportPath`) and date validators stay private to the+// pay-memory package β adapters only need to know about the directory+// roots and the vault-relative renderer.+export {+ payMemoryDirs,+ policyPath,+ vaultRelative as vaultRelativePath,+} from "./paths.ts";+export type { PayMemoryDirs } from "./paths.ts";++export { redactRawOutput, SECRET_KEYS } from "./redactor.ts";++export {+ DEFAULT_POLICY_TEMPLATE,+ writePolicyIfMissing,+ readPolicy,+} from "./policy.ts";+export type { WritePolicyOptions, WritePolicyResult } from "./policy.ts";++export { writeReceipt, RECEIPT_FRONTMATTER_TYPE } from "./receipt.ts";++export { writeAsset, ASSET_FRONTMATTER_TYPE } from "./asset.ts";++export {+ aggregateReceipts,+ writeReport,+ REPORT_FRONTMATTER_TYPE,+} from "./report.ts";++export {+ POLICY_SCHEMA_VERSION,+ policyJsonPath,+ loadPolicyRules,+ evaluatePolicy,+ checkPolicy,+} from "./policy-rules.ts";+export type {+ PolicyRules,+ PolicyCheckRequest,+ PolicyDecision,+ PolicyDecisionStatus,+} from "./policy-rules.ts";++export {+ buildPaymentDigest,+ renderPaymentDigestTelegram,+ DIGEST_SILENT_TOKEN,+} from "./digest.ts";+export type { PaymentDigest, BuildPaymentDigestOptions, RenderDigestOptions } from "./digest.ts";++export {+ PENDING_REQUEST_FRONTMATTER_TYPE,+ pendingDir,+ pendingRequestPath,+ writePendingRequest,+ loadPendingRequest,+ listPendingRequests,+ approvePendingRequest,+ rejectPendingRequest,+ consumePendingRequest,+} from "./approval.ts";+export type {+ RequestStatus,+ PendingRequestInput,+ PendingRequestOutput,+ PendingRequestSummary,+ ListPendingRequestsOptions,+ ApproveOptions,+ RejectOptions,+ ConsumeOptions,+ LoadedPendingRequest,+} from "./approval.ts";++export type {+ ReceiptInput,+ ReceiptOutput,+ AssetInput,+ AssetOutput,+ ReportInput,+ ReportOutput,+ PaymentReceiptSummary,+} from "./types.ts";diff --git a/src/core/pay-memory/paths.ts b/src/core/pay-memory/paths.tsnew file mode 100644index 00000000..babe1472--- /dev/null+++ b/src/core/pay-memory/paths.ts@@ -0,0 +1,224 @@+/**+ * Filesystem paths and date utilities for the Pay Memory layout.+ *+ * The layout sits inside `<vault>/AI Wiki/`:+ * - policies/spending.md+ * - payments/YYYY-MM-DD/<slug>.md+ * - assets/<slug>.md+ * - drafts/<slug>.md (written by other tools β kept here for completeness)+ * - reports/<slug>.md+ *+ * Date subdirectories use the hyphenated `YYYY-MM-DD` form (ISO 8601 calendar+ * date). This intentionally differs from the dotted `YYYY.MM.DD` used by the+ * Daily event log β the two systems are independent.+ */++import { join } from "node:path";++export {+ ensureInsideVault,+ vaultRelative,+} from "../path-safety.ts";++const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;+const HHMM_RE = /^(\d{2}):(\d{2})$/;++export interface PayMemoryDirs {+ readonly policies: string;+ readonly payments: string;+ readonly assets: string;+ readonly drafts: string;+ readonly reports: string;+}++export function payMemoryDirs(vault: string): PayMemoryDirs {+ const root = join(vault, "AI Wiki");+ return {+ policies: join(root, "policies"),+ payments: join(root, "payments"),+ assets: join(root, "assets"),+ drafts: join(root, "drafts"),+ reports: join(root, "reports"),+ };+}++export function policyPath(vault: string): string {+ return join(payMemoryDirs(vault).policies, "spending.md");+}++export function paymentsDateDir(vault: string, date: string): string {+ return join(payMemoryDirs(vault).payments, validateIsoDate(date));+}++export function receiptPath(vault: string, date: string, slug: string): string {+ return join(paymentsDateDir(vault, date), `${validateSlug(slug)}.md`);+}++export function assetPath(vault: string, slug: string): string {+ return join(payMemoryDirs(vault).assets, `${validateSlug(slug)}.md`);+}++export function reportPath(vault: string, slug: string): string {+ return join(payMemoryDirs(vault).reports, `${validateSlug(slug)}.md`);+}++// Windows reserves a small set of base filenames (case-insensitive) and+// rejects any path whose final component matches them β even with an+// extension. We reject these here so the same vault can be cloned to a+// Windows host without surprise EINVALs at write time.+const WINDOWS_RESERVED_BASENAME_RE =+ /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;++/**+ * Reject slugs that could escape the intended Pay Memory subdirectory or+ * (under `..` traversal) silently land elsewhere in the vault, plus a few+ * Windows-specific filename hazards so the artefact is portable.+ *+ * `ensureInsideVault` would still catch a slug that resolves outside the+ * vault root, but a slug like `../etc/passwd` resolves to a sibling vault+ * directory which is technically inside the vault β defense in depth.+ */+export function validateSlug(slug: string): string {+ const trimmed = slug.trim();+ if (!trimmed) throw new Error("slug must not be empty");+ if (trimmed.includes("/") || trimmed.includes("\\")) {+ throw new Error(`slug must not contain path separators: ${slug}`);+ }+ if (trimmed === ".." || trimmed === "." || /(?:^|[^\w])\.\.(?:$|[^\w])/.test(trimmed)) {+ throw new Error(`slug must not contain '..' traversal: ${slug}`);+ }+ if (/[. ]$/.test(trimmed)) {+ throw new Error(+ `slug must not end with '.' or whitespace (Windows-incompatible): ${slug}`,+ );+ }+ if (WINDOWS_RESERVED_BASENAME_RE.test(trimmed)) {+ throw new Error(`slug uses a Windows-reserved filename: ${slug}`);+ }+ return trimmed;+}++/** Validate `YYYY-MM-DD`. Throws on bad shape or invalid calendar date. */+export function validateIsoDate(value: string): string {+ const m = ISO_DATE_RE.exec(value);+ if (!m) {+ throw new Error("payment date must use YYYY-MM-DD format");+ }+ const year = parseInt(m[1]!, 10);+ const month = parseInt(m[2]!, 10);+ const day = parseInt(m[3]!, 10);+ const utc = new Date(Date.UTC(year, month - 1, day));+ if (+ utc.getUTCFullYear() !== year ||+ utc.getUTCMonth() !== month - 1 ||+ utc.getUTCDate() !== day+ ) {+ throw new Error(`payment date is not a valid calendar date: ${value}`);+ }+ return value;+}++/** Validate `HH:MM` 24-hour time. Throws on bad shape. Mirrors event-log. */+export function validateIsoTime(value: string): string {+ const m = HHMM_RE.exec(value);+ if (!m) {+ throw new Error("payment time must use HH:MM 24-hour format");+ }+ const hour = parseInt(m[1]!, 10);+ const minute = parseInt(m[2]!, 10);+ if (hour > 23 || minute > 59) {+ throw new Error(+ `payment time out of range: ${value} (hour must be 0-23, minute 0-59)`,+ );+ }+ return value;+}++/** Today's date as `YYYY-MM-DD` in `tz` (or host local). */+export function isoDateNow(tz?: string | null): string {+ const fmt = new Intl.DateTimeFormat("en-CA", {+ timeZone: tz ?? undefined,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ return fmt.format(new Date());+}++/** Current time as `HH:MM` (24h) in `tz` (or host local). */+export function isoTimeNow(tz?: string | null): string {+ const parts = new Intl.DateTimeFormat("en-US", {+ timeZone: tz ?? undefined,+ hour: "2-digit",+ minute: "2-digit",+ hourCycle: "h23",+ }).formatToParts(new Date());+ const get = (type: string) => parts.find((p) => p.type === type)!.value;+ return `${get("hour")}:${get("minute")}`;+}++/**+ * Compose an ISO Z timestamp from a `YYYY-MM-DD` + `HH:MM` pair, treating+ * the supplied wall-clock as occurring in `tz` (or UTC if `tz` is null).+ *+ * Without `tz`, the wall-clock is taken to already be UTC and we emit the+ * `Z` form directly. With a `tz`, we compute that zone's offset for the+ * given instant and shift the wall-clock to a true UTC moment β so a+ * 09:00 Belgrade event becomes the correct `07:00Z` (or `06:00Z` outside+ * DST) instead of falsely labelling 09:00 itself as `Z`.+ *+ * The offset trick uses `Intl.DateTimeFormat` to format the same instant+ * twice (in UTC and in `tz`) and reads the difference. It's accurate to+ * the minute for every IANA zone except during the one-hour DST overlap,+ * where the choice is arbitrary β acceptable for a Markdown audit trail.+ */+export function isoTimestampZ(date: string, time: string, tz?: string | null): string {+ validateIsoDate(date);+ validateIsoTime(time);+ if (!tz) {+ return `${date}T${time}:00Z`;+ }+ const utcMillis = utcMillisForLocalWallClock(date, time, tz);+ return new Date(utcMillis).toISOString().replace(/\.\d{3}Z$/, "Z");+}++/**+ * Given a wall-clock `YYYY-MM-DD HH:MM` interpreted as occurring in IANA+ * `tz`, return the corresponding UTC milliseconds-since-epoch.+ *+ * Strategy: take the naive UTC instant for the literal wall-clock, then+ * subtract the offset between UTC and `tz` at that instant. That gives+ * the real UTC moment whose local-tz formatting matches the input.+ */+function utcMillisForLocalWallClock(date: string, time: string, tz: string): number {+ const naiveUtc = Date.parse(`${date}T${time}:00Z`);+ const offsetMinutes = tzOffsetMinutes(naiveUtc, tz);+ return naiveUtc - offsetMinutes * 60_000;+}++function tzOffsetMinutes(instantMs: number, tz: string): number {+ // Format the same instant in both `tz` and UTC; the spread between the+ // two formatted wall-clocks IS the zone's offset at that instant.+ const fmt = new Intl.DateTimeFormat("en-US", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ hourCycle: "h23",+ });+ const parts = fmt.formatToParts(new Date(instantMs));+ const get = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? "0");+ const localUtcMs = Date.UTC(+ get("year"),+ get("month") - 1,+ get("day"),+ get("hour"),+ get("minute"),+ get("second"),+ );+ return Math.round((localUtcMs - instantMs) / 60_000);+}+diff --git a/src/core/pay-memory/policy-rules.ts b/src/core/pay-memory/policy-rules.tsnew file mode 100644index 00000000..06571e96--- /dev/null+++ b/src/core/pay-memory/policy-rules.ts@@ -0,0 +1,339 @@+/**+ * Machine-readable spending policy (`AI Wiki/policies/spending.json`).+ *+ * Optional, opt-in companion to `spending.md`. When the JSON file is present,+ * it can be evaluated by the agent (or by `o2b check-payment-policy`) before+ * making a paid call to decide whether the call is allowed, requires user+ * approval, or is outright denied.+ *+ * Absence of the JSON file β‘ fail-open (`allowed: true`, `has_policy: false`).+ * The rationale is that the policy MVP is documentation-first; opt-in+ * enforcement should not silently block existing flows that have only the+ * Markdown policy. Once a user creates the JSON file, it becomes+ * authoritative.+ */++import { readFileSync } from "node:fs";+import { join } from "node:path";++import { aggregateReceipts } from "./report.ts";+import { isoDateNow, payMemoryDirs, validateIsoDate } from "./paths.ts";++export const POLICY_SCHEMA_VERSION = 1;++/**+ * Schema for `AI Wiki/policies/spending.json`. All fields are optional β+ * unspecified rules are interpreted as "no constraint".+ */+export interface PolicyRules {+ readonly schema_version?: number;+ /** Currency code all monetary fields are denominated in (default `USDC`). */+ readonly currency?: string;+ /** Maximum sum of `actual_amount` allowed across receipts on a single date. */+ readonly max_total_per_day?: number;+ /** Maximum amount allowed for a single paid call. */+ readonly max_single_call?: number;+ /** Service identifiers (e.g. `paysponge/fal`) the agent may call. */+ readonly allowed_services?: ReadonlyArray<string>;+ /** Per-category receipt-count caps for one date (e.g. `{ media_generation: 1 }`). */+ readonly max_per_category?: Readonly<Record<string, number>>;+ /** Above this amount the call requires explicit human approval. */+ readonly require_approval_above?: number;+}++export interface PolicyCheckRequest {+ readonly service: string;+ readonly expectedAmount?: number | null;+ readonly currency?: string | null;+ readonly category?: string | null;+ /** Date of the prospective receipt (YYYY-MM-DD). Defaults to today. */+ readonly date?: string | null;+ readonly tz?: string | null;+}++export type PolicyDecisionStatus = "allowed" | "approval_required" | "denied";++export interface PolicyDecision {+ readonly status: PolicyDecisionStatus;+ readonly allowed: boolean;+ readonly approvalRequired: boolean;+ readonly reasons: ReadonlyArray<string>;+ readonly rule: string | null;+ readonly hasPolicy: boolean;+ readonly policyPath: string | null;+ readonly currency: string | null;+}++/** Return the absolute path of the JSON policy file. */+export function policyJsonPath(vault: string): string {+ return join(payMemoryDirs(vault).policies, "spending.json");+}++/**+ * Load and validate `policies/spending.json` if it exists. Returns `null`+ * when the file is absent. Throws a descriptive error when present but+ * malformed β refusing to silently degrade to "no policy" if the user+ * intended one and miswrote the JSON.+ */+export function loadPolicyRules(vault: string): PolicyRules | null {+ const target = policyJsonPath(vault);+ let text: string;+ try {+ text = readFileSync(target, "utf8");+ } catch (err) {+ // Race-free absent-file handling: try the read first; only translate+ // ENOENT into a `null` return. Other I/O errors (EACCES, EISDIR β¦)+ // are surfaced so the user sees the real cause.+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return null;+ throw new Error(+ `failed to read ${target}: ${(err as Error).message ?? String(err)}`,+ );+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch (err) {+ throw new Error(+ `${target} is not valid JSON: ${(err as Error).message ?? String(err)}`,+ );+ }+ return validatePolicyRules(parsed, target);+}++function validatePolicyRules(value: unknown, source: string): PolicyRules {+ if (typeof value !== "object" || value === null || Array.isArray(value)) {+ throw new Error(`${source} must be a JSON object at the root`);+ }+ const obj = value as Record<string, unknown>;++ const out: Record<string, unknown> = {};++ if ("schema_version" in obj) {+ const v = obj["schema_version"];+ if (typeof v !== "number") {+ throw new Error(`${source}: schema_version must be a number`);+ }+ // Fail-fast on unsupported versions instead of silently degrading to v1+ // semantics. A future schema bump will change field meanings (e.g. new+ // amount-rule shapes), so misreading v2 as v1 could approve calls the+ // user thought they had blocked.+ if (v !== POLICY_SCHEMA_VERSION) {+ throw new Error(+ `${source}: unsupported schema_version ${v}; expected ${POLICY_SCHEMA_VERSION}. ` ++ "Upgrade Open Second Brain or roll the policy back to the matching schema.",+ );+ }+ out["schema_version"] = v;+ }+ if ("currency" in obj) {+ if (typeof obj["currency"] !== "string") {+ throw new Error(`${source}: currency must be a string`);+ }+ out["currency"] = obj["currency"];+ }+ for (const k of ["max_total_per_day", "max_single_call", "require_approval_above"] as const) {+ if (k in obj) {+ const v = obj[k];+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {+ throw new Error(`${source}: ${k} must be a non-negative finite number`);+ }+ out[k] = v;+ }+ }+ if ("allowed_services" in obj) {+ const v = obj["allowed_services"];+ if (!Array.isArray(v) || !v.every((s) => typeof s === "string")) {+ throw new Error(`${source}: allowed_services must be an array of strings`);+ }+ out["allowed_services"] = [...v] as string[];+ }+ if ("max_per_category" in obj) {+ const v = obj["max_per_category"];+ if (typeof v !== "object" || v === null || Array.isArray(v)) {+ throw new Error(`${source}: max_per_category must be an object`);+ }+ const map: Record<string, number> = {};+ for (const [k, n] of Object.entries(v as Record<string, unknown>)) {+ if (typeof n !== "number" || !Number.isInteger(n) || n < 0) {+ throw new Error(+ `${source}: max_per_category.${k} must be a non-negative integer`,+ );+ }+ map[k] = n;+ }+ out["max_per_category"] = map;+ }+ return out as PolicyRules;+}++/**+ * Evaluate a prospective paid call against the loaded policy. Pure function+ * β does not read or write any file. The caller is expected to have already+ * loaded the policy and pre-aggregated today's receipts (or the helper+ * `checkPolicy` below will do both).+ */+export function evaluatePolicy(+ rules: PolicyRules | null,+ request: PolicyCheckRequest,+ context: { readonly daySpend: number; readonly dayCategoryCount: number },+): PolicyDecision {+ if (!rules) {+ return {+ status: "allowed",+ allowed: true,+ approvalRequired: false,+ reasons: [],+ rule: null,+ hasPolicy: false,+ policyPath: null,+ currency: null,+ };+ }++ const reasons: string[] = [];+ let denyRule: string | null = null;+ let approvalRule: string | null = null;+ const policyCurrency = rules.currency ?? "USDC";++ // 1. Allowlist on `service`.+ if (rules.allowed_services && rules.allowed_services.length > 0) {+ if (!rules.allowed_services.includes(request.service)) {+ reasons.push(+ `service ${JSON.stringify(request.service)} is not in allowed_services`,+ );+ denyRule ??= "allowed_services";+ }+ }++ // 2. Currency mismatch β non-fatal, but flagged so caller knows.+ const reqCurrency = request.currency ?? policyCurrency;+ if (request.currency && request.currency !== policyCurrency) {+ reasons.push(+ `request currency ${request.currency} differs from policy ${policyCurrency} β ` ++ "amount-based limits cannot be evaluated; please normalize before checking",+ );+ denyRule ??= "currency_mismatch";+ }++ const amount = typeof request.expectedAmount === "number" ? request.expectedAmount : null;++ // 2b. Missing-amount guard. If the policy declares any amount-based+ // rule, an absent `expected_amount` cannot be evaluated against it+ // and we MUST NOT fail-open: an agent that omits the amount would+ // otherwise bypass the daily budget, the single-call cap, and the+ // approval threshold simultaneously. We require explicit user+ // approval in that case (denial would also be defensible, but+ // `approval_required` keeps the door open for low-stakes prices+ // the agent honestly cannot estimate).+ if (+ amount === null &&+ (rules.max_single_call !== undefined ||+ rules.max_total_per_day !== undefined ||+ rules.require_approval_above !== undefined)+ ) {+ reasons.push(+ "expected_amount is required to evaluate amount-based policy rules; " ++ "request human approval explicitly",+ );+ approvalRule ??= "missing_expected_amount";+ }++ // 3. Single-call cap.+ if (+ rules.max_single_call !== undefined &&+ amount !== null &&+ amount > rules.max_single_call+ ) {+ reasons.push(+ `expected amount ${amount} ${reqCurrency} exceeds max_single_call ` ++ `${rules.max_single_call} ${policyCurrency}`,+ );+ denyRule ??= "max_single_call";+ }++ // 4. Day-budget cap (sum of recorded actuals + this expected).+ if (+ rules.max_total_per_day !== undefined &&+ amount !== null &&+ context.daySpend + amount > rules.max_total_per_day+ ) {+ reasons.push(+ `daily spend ${context.daySpend} + ${amount} = ${context.daySpend + amount} ` ++ `exceeds max_total_per_day ${rules.max_total_per_day} ${policyCurrency}`,+ );+ denyRule ??= "max_total_per_day";+ }++ // 5. Per-category count cap.+ if (request.category && rules.max_per_category) {+ const cap = rules.max_per_category[request.category];+ if (cap !== undefined && context.dayCategoryCount >= cap) {+ reasons.push(+ `category '${request.category}' already has ${context.dayCategoryCount} ` ++ `receipt(s) today; cap is ${cap}`,+ );+ denyRule ??= "max_per_category";+ }+ }++ // 6. Approval threshold (soft gate; only marks if otherwise allowed).+ if (+ rules.require_approval_above !== undefined &&+ amount !== null &&+ amount > rules.require_approval_above+ ) {+ approvalRule = "require_approval_above";+ reasons.push(+ `expected amount ${amount} ${reqCurrency} exceeds approval threshold ` ++ `${rules.require_approval_above} ${policyCurrency}`,+ );+ }++ const status: PolicyDecisionStatus = denyRule+ ? "denied"+ : approvalRule+ ? "approval_required"+ : "allowed";++ return {+ status,+ allowed: status === "allowed",+ approvalRequired: status === "approval_required",+ reasons,+ rule: denyRule ?? approvalRule,+ hasPolicy: true,+ policyPath: null, // set by `checkPolicy` wrapper that knows the source+ currency: policyCurrency,+ };+}++/**+ * Top-level convenience: load the policy, aggregate today's receipts to+ * compute spend/count context, and evaluate.+ */+export function checkPolicy(+ vault: string,+ request: PolicyCheckRequest,+): PolicyDecision {+ const rules = loadPolicyRules(vault);+ const date = validateIsoDate(request.date ?? isoDateNow(request.tz));+ const summaries = aggregateReceipts(vault, date);+ const policyCurrency = rules?.currency ?? "USDC";++ let daySpend = 0;+ for (const s of summaries) {+ if (!s.actualAmount) continue;+ if (s.currency && s.currency !== policyCurrency) continue;+ const n = parseFloat(s.actualAmount);+ if (Number.isFinite(n)) daySpend += n;+ }+ const dayCategoryCount = request.category+ ? summaries.filter((s) => s.category === request.category).length+ : 0;++ const decision = evaluatePolicy(rules, request, { daySpend, dayCategoryCount });+ return {+ ...decision,+ policyPath: rules ? policyJsonPath(vault) : null,+ };+}diff --git a/src/core/pay-memory/policy.ts b/src/core/pay-memory/policy.tsnew file mode 100644index 00000000..430a80d4--- /dev/null+++ b/src/core/pay-memory/policy.ts@@ -0,0 +1,139 @@+/**+ * Spending-policy template writer.+ *+ * Pay Memory does not enforce policy at runtime β this MVP ships a Markdown+ * document that the agent must read before paying and reference in the+ * receipt. The default template uses generic placeholders so it does not+ * pin a specific paid service; a commented-out `paysponge/fal` example sits+ * inside the file as a reference for demo flows.+ */++import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname } from "node:path";++import {+ atomicCreateFileSyncExclusive,+ atomicWriteFileSync,+} from "../fs-atomic.ts";+import { policyPath } from "./paths.ts";++export const DEFAULT_POLICY_TEMPLATE = `# Agent Spending Policy++This file is read by the agent before any paid action. The agent MUST cite+this policy in the resulting payment receipt.++This MVP does not enforce limits at the payment layer. The policy exists so+that a human reviewer can see, after the fact, which rules the agent agreed+to follow.++## Budget++- Max total spend for the current task: TODO (e.g. $0.10)+- Max single paid call: TODO (e.g. $0.07)+- Max paid generations per task: TODO (e.g. 1)+- Approve repeats: false+- Approve dynamic pricing: false++## Allowed services++List the services the agent is allowed to call. One per line. Edit before+running a paid task.++- TODO++<!--+Example for the OpenSecondBrain hackathon demo:++- paysponge/fal+-->++## Required before each paid call++The agent must state:++- service name+- expected price range+- reason for payment+- expected output+- which vault files will be created or updated++## Required after each paid call++The agent must save:++- raw payment-tool output (after redaction)+- payment amount, if available+- service endpoint, if available+- generated asset URL or response identifier+- payment receipt note in \`AI Wiki/payments/<date>/\`+- daily event log entry referencing the receipt+`;++export type PolicyWriteStatus = "created" | "overwritten" | "skipped";++export interface WritePolicyResult {+ readonly path: string;+ readonly status: PolicyWriteStatus;+ readonly created: boolean;+ readonly overwritten: boolean;+ readonly skipped: boolean;+}++export interface WritePolicyOptions {+ readonly overwrite?: boolean;+}++export function writePolicyIfMissing(+ vault: string,+ opts: WritePolicyOptions = {},+): WritePolicyResult {+ const target = policyPath(vault);+ const overwrite = opts.overwrite ?? false;+ mkdirSync(dirname(target), { recursive: true });++ if (overwrite) {+ // existsSync here is only for the report status (created vs overwritten);+ // the actual write is atomic regardless. A torn read of the result+ // status under concurrent overwrite is acceptable β disk state is+ // always correct.+ const existed = existsSync(target);+ atomicWriteFileSync(target, DEFAULT_POLICY_TEMPLATE);+ return existed+ ? buildPolicyResult(target, "overwritten")+ : buildPolicyResult(target, "created");+ }++ // Race-free "create only if missing": link(2) returns EEXIST atomically.+ try {+ atomicCreateFileSyncExclusive(target, DEFAULT_POLICY_TEMPLATE);+ return buildPolicyResult(target, "created");+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === "EEXIST") {+ return buildPolicyResult(target, "skipped");+ }+ throw err;+ }+}++function buildPolicyResult(path: string, status: PolicyWriteStatus): WritePolicyResult {+ return {+ path,+ status,+ created: status === "created",+ overwritten: status === "overwritten",+ skipped: status === "skipped",+ };+}++/** Read the spending policy file if it exists; returns null otherwise. */+export function readPolicy(vault: string): string | null {+ const target = policyPath(vault);+ // Single try-read avoids the existsSyncβreadFileSync TOCTOU window: if+ // the file is removed between the two calls we'd otherwise throw ENOENT+ // instead of returning null per the documented contract.+ try {+ return readFileSync(target, "utf8");+ } catch {+ return null;+ }+}diff --git a/src/core/pay-memory/receipt.ts b/src/core/pay-memory/receipt.tsnew file mode 100644index 00000000..04ab58ef--- /dev/null+++ b/src/core/pay-memory/receipt.ts@@ -0,0 +1,272 @@+/**+ * Payment receipt writer.+ *+ * Builds the deterministic Markdown receipt described in the spec. Optional+ * fields fall back to a `_(not provided)_` placeholder in the body so every+ * receipt has the same set of headings and is uniformly searchable. Frontmatter+ * keys are only emitted when the input value is non-empty β this keeps the+ * report aggregator simple (presence == relevant) and avoids littering the+ * vault with empty quoted strings.+ */++import type { FrontmatterMap } from "../types.ts";+import { slugify, writeFrontmatterAtomic } from "../vault.ts";+import {+ formatCode,+ NOT_PROVIDED,+ putIfPresent,+ sanitizeWikilinkTarget,+ stripMarkdownExt,+} from "./_md.ts";+import {+ ensureInsideVault,+ isoDateNow,+ isoTimeNow,+ isoTimestampZ,+ receiptPath,+ validateIsoDate,+ validateIsoTime,+ vaultRelative,+} from "./paths.ts";+import { redactRawOutput } from "./redactor.ts";+import type { ReceiptInput, ReceiptOutput } from "./types.ts";++export const RECEIPT_FRONTMATTER_TYPE = "agent-payment-receipt";++export function writeReceipt(vault: string, input: ReceiptInput): ReceiptOutput {+ if (!input.service?.trim()) throw new Error("receipt requires a service");+ if (!input.status?.trim()) throw new Error("receipt requires a status");+ if (!input.reason?.trim()) throw new Error("receipt requires a reason");+ if (!input.agent?.trim()) throw new Error("receipt requires an agent");++ const tz = input.tz ?? null;+ const date = validateIsoDate(input.date ?? isoDateNow(tz));+ const time = validateIsoTime(input.time ?? isoTimeNow(tz));+ const slug = (input.slug && input.slug.trim()) || defaultReceiptSlug(input.service, input.reason);++ const target = receiptPath(vault, date, slug);+ ensureInsideVault(target, vault);++ const created = isoTimestampZ(date, time, tz);+ const paymentLayer = input.paymentLayer?.trim() || "pay.sh";+ const network = input.network?.trim() || "solana";+ const metadata: FrontmatterMap = {+ type: RECEIPT_FRONTMATTER_TYPE,+ agent: input.agent.trim(),+ payment_layer: paymentLayer,+ network,+ service: input.service.trim(),+ status: input.status.trim(),+ reason: input.reason.trim(),+ created,+ };+ if (tz) metadata["timezone"] = tz;+ putIfPresent(metadata, "category", input.category);+ putIfPresent(metadata, "endpoint", input.endpoint);+ putIfPresent(metadata, "expected_cost", input.expectedCost);+ putIfPresent(metadata, "actual_amount", input.actualAmount);+ putIfPresent(metadata, "currency", input.currency);+ putIfPresent(metadata, "payment_proof", input.paymentProof);+ putIfPresent(metadata, "result_ref", input.resultRef);+ putIfPresent(metadata, "result_note", input.resultNote);++ // Policy + approval audit fields. Always emit `policy_status` so a+ // human reading the receipt can tell the difference between "we+ // checked and it was allowed" and "we never checked" β the latter is+ // not a problem in itself, but it must not masquerade as the former.+ metadata["policy_status"] = input.policyStatus ?? "not_checked";+ putIfPresent(metadata, "policy_rule", input.policyRule);+ if (input.policyReasons && input.policyReasons.length > 0) {+ metadata["policy_reasons"] = [...input.policyReasons];+ }+ putIfPresent(metadata, "policy_checked_at", input.policyCheckedAt);+ putIfPresent(metadata, "approval_request", input.approvalRequestId);+ putIfPresent(metadata, "approval_status", input.approvalStatus);+ putIfPresent(metadata, "approved_by", input.approvedBy);+ putIfPresent(metadata, "approved_at", input.approvedAt);++ const body = renderReceiptBody(input);+ writeFrontmatterAtomic(target, metadata, body, {+ overwrite: input.overwrite,+ existsErrorKind: "receipt",+ vaultForRelativePath: vault,+ });++ return {+ path: target,+ relativePath: vaultRelative(target, vault),+ slug,+ date,+ created,+ };+}++function defaultReceiptSlug(service: string, reason: string): string {+ const tail = service.split("/").pop() ?? service;+ return slugify(`${tail}-${reason}`);+}++/**+ * Render the body of the "Spending policy check" section. The previous+ * version always claimed the policy approved the call β which is a lie+ * when the caller never ran a policy check at all, when the check+ * returned `denied`, or when the call was waved through by a human+ * after `approval_required`. This version shows the real state.+ */+function renderPolicySection(input: ReceiptInput): string[] {+ const status = input.policyStatus ?? "not_checked";+ const out: string[] = ["Decision:", ""];+ switch (status) {+ case "allowed":+ out.push(+ "Allowed by the configured spending policy. The agent ran a policy",+ "check before initiating this paid call.",+ );+ break;+ case "approval_required":+ out.push(+ "Policy returned `approval_required` β a human approval was needed",+ "before initiating this paid call.",+ );+ break;+ case "denied":+ out.push(+ "Policy returned `denied` β this receipt records a paid call that",+ "the policy did not approve. If the call still proceeded, a human",+ "explicitly waved the policy aside; check the approval section",+ "below for who and why.",+ );+ break;+ case "not_checked":+ default:+ out.push(+ "Not checked. The receipt was created without a policy decision β",+ "either no `AI Wiki/policies/spending.json` is configured, or the",+ "caller chose not to evaluate the policy. This is *not* a claim",+ "that the call was allowed.",+ );+ break;+ }+ if (input.policyRule?.trim()) {+ out.push("", `Rule fired: \`${input.policyRule.trim()}\``);+ }+ if (input.policyReasons && input.policyReasons.length > 0) {+ out.push("", "Reasons:", "");+ for (const r of input.policyReasons) out.push(`- ${r}`);+ }+ if (input.policyCheckedAt?.trim()) {+ out.push("", `Policy checked at: \`${input.policyCheckedAt.trim()}\``);+ }+ if (+ input.approvalRequestId?.trim() ||+ input.approvalStatus?.trim() ||+ input.approvedBy?.trim()+ ) {+ out.push("", "Approval:");+ if (input.approvalRequestId?.trim()) {+ out.push(+ "",+ `Request: [[AI Wiki/payments/_pending/${input.approvalRequestId.trim()}]]`,+ );+ }+ if (input.approvalStatus?.trim()) {+ out.push(`Status: \`${input.approvalStatus.trim()}\``);+ }+ if (input.approvedBy?.trim()) {+ out.push(`Approved by: ${input.approvedBy.trim()}`);+ }+ if (input.approvedAt?.trim()) {+ out.push(`Approved at: \`${input.approvedAt.trim()}\``);+ }+ }+ out.push("");+ return out;+}++function fieldOrPlaceholder(value: string | null | undefined): string {+ if (value === null || value === undefined) return NOT_PROVIDED;+ const trimmed = String(value).trim();+ return trimmed || NOT_PROVIDED;+}++function renderReceiptBody(input: ReceiptInput): string {+ const reason = input.reason.trim();+ const title = `Payment Receipt: ${reason}`;+ const resultNote = input.resultNote?.trim();+ const resultNoteLine = resultNote+ ? `[[${stripMarkdownExt(sanitizeWikilinkTarget(resultNote))}]]`+ : NOT_PROVIDED;+ const rawOutput = input.rawOutput ? redactRawOutput(input.rawOutput) : null;++ const lines: string[] = [+ `# ${title}`,+ "",+ "## Why this paid call was made",+ "",+ reason,+ "",+ "## Spending policy check",+ "",+ "Policy file:",+ "",+ "[[AI Wiki/policies/spending]]",+ "",+ ...renderPolicySection(input),+ "## Expected cost",+ "",+ fieldOrPlaceholder(input.expectedCost),+ "",+ "## Request",+ "",+ "Service:",+ "",+ formatCode(input.service),+ "",+ "Endpoint:",+ "",+ formatCode(input.endpoint),+ "",+ "Reason:",+ "",+ reason,+ "",+ "## Payment",+ "",+ "Amount:",+ "",+ formatCode(input.actualAmount),+ "",+ "Currency:",+ "",+ formatCode(input.currency),+ "",+ "Payment proof / transaction / receipt:",+ "",+ formatCode(input.paymentProof),+ "",+ "## Result",+ "",+ "Generated asset:",+ "",+ formatCode(input.resultRef),+ "",+ "Asset note:",+ "",+ resultNoteLine,+ "",+ "## Raw pay.sh output",+ "",+ ];+ if (rawOutput) {+ lines.push("```text", rawOutput.replace(/\r\n?/g, "\n").replace(/\s+$/g, ""), "```");+ } else {+ lines.push(NOT_PROVIDED);+ }+ lines.push(+ "",+ "> Verify raw output above does not contain credentials before sharing this",+ "> receipt outside the vault. Best-effort redaction has been applied.",+ );+ return lines.join("\n");+}+diff --git a/src/core/pay-memory/redactor.ts b/src/core/pay-memory/redactor.tsnew file mode 100644index 00000000..314002a2--- /dev/null+++ b/src/core/pay-memory/redactor.ts@@ -0,0 +1,126 @@+/**+ * Best-effort redactor for raw payment-tool output before it lands in a+ * Markdown receipt.+ *+ * Six secret-bearing keys are recognized in four assignment shapes:+ *+ * key=value env-style assignments+ * key: value YAML / log lines / single-line `key: token`+ * "key": "value" JSON object entries+ * Authorization: Bearer <token> HTTP authorization header (special case)+ *+ * Each match keeps the key (and surrounding quoting) and replaces the value+ * with the literal `***REDACTED***`. The transform is intentionally narrow β+ * the receipt body still carries a disclaimer that the agent must visually+ * inspect output before posting it externally.+ */++const PLACEHOLDER = "***REDACTED***";++/**+ * Maximum input size accepted by `redactRawOutput`. Receipts have no+ * legitimate reason to embed multi-megabyte payloads β a runaway pipe of+ * server logs is the realistic cause of an oversize input. Capping at+ * 256 KB keeps the four-pass regex pipeline bounded and avoids a DoS+ * vector for whoever's caller is feeding the redactor.+ */+export const MAX_REDACTOR_INPUT = 256 * 1024;+const TRUNCATION_MARKER =+ "\n\n[β¦truncated for size; original exceeded 256 KB. Inspect `pay` raw output before sharing.]\n";++/**+ * Canonical list of secret-bearing field names. Each entry is the+ * underscore-separated canonical form; the regex builder below makes+ * `_` and `-` interchangeable and `_` optional, so a single entry+ * `api_key` covers `api_key` / `apikey` / `api-key` automatically. Don't+ * add the visual variants here β they're already covered.+ */+export const SECRET_KEYS: ReadonlyArray<string> = [+ "api_key",+ "token",+ "access_token",+ "refresh_token",+ "bearer",+ "secret",+ "client_secret",+ "authorization",+ "private_key",+ "password",+ "passwd",+ "pwd",+ "credential",+ "credentials",+ "session_token",+];++const KEY_PATTERN = SECRET_KEYS.map((k) => k.replace(/[-_]/g, "[-_]?")).join("|");++// `key=value` (env-style): value runs to whitespace or end of line.+const ENV_RE = new RegExp(`\\b(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`, "gi");++// `key: value` outside of JSON quoting. Excludes the `"key": ...` JSON shape+// and the `Authorization: Bearer X` header (handled below). Value runs to end+// of line; quoted values are matched as a unit so we replace just the inside.+const COLON_VALUE_RE = new RegExp(+ `(?<!")\\b(${KEY_PATTERN})(\\s*:\\s*)("[^"]*"|'[^']*'|[^\\r\\n]+)`,+ "gi",+);++// `"key": "value"` JSON entries. Matches the value (string, number, true/false).+const JSON_ENTRY_RE = new RegExp(+ `("(?:${KEY_PATTERN})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"|true|false|null|-?\\d+(?:\\.\\d+)?)`,+ "gi",+);++// `Authorization: Bearer <token>` HTTP header form. The COLON_VALUE_RE above+// already redacts `authorization: ...` lines, but a header on its own line of+// the form `Authorization: Bearer <token>` is so common that we keep the+// "Bearer" prefix human-readable and only replace the token after it.+const BEARER_RE = /\b(Bearer\s+)([A-Za-z0-9._\-+/=]+)/gi;++export function redactRawOutput(text: string): string {+ if (!text) return text;++ let out =+ text.length > MAX_REDACTOR_INPUT+ ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER+ : text;++ // Order matters: handle JSON entries first so the COLON_VALUE_RE doesn't+ // also match inside JSON pairs (the negative-lookbehind keeps it off the+ // `"key":` portion, but if we ran COLON_VALUE_RE first, a value like+ // `"token": "abc123"` could be partially mangled).+ out = out.replace(JSON_ENTRY_RE, (_match, keyPart: string, value: string) => {+ if (value.startsWith('"')) return `${keyPart}"${PLACEHOLDER}"`;+ return `${keyPart}${PLACEHOLDER}`;+ });++ out = out.replace(ENV_RE, (_match, key: string, sep: string) => {+ return `${key}${sep}${PLACEHOLDER}`;+ });++ // Bearer headers BEFORE the generic colon rule. Otherwise the+ // `authorization: ...` clause in COLON_VALUE_RE would consume the entire+ // `Bearer <token>` value first, leaving the helpful `Bearer ` prefix+ // stripped from the receipt. Running BEARER_RE first replaces the token+ // alone; the COLON pass below then skips any value that already contains+ // the placeholder so the prefix survives.+ out = out.replace(BEARER_RE, (_match, prefix: string) => `${prefix}${PLACEHOLDER}`);++ out = out.replace(COLON_VALUE_RE, (match, key: string, sep: string, value: string) => {+ // Already-redacted values (e.g. `Authorization: Bearer ***REDACTED***`+ // from the BEARER pass above) are passed through verbatim β re-running+ // the colon rule on them would clobber the `Bearer ` prefix that we+ // intentionally preserved.+ if (value.includes(PLACEHOLDER)) return match;+ if (value.startsWith('"') && value.endsWith('"')) {+ return `${key}${sep}"${PLACEHOLDER}"`;+ }+ if (value.startsWith("'") && value.endsWith("'")) {+ return `${key}${sep}'${PLACEHOLDER}'`;+ }+ return `${key}${sep}${PLACEHOLDER}`;+ });++ return out;+}diff --git a/src/core/pay-memory/report.ts b/src/core/pay-memory/report.tsnew file mode 100644index 00000000..2169c886--- /dev/null+++ b/src/core/pay-memory/report.ts@@ -0,0 +1,167 @@+/**+ * Daily payment report aggregator.+ *+ * `aggregateReceipts` walks `<vault>/AI Wiki/payments/<date>/`, parses each+ * `.md` file's frontmatter, and returns the receipts that match the expected+ * `type: agent-payment-receipt` shape. `writeReport` then renders a Markdown+ * summary into `<vault>/AI Wiki/reports/<slug>.md`.+ *+ * Receipts whose frontmatter cannot be parsed (or whose `type` is missing)+ * are silently skipped β the report is best-effort and meant to surface+ * what is recordable, not to fail the whole task because one file was edited+ * by hand.+ */++import { readdirSync } from "node:fs";+import { join } from "node:path";++import type { FrontmatterMap, FrontmatterValue } from "../types.ts";+import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../vault.ts";+import {+ frontmatterStr,+ nowIsoZ,+ NOT_PROVIDED,+ stripMarkdownExt,+} from "./_md.ts";+import {+ ensureInsideVault,+ paymentsDateDir,+ reportPath,+ validateIsoDate,+ vaultRelative,+} from "./paths.ts";+import { RECEIPT_FRONTMATTER_TYPE } from "./receipt.ts";+import type { PaymentReceiptSummary, ReportInput, ReportOutput } from "./types.ts";++export const REPORT_FRONTMATTER_TYPE = "payment-report";++export function aggregateReceipts(vault: string, date: string): PaymentReceiptSummary[] {+ const dir = paymentsDateDir(vault, date);+ // No existsSync pre-check β readdirSync on a missing directory throws+ // ENOENT cleanly and saves a stat. Race-free in the same way as+ // try/catch on readFile.+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return [];+ throw err;+ }++ const summaries: PaymentReceiptSummary[] = [];+ for (const entry of entries) {+ if (!entry.isFile()) continue;+ if (!entry.name.toLowerCase().endsWith(".md")) continue;+ const full = join(dir, entry.name);+ let meta: FrontmatterMap;+ try {+ [meta] = parseFrontmatter(full);+ } catch {+ continue;+ }+ if (frontmatterStr(meta["type"]) !== RECEIPT_FRONTMATTER_TYPE) continue;+ const service = frontmatterStr(meta["service"]);+ const status = frontmatterStr(meta["status"]);+ if (!service || !status) continue;+ summaries.push({+ path: vaultRelative(full, vault),+ service,+ status,+ category: frontmatterStr(meta["category"]) || null,+ actualAmount: frontmatterStr(meta["actual_amount"]) || null,+ currency: frontmatterStr(meta["currency"]) || null,+ resultRef: frontmatterStr(meta["result_ref"]) || null,+ resultNote: frontmatterStr(meta["result_note"]) || null,+ reason: frontmatterStr(meta["reason"]) || null,+ });+ }+ // Stable order across platforms: by service, then by relative path.+ summaries.sort((a, b) => {+ const s = a.service.localeCompare(b.service);+ return s !== 0 ? s : a.path.localeCompare(b.path);+ });+ return summaries;+}++export function writeReport(vault: string, input: ReportInput): ReportOutput {+ const date = validateIsoDate(input.date);+ const title = (input.title && input.title.trim()) || `Payment Report ${date}`;+ const slug = (input.slug && input.slug.trim()) || slugify(`payment-report-${date}`);++ const target = reportPath(vault, slug);+ ensureInsideVault(target, vault);++ const summaries = aggregateReceipts(vault, date);+ const created = nowIsoZ();++ const metadata: FrontmatterMap = {+ type: REPORT_FRONTMATTER_TYPE,+ title,+ date,+ created,+ receipts_used: summaries.length as FrontmatterValue,+ };+ if (input.task?.trim()) metadata["task"] = input.task.trim();++ writeFrontmatterAtomic(+ target,+ metadata,+ renderReportBody(date, title, input.task ?? null, summaries),+ {+ overwrite: input.overwrite,+ existsErrorKind: "report",+ vaultForRelativePath: vault,+ },+ );++ return {+ path: target,+ relativePath: vaultRelative(target, vault),+ slug,+ receiptsUsed: summaries.length,+ };+}++function renderReportBody(+ date: string,+ title: string,+ task: string | null,+ summaries: PaymentReceiptSummary[],+): string {+ const lines: string[] = [`# ${title}`, "", `Date: ${date}`, ""];++ lines.push("## Task", "");+ lines.push(task && task.trim() ? task.trim() : NOT_PROVIDED);+ lines.push("");++ lines.push("## Paid services used", "");+ if (summaries.length === 0) {+ lines.push("No receipts found for this date.");+ } else {+ for (const s of summaries) {+ lines.push(`### ${s.service}`, "");+ lines.push(`Status: \`${s.status}\``);+ if (s.reason) lines.push(`Reason: ${s.reason}`);+ lines.push(`Receipt: [[${stripMarkdownExt(s.path)}]]`);+ if (s.actualAmount) {+ const amount = s.currency ? `${s.actualAmount} ${s.currency}` : s.actualAmount;+ lines.push(`Amount: \`${amount}\``);+ }+ if (s.resultRef) lines.push(`Result: \`${s.resultRef}\``);+ if (s.resultNote) lines.push(`Asset: [[${stripMarkdownExt(s.resultNote)}]]`);+ lines.push("");+ }+ }++ lines.push("## Files", "");+ if (summaries.length === 0) {+ lines.push(NOT_PROVIDED);+ } else {+ for (const s of summaries) {+ lines.push(`- [[${stripMarkdownExt(s.path)}]]`);+ if (s.resultNote) lines.push(`- [[${stripMarkdownExt(s.resultNote)}]]`);+ }+ }+ return lines.join("\n");+}+diff --git a/src/core/pay-memory/types.ts b/src/core/pay-memory/types.tsnew file mode 100644index 00000000..6cf4079e--- /dev/null+++ b/src/core/pay-memory/types.ts@@ -0,0 +1,119 @@+/**+ * Shared types for the Pay Memory layer.+ *+ * Inputs and outputs of the four core helpers (`writeReceipt`, `writeAsset`,+ * `aggregateReceipts`, `writeReport`). Intentionally separate from the CLI/MCP+ * surfaces β both layers translate user/agent inputs into these shapes and+ * delegate, so the helpers stay pure and easy to test.+ */++export type ReceiptPolicyStatus =+ | "allowed"+ | "approval_required"+ | "denied"+ | "not_checked";++export interface ReceiptInput {+ readonly agent: string;+ readonly service: string;+ readonly status: string;+ readonly reason: string;+ /**+ * Payment rail used to authorise the call (default `pay.sh`). Override+ * when a future rail joins the audit trail β hardcoding `pay.sh` would+ * make the receipt lie about its provenance.+ */+ readonly paymentLayer?: string | null;+ /**+ * Underlying settlement network (default `solana`). Same reasoning:+ * leave the door open for non-Solana rails without retconning past+ * receipts to claim a network they didn't use.+ */+ readonly network?: string | null;+ readonly category?: string | null;+ readonly endpoint?: string | null;+ readonly expectedCost?: string | null;+ readonly actualAmount?: string | null;+ readonly currency?: string | null;+ readonly paymentProof?: string | null;+ readonly resultRef?: string | null;+ readonly resultNote?: string | null;+ readonly rawOutput?: string | null;+ readonly slug?: string | null;+ readonly date?: string | null;+ readonly time?: string | null;+ readonly overwrite?: boolean;+ readonly tz?: string | null;+ /**+ * Policy / approval audit fields. The receipt renderer uses these to+ * tell the truth about how the paid call was authorised β without+ * them the body falls back to "policy: not checked" rather than+ * cheerfully claiming the policy approved a call we never evaluated.+ */+ readonly policyStatus?: ReceiptPolicyStatus | null;+ readonly policyRule?: string | null;+ readonly policyReasons?: ReadonlyArray<string> | null;+ readonly policyCheckedAt?: string | null;+ readonly approvalRequestId?: string | null;+ readonly approvalStatus?:+ | "pending"+ | "approved"+ | "rejected"+ | "consumed"+ | null;+ readonly approvedBy?: string | null;+ readonly approvedAt?: string | null;+}++export interface ReceiptOutput {+ readonly path: string;+ readonly relativePath: string;+ readonly slug: string;+ readonly date: string;+ readonly created: string;+}++export interface AssetInput {+ readonly title: string;+ readonly service: string;+ readonly resultUrl: string;+ readonly sourceReceipt?: string | null;+ readonly prompt?: string | null;+ readonly usedIn?: string | null;+ readonly slug?: string | null;+ readonly overwrite?: boolean;+}++export interface AssetOutput {+ readonly path: string;+ readonly relativePath: string;+ readonly slug: string;+ readonly created: string;+}++export interface ReportInput {+ readonly date: string;+ readonly title?: string | null;+ readonly task?: string | null;+ readonly slug?: string | null;+ readonly overwrite?: boolean;+}++export interface ReportOutput {+ readonly path: string;+ readonly relativePath: string;+ readonly slug: string;+ readonly receiptsUsed: number;+}++export interface PaymentReceiptSummary {+ readonly path: string;+ readonly service: string;+ readonly status: string;+ readonly category: string | null;+ readonly actualAmount: string | null;+ readonly currency: string | null;+ readonly resultRef: string | null;+ readonly resultNote: string | null;+ readonly reason: string | null;+}diff --git a/src/core/vault.ts b/src/core/vault.tsindex c1811c4c..a61fbcc1 100644--- a/src/core/vault.ts+++ b/src/core/vault.ts@@ -10,6 +10,10 @@import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";import { dirname, join, relative } from "node:path";+import {+ atomicCreateFileSyncExclusive,+ atomicWriteFileSync,+} from "./fs-atomic.ts";import type { FrontmatterMap, FrontmatterValue, VaultPage } from "./types.ts";const FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;@@ -73,12 +77,11 @@ export function parseFrontmatter(path: string): readonly [FrontmatterMap, string}/**- * Write a Markdown file with YAML-like frontmatter. Lists are serialized as- * inline arrays. Scalars that would break the simple parser are quoted and- * standard control chars are escaped.+ * Render a Markdown file with YAML-like frontmatter to a string. Pure+ * function β exposed so callers can decide *how* to persist (atomic,+ * exclusive, plain) without duplicating the YAML formatter.*/-export function writeFrontmatter(path: string, metadata: FrontmatterMap, body: string): void {- mkdirSync(dirname(path), { recursive: true });+export function formatFrontmatter(metadata: FrontmatterMap, body: string): string {const lines: string[] = ["---"];for (const [key, value] of Object.entries(metadata)) {lines.push(`${key}: ${formatYamlValue(value)}`);@@ -88,7 +91,89 @@ export function writeFrontmatter(path: string, metadata: FrontmatterMap, body: slines.push("");lines.push(body);}- writeFileSync(path, lines.join("\n") + "\n", "utf8");+ return lines.join("\n") + "\n";+}++/**+ * Write a Markdown file with YAML-like frontmatter. Lists are serialized as+ * inline arrays. Scalars that would break the simple parser are quoted and+ * standard control chars are escaped.+ *+ * This variant is non-atomic β used for non-critical writes where a torn+ * file on crash is acceptable (the regenerated `index.md` would just be+ * rebuilt next run; the bootstrap files are templates that can be+ * re-emitted). For Pay Memory writes that must survive concurrent+ * agents and crashes, use `writeFrontmatterAtomic` instead.+ */+export function writeFrontmatter(path: string, metadata: FrontmatterMap, body: string): void {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, formatFrontmatter(metadata, body), "utf8");+}++export interface WriteFrontmatterAtomicOptions {+ /**+ * When `true`, overwrite an existing target atomically (`rename(2)`).+ * When `false` (default), fail with an `EEXIST`-shaped Error if the+ * target already exists, atomically (`link(2)` semantics).+ */+ readonly overwrite?: boolean;+ /**+ * Optional human-readable label for the artifact kind (e.g. `"receipt"`,+ * `"asset"`, `"pending request"`). When the underlying write hits+ * `EEXIST` and `overwrite` is false, the resulting error message becomes+ * `"<kind> already exists: <path>"` instead of the raw `EEXIST: ...`.+ * The label is purely cosmetic β callers that don't supply it get the+ * native errno error.+ */+ readonly existsErrorKind?: string;+ /** Vault root used to render the relative path in the EEXIST message. */+ readonly vaultForRelativePath?: string;+}++/**+ * Atomic frontmatter writer with optional exclusive-create semantics.+ *+ * Used by Pay Memory writers (receipt, asset, report, policy) where:+ * - the file must not be torn on crash β atomic rename/link;+ * - "refuse to overwrite" must be race-free across concurrent processes+ * (CLI + MCP server, multiple agents) β exclusive `link(2)` instead+ * of the TOCTOU-prone `existsSync` + `writeFileSync` pair.+ *+ * On EEXIST the function throws either:+ * - the native `Error & { code: "EEXIST" }` when no `existsErrorKind`+ * was supplied (matches the underlying `link(2)` semantics so callers+ * that want to inspect `err.code` still can), or+ * - a friendlier `Error("<kind> already exists: <relative-path>")`+ * when `existsErrorKind` was supplied β saves every caller from+ * re-implementing the same try/catch.+ */+export function writeFrontmatterAtomic(+ path: string,+ metadata: FrontmatterMap,+ body: string,+ opts: WriteFrontmatterAtomicOptions = {},+): void {+ const contents = formatFrontmatter(metadata, body);+ if (opts.overwrite) {+ atomicWriteFileSync(path, contents);+ return;+ }+ try {+ atomicCreateFileSyncExclusive(path, contents);+ } catch (err) {+ if (+ opts.existsErrorKind &&+ (err as NodeJS.ErrnoException)?.code === "EEXIST"+ ) {+ const rel = opts.vaultForRelativePath+ ? path.startsWith(opts.vaultForRelativePath + "/")+ ? path.slice(opts.vaultForRelativePath.length + 1)+ : path+ : path;+ throw new Error(`${opts.existsErrorKind} already exists: ${rel}`);+ }+ throw err;+ }}/**diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 3dc1c52e..dde2ec87 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -38,6 +38,27 @@ export function buildInstructions(defaultAgent: string): string {"unless deliberately logging on another agent's behalf.\n\n" +"Other tools: second_brain_status (config status), " +"vault_health (verify vault), second_brain_query (look up notes), " +- "second_brain_capture (add wiki pages)."+ "second_brain_capture (add wiki pages).\n\n" ++ "Pay Memory tools record paid agent actions as inspectable Markdown:\n" ++ " - payment_memory_init bootstraps the layout and writes the " ++ "spending policy template (run once per vault).\n" ++ " - payment_policy_check evaluates a prospective paid call against " ++ "`AI Wiki/policies/spending.json` (allowed / approval_required / denied).\n" ++ " - payment_request_approval creates a pending-payment-request the " ++ "user must approve before you run `pay`; payment_request_status polls " ++ "for approval; payment_request_consume links the eventual receipt.\n" ++ " - payment_receipt_append saves a Markdown receipt for one paid " ++ "API call (`raw_output` is redacted before persisting).\n" ++ " - asset_capture saves a generated asset note linked back to its " ++ "source receipt.\n" ++ " - payment_report_generate aggregates a date's receipts into a " ++ "Markdown report.\n" ++ "These tools never execute payments β they only persist memory. " ++ "After a successful paid call also append a daily event with " ++ "event_log_append so the receipt is discoverable in `Daily/`. When " ++ "an approval workflow is in use, the recommended sequence is: " ++ "payment_policy_check β payment_request_approval β poll " ++ "payment_request_status β run `pay` β payment_receipt_append β " ++ "asset_capture β payment_request_consume β event_log_append.");}diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex a52f3ac6..c775d31b 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -16,6 +16,27 @@ import {} from "../core/config.ts";import { doctor } from "../core/doctor.ts";import { appendEvent, validateEventTime } from "../core/event-log.ts";+import {+ checkPolicy,+ consumePendingRequest,+ loadPendingRequest,+ payMemoryDirs,+ vaultRelativePath,+ writeAsset,+ writePendingRequest,+ writePolicyIfMissing,+ writeReceipt,+ writeReport,+} from "../core/pay-memory/index.ts";+import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";+import {+ normalizeAgentArgument,+ PLACEHOLDER_AGENT_VALUES,+} from "../core/agent-identity.ts";+import {+ ensureInsideVault,+ vaultRelative,+} from "../core/path-safety.ts";import { listVaultPages, slugify, writeFrontmatter } from "../core/vault.ts";import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";@@ -32,57 +53,26 @@ export interface ToolDefinition {readonly handler: (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown;}+// PLACEHOLDER_AGENT_VALUES + normalizeAgentArgument live in+// `src/core/agent-identity.ts` so the OpenClaw native plugin can import+// the same constants without reaching across to the MCP module. Re-exported+// at the bottom of this file for callers that previously imported them+// from here.+/**- * Strings the LLM is most likely to emit as a guess for the `agent` argument- * when it doesn't actually know its identity. None are useful as a real- * `@<name>` in Daily β they should fall back to the server-resolved default.- * Compared case-insensitively, after a leading `@` is stripped.- *- * Mirrored verbatim by the OpenClaw plugin entry so all runtimes filter the- * same hallucination shapes out of Daily.+ * Wrapper that swallows path-escape errors and returns the raw input β+ * used in tool *output* paths where we'd rather hand back the unsafe+ * string than throw mid-render. Keep this as a separate verb so callers+ * deliberately opt into the lenient behaviour.*/-const PLACEHOLDER_AGENT_VALUES = new Set([- "agent",- "assistant",- "ai",- "ai-assistant",- "bot",- "chatbot",- "claude",- "claude-code",- "codex",- "codex-cli",- "codex-exec",- "copilot",- "gemini",- "gpt",- "gpt-4",- "gpt-5",- "hermes",- "llm",- "model",- "openai",- "openclaw",- "user",-]);-function vaultRelpath(target: string, vault: string): string {try {- return relative(resolve(vault), resolve(target));+ return vaultRelative(target, vault);} catch {return target;}}-function ensureInsideVault(target: string, vault: string): string {- const resolvedTarget = resolve(target);- const resolvedVault = resolve(vault);- if (resolvedTarget !== resolvedVault && !resolvedTarget.startsWith(resolvedVault + "/")) {- throw new Error(`path escapes vault: ${target}`);- }- return resolvedTarget;-}-function coerceStr(args: Record<string, unknown>, key: string, required = true, defaultValue: string | null = null): string | null {const value = args[key];if (value === undefined || value === null || (typeof value === "string" && value.trim() === "")) {@@ -123,14 +113,41 @@ function coerceInt(return value;}-function normalizeAgentArgument(value: string | null): string | null {- if (value === null || value === undefined) return null;- const cleaned = value.trim().replace(/^@+/, "").trim();- if (!cleaned) return null;- if (PLACEHOLDER_AGENT_VALUES.has(cleaned.toLowerCase())) return null;- return cleaned;+/**+ * Coerce an optional MCP argument that should be a finite number. Accepts+ * a real number, a numeric string (`"0.05"`), or an absent value+ * (`undefined`/`null`/empty string/whitespace-only string β `null`).+ * Anything else throws INVALID_PARAMS.+ *+ * Crucially, `Number(" ")` evaluates to `0` in JS β without this helper a+ * whitespace-only field would silently change a policy decision. We trim+ * first and treat trimmed-empty as "not provided".+ */+function coerceOptionalNumber(+ args: Record<string, unknown>,+ key: string,+): number | null {+ const raw = args[key];+ if (raw === undefined || raw === null) return null;+ if (typeof raw === "number") {+ if (!Number.isFinite(raw)) {+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a finite number`);+ }+ return raw;+ }+ if (typeof raw === "string") {+ const trimmed = raw.trim();+ if (trimmed === "") return null;+ const parsed = Number(trimmed);+ if (!Number.isFinite(parsed)) {+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a number or numeric string`);+ }+ return parsed;+ }+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a number or numeric string`);}+// ββ Tool implementations ββββββββββββββββββββββββββββββββββββββββββββββββββββasync function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>> {@@ -261,6 +278,303 @@ async function toolVaultHealth(};}+// ββ Pay Memory tools ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++async function toolPaymentMemoryInit(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const overwrite = Boolean(args["overwrite"] ?? false);+ const agentArg = coerceStr(args, "agent", false);+ const agent =+ normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);++ const dirs = payMemoryDirs(ctx.vault);+ const dirList = [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports];+ const created: string[] = [];+ const skipped: string[] = [];+ for (const dir of dirList) {+ const existed = existsSync(dir);+ mkdirSync(dir, { recursive: true });+ (existed ? skipped : created).push(vaultRelativePath(dir, ctx.vault));+ }+ const policy = writePolicyIfMissing(ctx.vault, { overwrite });+ return {+ vault_path: ctx.vault,+ agent,+ created,+ skipped,+ policy_path: vaultRelativePath(policy.path, ctx.vault),+ policy_status: policy.status,+ };+}++async function toolPaymentReceiptAppend(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const agentArg = coerceStr(args, "agent", false);+ const agent =+ normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ const tz = resolveTimezone(ctx.configPath ?? undefined);++ let policyStatus = coerceStr(args, "policy_status", false) as+ | ReceiptPolicyStatus+ | null;+ let policyRule = coerceStr(args, "policy_rule", false);+ const policyReasonsRaw = args["policy_reasons"];+ let policyReasons: string[] | null = null;+ if (policyReasonsRaw !== undefined && policyReasonsRaw !== null) {+ if (+ !Array.isArray(policyReasonsRaw) ||+ !policyReasonsRaw.every((s) => typeof s === "string")+ ) {+ throw new MCPError(INVALID_PARAMS, "policy_reasons must be an array of strings");+ }+ policyReasons = [...policyReasonsRaw] as string[];+ }+ let policyCheckedAt = coerceStr(args, "policy_checked_at", false);+ let approvalStatus: "pending" | "approved" | "rejected" | "consumed" | null = null;+ let approvedBy: string | null = null;+ let approvedAt: string | null = null;+ const fromRequest = coerceStr(args, "from_request", false);+ if (fromRequest) {+ const loaded = loadPendingRequest(ctx.vault, fromRequest);+ if (!loaded) {+ throw new Error(`pending request not found: ${fromRequest}`);+ }+ const meta = loaded.metadata;+ const get = (k: string): string | null => {+ const v = meta[k];+ if (v === undefined || v === null) return null;+ return Array.isArray(v) ? v.join(", ") : String(v);+ };+ policyStatus ??= (get("policy_status") as ReceiptPolicyStatus | null) ?? null;+ policyRule ??= get("policy_rule");+ approvalStatus = loaded.status;+ approvedBy = get("approved_by");+ approvedAt = get("approved_at");+ }+ if (policyStatus !== null) {+ const allowed: ReadonlyArray<ReceiptPolicyStatus> = [+ "allowed",+ "approval_required",+ "denied",+ "not_checked",+ ];+ if (!allowed.includes(policyStatus)) {+ throw new MCPError(+ INVALID_PARAMS,+ `policy_status must be one of: ${allowed.join(", ")}`,+ );+ }+ }++ const result = writeReceipt(ctx.vault, {+ agent,+ service: coerceStr(args, "service", true)!,+ status: coerceStr(args, "status", true)!,+ reason: coerceStr(args, "reason", true)!,+ paymentLayer: coerceStr(args, "payment_layer", false),+ network: coerceStr(args, "network", false),+ category: coerceStr(args, "category", false),+ endpoint: coerceStr(args, "endpoint", false),+ expectedCost: coerceStr(args, "expected_cost", false),+ actualAmount: coerceStr(args, "actual_amount", false),+ currency: coerceStr(args, "currency", false),+ paymentProof: coerceStr(args, "payment_proof", false),+ resultRef: coerceStr(args, "result_ref", false),+ resultNote: coerceStr(args, "result_note", false),+ rawOutput: coerceStr(args, "raw_output", false),+ slug: coerceStr(args, "slug", false),+ date: coerceStr(args, "date", false),+ time: coerceStr(args, "time", false),+ overwrite: Boolean(args["overwrite"] ?? false),+ tz,+ policyStatus,+ policyRule,+ policyReasons,+ policyCheckedAt,+ approvalRequestId: fromRequest,+ approvalStatus,+ approvedBy,+ approvedAt,+ });+ return {+ path: result.relativePath,+ absolute_path: resolve(result.path),+ slug: result.slug,+ date: result.date,+ created: result.created,+ };+}++async function toolAssetCapture(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const result = writeAsset(ctx.vault, {+ title: coerceStr(args, "title", true)!,+ service: coerceStr(args, "service", true)!,+ resultUrl: coerceStr(args, "result_url", true)!,+ sourceReceipt: coerceStr(args, "source_receipt", false),+ prompt: coerceStr(args, "prompt", false),+ usedIn: coerceStr(args, "used_in", false),+ slug: coerceStr(args, "slug", false),+ overwrite: Boolean(args["overwrite"] ?? false),+ });+ return {+ path: result.relativePath,+ absolute_path: resolve(result.path),+ slug: result.slug,+ created: result.created,+ };+}++async function toolPaymentRequestApproval(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const agentArg = coerceStr(args, "agent", false);+ const agent =+ normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ const tz = resolveTimezone(ctx.configPath ?? undefined);++ const expectedAmount = coerceOptionalNumber(args, "expected_amount");++ const vaultFiles = args["vault_files"];+ let vaultFilesList: string[] | null = null;+ if (vaultFiles !== undefined && vaultFiles !== null) {+ if (!Array.isArray(vaultFiles) || !vaultFiles.every((s) => typeof s === "string")) {+ throw new MCPError(INVALID_PARAMS, "vault_files must be an array of strings");+ }+ vaultFilesList = [...vaultFiles] as string[];+ }++ const result = writePendingRequest(ctx.vault, {+ agent,+ service: coerceStr(args, "service", true)!,+ reason: coerceStr(args, "reason", true)!,+ expectedAmount,+ currency: coerceStr(args, "currency", false),+ category: coerceStr(args, "category", false),+ endpoint: coerceStr(args, "endpoint", false),+ expectedOutput: coerceStr(args, "expected_output", false),+ vaultFiles: vaultFilesList,+ slug: coerceStr(args, "slug", false),+ date: coerceStr(args, "date", false),+ time: coerceStr(args, "time", false),+ enforcePolicy: Boolean(args["enforce_policy"] ?? false),+ tz,+ });+ return {+ id: result.id,+ path: result.relativePath,+ absolute_path: resolve(result.path),+ status: result.status,+ created: result.created,+ policy_status: result.policyDecision.status,+ policy_rule: result.policyDecision.rule,+ };+}++async function toolPaymentRequestStatus(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const id = coerceStr(args, "id", true)!;+ const loaded = loadPendingRequest(ctx.vault, id);+ if (!loaded) {+ throw new Error(`pending request not found: ${id}`);+ }+ const meta = loaded.metadata;+ const get = (k: string): string | null => {+ const v = meta[k];+ if (v === undefined || v === null) return null;+ return Array.isArray(v) ? v.join(", ") : String(v);+ };+ return {+ id,+ path: loaded.relativePath,+ status: loaded.status,+ service: get("service"),+ reason: get("reason"),+ expected_amount: get("expected_amount"),+ currency: get("currency"),+ created: get("created"),+ approved_by: get("approved_by"),+ approved_at: get("approved_at"),+ rejected_by: get("rejected_by"),+ rejected_at: get("rejected_at"),+ rejection_reason: get("rejection_reason"),+ receipt: get("receipt"),+ policy_status: get("policy_status"),+ policy_rule: get("policy_rule"),+ };+}++async function toolPaymentRequestConsume(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const id = coerceStr(args, "id", true)!;+ const receiptPath = coerceStr(args, "receipt", true)!;+ const result = await consumePendingRequest(ctx.vault, id, { receiptPath });+ return {+ id: result.id,+ path: result.relativePath,+ status: result.status,+ };+}++async function toolPaymentPolicyCheck(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const expectedAmount = coerceOptionalNumber(args, "expected_amount");+ const tz = resolveTimezone(ctx.configPath ?? undefined);+ const decision = checkPolicy(ctx.vault, {+ service: coerceStr(args, "service", true)!,+ expectedAmount,+ currency: coerceStr(args, "currency", false),+ category: coerceStr(args, "category", false),+ date: coerceStr(args, "date", false),+ tz,+ });+ return {+ status: decision.status,+ allowed: decision.allowed,+ approval_required: decision.approvalRequired,+ rule: decision.rule,+ reasons: decision.reasons,+ has_policy: decision.hasPolicy,+ policy_path:+ decision.policyPath !== null+ ? vaultRelativePath(decision.policyPath, ctx.vault)+ : null,+ currency: decision.currency,+ };+}++async function toolPaymentReportGenerate(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const result = writeReport(ctx.vault, {+ date: coerceStr(args, "date", true)!,+ title: coerceStr(args, "title", false),+ task: coerceStr(args, "task", false),+ slug: coerceStr(args, "slug", false),+ overwrite: Boolean(args["overwrite"] ?? false),+ });+ return {+ path: result.relativePath,+ absolute_path: resolve(result.path),+ slug: result.slug,+ receipts_used: result.receiptsUsed,+ };+}+function isDir(p: string): boolean {if (!existsSync(p)) return false;try {@@ -353,6 +667,203 @@ export function buildToolTable(): ToolDefinition[] {},handler: toolVaultHealth,},+ {+ name: "payment_memory_init",+ description:+ "Bootstrap the Pay Memory layout (policies/, payments/, assets/, drafts/, reports/) and write the spending policy template.",+ inputSchema: {+ type: "object",+ properties: {+ agent: { type: "string", description: "Agent identity (defaults to server-resolved name)." },+ overwrite: {+ type: "boolean",+ description: "Overwrite an existing policy file. Directories are always idempotent.",+ },+ },+ additionalProperties: false,+ },+ handler: toolPaymentMemoryInit,+ },+ {+ name: "payment_receipt_append",+ description:+ "Save a Markdown receipt for one paid API call. raw_output is run through a redactor before persisting.",+ inputSchema: {+ type: "object",+ properties: {+ agent: { type: "string", description: "Agent identity (defaults to server-resolved name)." },+ service: { type: "string", description: "Provider/skill identifier, e.g. 'paysponge/fal'." },+ status: { type: "string", description: "Outcome of the paid call ('success', 'failed', ...)." },+ reason: { type: "string", description: "Why the paid call was made β short imperative sentence." },+ category: { type: "string", description: "Optional category tag." },+ endpoint: { type: "string", description: "Gateway endpoint URL returned by pay-skills." },+ expected_cost: { type: "string", description: "Pre-call expected price range." },+ actual_amount: { type: "string", description: "Actual amount charged (parsed from pay-tool output)." },+ currency: { type: "string", description: "Currency code (e.g. 'USDC')." },+ payment_proof: { type: "string", description: "Public proof / signature / receipt id." },+ result_ref: { type: "string", description: "Generated asset URL or response id." },+ result_note: { type: "string", description: "Vault path to the asset note (wikilink target)." },+ raw_output: { type: "string", description: "Raw payment-tool output to persist after redaction." },+ slug: { type: "string", description: "Optional slug override; default derives from service+reason." },+ date: { type: "string", description: "Receipt date in YYYY-MM-DD; default = today (vault tz)." },+ time: { type: "string", description: "Receipt time in HH:MM 24h; default = now (vault tz)." },+ overwrite: { type: "boolean", description: "Allow overwriting an existing receipt." },+ policy_status: {+ type: "string",+ enum: ["allowed", "approval_required", "denied", "not_checked"],+ description:+ "Real outcome of the spending-policy check. Defaults to `not_checked` when omitted β the receipt body will explicitly say so rather than claiming the policy approved the call.",+ },+ policy_rule: {+ type: "string",+ description: "Policy rule name that fired (e.g. `max_single_call`).",+ },+ policy_reasons: {+ type: "array",+ items: { type: "string" },+ description: "Human-readable reasons returned by the policy check.",+ },+ policy_checked_at: {+ type: "string",+ description: "ISO-Z timestamp at which the policy was evaluated.",+ },+ from_request: {+ type: "string",+ description:+ "Pending-payment-request id. When supplied, the receipt inherits policy / approval audit fields from that request β the agent doesn't have to re-state them.",+ },+ payment_layer: {+ type: "string",+ description: "Payment rail (default `pay.sh`). Override only when a different rail was used.",+ },+ network: {+ type: "string",+ description: "Settlement network (default `solana`). Override only when a different network was used.",+ },+ },+ required: ["service", "status", "reason"],+ additionalProperties: false,+ },+ handler: toolPaymentReceiptAppend,+ },+ {+ name: "asset_capture",+ description:+ "Save a Markdown note for an asset produced by a paid API call. Frontmatter links back to the receipt.",+ inputSchema: {+ type: "object",+ properties: {+ title: { type: "string", description: "Human-readable asset title." },+ service: { type: "string", description: "Provider/skill identifier that produced the asset." },+ result_url: { type: "string", description: "URL or identifier of the generated asset." },+ source_receipt: { type: "string", description: "Vault path to the receipt note." },+ prompt: { type: "string", description: "Prompt sent to the service (rendered as a quote block)." },+ used_in: { type: "string", description: "Vault path of the draft/page that consumes this asset." },+ slug: { type: "string", description: "Optional slug override; default derives from title." },+ overwrite: { type: "boolean", description: "Allow overwriting an existing asset note." },+ },+ required: ["title", "service", "result_url"],+ additionalProperties: false,+ },+ handler: toolAssetCapture,+ },+ {+ name: "payment_request_approval",+ description:+ "Create a pending-payment-request that the user must approve before the agent runs `pay`. Records the policy check at request time.",+ inputSchema: {+ type: "object",+ properties: {+ agent: { type: "string" },+ service: { type: "string" },+ reason: { type: "string" },+ expected_amount: { type: ["number", "string"] },+ currency: { type: "string" },+ category: { type: "string" },+ endpoint: { type: "string" },+ expected_output: { type: "string" },+ vault_files: { type: "array", items: { type: "string" } },+ slug: { type: "string" },+ date: { type: "string" },+ time: { type: "string" },+ enforce_policy: {+ type: "boolean",+ description: "If true, refuse to create the request when the policy denies it.",+ },+ },+ required: ["service", "reason"],+ additionalProperties: false,+ },+ handler: toolPaymentRequestApproval,+ },+ {+ name: "payment_request_status",+ description:+ "Look up a pending-payment-request by id and return its current status and metadata. The agent uses this to poll for human approval.",+ inputSchema: {+ type: "object",+ properties: {+ id: { type: "string", description: "The request id (slug)." },+ },+ required: ["id"],+ additionalProperties: false,+ },+ handler: toolPaymentRequestStatus,+ },+ {+ name: "payment_request_consume",+ description:+ "Mark an `approved` request as `consumed` and link the resulting receipt path. Called by the agent after the paid call succeeded.",+ inputSchema: {+ type: "object",+ properties: {+ id: { type: "string" },+ receipt: { type: "string", description: "Vault-relative path to the receipt note." },+ },+ required: ["id", "receipt"],+ additionalProperties: false,+ },+ handler: toolPaymentRequestConsume,+ },+ {+ name: "payment_policy_check",+ description:+ "Evaluate a prospective paid call against AI Wiki/policies/spending.json. Returns allowed / approval_required / denied + the rule that fired.",+ inputSchema: {+ type: "object",+ properties: {+ service: { type: "string", description: "Provider/skill identifier, e.g. 'paysponge/fal'." },+ expected_amount: {+ type: ["number", "string"],+ description: "Expected payment amount; numeric or numeric-string.",+ },+ currency: { type: "string", description: "Currency code; defaults to the policy currency." },+ category: { type: "string", description: "Optional category for per-category caps." },+ date: { type: "string", description: "Date in YYYY-MM-DD; default = today (vault tz)." },+ },+ required: ["service"],+ additionalProperties: false,+ },+ handler: toolPaymentPolicyCheck,+ },+ {+ name: "payment_report_generate",+ description:+ "Aggregate a date's payment receipts into a Markdown report under AI Wiki/reports/.",+ inputSchema: {+ type: "object",+ properties: {+ date: { type: "string", description: "Date in YYYY-MM-DD whose receipts will be aggregated." },+ title: { type: "string", description: "Report title; default 'Payment Report <date>'." },+ task: { type: "string", description: "Optional task description rendered in the body." },+ slug: { type: "string", description: "Optional slug override." },+ overwrite: { type: "boolean", description: "Allow overwriting an existing report." },+ },+ required: ["date"],+ additionalProperties: false,+ },+ handler: toolPaymentReportGenerate,+ },];}@@ -362,5 +873,7 @@ export function findTool(tools: ReadonlyArray<ToolDefinition>, name: string): Toreturn tool;}-// Re-export for callers that need to filter agent guesses themselves.-export { PLACEHOLDER_AGENT_VALUES };+// Re-export for callers that previously imported these from here. The+// canonical home is `src/core/agent-identity.ts`; new code should import+// from there.+export { PLACEHOLDER_AGENT_VALUES, normalizeAgentArgument };diff --git a/src/openclaw/index.ts b/src/openclaw/index.tsindex 2903d365..c8ae6e68 100644--- a/src/openclaw/index.ts+++ b/src/openclaw/index.ts@@ -5,16 +5,16 @@* is no longer a hand-translated copy of the Python original β both runtimes* share the same source of truth.*- * The plugin exposes the same five tools the MCP server does- * (`second_brain_status`, `second_brain_query`, `second_brain_capture`,- * `event_log_append`, `vault_health`), with parameter schemas mirrored from- * `src/mcp/tools.ts`. No subprocess creation; passes the OpenClaw security- * scanner.+ * The plugin exposes the full Open Second Brain tool surface β the original+ * five (`second_brain_status`, `second_brain_query`, `second_brain_capture`,+ * `event_log_append`, `vault_health`) plus the eight Pay Memory tools added+ * in v0.8.0 β with parameter schemas mirrored from `src/mcp/tools.ts`.+ * No subprocess creation; passes the OpenClaw security scanner.*/import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";import { existsSync } from "node:fs";-import { join } from "node:path";+import { join, resolve as resolvePath } from "node:path";import {discoverConfig,@@ -25,8 +25,25 @@ import {import { doctor } from "../core/doctor.ts";import { appendEvent, validateEventTime } from "../core/event-log.ts";import { buildReminder } from "../core/identity-reminder.ts";+import {+ checkPolicy,+ consumePendingRequest,+ loadPendingRequest,+ vaultRelativePath,+ writeAsset,+ writePendingRequest,+ writePolicyIfMissing,+ writeReceipt,+ writeReport,+ payMemoryDirs,+} from "../core/pay-memory/index.ts";+import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";+import { mkdirSync } from "node:fs";import { listVaultPages, slugify, writeFrontmatter } from "../core/vault.ts";-import { PLACEHOLDER_AGENT_VALUES } from "../mcp/tools.ts";+import {+ normalizeAgentArgument,+ PLACEHOLDER_AGENT_VALUES,+} from "../core/agent-identity.ts";interface PluginConfig {vault?: string;@@ -56,23 +73,52 @@ function resolveOpenclawAgent(api: { pluginConfig?: Record<string, unknown> },argAgent: string | null,): string {- const normalized = normalizeAgentArg(argAgent);+ const normalized = normalizeAgentArgument(argAgent);if (normalized) return normalized;const cfg = (api.pluginConfig ?? {}) as PluginConfig;return cfg.agentName ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();}-function normalizeAgentArg(value: string | null): string | null {- if (value === null || value === undefined) return null;- const cleaned = String(value).trim().replace(/^@+/, "").trim();- if (!cleaned) return null;- if (PLACEHOLDER_AGENT_VALUES.has(cleaned.toLowerCase())) return null;- return cleaned;+/**+ * Helper for Pay Memory tools that need a numeric `expected_amount` field.+ * The OpenClaw schema declares the type as `["number", "string"]` to match+ * the MCP shape β agents sometimes serialise numbers as strings.+ *+ * Whitespace-only strings are treated as "not provided", *not* as `0`.+ * Without the explicit trim, `Number(" ")` evaluates to `0` and would+ * silently change a policy decision.+ */+function coerceExpectedAmount(value: unknown): number | null {+ if (value === undefined || value === null) return null;+ if (typeof value === "number") {+ if (!Number.isFinite(value)) {+ throw new Error("expected_amount must be a finite number");+ }+ return value;+ }+ if (typeof value === "string") {+ const trimmed = value.trim();+ if (trimmed === "") return null;+ const parsed = Number(trimmed);+ if (!Number.isFinite(parsed)) {+ throw new Error("expected_amount must be a number or numeric string");+ }+ return parsed;+ }+ throw new Error("expected_amount must be a number or numeric string");}-function vaultRel(target: string, vault: string): string {- if (target.startsWith(vault + "/")) return target.slice(vault.length + 1);- return target;+function strOrNull(value: unknown): string | null {+ if (value === undefined || value === null) return null;+ if (typeof value !== "string") return null;+ const trimmed = value.trim();+ return trimmed ? trimmed : null;+}++function asJson(payload: unknown): { content: Array<{ type: "text"; text: string }> } {+ return {+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],+ };}export default definePluginEntry({@@ -90,7 +136,7 @@ export default definePluginEntry({api.on("before_prompt_build", () => {const cfg = (api.pluginConfig ?? {}) as PluginConfig;const agent =- normalizeAgentArg(cfg.agentName ?? null) ??+ normalizeAgentArgument(cfg.agentName ?? null) ??process.env["VAULT_AGENT_NAME"] ??resolveAgentName();if (agent === "agent") return undefined;@@ -152,7 +198,7 @@ export default definePluginEntry({: pages.filter((p) => p.title.toLowerCase().includes(needle))).slice(0, limit)- .map((p) => ({ title: p.title, path: vaultRel(p.path, vault), metadata: p.metadata }));+ .map((p) => ({ title: p.title, path: vaultRelativePath(p.path, vault), metadata: p.metadata }));const result = {vault_path: vault,@@ -207,7 +253,7 @@ export default definePluginEntry({// signal whenever overwrite=true.const noteExisted = existsSync(target);if (noteExisted && !overwrite) {- throw new Error(`note already exists: ${vaultRel(target, vault)}`);+ throw new Error(`note already exists: ${vaultRelativePath(target, vault)}`);}const metadata: Record<string, string | number | boolean | string[]> = {title,@@ -217,7 +263,7 @@ export default definePluginEntry({if (tags.length > 0) metadata["tags"] = tags;writeFrontmatter(target, metadata, content.trim());const result = {- path: vaultRel(target, vault),+ path: vaultRelativePath(target, vault),absolute_path: target,slug,overwritten: noteExisted && overwrite,@@ -258,7 +304,7 @@ export default definePluginEntry({const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();const path = await appendEvent(vault, agent, message, { date, time, tz });const result = {- path: vaultRel(path, vault),+ path: vaultRelativePath(path, vault),absolute_path: path,agent,date,@@ -296,5 +342,433 @@ export default definePluginEntry({},},);++ // ββ Pay Memory tools βββββββββββββββββββββββββββββββββββββββββββββββββββ++ api.registerTool({+ name: "payment_memory_init",+ description:+ "Bootstrap the Pay Memory layout (policies/, payments/, assets/, drafts/, reports/) and write the spending policy template.",+ parameters: {+ type: "object",+ properties: {+ agent: { type: "string" },+ overwrite: { type: "boolean" },+ },+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const overwrite = Boolean(params["overwrite"] ?? false);+ const agent = resolveOpenclawAgent(api, (params["agent"] as string | undefined) ?? null);++ const dirs = payMemoryDirs(vault);+ const created: string[] = [];+ const skipped: string[] = [];+ for (const dir of [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports]) {+ const existed = existsSync(dir);+ mkdirSync(dir, { recursive: true });+ (existed ? skipped : created).push(vaultRelativePath(dir, vault));+ }+ const policy = writePolicyIfMissing(vault, { overwrite });+ return asJson({+ vault_path: vault,+ agent,+ created,+ skipped,+ policy_path: vaultRelativePath(policy.path, vault),+ policy_status: policy.status,+ });+ },+ });++ api.registerTool({+ name: "payment_receipt_append",+ description:+ "Save a Markdown receipt for one paid API call. raw_output is run through a redactor before persisting.",+ parameters: {+ type: "object",+ properties: {+ agent: { type: "string" },+ service: { type: "string" },+ status: { type: "string" },+ reason: { type: "string" },+ category: { type: "string" },+ endpoint: { type: "string" },+ expected_cost: { type: "string" },+ actual_amount: { type: "string" },+ currency: { type: "string" },+ payment_proof: { type: "string" },+ result_ref: { type: "string" },+ result_note: { type: "string" },+ raw_output: { type: "string" },+ slug: { type: "string" },+ date: { type: "string" },+ time: { type: "string" },+ overwrite: { type: "boolean" },+ policy_status: {+ type: "string",+ enum: ["allowed", "approval_required", "denied", "not_checked"],+ },+ policy_rule: { type: "string" },+ policy_reasons: { type: "array", items: { type: "string" } },+ policy_checked_at: { type: "string" },+ from_request: { type: "string" },+ payment_layer: { type: "string" },+ network: { type: "string" },+ },+ required: ["service", "status", "reason"],+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();+ const agent = resolveOpenclawAgent(api, (params["agent"] as string | undefined) ?? null);++ let policyStatus = strOrNull(params["policy_status"]) as+ | ReceiptPolicyStatus+ | null;+ let policyRule = strOrNull(params["policy_rule"]);+ const policyReasonsRaw = params["policy_reasons"];+ let policyReasons: string[] | null = null;+ if (policyReasonsRaw !== undefined && policyReasonsRaw !== null) {+ if (+ !Array.isArray(policyReasonsRaw) ||+ !policyReasonsRaw.every((s) => typeof s === "string")+ ) {+ throw new Error("policy_reasons must be an array of strings");+ }+ policyReasons = [...policyReasonsRaw] as string[];+ }+ let policyCheckedAt = strOrNull(params["policy_checked_at"]);+ let approvalStatus:+ | "pending"+ | "approved"+ | "rejected"+ | "consumed"+ | null = null;+ let approvedBy: string | null = null;+ let approvedAt: string | null = null;+ const fromRequest = strOrNull(params["from_request"]);+ if (fromRequest) {+ const loaded = loadPendingRequest(vault, fromRequest);+ if (!loaded) throw new Error(`pending request not found: ${fromRequest}`);+ const meta = loaded.metadata;+ const get = (k: string): string | null => {+ const v = meta[k];+ if (v === undefined || v === null) return null;+ return Array.isArray(v) ? v.join(", ") : String(v);+ };+ policyStatus ??= (get("policy_status") as ReceiptPolicyStatus | null) ?? null;+ policyRule ??= get("policy_rule");+ approvalStatus = loaded.status;+ approvedBy = get("approved_by");+ approvedAt = get("approved_at");+ }+ if (policyStatus !== null) {+ const allowed: ReadonlyArray<ReceiptPolicyStatus> = [+ "allowed",+ "approval_required",+ "denied",+ "not_checked",+ ];+ if (!allowed.includes(policyStatus)) {+ throw new Error(+ `policy_status must be one of: ${allowed.join(", ")}`,+ );+ }+ }++ const result = writeReceipt(vault, {+ agent,+ service: String(params["service"]),+ status: String(params["status"]),+ reason: String(params["reason"]),+ paymentLayer: strOrNull(params["payment_layer"]),+ network: strOrNull(params["network"]),+ category: strOrNull(params["category"]),+ endpoint: strOrNull(params["endpoint"]),+ expectedCost: strOrNull(params["expected_cost"]),+ actualAmount: strOrNull(params["actual_amount"]),+ currency: strOrNull(params["currency"]),+ paymentProof: strOrNull(params["payment_proof"]),+ resultRef: strOrNull(params["result_ref"]),+ resultNote: strOrNull(params["result_note"]),+ rawOutput: strOrNull(params["raw_output"]),+ slug: strOrNull(params["slug"]),+ date: strOrNull(params["date"]),+ time: strOrNull(params["time"]),+ overwrite: Boolean(params["overwrite"] ?? false),+ tz,+ policyStatus,+ policyRule,+ policyReasons,+ policyCheckedAt,+ approvalRequestId: fromRequest,+ approvalStatus,+ approvedBy,+ approvedAt,+ });+ return asJson({+ path: result.relativePath,+ absolute_path: resolvePath(result.path),+ slug: result.slug,+ date: result.date,+ created: result.created,+ });+ },+ });++ api.registerTool({+ name: "asset_capture",+ description:+ "Save a Markdown note for an asset produced by a paid call, linked to its receipt.",+ parameters: {+ type: "object",+ properties: {+ title: { type: "string" },+ service: { type: "string" },+ result_url: { type: "string" },+ source_receipt: { type: "string" },+ prompt: { type: "string" },+ used_in: { type: "string" },+ slug: { type: "string" },+ overwrite: { type: "boolean" },+ },+ required: ["title", "service", "result_url"],+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const result = writeAsset(vault, {+ title: String(params["title"]),+ service: String(params["service"]),+ resultUrl: String(params["result_url"]),+ sourceReceipt: strOrNull(params["source_receipt"]),+ prompt: strOrNull(params["prompt"]),+ usedIn: strOrNull(params["used_in"]),+ slug: strOrNull(params["slug"]),+ overwrite: Boolean(params["overwrite"] ?? false),+ });+ return asJson({+ path: result.relativePath,+ absolute_path: resolvePath(result.path),+ slug: result.slug,+ created: result.created,+ });+ },+ });++ api.registerTool({+ name: "payment_report_generate",+ description:+ "Aggregate a date's payment receipts into a Markdown report under AI Wiki/reports/.",+ parameters: {+ type: "object",+ properties: {+ date: { type: "string" },+ title: { type: "string" },+ task: { type: "string" },+ slug: { type: "string" },+ overwrite: { type: "boolean" },+ },+ required: ["date"],+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const result = writeReport(vault, {+ date: String(params["date"]),+ title: strOrNull(params["title"]),+ task: strOrNull(params["task"]),+ slug: strOrNull(params["slug"]),+ overwrite: Boolean(params["overwrite"] ?? false),+ });+ return asJson({+ path: result.relativePath,+ absolute_path: resolvePath(result.path),+ slug: result.slug,+ receipts_used: result.receiptsUsed,+ });+ },+ });++ api.registerTool({+ name: "payment_policy_check",+ description:+ "Evaluate a prospective paid call against AI Wiki/policies/spending.json. Returns allowed / approval_required / denied + the rule that fired.",+ parameters: {+ type: "object",+ properties: {+ service: { type: "string" },+ expected_amount: { type: ["number", "string"] },+ currency: { type: "string" },+ category: { type: "string" },+ date: { type: "string" },+ },+ required: ["service"],+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();+ const decision = checkPolicy(vault, {+ service: String(params["service"]),+ expectedAmount: coerceExpectedAmount(params["expected_amount"]),+ currency: strOrNull(params["currency"]),+ category: strOrNull(params["category"]),+ date: strOrNull(params["date"]),+ tz,+ });+ return asJson({+ status: decision.status,+ allowed: decision.allowed,+ approval_required: decision.approvalRequired,+ rule: decision.rule,+ reasons: decision.reasons,+ has_policy: decision.hasPolicy,+ policy_path:+ decision.policyPath !== null+ ? vaultRelativePath(decision.policyPath, vault)+ : null,+ currency: decision.currency,+ });+ },+ });++ api.registerTool({+ name: "payment_request_approval",+ description:+ "Create a pending-payment-request that the user must approve before the agent runs `pay`. Records the policy check at request time.",+ parameters: {+ type: "object",+ properties: {+ agent: { type: "string" },+ service: { type: "string" },+ reason: { type: "string" },+ expected_amount: { type: ["number", "string"] },+ currency: { type: "string" },+ category: { type: "string" },+ endpoint: { type: "string" },+ expected_output: { type: "string" },+ vault_files: { type: "array", items: { type: "string" } },+ slug: { type: "string" },+ date: { type: "string" },+ time: { type: "string" },+ enforce_policy: { type: "boolean" },+ },+ required: ["service", "reason"],+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();+ const agent = resolveOpenclawAgent(api, (params["agent"] as string | undefined) ?? null);+ const vaultFilesRaw = params["vault_files"];+ let vaultFiles: string[] | null = null;+ if (vaultFilesRaw !== undefined && vaultFilesRaw !== null) {+ if (+ !Array.isArray(vaultFilesRaw) ||+ !vaultFilesRaw.every((s) => typeof s === "string")+ ) {+ throw new Error("vault_files must be an array of strings");+ }+ vaultFiles = [...vaultFilesRaw] as string[];+ }+ const result = writePendingRequest(vault, {+ agent,+ service: String(params["service"]),+ reason: String(params["reason"]),+ expectedAmount: coerceExpectedAmount(params["expected_amount"]),+ currency: strOrNull(params["currency"]),+ category: strOrNull(params["category"]),+ endpoint: strOrNull(params["endpoint"]),+ expectedOutput: strOrNull(params["expected_output"]),+ vaultFiles,+ slug: strOrNull(params["slug"]),+ date: strOrNull(params["date"]),+ time: strOrNull(params["time"]),+ enforcePolicy: Boolean(params["enforce_policy"] ?? false),+ tz,+ });+ return asJson({+ id: result.id,+ path: result.relativePath,+ absolute_path: resolvePath(result.path),+ status: result.status,+ created: result.created,+ policy_status: result.policyDecision.status,+ policy_rule: result.policyDecision.rule,+ });+ },+ });++ api.registerTool({+ name: "payment_request_status",+ description:+ "Look up a pending-payment-request by id and return its current status and metadata. The agent uses this to poll for human approval.",+ parameters: {+ type: "object",+ properties: { id: { type: "string" } },+ required: ["id"],+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const id = String(params["id"]);+ const loaded = loadPendingRequest(vault, id);+ if (!loaded) throw new Error(`pending request not found: ${id}`);+ const meta = loaded.metadata;+ const get = (k: string): string | null => {+ const v = meta[k];+ if (v === undefined || v === null) return null;+ return Array.isArray(v) ? v.join(", ") : String(v);+ };+ return asJson({+ id,+ path: loaded.relativePath,+ status: loaded.status,+ service: get("service"),+ reason: get("reason"),+ expected_amount: get("expected_amount"),+ currency: get("currency"),+ created: get("created"),+ approved_by: get("approved_by"),+ approved_at: get("approved_at"),+ rejected_by: get("rejected_by"),+ rejected_at: get("rejected_at"),+ rejection_reason: get("rejection_reason"),+ receipt: get("receipt"),+ policy_status: get("policy_status"),+ policy_rule: get("policy_rule"),+ });+ },+ });++ api.registerTool({+ name: "payment_request_consume",+ description:+ "Mark an `approved` request as `consumed` and link the resulting receipt path. Called by the agent after the paid call succeeded.",+ parameters: {+ type: "object",+ properties: {+ id: { type: "string" },+ receipt: { type: "string" },+ },+ required: ["id", "receipt"],+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const result = await consumePendingRequest(vault, String(params["id"]), {+ receiptPath: String(params["receipt"]),+ });+ return asJson({+ id: result.id,+ path: result.relativePath,+ status: result.status,+ });+ },+ });},});diff --git a/tests/cli/pay-memory.test.ts b/tests/cli/pay-memory.test.tsnew file mode 100644index 00000000..08d8cbed--- /dev/null+++ b/tests/cli/pay-memory.test.ts@@ -0,0 +1,556 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pay-cli-test-"));+ vault = join(tmp, "vault");+ config = join(tmp, "config.yaml");+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("init-pay-memory", () => {+ test("creates the layout, policy, and reports the agent", async () => {+ const r = await runCli(+ ["init-pay-memory", "--vault", vault, "--agent", "hermes-vps-agent"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("pay-memory layout initialized:");+ expect(r.stdout).toContain("agent: hermes-vps-agent");+ for (const sub of ["policies", "payments", "assets", "drafts", "reports"]) {+ expect(existsSync(join(vault, "AI Wiki", sub))).toBe(true);+ }+ expect(existsSync(join(vault, "AI Wiki", "policies", "spending.md"))).toBe(true);+ });++ test("re-running is idempotent and skips the policy by default", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const policy = join(vault, "AI Wiki", "policies", "spending.md");+ writeFileSync(policy, "edited\n", "utf8");+ const r = await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("skipped:");+ expect(readFileSync(policy, "utf8")).toBe("edited\n");+ });++ test("--overwrite rewrites the policy", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const policy = join(vault, "AI Wiki", "policies", "spending.md");+ writeFileSync(policy, "stale\n", "utf8");+ const r = await runCli(["init-pay-memory", "--vault", vault, "--overwrite"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("overwritten:");+ expect(readFileSync(policy, "utf8")).toContain("# Agent Spending Policy");+ });++ test("--json emits a structured payload", async () => {+ const r = await runCli(["init-pay-memory", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout);+ expect(payload.vault_path).toBe(vault);+ expect(payload.policy_path).toBe("AI Wiki/policies/spending.md");+ expect(payload.policy_status).toBe("created");+ expect(payload.created).toContain("AI Wiki/policies");+ });+});++describe("append-payment-receipt", () => {+ test("writes a receipt and redacts secrets in --raw-output-file", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const rawFile = join(tmp, "raw.txt");+ writeFileSync(+ rawFile,+ [+ "request: GET /v1/quote",+ "Authorization: Bearer eyJhbGciOi.SECRET",+ '{"api_key": "sk_live_abc", "ok": true}',+ ].join("\n"),+ "utf8",+ );+ const r = await runCli(+ [+ "append-payment-receipt",+ "--vault", vault,+ "--agent", "hermes-vps-agent",+ "--service", "paysponge/fal",+ "--status", "success",+ "--reason", "Generate one original blog header image",+ "--actual-amount", "0.05",+ "--currency", "USDC",+ "--result-ref", "https://fal-cdn.example/img.png",+ "--result-note", "AI Wiki/assets/blog-header.md",+ "--raw-output-file", rawFile,+ "--date", "2026-05-10",+ "--time", "17:20",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("receipt: AI Wiki/payments/2026-05-10/");+ const receiptPath = r.stdout.match(/^receipt: (.+)$/m)![1]!.trim();+ const text = readFileSync(join(vault, receiptPath), "utf8");+ expect(text).toContain("paysponge/fal");+ expect(text).toContain("hermes-vps-agent");+ expect(text).toContain("***REDACTED***");+ expect(text).not.toContain("sk_live_abc");+ });++ test("refuses to overwrite without --overwrite", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const args = [+ "append-payment-receipt",+ "--vault", vault,+ "--agent", "h",+ "--service", "x/y",+ "--status", "success",+ "--reason", "test",+ "--slug", "fixed-slug",+ "--date", "2026-05-10",+ "--time", "00:00",+ ];+ const first = await runCli(args, { env: { OPEN_SECOND_BRAIN_CONFIG: config } });+ expect(first.returncode).toBe(0);+ const second = await runCli(args, { env: { OPEN_SECOND_BRAIN_CONFIG: config } });+ expect(second.returncode).toBe(1);+ expect(second.stderr).toContain("already exists");+ const third = await runCli([...args, "--overwrite"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(third.returncode).toBe(0);+ });++ test("missing required flags exit with code 2", async () => {+ const r = await runCli(+ ["append-payment-receipt", "--vault", vault, "--service", "x", "--status", "success"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("missing required flag: --reason");+ });+});++describe("capture-asset", () => {+ test("writes an asset note with prompt-file and source receipt", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const promptFile = join(tmp, "prompt.txt");+ writeFileSync(promptFile, "A recursive technical illustration\nNo logos\n", "utf8");+ const r = await runCli(+ [+ "capture-asset",+ "--vault", vault,+ "--title", "Blog Header: Pay Memory",+ "--service", "paysponge/fal",+ "--result-url", "https://fal-cdn.example/img.png",+ "--source-receipt", "AI Wiki/payments/2026-05-10/fal-blog.md",+ "--prompt-file", promptFile,+ "--used-in", "AI Wiki/drafts/blog-post.md",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("asset: AI Wiki/assets/");+ const assetPath = r.stdout.match(/^asset: (.+)$/m)![1]!.trim();+ const text = readFileSync(join(vault, assetPath), "utf8");+ expect(text).toContain("# Blog Header: Pay Memory");+ expect(text).toContain("> A recursive technical illustration");+ expect(text).toContain('source_receipt: "[[AI Wiki/payments/2026-05-10/fal-blog]]"');+ });+});++describe("payment-report", () => {+ test("aggregates receipts written earlier and prints receipts_used", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ for (const slug of ["fal-1", "alpha-1"]) {+ const r = await runCli(+ [+ "append-payment-receipt",+ "--vault", vault,+ "--agent", "h",+ "--service", slug.startsWith("fal") ? "paysponge/fal" : "alpha/translate",+ "--status", "success",+ "--reason", `reason-${slug}`,+ "--actual-amount", "0.03",+ "--currency", "USDC",+ "--slug", slug,+ "--date", "2026-05-10",+ "--time", "17:20",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ }+ const report = await runCli(+ [+ "payment-report",+ "--vault", vault,+ "--date", "2026-05-10",+ "--title", "Demo Report",+ "--task", "test task",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(report.returncode).toBe(0);+ expect(report.stdout).toContain("report: AI Wiki/reports/");+ expect(report.stdout).toContain("receipts: 2");+ const reportPath = report.stdout.match(/^report: (.+)$/m)![1]!.trim();+ const text = readFileSync(join(vault, reportPath), "utf8");+ expect(text).toContain("### paysponge/fal");+ expect(text).toContain("### alpha/translate");+ expect(text).toContain("Demo Report");+ expect(text).toContain("test task");+ });++ test("--date must be ISO YYYY-MM-DD", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const r = await runCli(+ ["payment-report", "--vault", vault, "--date", "2026.05.10"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("YYYY-MM-DD");+ });+});++describe("check-payment-policy", () => {+ test("fail-open when no policy.json exists (exit 0, has_policy=false)", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const r = await runCli(+ ["check-payment-policy", "--vault", vault, "--service", "x/y", "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout);+ expect(payload.has_policy).toBe(false);+ expect(payload.allowed).toBe(true);+ });++ test("denies when service is not in allowed_services (exit 1)", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ writeFileSync(+ join(vault, "AI Wiki", "policies", "spending.json"),+ JSON.stringify({ allowed_services: ["paysponge/fal"] }),+ "utf8",+ );+ const r = await runCli(+ ["check-payment-policy", "--vault", vault, "--service", "alpha/translate"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(1);+ expect(r.stdout).toContain("status: denied");+ expect(r.stdout).toContain("rule: allowed_services");+ });++ test("approval_required path returns exit 3", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ writeFileSync(+ join(vault, "AI Wiki", "policies", "spending.json"),+ JSON.stringify({+ allowed_services: ["x/y"],+ require_approval_above: 0.05,+ }),+ "utf8",+ );+ const r = await runCli(+ [+ "check-payment-policy",+ "--vault", vault,+ "--service", "x/y",+ "--expected-amount", "0.07",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(3);+ expect(r.stdout).toContain("status: approval_required");+ });++ test("--expected-amount must be numeric (exit 2)", async () => {+ const r = await runCli(+ ["check-payment-policy", "--vault", vault, "--service", "x/y", "--expected-amount", "abc"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("must be a number");+ });++ test("whitespace-only --expected-amount is treated as missing, not as 0", async () => {+ // The bug: `Number(" ")` returns `0`. Without trimming the helper+ // would let an agent (or a stray shell-escape) bypass the+ // missing-amount guard by submitting whitespace.+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ writeFileSync(+ join(vault, "AI Wiki", "policies", "spending.json"),+ JSON.stringify({+ allowed_services: ["x/y"],+ max_single_call: 0.05,+ }),+ "utf8",+ );+ const r = await runCli(+ [+ "check-payment-policy",+ "--vault", vault,+ "--service", "x/y",+ "--expected-amount", " ",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ // approval_required β exit 3 (missing-amount guard fires)+ expect(r.returncode).toBe(3);+ expect(r.stdout).toContain("missing_expected_amount");+ });+});++describe("approval workflow (request β approve β consume)", () => {+ test("end-to-end happy path", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const req = await runCli(+ [+ "request-payment-approval",+ "--vault", vault,+ "--service", "paysponge/fal",+ "--reason", "header image",+ "--expected-amount", "0.05",+ "--currency", "USDC",+ "--slug", "demo-1",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(req.returncode).toBe(0);+ expect(req.stdout).toContain("pending: AI Wiki/payments/_pending/demo-1.md");++ const approve = await runCli(+ [+ "approve-payment-request",+ "--vault", vault,+ "--id", "demo-1",+ "--approved-by", "sergey",+ "--note", "ok for demo",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(approve.returncode).toBe(0);+ expect(approve.stdout).toContain("status: approved");++ const consume = await runCli(+ [+ "consume-payment-request",+ "--vault", vault,+ "--id", "demo-1",+ "--receipt", "AI Wiki/payments/2026-05-10/fal-1.md",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(consume.returncode).toBe(0);+ expect(consume.stdout).toContain("status: consumed");++ const text = readFileSync(+ join(vault, "AI Wiki", "payments", "_pending", "demo-1.md"),+ "utf8",+ );+ expect(text).toContain("status: consumed");+ expect(text).toContain("approved_by: sergey");+ expect(text).toContain("receipt: AI Wiki/payments/2026-05-10/fal-1.md");+ });++ test("reject blocks subsequent approve", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ await runCli(+ [+ "request-payment-approval",+ "--vault", vault,+ "--service", "x/y",+ "--reason", "test",+ "--slug", "rej-1",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ const reject = await runCli(+ [+ "reject-payment-request",+ "--vault", vault,+ "--id", "rej-1",+ "--rejected-by", "sergey",+ "--reason", "no",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(reject.returncode).toBe(0);+ const approve = await runCli(+ ["approve-payment-request", "--vault", vault, "--id", "rej-1", "--approved-by", "x"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(approve.returncode).toBe(1);+ expect(approve.stderr).toContain("cannot transition");+ });++ test("list-pending-payments default shows only pending", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ for (const slug of ["a", "b"]) {+ await runCli(+ [+ "request-payment-approval",+ "--vault", vault,+ "--service", "x/y",+ "--reason", `r-${slug}`,+ "--slug", slug,+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ }+ await runCli(+ ["approve-payment-request", "--vault", vault, "--id", "a", "--approved-by", "sergey"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ const listPending = await runCli(+ ["list-pending-payments", "--vault", vault, "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ const pending = JSON.parse(listPending.stdout);+ expect(pending.length).toBe(1);+ expect(pending[0].id).toBe("b");++ const listAll = await runCli(+ ["list-pending-payments", "--vault", vault, "--status", "all", "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ const all = JSON.parse(listAll.stdout);+ expect(all.length).toBe(2);+ expect(all.map((s: { id: string }) => s.id).sort()).toEqual(["a", "b"]);+ });++ test("--status validates against the allowed set", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const r = await runCli(+ ["list-pending-payments", "--vault", vault, "--status", "weird"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("--status must be one of");+ });+});++describe("payment-digest", () => {+ test("emits [SILENT] when no receipts on the date", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const r = await runCli(+ ["payment-digest", "--vault", vault, "--date", "2026-05-10"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout.trim()).toBe("[SILENT]");+ });++ test("renders 4-line digest after receipts exist", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ await runCli(+ [+ "append-payment-receipt",+ "--vault", vault,+ "--service", "paysponge/fal",+ "--status", "success",+ "--reason", "header",+ "--actual-amount", "0.05",+ "--currency", "USDC",+ "--slug", "fal-1",+ "--date", "2026-05-10",+ "--time", "12:00",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ const r = await runCli(+ ["payment-digest", "--vault", vault, "--date", "2026-05-10"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("π³ ΠΠΏΠ»Π°ΡΠ΅Π½ΠΎ ΡΠ΅ΡΠ²ΠΈΡΠΎΠ²: **1**");+ expect(r.stdout).toContain("π° Π‘ΡΠΌΠΌΠ°: **0.05 USDC**");+ expect(r.stdout).toContain("π Π€Π°ΠΉΠ»Ρ ΡΠ΅ΠΊΠΎΠ²: **1**");+ });++ test("--json returns structured payload", async () => {+ await runCli(["init-pay-memory", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const r = await runCli(+ ["payment-digest", "--vault", vault, "--date", "2026-05-10", "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout);+ expect(payload.date).toBe("2026-05-10");+ expect(payload.receipts).toBe(0);+ });++ test("--empty-mode validates", async () => {+ const r = await runCli(+ ["payment-digest", "--vault", vault, "--date", "2026-05-10", "--empty-mode", "weird"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("--empty-mode must be");+ });+});++describe("HELP includes Pay Memory section", () => {+ test("`o2b` (no args) lists the new commands", async () => {+ const r = await runCli([]);+ expect(r.returncode).toBe(2);+ expect(r.stdout).toContain("Pay Memory:");+ expect(r.stdout).toContain("init-pay-memory");+ expect(r.stdout).toContain("append-payment-receipt");+ expect(r.stdout).toContain("capture-asset");+ expect(r.stdout).toContain("payment-report");+ expect(r.stdout).toContain("check-payment-policy");+ });+});diff --git a/tests/core/fs-atomic.test.ts b/tests/core/fs-atomic.test.tsnew file mode 100644index 00000000..1c611b63--- /dev/null+++ b/tests/core/fs-atomic.test.ts@@ -0,0 +1,88 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ atomicCreateFileSyncExclusive,+ atomicWriteFileSync,+} from "../../src/core/fs-atomic.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-fs-atomic-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("atomicWriteFileSync", () => {+ test("writes new file and overwrites existing", () => {+ const target = join(tmp, "x.md");+ atomicWriteFileSync(target, "first");+ expect(readFileSync(target, "utf8")).toBe("first");+ atomicWriteFileSync(target, "second");+ expect(readFileSync(target, "utf8")).toBe("second");+ });++ test("creates parent directories", () => {+ const target = join(tmp, "a", "b", "c.md");+ atomicWriteFileSync(target, "deep");+ expect(readFileSync(target, "utf8")).toBe("deep");+ });++ test("leaves no orphaned temp file on success", () => {+ const target = join(tmp, "x.md");+ atomicWriteFileSync(target, "hi");+ const stragglers = readdirSync(tmp).filter((n) => n.startsWith(".") && n.endsWith(".tmp"));+ expect(stragglers).toEqual([]);+ });+});++describe("atomicCreateFileSyncExclusive", () => {+ test("creates a new file", () => {+ const target = join(tmp, "x.md");+ atomicCreateFileSyncExclusive(target, "hello");+ expect(readFileSync(target, "utf8")).toBe("hello");+ });++ test("throws EEXIST on an existing file", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "preexisting");+ expect(() => atomicCreateFileSyncExclusive(target, "new")).toThrow();+ try {+ atomicCreateFileSyncExclusive(target, "new");+ } catch (err) {+ expect((err as NodeJS.ErrnoException).code).toBe("EEXIST");+ }+ expect(readFileSync(target, "utf8")).toBe("preexisting");+ });++ test("removes its temp inode after EEXIST", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "preexisting");+ try {+ atomicCreateFileSyncExclusive(target, "new");+ } catch {+ // expected+ }+ const stragglers = readdirSync(tmp).filter((n) => n.startsWith(".") && n.endsWith(".tmp"));+ expect(stragglers).toEqual([]);+ });++ test("removes its temp inode after success", () => {+ const target = join(tmp, "x.md");+ atomicCreateFileSyncExclusive(target, "ok");+ expect(existsSync(target)).toBe(true);+ const stragglers = readdirSync(tmp).filter((n) => n.startsWith(".") && n.endsWith(".tmp"));+ expect(stragglers).toEqual([]);+ });++ test("creates parent directories", () => {+ const target = join(tmp, "a", "b", "c.md");+ atomicCreateFileSyncExclusive(target, "deep");+ expect(readFileSync(target, "utf8")).toBe("deep");+ });+});diff --git a/tests/core/path-safety.test.ts b/tests/core/path-safety.test.tsnew file mode 100644index 00000000..63b7d251--- /dev/null+++ b/tests/core/path-safety.test.ts@@ -0,0 +1,100 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";++import { ensureInsideVault, vaultRelative } from "../../src/core/path-safety.ts";++// Resolving `/v` produces a platform-appropriate absolute path:+// `/v` on POSIX, `C:\v` (or the current drive) on Windows. Building all+// fixtures off this anchor keeps the assertions portable across both+// without baking POSIX separators into the test inputs.+const VAULT = resolve("/v");+const SIBLING = resolve("/v-evil");+const OUTSIDE = resolve("/etc/passwd");++describe("ensureInsideVault", () => {+ test("accepts the vault root itself", () => {+ expect(ensureInsideVault(VAULT, VAULT)).toBe(VAULT);+ });++ test("accepts descendants", () => {+ const target = join(VAULT, "AI Wiki", "notes", "x.md");+ expect(ensureInsideVault(target, VAULT)).toBe(target);+ });++ test("rejects siblings sharing a name prefix", () => {+ // Without using `path.sep`, the naive `startsWith(vault + "/")` check+ // would happily admit `/v-evil/...` because `/v-evil` starts with `/v`+ // when concatenated. The fixed implementation rejects it.+ expect(() => ensureInsideVault(join(SIBLING, "x.md"), VAULT)).toThrow(+ /escapes vault/,+ );+ });++ test("rejects paths that resolve outside the vault", () => {+ expect(() => ensureInsideVault(OUTSIDE, VAULT)).toThrow();+ expect(() => ensureInsideVault(join(VAULT, "..", "etc", "passwd"), VAULT)).toThrow();+ });++ test("returns the resolved absolute path", () => {+ const target = join(VAULT, "AI Wiki", "x.md");+ expect(ensureInsideVault(target, VAULT)).toBe(target);+ });+});++describe("ensureInsideVault β realpath / symlink escape", () => {+ // These tests need real on-disk symlinks so realpath() can follow them;+ // the synthetic-path tests above exercise the lexical-only fast path.+ let tmp: string;+ let vault: string;+ let outside: string;++ beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-path-safety-real-"));+ vault = join(tmp, "vault");+ outside = join(tmp, "outside");+ mkdirSync(vault, { recursive: true });+ mkdirSync(outside, { recursive: true });+ writeFileSync(join(outside, "secret.md"), "secret\n");+ });++ afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ });++ test("rejects a target whose ancestor is a symlink to outside the vault", () => {+ // <vault>/escape -> <outside>+ symlinkSync(outside, join(vault, "escape"), "dir");+ const target = join(vault, "escape", "secret.md");+ expect(() => ensureInsideVault(target, vault)).toThrow(/escapes vault via symlink/);+ });++ test("accepts a target inside a real subdirectory", () => {+ const sub = join(vault, "AI Wiki");+ mkdirSync(sub, { recursive: true });+ expect(ensureInsideVault(join(sub, "x.md"), vault)).toBe(join(sub, "x.md"));+ });++ test("accepts a still-non-existent target whose existing ancestor is the vault itself", () => {+ // No symlink involved; just a fresh slug on a real vault. realpath+ // protection should not crash on a path component that doesn't exist+ // yet (the writer creates it after this check passes).+ expect(+ ensureInsideVault(join(vault, "AI Wiki", "payments", "2026-05-10", "x.md"), vault),+ ).toBe(join(vault, "AI Wiki", "payments", "2026-05-10", "x.md"));+ });+});++describe("vaultRelative", () => {+ test("renders descendant paths with forward slashes", () => {+ const target = join(VAULT, "AI Wiki", "notes", "x.md");+ // The renderer always emits forward slashes, even when the host+ // separator is `\`, so wikilinks/Obsidian behave consistently.+ expect(vaultRelative(target, VAULT)).toBe("AI Wiki/notes/x.md");+ });++ test("returns empty string for the vault root itself", () => {+ expect(vaultRelative(VAULT, VAULT)).toBe("");+ });+});diff --git a/tests/core/pay-memory.approval.test.ts b/tests/core/pay-memory.approval.test.tsnew file mode 100644index 00000000..ad9cd222--- /dev/null+++ b/tests/core/pay-memory.approval.test.ts@@ -0,0 +1,204 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ approvePendingRequest,+ consumePendingRequest,+ listPendingRequests,+ loadPendingRequest,+ PENDING_REQUEST_FRONTMATTER_TYPE,+ rejectPendingRequest,+ writePendingRequest,+} from "../../src/core/pay-memory/approval.ts";+import { policyJsonPath } from "../../src/core/pay-memory/policy-rules.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pay-approval-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const baseInput = {+ agent: "hermes-vps-agent",+ service: "paysponge/fal",+ reason: "Generate one blog header image",+ date: "2026-05-10",+ time: "10:00",+};++describe("writePendingRequest", () => {+ test("creates a pending-payment-request artifact with frontmatter and body", () => {+ const out = writePendingRequest(tmp, baseInput);+ expect(out.status).toBe("pending");+ expect(out.relativePath.startsWith("AI Wiki/payments/_pending/")).toBe(true);+ expect(out.id.startsWith("req-2026-05-10-1000-fal-")).toBe(true);+ expect(out.policyDecision.hasPolicy).toBe(false);++ const text = readFileSync(out.path, "utf8");+ expect(text).toContain(`type: ${PENDING_REQUEST_FRONTMATTER_TYPE}`);+ expect(text).toContain("status: pending");+ expect(text).toContain("# Pending Payment Request: Generate one blog header image");+ expect(text).toContain("o2b approve-payment-request");+ });++ test("records expected_amount + currency + endpoint when supplied", () => {+ const out = writePendingRequest(tmp, {+ ...baseInput,+ expectedAmount: 0.05,+ currency: "USDC",+ endpoint: "https://gateway.example/v1/fal",+ expectedOutput: "PNG image, 1024Γ512",+ vaultFiles: ["AI Wiki/drafts/post.md", "AI Wiki/assets/header.md"],+ });+ const text = readFileSync(out.path, "utf8");+ expect(text).toContain("expected_amount: 0.05");+ expect(text).toContain("currency: USDC");+ expect(text).toContain("- `AI Wiki/drafts/post.md`");+ expect(text).toContain("PNG image, 1024Γ512");+ });++ test("records the policy decision when policies/spending.json is present", () => {+ mkdirSync(join(tmp, "AI Wiki", "policies"), { recursive: true });+ writeFileSync(+ policyJsonPath(tmp),+ JSON.stringify({ allowed_services: ["paysponge/fal"], require_approval_above: 0.04 }),+ "utf8",+ );+ const out = writePendingRequest(tmp, { ...baseInput, expectedAmount: 0.05 });+ expect(out.policyDecision.status).toBe("approval_required");+ const text = readFileSync(out.path, "utf8");+ expect(text).toContain("policy_status: approval_required");+ expect(text).toContain("Status: `approval_required`");+ });++ test("enforcePolicy=true blocks creation when policy denies", () => {+ mkdirSync(join(tmp, "AI Wiki", "policies"), { recursive: true });+ writeFileSync(+ policyJsonPath(tmp),+ JSON.stringify({ allowed_services: ["paysponge/fal"] }),+ "utf8",+ );+ expect(() =>+ writePendingRequest(tmp, {+ ...baseInput,+ service: "alpha/translate",+ enforcePolicy: true,+ }),+ ).toThrow(/policy denied/);+ });++ test("rejects missing required fields", () => {+ expect(() => writePendingRequest(tmp, { ...baseInput, service: "" })).toThrow();+ expect(() => writePendingRequest(tmp, { ...baseInput, reason: "" })).toThrow();+ expect(() => writePendingRequest(tmp, { ...baseInput, agent: "" })).toThrow();+ });++ test("refuses to overwrite an existing request id", () => {+ writePendingRequest(tmp, { ...baseInput, slug: "fixed" });+ expect(() => writePendingRequest(tmp, { ...baseInput, slug: "fixed" })).toThrow(+ /already exists/,+ );+ });+});++describe("state transitions", () => {+ test("pending β approved sets status, approved_by, approved_at", async () => {+ const created = writePendingRequest(tmp, { ...baseInput, slug: "t-1" });+ const out = await approvePendingRequest(tmp, "t-1", { approvedBy: "sergey", note: "ok" });+ expect(out.status).toBe("approved");+ expect(out.id).toBe("t-1");+ const reloaded = loadPendingRequest(tmp, "t-1")!;+ expect(reloaded.metadata["status"]).toBe("approved");+ expect(reloaded.metadata["approved_by"]).toBe("sergey");+ expect(reloaded.metadata["approval_note"]).toBe("ok");+ expect(typeof reloaded.metadata["approved_at"]).toBe("string");+ void created;+ });++ test("pending β rejected sets reason", async () => {+ writePendingRequest(tmp, { ...baseInput, slug: "t-2" });+ await rejectPendingRequest(tmp, "t-2", { rejectedBy: "sergey", reason: "too expensive" });+ const reloaded = loadPendingRequest(tmp, "t-2")!;+ expect(reloaded.metadata["status"]).toBe("rejected");+ expect(reloaded.metadata["rejection_reason"]).toBe("too expensive");+ });++ test("approve then consume requires the approved state", async () => {+ writePendingRequest(tmp, { ...baseInput, slug: "t-3" });+ await expect(+ consumePendingRequest(tmp, "t-3", { receiptPath: "x" }),+ ).rejects.toThrow(/cannot transition request t-3 from pending to consumed/);+ await approvePendingRequest(tmp, "t-3", { approvedBy: "sergey" });+ const out = await consumePendingRequest(tmp, "t-3", {+ receiptPath: "AI Wiki/payments/2026-05-10/x.md",+ });+ expect(out.status).toBe("consumed");+ const reloaded = loadPendingRequest(tmp, "t-3")!;+ expect(reloaded.metadata["receipt"]).toBe("AI Wiki/payments/2026-05-10/x.md");+ });++ test("rejected and consumed are terminal", async () => {+ writePendingRequest(tmp, { ...baseInput, slug: "t-4" });+ await rejectPendingRequest(tmp, "t-4", { rejectedBy: "sergey" });+ await expect(+ approvePendingRequest(tmp, "t-4", { approvedBy: "x" }),+ ).rejects.toThrow();++ writePendingRequest(tmp, { ...baseInput, slug: "t-5" });+ await approvePendingRequest(tmp, "t-5", { approvedBy: "sergey" });+ await consumePendingRequest(tmp, "t-5", { receiptPath: "x" });+ await expect(+ consumePendingRequest(tmp, "t-5", { receiptPath: "y" }),+ ).rejects.toThrow();+ });++ test("transitioning a non-existent request throws", async () => {+ await expect(+ approvePendingRequest(tmp, "nope", { approvedBy: "x" }),+ ).rejects.toThrow(/not found/);+ });++ test("concurrent approve+reject on the same id: exactly one transition wins", async () => {+ // The race the v0.8.0 review flagged: two processes both read+ // `pending`, both pass the check, both write β last writer wins.+ // With the per-request lockfile the second transition observes the+ // first one's terminal state and is rejected.+ writePendingRequest(tmp, { ...baseInput, slug: "race-1" });+ const results = await Promise.allSettled([+ approvePendingRequest(tmp, "race-1", { approvedBy: "sergey" }),+ rejectPendingRequest(tmp, "race-1", { rejectedBy: "sergey" }),+ ]);+ const ok = results.filter((r) => r.status === "fulfilled");+ const failed = results.filter((r) => r.status === "rejected");+ expect(ok.length).toBe(1);+ expect(failed.length).toBe(1);+ if (failed[0]!.status === "rejected") {+ expect(String(failed[0]!.reason)).toMatch(/cannot transition/);+ }+ });+});++describe("listPendingRequests", () => {+ test("filters by status (default pending)", async () => {+ writePendingRequest(tmp, { ...baseInput, slug: "p-1" });+ writePendingRequest(tmp, { ...baseInput, slug: "p-2" });+ await rejectPendingRequest(tmp, "p-2", { rejectedBy: "x" });++ const pending = listPendingRequests(tmp);+ expect(pending.map((s) => s.id)).toEqual(["p-1"]);+ const all = listPendingRequests(tmp, { status: "all" });+ expect(all.map((s) => s.id).sort()).toEqual(["p-1", "p-2"]);+ const rejected = listPendingRequests(tmp, { status: "rejected" });+ expect(rejected.map((s) => s.id)).toEqual(["p-2"]);+ });++ test("returns empty when the directory is missing", () => {+ expect(listPendingRequests(tmp)).toEqual([]);+ });+});diff --git a/tests/core/pay-memory.asset.test.ts b/tests/core/pay-memory.asset.test.tsnew file mode 100644index 00000000..61a9221e--- /dev/null+++ b/tests/core/pay-memory.asset.test.ts@@ -0,0 +1,88 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { parseFrontmatter } from "../../src/core/vault.ts";+import { writeAsset } from "../../src/core/pay-memory/asset.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pay-asset-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const base = {+ title: "Blog Header: OpenSecondBrain Pay Memory",+ service: "paysponge/fal",+ resultUrl: "https://fal-cdn.example/abc.png",+};++describe("writeAsset", () => {+ test("creates the note with derived slug and frontmatter", () => {+ const out = writeAsset(tmp, base);+ expect(out.relativePath.startsWith("AI Wiki/assets/")).toBe(true);+ expect(out.slug).toContain("blog-header");++ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["type"]).toBe("generated-asset");+ expect(meta["title"]).toBe(base.title);+ expect(meta["source"]).toBe(base.service);+ expect(meta["result_url"]).toBe(base.resultUrl);+ expect(body).toContain(`# ${base.title}`);+ expect(body).toContain(base.resultUrl);+ });++ test("links to source receipt and used-in draft as wikilinks", () => {+ const out = writeAsset(tmp, {+ ...base,+ sourceReceipt: "AI Wiki/payments/2026-05-10/fal-blog.md",+ usedIn: "AI Wiki/drafts/blog-post.md",+ prompt: "A recursive technical blog illustration\nNo logos\nNo text",+ });+ const text = readFileSync(out.path, "utf8");+ expect(text).toContain('source_receipt: "[[AI Wiki/payments/2026-05-10/fal-blog]]"');+ expect(text).toContain('used_in: "[[AI Wiki/drafts/blog-post]]"');+ expect(text).toContain("> A recursive technical blog illustration");+ expect(text).toContain("> No logos");+ });++ test("refuses to overwrite without flag", () => {+ writeAsset(tmp, base);+ expect(() => writeAsset(tmp, base)).toThrow(/already exists/);+ expect(() => writeAsset(tmp, { ...base, overwrite: true })).not.toThrow();+ });++ test("rejects missing required fields", () => {+ expect(() => writeAsset(tmp, { ...base, title: "" })).toThrow();+ expect(() => writeAsset(tmp, { ...base, service: "" })).toThrow();+ expect(() => writeAsset(tmp, { ...base, resultUrl: "" })).toThrow();+ });++ test("respects explicit slug", () => {+ const out = writeAsset(tmp, { ...base, slug: "custom" });+ expect(out.slug).toBe("custom");+ expect(out.path.endsWith("custom.md")).toBe(true);+ });++ test("sanitizes brackets in source_receipt wikilink", () => {+ const out = writeAsset(tmp, {+ ...base,+ sourceReceipt: "AI Wiki/payments/2026-05-10/fal[v2].md",+ });+ const text = readFileSync(out.path, "utf8");+ expect(text).toContain('source_receipt: "[[AI Wiki/payments/2026-05-10/falv2]]"');+ expect(text).toContain("Receipt: [[AI Wiki/payments/2026-05-10/falv2]]");+ });++ test("escapes backticks in service name", () => {+ const out = writeAsset(tmp, { ...base, service: "weird/`evil`-svc" });+ const text = readFileSync(out.path, "utf8");+ expect(text).toContain("`weird/ΛevilΛ-svc`");+ expect(text).not.toContain("`weird/`evil`-svc`");+ });+});diff --git a/tests/core/pay-memory.digest.test.ts b/tests/core/pay-memory.digest.test.tsnew file mode 100644index 00000000..67aeaefb--- /dev/null+++ b/tests/core/pay-memory.digest.test.ts@@ -0,0 +1,139 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ buildPaymentDigest,+ DIGEST_SILENT_TOKEN,+ renderPaymentDigestTelegram,+} from "../../src/core/pay-memory/digest.ts";+import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pay-digest-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const baseInput = {+ agent: "h",+ status: "success",+ reason: "demo",+ date: "2026-05-10",+ time: "10:00",+};++describe("buildPaymentDigest", () => {+ test("empty when no receipts", () => {+ const d = buildPaymentDigest(tmp, { date: "2026-05-10" });+ expect(d.receipts).toBe(0);+ expect(d.services).toBe(0);+ expect(d.totalAmount).toBeNull();+ expect(d.currency).toBeNull();+ });++ test("counts unique services and sums same-currency amounts", () => {+ writeReceipt(tmp, {+ ...baseInput, service: "paysponge/fal", slug: "f1",+ actualAmount: "0.05", currency: "USDC",+ });+ writeReceipt(tmp, {+ ...baseInput, service: "paysponge/fal", slug: "f2",+ actualAmount: "0.02", currency: "USDC", reason: "demo-2",+ });+ writeReceipt(tmp, {+ ...baseInput, service: "alpha/translate", slug: "a1",+ actualAmount: "0.01", currency: "USDC", reason: "demo-3",+ });+ const d = buildPaymentDigest(tmp, { date: "2026-05-10" });+ expect(d.receipts).toBe(3);+ expect(d.services).toBe(2);+ expect(d.totalAmount).toBeCloseTo(0.08, 6);+ expect(d.currency).toBe("USDC");+ });++ test("totalAmount=null when receipts mix currencies", () => {+ writeReceipt(tmp, {+ ...baseInput, service: "x/y", slug: "u1",+ actualAmount: "0.05", currency: "USDC",+ });+ writeReceipt(tmp, {+ ...baseInput, service: "x/y", slug: "u2",+ actualAmount: "1.0", currency: "EUR", reason: "demo-2",+ });+ const d = buildPaymentDigest(tmp, { date: "2026-05-10" });+ expect(d.receipts).toBe(2);+ // Mixed-currency days do not produce a unitless numeric sum β both+ // total and currency are null so the renderer falls back to "β".+ expect(d.totalAmount).toBeNull();+ expect(d.currency).toBeNull();+ });++ test("ignores receipts without actual_amount", () => {+ writeReceipt(tmp, { ...baseInput, service: "x/y", slug: "n1" });+ const d = buildPaymentDigest(tmp, { date: "2026-05-10" });+ expect(d.receipts).toBe(1);+ expect(d.totalAmount).toBeNull();+ });+});++describe("renderPaymentDigestTelegram", () => {+ test("renders the 4-line Russian summary", () => {+ const text = renderPaymentDigestTelegram({+ date: "2026-05-10",+ services: 2,+ receipts: 3,+ totalAmount: 0.08,+ currency: "USDC",+ reportPath: "AI Wiki/reports/payment-report-2026-05-10.md",+ });+ expect(text).toContain("π³ ΠΠΏΠ»Π°ΡΠ΅Π½ΠΎ ΡΠ΅ΡΠ²ΠΈΡΠΎΠ²: **2**");+ expect(text).toContain("π° Π‘ΡΠΌΠΌΠ°: **0.08 USDC**");+ expect(text).toContain("π Π€Π°ΠΉΠ»Ρ ΡΠ΅ΠΊΠΎΠ²: **3**");+ expect(text).toContain(+ "π ΠΡΡΡΡ: `AI Wiki/reports/payment-report-2026-05-10.md`",+ );+ });++ test("emits [SILENT] when receipts == 0 in default mode", () => {+ const text = renderPaymentDigestTelegram({+ date: "x", services: 0, receipts: 0, totalAmount: null, currency: null,+ });+ expect(text).toBe(DIGEST_SILENT_TOKEN);+ });++ test("emits empty string with emptyMode=empty", () => {+ const text = renderPaymentDigestTelegram(+ { date: "x", services: 0, receipts: 0, totalAmount: null, currency: null },+ { emptyMode: "empty" },+ );+ expect(text).toBe("");+ });++ test("emits human summary with emptyMode=summary", () => {+ const text = renderPaymentDigestTelegram(+ { date: "2026-05-10", services: 0, receipts: 0, totalAmount: null, currency: null },+ { emptyMode: "summary" },+ );+ expect(text).toContain("Π½Π΅Ρ ΡΠ΅ΠΊΠΎΠ² Π·Π° 2026-05-10");+ });++ test("trims trailing zeros in amount formatting", () => {+ const text = renderPaymentDigestTelegram({+ date: "x", services: 1, receipts: 1, totalAmount: 0.5, currency: "USDC",+ });+ expect(text).toContain("π° Π‘ΡΠΌΠΌΠ°: **0.5 USDC**");+ });++ test("falls back to dash when totalAmount is null but receipts > 0", () => {+ const text = renderPaymentDigestTelegram({+ date: "x", services: 1, receipts: 1, totalAmount: null, currency: null,+ });+ expect(text).toContain("π° Π‘ΡΠΌΠΌΠ°: **β**");+ });+});diff --git a/tests/core/pay-memory.paths.test.ts b/tests/core/pay-memory.paths.test.tsnew file mode 100644index 00000000..536c5213--- /dev/null+++ b/tests/core/pay-memory.paths.test.ts@@ -0,0 +1,170 @@+import { describe, expect, test } from "bun:test";+import { join } from "node:path";++import {+ assetPath,+ isoDateNow,+ isoTimeNow,+ isoTimestampZ,+ payMemoryDirs,+ paymentsDateDir,+ policyPath,+ receiptPath,+ reportPath,+ validateIsoDate,+ validateIsoTime,+ validateSlug,+} from "../../src/core/pay-memory/paths.ts";++describe("payMemoryDirs", () => {+ test("composes the canonical AI Wiki layout", () => {+ const dirs = payMemoryDirs("/vault");+ expect(dirs.policies).toBe(join("/vault", "AI Wiki", "policies"));+ expect(dirs.payments).toBe(join("/vault", "AI Wiki", "payments"));+ expect(dirs.assets).toBe(join("/vault", "AI Wiki", "assets"));+ expect(dirs.drafts).toBe(join("/vault", "AI Wiki", "drafts"));+ expect(dirs.reports).toBe(join("/vault", "AI Wiki", "reports"));+ });++ test("policyPath, receiptPath, assetPath, reportPath", () => {+ expect(policyPath("/v")).toBe(join("/v", "AI Wiki", "policies", "spending.md"));+ expect(receiptPath("/v", "2026-05-10", "fal-x")).toBe(+ join("/v", "AI Wiki", "payments", "2026-05-10", "fal-x.md"),+ );+ expect(assetPath("/v", "header")).toBe(join("/v", "AI Wiki", "assets", "header.md"));+ expect(reportPath("/v", "demo")).toBe(join("/v", "AI Wiki", "reports", "demo.md"));+ });++ test("paymentsDateDir validates date", () => {+ expect(paymentsDateDir("/v", "2026-05-10")).toBe(+ join("/v", "AI Wiki", "payments", "2026-05-10"),+ );+ expect(() => paymentsDateDir("/v", "2026.05.10")).toThrow();+ expect(() => paymentsDateDir("/v", "10-05-2026")).toThrow();+ });+});++describe("validateIsoDate", () => {+ test("accepts well-formed ISO dates", () => {+ expect(validateIsoDate("2026-05-10")).toBe("2026-05-10");+ expect(validateIsoDate("2024-02-29")).toBe("2024-02-29"); // leap year+ });++ test("rejects bad shapes and impossible calendar dates", () => {+ expect(() => validateIsoDate("2026/05/10")).toThrow();+ expect(() => validateIsoDate("2026-13-01")).toThrow();+ expect(() => validateIsoDate("2026-02-30")).toThrow();+ expect(() => validateIsoDate("2025-02-29")).toThrow(); // non-leap+ expect(() => validateIsoDate("")).toThrow();+ });++ test("differentiates format vs calendar errors", () => {+ expect(() => validateIsoDate("nope")).toThrow(/format/);+ expect(() => validateIsoDate("2026-13-01")).toThrow(/valid calendar date/);+ expect(() => validateIsoDate("2025-02-29")).toThrow(/valid calendar date/);+ });+});++describe("validateIsoTime", () => {+ test("accepts 24-hour HH:MM", () => {+ expect(validateIsoTime("00:00")).toBe("00:00");+ expect(validateIsoTime("23:59")).toBe("23:59");+ });++ test("rejects out-of-range or malformed", () => {+ expect(() => validateIsoTime("24:00")).toThrow();+ expect(() => validateIsoTime("12:60")).toThrow();+ expect(() => validateIsoTime("9:30")).toThrow();+ });++ test("differentiates format vs range errors", () => {+ expect(() => validateIsoTime("nope")).toThrow(/format/);+ expect(() => validateIsoTime("24:00")).toThrow(/out of range/);+ expect(() => validateIsoTime("12:60")).toThrow(/out of range/);+ });+});++describe("validateSlug", () => {+ test("accepts plain slugs", () => {+ expect(validateSlug("fal-blog-header")).toBe("fal-blog-header");+ expect(validateSlug("alpha_beta-2")).toBe("alpha_beta-2");+ });++ test("rejects path separators", () => {+ expect(() => validateSlug("a/b")).toThrow(/path separators/);+ expect(() => validateSlug("a\\b")).toThrow(/path separators/);+ });++ test("rejects traversal", () => {+ expect(() => validateSlug("..")).toThrow(/traversal/);+ expect(() => validateSlug("..-evil")).toThrow(/traversal/);+ expect(() => validateSlug("evil-..")).toThrow(/traversal/);+ });++ test("rejects empty", () => {+ expect(() => validateSlug("")).toThrow();+ expect(() => validateSlug(" ")).toThrow();+ });++ test("trims whitespace", () => {+ expect(validateSlug(" ok-slug ")).toBe("ok-slug");+ });+});++describe("receiptPath / assetPath / reportPath reject traversal slugs", () => {+ test("receiptPath rejects '../escape'", () => {+ expect(() => receiptPath("/v", "2026-05-10", "../escape")).toThrow();+ });+ test("assetPath rejects 'a/b'", () => {+ expect(() => assetPath("/v", "a/b")).toThrow();+ });+ test("reportPath rejects '..'", () => {+ expect(() => reportPath("/v", "..")).toThrow();+ });+});++describe("isoDateNow / isoTimeNow", () => {+ test("returns YYYY-MM-DD and HH:MM shapes", () => {+ expect(isoDateNow()).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ expect(isoTimeNow()).toMatch(/^\d{2}:\d{2}$/);+ // With an explicit timezone the shape is preserved.+ expect(isoDateNow("UTC")).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ expect(isoTimeNow("UTC")).toMatch(/^\d{2}:\d{2}$/);+ });+});++describe("isoTimestampZ", () => {+ test("composes ISO Z timestamp from date+time (no tz = treat as UTC)", () => {+ expect(isoTimestampZ("2026-05-10", "17:20")).toBe("2026-05-10T17:20:00Z");+ });++ test("propagates validation errors", () => {+ expect(() => isoTimestampZ("nope", "17:20")).toThrow();+ expect(() => isoTimestampZ("2026-05-10", "25:00")).toThrow();+ });++ test("converts a local wall-clock in the given tz to real UTC", () => {+ // 09:00 in Asia/Tokyo (UTC+9, no DST) == 00:00Z same day. The point+ // of the tz-aware path is that 09:00 is not just relabelled `09:00Z`+ // (the bug the v0.8.0 review flagged) but actually shifted by the+ // zone's offset.+ expect(isoTimestampZ("2026-05-10", "09:00", "Asia/Tokyo")).toBe(+ "2026-05-10T00:00:00Z",+ );+ // Day rollover: 06:00 Tokyo = 21:00 UTC the previous day.+ expect(isoTimestampZ("2026-05-10", "06:00", "Asia/Tokyo")).toBe(+ "2026-05-09T21:00:00Z",+ );+ });++ test("uses the offset that was in effect for that specific instant (DST aware)", () => {+ // Belgrade is UTC+1 in winter, UTC+2 in summer. Same wall-clock,+ // different real UTC depending on the date.+ expect(isoTimestampZ("2026-01-15", "12:00", "Europe/Belgrade")).toBe(+ "2026-01-15T11:00:00Z",+ );+ expect(isoTimestampZ("2026-07-15", "12:00", "Europe/Belgrade")).toBe(+ "2026-07-15T10:00:00Z",+ );+ });+});diff --git a/tests/core/pay-memory.policy-rules.test.ts b/tests/core/pay-memory.policy-rules.test.tsnew file mode 100644index 00000000..88e8390d--- /dev/null+++ b/tests/core/pay-memory.policy-rules.test.ts@@ -0,0 +1,237 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ checkPolicy,+ evaluatePolicy,+ loadPolicyRules,+ policyJsonPath,+} from "../../src/core/pay-memory/policy-rules.ts";+import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pay-policy-rules-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function writePolicy(rules: unknown) {+ const path = policyJsonPath(tmp);+ mkdirSync(join(tmp, "AI Wiki", "policies"), { recursive: true });+ writeFileSync(path, JSON.stringify(rules, null, 2), "utf8");+}++describe("loadPolicyRules", () => {+ test("returns null when file is absent", () => {+ expect(loadPolicyRules(tmp)).toBeNull();+ });++ test("parses a well-formed policy", () => {+ writePolicy({+ schema_version: 1,+ currency: "USDC",+ max_total_per_day: 0.1,+ max_single_call: 0.07,+ allowed_services: ["paysponge/fal"],+ max_per_category: { media_generation: 1 },+ require_approval_above: 0.05,+ });+ const rules = loadPolicyRules(tmp)!;+ expect(rules.currency).toBe("USDC");+ expect(rules.max_total_per_day).toBe(0.1);+ expect(rules.allowed_services).toEqual(["paysponge/fal"]);+ expect(rules.max_per_category!["media_generation"]).toBe(1);+ });++ test("rejects malformed JSON", () => {+ const path = policyJsonPath(tmp);+ mkdirSync(join(tmp, "AI Wiki", "policies"), { recursive: true });+ writeFileSync(path, "{ not json", "utf8");+ expect(() => loadPolicyRules(tmp)).toThrow(/not valid JSON/);+ });++ test("rejects bad types", () => {+ writePolicy({ max_total_per_day: "0.10" });+ expect(() => loadPolicyRules(tmp)).toThrow(/non-negative finite/);+ });++ test("rejects negative numbers", () => {+ writePolicy({ max_single_call: -1 });+ expect(() => loadPolicyRules(tmp)).toThrow(/non-negative/);+ });+});++describe("evaluatePolicy", () => {+ test("fail-open when no rules", () => {+ const d = evaluatePolicy(null, { service: "x/y" }, { daySpend: 0, dayCategoryCount: 0 });+ expect(d.allowed).toBe(true);+ expect(d.hasPolicy).toBe(false);+ });++ test("denies a service not in allowed_services", () => {+ const d = evaluatePolicy(+ { allowed_services: ["paysponge/fal"] },+ { service: "alpha/translate" },+ { daySpend: 0, dayCategoryCount: 0 },+ );+ expect(d.allowed).toBe(false);+ expect(d.rule).toBe("allowed_services");+ expect(d.reasons[0]).toContain("not in allowed_services");+ });++ test("denies when expected_amount > max_single_call", () => {+ const d = evaluatePolicy(+ { allowed_services: ["x/y"], max_single_call: 0.05 },+ { service: "x/y", expectedAmount: 0.1 },+ { daySpend: 0, dayCategoryCount: 0 },+ );+ expect(d.rule).toBe("max_single_call");+ });++ test("denies when day spend + expected exceeds max_total_per_day", () => {+ const d = evaluatePolicy(+ { allowed_services: ["x/y"], max_total_per_day: 0.1 },+ { service: "x/y", expectedAmount: 0.05 },+ { daySpend: 0.07, dayCategoryCount: 0 },+ );+ expect(d.rule).toBe("max_total_per_day");+ });++ test("denies when category count cap reached", () => {+ const d = evaluatePolicy(+ { allowed_services: ["x/y"], max_per_category: { media_generation: 1 } },+ { service: "x/y", category: "media_generation" },+ { daySpend: 0, dayCategoryCount: 1 },+ );+ expect(d.rule).toBe("max_per_category");+ });++ test("flags approval_required when amount > require_approval_above", () => {+ const d = evaluatePolicy(+ { require_approval_above: 0.05 },+ { service: "x/y", expectedAmount: 0.07 },+ { daySpend: 0, dayCategoryCount: 0 },+ );+ expect(d.status).toBe("approval_required");+ expect(d.approvalRequired).toBe(true);+ expect(d.rule).toBe("require_approval_above");+ });++ test("missing expected_amount triggers approval_required when amount-rules exist", () => {+ // Policy declares any amount-based rule; agent omits expectedAmount.+ // Must not fail-open β otherwise the daily budget / single-call cap /+ // approval threshold can be bypassed by simply not stating the cost.+ for (const rule of [+ { max_single_call: 0.05 },+ { max_total_per_day: 0.10 },+ { require_approval_above: 0.03 },+ ] as const) {+ const d = evaluatePolicy(+ { allowed_services: ["x/y"], ...rule },+ { service: "x/y" }, // expectedAmount omitted+ { daySpend: 0, dayCategoryCount: 0 },+ );+ expect(d.status).toBe("approval_required");+ expect(d.rule).toBe("missing_expected_amount");+ }+ });++ test("missing expected_amount stays allowed when policy has no amount-rules", () => {+ const d = evaluatePolicy(+ { allowed_services: ["x/y"] },+ { service: "x/y" },+ { daySpend: 0, dayCategoryCount: 0 },+ );+ expect(d.status).toBe("allowed");+ });++ test("currency mismatch flags as denied with currency_mismatch rule", () => {+ const d = evaluatePolicy(+ { currency: "USDC", max_single_call: 0.1 },+ { service: "x/y", expectedAmount: 0.05, currency: "EUR" },+ { daySpend: 0, dayCategoryCount: 0 },+ );+ expect(d.allowed).toBe(false);+ expect(d.rule).toBe("currency_mismatch");+ });+});++describe("checkPolicy (end-to-end)", () => {+ test("aggregates today's receipts and applies day-budget cap", () => {+ writePolicy({+ currency: "USDC",+ allowed_services: ["x/y"],+ max_total_per_day: 0.1,+ });+ // Pre-write a receipt that consumed 0.07 USDC today.+ writeReceipt(tmp, {+ agent: "h",+ service: "x/y",+ status: "success",+ reason: "earlier",+ slug: "earlier-1",+ date: "2026-05-10",+ time: "08:00",+ actualAmount: "0.07",+ currency: "USDC",+ });+ const denied = checkPolicy(tmp, {+ service: "x/y",+ expectedAmount: 0.05,+ date: "2026-05-10",+ });+ expect(denied.allowed).toBe(false);+ expect(denied.rule).toBe("max_total_per_day");++ const ok = checkPolicy(tmp, {+ service: "x/y",+ expectedAmount: 0.02,+ date: "2026-05-10",+ });+ expect(ok.allowed).toBe(true);+ });++ test("category counter looks at the category frontmatter", () => {+ writePolicy({+ allowed_services: ["x/y"],+ max_per_category: { media_generation: 1 },+ });+ writeReceipt(tmp, {+ agent: "h",+ service: "x/y",+ status: "success",+ reason: "first",+ slug: "first-1",+ category: "media_generation",+ date: "2026-05-10",+ time: "08:00",+ });+ const denied = checkPolicy(tmp, {+ service: "x/y",+ category: "media_generation",+ date: "2026-05-10",+ });+ expect(denied.allowed).toBe(false);+ expect(denied.rule).toBe("max_per_category");+ });++ test("policy_path is the JSON file when present", () => {+ writePolicy({ allowed_services: ["x/y"] });+ const d = checkPolicy(tmp, { service: "x/y" });+ expect(d.policyPath).toBe(policyJsonPath(tmp));+ expect(d.hasPolicy).toBe(true);+ });++ test("policyPath is null when no policy file exists", () => {+ const d = checkPolicy(tmp, { service: "x/y" });+ expect(d.policyPath).toBeNull();+ expect(d.hasPolicy).toBe(false);+ expect(d.allowed).toBe(true);+ });+});diff --git a/tests/core/pay-memory.policy.test.ts b/tests/core/pay-memory.policy.test.tsnew file mode 100644index 00000000..2675e4c3--- /dev/null+++ b/tests/core/pay-memory.policy.test.ts@@ -0,0 +1,76 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ DEFAULT_POLICY_TEMPLATE,+ readPolicy,+ writePolicyIfMissing,+} from "../../src/core/pay-memory/policy.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pay-policy-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("writePolicyIfMissing", () => {+ test("creates the policy on first run", () => {+ const result = writePolicyIfMissing(tmp);+ expect(result.created).toBe(true);+ expect(result.skipped).toBe(false);+ expect(result.overwritten).toBe(false);+ expect(readFileSync(result.path, "utf8")).toBe(DEFAULT_POLICY_TEMPLATE);+ });++ test("re-running without --overwrite leaves existing content intact", () => {+ const first = writePolicyIfMissing(tmp);+ writeFileSync(first.path, "manually edited\n", "utf8");+ const second = writePolicyIfMissing(tmp);+ expect(second.skipped).toBe(true);+ expect(second.created).toBe(false);+ expect(readFileSync(second.path, "utf8")).toBe("manually edited\n");+ });++ test("--overwrite rewrites the policy", () => {+ const first = writePolicyIfMissing(tmp);+ writeFileSync(first.path, "stale\n", "utf8");+ const second = writePolicyIfMissing(tmp, { overwrite: true });+ expect(second.overwritten).toBe(true);+ expect(second.created).toBe(false);+ expect(readFileSync(second.path, "utf8")).toBe(DEFAULT_POLICY_TEMPLATE);+ });+});++describe("readPolicy", () => {+ test("returns null when missing", () => {+ expect(readPolicy(tmp)).toBeNull();+ });++ test("returns content when present", () => {+ writePolicyIfMissing(tmp);+ expect(readPolicy(tmp)).toBe(DEFAULT_POLICY_TEMPLATE);+ });+});++describe("DEFAULT_POLICY_TEMPLATE", () => {+ test("includes generic placeholders, not pinned services", () => {+ expect(DEFAULT_POLICY_TEMPLATE).toContain("## Allowed services");+ expect(DEFAULT_POLICY_TEMPLATE).toContain("- TODO");+ // The example service appears only as a comment-block hint.+ const idx = DEFAULT_POLICY_TEMPLATE.indexOf("paysponge/fal");+ expect(idx).toBeGreaterThan(-1);+ const before = DEFAULT_POLICY_TEMPLATE.slice(0, idx);+ expect(before.lastIndexOf("<!--")).toBeGreaterThan(before.lastIndexOf("-->"));+ });++ test("documents the post-call evidence the agent must save", () => {+ expect(DEFAULT_POLICY_TEMPLATE).toContain("raw payment-tool output");+ expect(DEFAULT_POLICY_TEMPLATE).toContain("AI Wiki/payments/<date>/");+ });+});diff --git a/tests/core/pay-memory.receipt.test.ts b/tests/core/pay-memory.receipt.test.tsnew file mode 100644index 00000000..746046ad--- /dev/null+++ b/tests/core/pay-memory.receipt.test.ts@@ -0,0 +1,234 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { parseFrontmatter } from "../../src/core/vault.ts";+import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pay-receipt-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const baseInput = {+ agent: "hermes-main",+ service: "paysponge/fal",+ status: "success",+ reason: "Generate one original blog header image",+ date: "2026-05-10",+ time: "17:20",+};++describe("writeReceipt", () => {+ test("writes a receipt with a default slug derived from service tail + reason", () => {+ const out = writeReceipt(tmp, baseInput);+ expect(out.date).toBe("2026-05-10");+ expect(out.created).toBe("2026-05-10T17:20:00Z");+ expect(out.slug.startsWith("fal-")).toBe(true);+ expect(out.relativePath.startsWith("AI Wiki/payments/2026-05-10/")).toBe(true);++ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["type"]).toBe("agent-payment-receipt");+ expect(meta["agent"]).toBe("hermes-main");+ expect(meta["service"]).toBe("paysponge/fal");+ expect(meta["status"]).toBe("success");+ expect(meta["payment_layer"]).toBe("pay.sh");+ expect(meta["network"]).toBe("solana");+ expect(meta["created"]).toBe("2026-05-10T17:20:00Z");+ expect(body).toContain("# Payment Receipt: Generate one original blog header image");+ expect(body).toContain("[[AI Wiki/policies/spending]]");+ });++ test("respects an explicit slug", () => {+ const out = writeReceipt(tmp, { ...baseInput, slug: "custom-slug" });+ expect(out.slug).toBe("custom-slug");+ expect(out.path.endsWith("custom-slug.md")).toBe(true);+ });++ test("refuses to overwrite without flag, allows with overwrite=true", () => {+ writeReceipt(tmp, baseInput);+ expect(() => writeReceipt(tmp, baseInput)).toThrow(/already exists/);+ const second = writeReceipt(tmp, { ...baseInput, overwrite: true });+ expect(second.slug).toBeDefined();+ });++ test("emits optional frontmatter only when present", () => {+ const out = writeReceipt(tmp, {+ ...baseInput,+ category: "media_generation",+ endpoint: "https://gateway.example/v1/fal",+ expectedCost: "$0.01-$0.07",+ actualAmount: "0.05",+ currency: "USDC",+ paymentProof: "5G3...sig",+ resultRef: "https://fal-cdn.example/abc.png",+ resultNote: "AI Wiki/assets/blog-header.md",+ rawOutput: "{\"ok\": true}",+ });+ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["category"]).toBe("media_generation");+ expect(meta["endpoint"]).toBe("https://gateway.example/v1/fal");+ expect(meta["expected_cost"]).toBe("$0.01-$0.07");+ expect(meta["actual_amount"]).toBe("0.05");+ expect(meta["currency"]).toBe("USDC");+ expect(meta["payment_proof"]).toBe("5G3...sig");+ expect(meta["result_ref"]).toBe("https://fal-cdn.example/abc.png");+ expect(meta["result_note"]).toBe("AI Wiki/assets/blog-header.md");+ expect(body).toContain("[[AI Wiki/assets/blog-header]]");+ expect(body).toContain("`USDC`");+ expect(body).not.toContain("_(not provided)_");+ });++ test("renders placeholders for missing optional fields", () => {+ const out = writeReceipt(tmp, baseInput);+ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["endpoint"]).toBeUndefined();+ expect(meta["actual_amount"]).toBeUndefined();+ expect(body).toContain("_(not provided)_");+ });++ test("redacts secrets in raw_output before writing", () => {+ const raw = [+ "request: GET /v1/foo",+ 'Authorization: Bearer eyJhbGciOi.SECRET',+ 'response: {"api_key": "sk_live_abc", "ok": true}',+ ].join("\n");+ const out = writeReceipt(tmp, { ...baseInput, rawOutput: raw });+ const text = readFileSync(out.path, "utf8");+ expect(text).toContain("***REDACTED***");+ expect(text).not.toContain("sk_live_abc");+ expect(text).not.toContain("eyJhbGciOi.SECRET");+ expect(text).toContain("/v1/foo");+ });++ test("rejects missing required fields", () => {+ expect(() => writeReceipt(tmp, { ...baseInput, service: "" })).toThrow();+ expect(() => writeReceipt(tmp, { ...baseInput, status: "" })).toThrow();+ expect(() => writeReceipt(tmp, { ...baseInput, reason: "" })).toThrow();+ expect(() => writeReceipt(tmp, { ...baseInput, agent: "" })).toThrow();+ });++ test("sanitizes brackets in resultNote wikilink", () => {+ const out = writeReceipt(tmp, {+ ...baseInput,+ resultNote: "AI Wiki/assets/blog [draft].md",+ });+ const text = readFileSync(out.path, "utf8");+ expect(text).toContain("[[AI Wiki/assets/blog draft]]");+ expect(text).not.toContain("[draft]]]");+ });++ test("escapes backticks in inline-code rendered fields", () => {+ const out = writeReceipt(tmp, {+ ...baseInput,+ service: "weird/`inject`-svc",+ slug: "weird-1",+ });+ const text = readFileSync(out.path, "utf8");+ // Surrounding backticks must remain a single span β embedded backticks+ // are replaced with the visually similar grave-accent placeholder.+ expect(text).toContain("`weird/ΛinjectΛ-svc`");+ expect(text).not.toContain("`weird/`inject`-svc`");+ });++ test("policy_status defaults to `not_checked` and the body says so", () => {+ const out = writeReceipt(tmp, baseInput);+ const text = readFileSync(out.path, "utf8");+ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["policy_status"]).toBe("not_checked");+ expect(body).toContain("Not checked.");+ // The old hardcoded "Allowed by the configured spending policy" line+ // must NOT appear when no decision was supplied β that was the+ // pre-fix lie the v0.8.0 review flagged.+ expect(text).not.toContain("Allowed by the configured spending policy");+ });++ test("policy_status='allowed' renders the explicit allowed message", () => {+ const out = writeReceipt(tmp, { ...baseInput, slug: "a-1", policyStatus: "allowed" });+ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["policy_status"]).toBe("allowed");+ expect(body).toContain("Allowed by the configured spending policy");+ });++ test("approval_required renders rule + reasons + approval link", () => {+ const out = writeReceipt(tmp, {+ ...baseInput,+ slug: "ar-1",+ policyStatus: "approval_required",+ policyRule: "max_single_call",+ policyReasons: ["expected amount 0.10 USDC exceeds max_single_call 0.07 USDC"],+ approvalRequestId: "req-2026-05-10-fal",+ approvalStatus: "approved",+ approvedBy: "sergey",+ approvedAt: "2026-05-10T17:25:00Z",+ });+ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["policy_status"]).toBe("approval_required");+ expect(meta["policy_rule"]).toBe("max_single_call");+ expect(meta["approval_status"]).toBe("approved");+ expect(meta["approved_by"]).toBe("sergey");+ expect(body).toContain("Policy returned `approval_required`");+ expect(body).toContain("Rule fired: `max_single_call`");+ expect(body).toContain("expected amount 0.10 USDC exceeds max_single_call 0.07 USDC");+ expect(body).toContain("[[AI Wiki/payments/_pending/req-2026-05-10-fal]]");+ expect(body).toContain("Approved by: sergey");+ });++ test("payment_layer and network override hardcoded defaults", () => {+ const out = writeReceipt(tmp, {+ ...baseInput,+ slug: "rail-1",+ paymentLayer: "x402-direct",+ network: "ethereum",+ });+ const [meta] = parseFrontmatter(out.path);+ expect(meta["payment_layer"]).toBe("x402-direct");+ expect(meta["network"]).toBe("ethereum");+ });++ test("payment_layer and network defaults stay pay.sh / solana when unset", () => {+ const out = writeReceipt(tmp, { ...baseInput, slug: "rail-default" });+ const [meta] = parseFrontmatter(out.path);+ expect(meta["payment_layer"]).toBe("pay.sh");+ expect(meta["network"]).toBe("solana");+ });++ test("policy_status='denied' renders the truth β receipt records the override", () => {+ const out = writeReceipt(tmp, {+ ...baseInput,+ slug: "d-1",+ policyStatus: "denied",+ policyRule: "allowed_services",+ });+ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["policy_status"]).toBe("denied");+ expect(body).toContain("Policy returned `denied`");+ expect(body).toContain("explicitly waved the policy aside");+ });++ test("concurrent writers to the same slug: exactly one succeeds", async () => {+ // Race two writers via Promise.allSettled. Both call writeReceipt+ // synchronously inside an async wrapper, so they hit the+ // atomicCreateFileSyncExclusive path back-to-back. With the link(2)+ // semantic, one succeeds and the other receives an "already exists"+ // error β never both, never neither.+ const args = { ...baseInput, slug: "race-1" };+ const results = await Promise.allSettled([+ Promise.resolve().then(() => writeReceipt(tmp, args)),+ Promise.resolve().then(() => writeReceipt(tmp, args)),+ ]);+ const fulfilled = results.filter((r) => r.status === "fulfilled");+ const rejected = results.filter((r) => r.status === "rejected");+ expect(fulfilled.length).toBe(1);+ expect(rejected.length).toBe(1);+ if (rejected[0]!.status === "rejected") {+ expect(String(rejected[0]!.reason)).toContain("already exists");+ }+ });+});diff --git a/tests/core/pay-memory.redactor.test.ts b/tests/core/pay-memory.redactor.test.tsnew file mode 100644index 00000000..673e2197--- /dev/null+++ b/tests/core/pay-memory.redactor.test.ts@@ -0,0 +1,80 @@+import { describe, expect, test } from "bun:test";++import { redactRawOutput, SECRET_KEYS } from "../../src/core/pay-memory/redactor.ts";++describe("redactRawOutput", () => {+ test("redacts env-style key=value", () => {+ expect(redactRawOutput("API_KEY=sk_live_abc123 other=visible")).toBe(+ "API_KEY=***REDACTED*** other=visible",+ );+ expect(redactRawOutput("token=eyJhbGciOi.LongString")).toBe("token=***REDACTED***");+ });++ test("redacts YAML / log-style key: value", () => {+ expect(redactRawOutput("api_key: sk_test_xyz")).toBe("api_key: ***REDACTED***");+ expect(redactRawOutput("Authorization: super-secret-value")).toBe(+ "Authorization: ***REDACTED***",+ );+ });++ test("redacts JSON entries", () => {+ expect(redactRawOutput('{"api_key": "abc", "name": "ok"}')).toBe(+ '{"api_key": "***REDACTED***", "name": "ok"}',+ );+ expect(redactRawOutput('{"token":"long.signed.value"}')).toBe(+ '{"token":"***REDACTED***"}',+ );+ });++ test("redacts Authorization: Bearer headers and preserves the `Bearer` prefix", () => {+ expect(redactRawOutput("Authorization: Bearer abc.def.ghi")).toBe(+ "Authorization: Bearer ***REDACTED***",+ );+ // When the key is absent but the bearer token is, fall back to the bearer rule.+ expect(redactRawOutput("Sent header: Bearer abc.def")).toBe(+ "Sent header: Bearer ***REDACTED***",+ );+ });++ test("does not match unrelated phrases that contain secret-key words", () => {+ // No `=`, `:`, or quoted-key shape β the word "secret" stays.+ expect(redactRawOutput("My favourite secret recipe is curry.")).toBe(+ "My favourite secret recipe is curry.",+ );+ });++ test("multi-line input", () => {+ const input = [+ "request:",+ " api_key: abc123",+ " endpoint: https://example/v1/foo",+ "response:",+ ' {"token": "xyz"}',+ ].join("\n");+ const out = redactRawOutput(input);+ expect(out).toContain("api_key: ***REDACTED***");+ expect(out).toContain('"token": "***REDACTED***"');+ expect(out).toContain("https://example/v1/foo");+ });++ test("handles empty input", () => {+ expect(redactRawOutput("")).toBe("");+ });++ test("SECRET_KEYS is non-empty and includes the documented set", () => {+ for (const key of ["api_key", "token", "secret", "bearer", "authorization", "private_key"]) {+ expect(SECRET_KEYS).toContain(key);+ }+ });++ test("redacts password / credential / session_token assignments", () => {+ expect(redactRawOutput("password: hunter2")).toBe("password: ***REDACTED***");+ expect(redactRawOutput("PASSWD=somepw123")).toBe("PASSWD=***REDACTED***");+ expect(redactRawOutput('{"credential": "abc"}')).toBe(+ '{"credential": "***REDACTED***"}',+ );+ expect(redactRawOutput("session_token: eyJ.session.value")).toBe(+ "session_token: ***REDACTED***",+ );+ });+});diff --git a/tests/core/pay-memory.report.test.ts b/tests/core/pay-memory.report.test.tsnew file mode 100644index 00000000..526409c4--- /dev/null+++ b/tests/core/pay-memory.report.test.ts@@ -0,0 +1,121 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { parseFrontmatter } from "../../src/core/vault.ts";+import {+ aggregateReceipts,+ writeReport,+} from "../../src/core/pay-memory/report.ts";+import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-pay-report-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const baseReceipt = {+ agent: "hermes-main",+ service: "paysponge/fal",+ status: "success",+ reason: "Header image",+ date: "2026-05-10",+ time: "17:20",+};++describe("aggregateReceipts", () => {+ test("returns [] when the date directory is missing", () => {+ expect(aggregateReceipts(tmp, "2026-05-10")).toEqual([]);+ });++ test("collects multiple receipts and sorts by service", () => {+ writeReceipt(tmp, {+ ...baseReceipt,+ slug: "fal-1",+ actualAmount: "0.05",+ currency: "USDC",+ resultRef: "https://fal/img1",+ resultNote: "AI Wiki/assets/img1.md",+ });+ writeReceipt(tmp, {+ ...baseReceipt,+ service: "alpha/translate",+ slug: "alpha-1",+ reason: "Translate caption",+ actualAmount: "0.02",+ currency: "USDC",+ });+ const summaries = aggregateReceipts(tmp, "2026-05-10");+ expect(summaries.length).toBe(2);+ expect(summaries[0]!.service).toBe("alpha/translate");+ expect(summaries[1]!.service).toBe("paysponge/fal");+ expect(summaries[1]!.actualAmount).toBe("0.05");+ expect(summaries[1]!.resultRef).toBe("https://fal/img1");+ expect(summaries[1]!.resultNote).toBe("AI Wiki/assets/img1.md");+ });++ test("ignores files without the receipt frontmatter type", () => {+ writeReceipt(tmp, { ...baseReceipt, slug: "real-1" });+ const dir = join(tmp, "AI Wiki", "payments", "2026-05-10");+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, "stray.md"),+ "---\ntype: note\n---\n\nNot a receipt.\n",+ "utf8",+ );+ writeFileSync(join(dir, "no-frontmatter.md"), "Just a note.\n", "utf8");+ const summaries = aggregateReceipts(tmp, "2026-05-10");+ expect(summaries.length).toBe(1);+ expect(summaries[0]!.service).toBe("paysponge/fal");+ });+});++describe("writeReport", () => {+ test("renders a report with frontmatter and per-service sections", () => {+ writeReceipt(tmp, {+ ...baseReceipt,+ slug: "fal-1",+ actualAmount: "0.05",+ currency: "USDC",+ resultRef: "https://fal/img1",+ resultNote: "AI Wiki/assets/img1.md",+ });+ const out = writeReport(tmp, {+ date: "2026-05-10",+ title: "Demo Report",+ task: "Blog post about Pay Memory",+ });+ expect(out.receiptsUsed).toBe(1);+ expect(out.relativePath.startsWith("AI Wiki/reports/")).toBe(true);++ const [meta, body] = parseFrontmatter(out.path);+ expect(meta["type"]).toBe("payment-report");+ expect(meta["title"]).toBe("Demo Report");+ expect(meta["date"]).toBe("2026-05-10");+ expect(meta["receipts_used"]).toBe("1");+ expect(meta["task"]).toBe("Blog post about Pay Memory");+ expect(body).toContain("### paysponge/fal");+ expect(body).toContain("Amount: `0.05 USDC`");+ expect(body).toContain("[[AI Wiki/payments/2026-05-10/fal-1]]");+ expect(body).toContain("[[AI Wiki/assets/img1]]");+ });++ test("renders gracefully when there are no receipts", () => {+ const out = writeReport(tmp, { date: "2026-05-10" });+ expect(out.receiptsUsed).toBe(0);+ const text = readFileSync(out.path, "utf8");+ expect(text).toContain("No receipts found for this date.");+ });++ test("refuses to overwrite without flag", () => {+ writeReport(tmp, { date: "2026-05-10" });+ expect(() => writeReport(tmp, { date: "2026-05-10" })).toThrow(/already exists/);+ expect(() => writeReport(tmp, { date: "2026-05-10", overwrite: true })).not.toThrow();+ });+});diff --git a/tests/e2e/pay-memory-factchecktools.sh b/tests/e2e/pay-memory-factchecktools.shnew file mode 100755index 00000000..dc029be9--- /dev/null+++ b/tests/e2e/pay-memory-factchecktools.sh@@ -0,0 +1,130 @@+#!/usr/bin/env bash+#+# Real-data manual e2e for Pay Memory via the Google Fact Check Tools API+# exposed on pay.sh (`solana-foundation/google/factchecktools`).+#+# Why this service:+# - The endpoint is published in the pay-skills catalog with no `$`+# marker, i.e. free at the gateway tier β no payment challenge is+# issued β so we can exercise the full pipeline without spending or+# even configuring a mainnet wallet.+# - The upstream is Google's real Fact Check Tools API, so the receipt+# and asset hold genuine fact-check claims rather than synthetic+# debugger fixtures.+#+# Usage:+# bash tests/e2e/pay-memory-factchecktools.sh [vault-dir] [query]+#+# vault-dir defaults to /tmp/o2b-factchecktools-<ts>+# query defaults to "climate change"+#+# To switch to mainnet (real Solana payment when the endpoint actually+# charges):+# 1. Run `pay setup` interactively and fund the resulting account.+# 2. Drop the `--sandbox` flag below.+# Open Second Brain itself never needs to know β the only difference on+# our side is the raw output the receipt embeds.++set -euo pipefail++ROOT=$(cd "$(dirname "$0")/../.." && pwd)+VAULT=${1:-/tmp/o2b-factchecktools-$(date +%s)}+QUERY=${2:-climate change}+CONFIG=$(mktemp -t o2b-factchecktools-config-XXXXXX.yaml)+RAW_OUTPUT=$(mktemp -t pay-factchecktools-output-XXXXXX.txt)++cleanup() {+ rm -f "$CONFIG" "$RAW_OUTPUT"+}+trap cleanup EXIT++if ! command -v pay >/dev/null 2>&1; then+ echo "error: \`pay\` CLI not found on PATH." >&2+ echo "Install per tests/e2e/pay-memory-sandbox.sh prerequisites." >&2+ exit 1+fi++if ! command -v bun >/dev/null 2>&1; then+ echo "error: \`bun\` CLI not found on PATH (needed by \`o2b\`)." >&2+ exit 1+fi++mkdir -p "$VAULT"+export OPEN_SECOND_BRAIN_CONFIG="$CONFIG"++ENDPOINT="https://factchecktools.google.gateway-402.com/v1alpha1/claims:search"+# URL-encode the query β bash printf + jq -sRr would be heavier; the+# subset we accept ([a-zA-Z0-9 ]+) maps directly via tr.+ENCODED_QUERY=$(printf '%s' "$QUERY" | sed 's/ /+/g')+URL="${ENDPOINT}?query=${ENCODED_QUERY}&languageCode=en&pageSize=5"++echo "==> pay --version"+pay --version++echo "==> pay --sandbox curl ${URL}"+pay --sandbox curl "$URL" 2>&1 | tee "$RAW_OUTPUT"++# Bail early if the upstream returned an error rather than a JSON claims+# payload β keeps the receipt honest about what actually happened.+if ! grep -q '"claims"' "$RAW_OUTPUT"; then+ echo "error: response did not include a \"claims\" field; aborting before saving a receipt." >&2+ exit 1+fi++DATE=$(date -u +%Y-%m-%d)+TIME=$(date -u +%H:%M)++echo+echo "==> o2b init"+bun run "$ROOT/src/cli/main.ts" init \+ --vault "$VAULT" \+ --name "Fact Check E2E" \+ --agent-name "claude-vps-agent" >/dev/null++echo "==> o2b init-pay-memory"+bun run "$ROOT/src/cli/main.ts" init-pay-memory --vault "$VAULT"++echo+echo "==> o2b append-payment-receipt"+bun run "$ROOT/src/cli/main.ts" append-payment-receipt \+ --vault "$VAULT" \+ --service "solana-foundation/google/factchecktools" \+ --status success \+ --reason "Fact-check claims search for \"$QUERY\"" \+ --category fact_check \+ --endpoint "$URL" \+ --expected-cost "\$0.00 (free at gateway)" \+ --actual-amount "0" \+ --currency "USDC" \+ --raw-output-file "$RAW_OUTPUT" \+ --slug "factcheck-${ENCODED_QUERY//+/-}" \+ --date "$DATE" \+ --time "$TIME" \+ --policy-status not_checked++echo+echo "==> o2b capture-asset"+RESULT_URL=$(grep -oE '"url": *"[^"]+"' "$RAW_OUTPUT" | head -1 | sed 's/^"url": *"//; s/"$//')+bun run "$ROOT/src/cli/main.ts" capture-asset \+ --vault "$VAULT" \+ --title "Fact-check claims: $QUERY" \+ --service "solana-foundation/google/factchecktools" \+ --result-url "${RESULT_URL:-https://factchecktools.google.com/}" \+ --source-receipt "AI Wiki/payments/$DATE/factcheck-${ENCODED_QUERY//+/-}.md" \+ --slug "factcheck-${ENCODED_QUERY//+/-}"++echo+echo "==> o2b payment-report"+bun run "$ROOT/src/cli/main.ts" payment-report \+ --vault "$VAULT" \+ --date "$DATE" \+ --title "Fact Check Tools E2E ($DATE)" \+ --task "Verify Pay Memory pipeline against Google factchecktools (real data)"++echo+echo "==> generated files"+find "$VAULT/AI Wiki" -type f | sort++echo+echo "==> done: vault preserved at $VAULT"+echo "Inspect the receipt to see real Google fact-check claims under \"## Raw pay.sh output\"."diff --git a/tests/e2e/pay-memory-mainnet-places.sh b/tests/e2e/pay-memory-mainnet-places.shnew file mode 100755index 00000000..fbc82c50--- /dev/null+++ b/tests/e2e/pay-memory-mainnet-places.sh@@ -0,0 +1,173 @@+#!/usr/bin/env bash+#+# Mainnet end-to-end for Pay Memory via the Google Places API exposed on+# pay.sh (`solana-foundation/google/places`).+#+# Unlike `pay-memory-sandbox.sh` and `pay-memory-factchecktools.sh`, this+# script issues a real Solana mainnet payment β fractions of a cent in+# USDC β and captures the resulting transaction signature into the+# receipt's `payment_proof` frontmatter field.+#+# Prerequisites:+# - `pay` CLI on PATH.+# - `bun` CLI on PATH (needed by `o2b`).+# - A funded mainnet account in `~/.config/pay/accounts.yml`. On a+# headless server the simplest path is `keystore: ephemeral` with+# an inline `secret_key_b58` β gnome-keyring is not required.+# - The account must hold enough USDC to cover the call (the Places+# `searchText` endpoint costs about $0.001 per request).+# - SOL is NOT required: the gateway (`places.google.gateway-402.com`)+# runs in operator-fee-payer mode and pays the Solana transaction+# fee on the sender's behalf.+#+# Usage:+# bash tests/e2e/pay-memory-mainnet-places.sh \+# [vault-dir] [account-name] [yolo-cap-usd] [query]+#+# vault-dir defaults to /tmp/o2b-mainnet-places-<ts>+# account-name defaults to `work` (must exist in accounts.yml)+# yolo-cap-usd defaults to 0.05 (auto-approve any 402 challenge under)+# query defaults to "coffee in Belgrade"++set -euo pipefail++ROOT=$(cd "$(dirname "$0")/../.." && pwd)+VAULT=${1:-/tmp/o2b-mainnet-places-$(date +%s)}+ACCOUNT=${2:-work}+YOLO_CAP=${3:-0.05}+QUERY=${4:-coffee in Belgrade}+CONFIG=$(mktemp -t o2b-mainnet-places-config-XXXXXX.yaml)+RAW_OUTPUT=$(mktemp -t pay-mainnet-places-output-XXXXXX.txt)++cleanup() {+ rm -f "$CONFIG" "$RAW_OUTPUT"+}+trap cleanup EXIT++if ! command -v pay >/dev/null 2>&1; then+ echo "error: \`pay\` CLI not found on PATH." >&2+ exit 1+fi++if ! command -v bun >/dev/null 2>&1; then+ echo "error: \`bun\` CLI not found on PATH (needed by \`o2b\`)." >&2+ exit 1+fi++mkdir -p "$VAULT"+export OPEN_SECOND_BRAIN_CONFIG="$CONFIG"++ENDPOINT="https://places.google.gateway-402.com/v1/places:searchText"++echo "==> pay --version + account preview"+pay --version+echo+pay account list 2>&1 | grep -A 1 "$ACCOUNT" || true+echo++echo "==> mainnet pay curl (yolo-upto \$$YOLO_CAP)"+pay --mainnet --account "$ACCOUNT" --yolo-upto "$YOLO_CAP" \+ curl -X POST "$ENDPOINT" \+ -H 'Content-Type: application/json' \+ -H 'X-Goog-FieldMask: places.displayName,places.formattedAddress,places.types' \+ -d "$(printf '{"textQuery":"%s","pageSize":3}' "$QUERY")" \+ 2>&1 | tee "$RAW_OUTPUT"++if ! grep -q '"places"' "$RAW_OUTPUT"; then+ echo "error: response did not include a \"places\" field; aborting before saving a receipt." >&2+ exit 1+fi++# Discover the tx signature on-chain. The gateway returns the API body+# but not the Solana signature; we look up the most recent tx on the+# sender's address. The first `getSignaturesForAddress` entry is always+# the freshly-finalised payment tx (memo `[12] Operator fee;+# [12] Platform fee` is pay.sh's MPP convention).+PUBKEY=$(pay account list 2>&1 | grep -oE 'mainnet [^]]+' | head -1 | sed 's/^mainnet //')+echo+echo "==> sender pubkey: $PUBKEY"++# Snapshot the most recent signature BEFORE pay curl effects propagate so+# we know which one is new. Skipped here because we already ran pay curl+# above β but `getSignaturesForAddress` on mainnet RPC can lag a few+# seconds behind tx finalisation, so retry a handful of times until a+# previously-unknown signature appears or we time out.+KNOWN=$(curl -sS -X POST -H "Content-Type: application/json" \+ -d "$(printf '{"jsonrpc":"2.0","id":0,"method":"getSignaturesForAddress","params":["%s",{"limit":5}]}' "$PUBKEY")" \+ https://api.mainnet-beta.solana.com 2>&1 |+ python3 -c "import sys,json;d=json.load(sys.stdin);r=d.get('result') or [];print(','.join(x['signature'] for x in r))")+TX=""+for attempt in $(seq 1 8); do+ CURRENT=$(curl -sS -X POST -H "Content-Type: application/json" \+ -d "$(printf '{"jsonrpc":"2.0","id":1,"method":"getSignaturesForAddress","params":["%s",{"limit":1}]}' "$PUBKEY")" \+ https://api.mainnet-beta.solana.com 2>&1 |+ python3 -c "import sys,json;d=json.load(sys.stdin);r=d.get('result') or [];print(r[0]['signature'] if r else '')")+ if [ -n "$CURRENT" ] && [ "$CURRENT" != "$(printf '%s' "$KNOWN" | cut -d, -f2-)" ]; then+ # Heuristic: the latest signature changed compared to what was the+ # second-most-recent before β i.e. a new tx landed.+ TX="$CURRENT"+ break+ fi+ sleep 2+done+echo "==> latest tx signature: ${TX:-<none>}"++DATE=$(date -u +%Y-%m-%d)+TIME=$(date -u +%H:%M)++echo+echo "==> o2b init"+bun run "$ROOT/src/cli/main.ts" init \+ --vault "$VAULT" \+ --name "Mainnet Places E2E" \+ --agent-name "claude-vps-agent" >/dev/null++echo "==> o2b init-pay-memory"+bun run "$ROOT/src/cli/main.ts" init-pay-memory --vault "$VAULT"++echo+echo "==> o2b append-payment-receipt (with real tx signature)"+bun run "$ROOT/src/cli/main.ts" append-payment-receipt \+ --vault "$VAULT" \+ --service "solana-foundation/google/places" \+ --status success \+ --reason "Places searchText for \"$QUERY\"" \+ --category place_search \+ --endpoint "$ENDPOINT" \+ --expected-cost "β€\$$YOLO_CAP (yolo cap)" \+ --actual-amount "0.001" \+ --currency "USDC" \+ --payment-proof "${TX:-(signature lookup failed)}" \+ --raw-output-file "$RAW_OUTPUT" \+ --slug "places-$(echo "$QUERY" | tr ' ' '-' | tr -cd 'a-z0-9-')" \+ --date "$DATE" \+ --time "$TIME" \+ --policy-status not_checked++echo+echo "==> o2b capture-asset"+RESULT_NAME=$(grep -oE '"text": *"[^"]+"' "$RAW_OUTPUT" | head -1 | sed 's/^"text": *"//; s/"$//')+SLUG="places-$(echo "$QUERY" | tr ' ' '-' | tr -cd 'a-z0-9-')"+bun run "$ROOT/src/cli/main.ts" capture-asset \+ --vault "$VAULT" \+ --title "Places searchText: $QUERY" \+ --service "solana-foundation/google/places" \+ --result-url "${ENDPOINT}" \+ --source-receipt "AI Wiki/payments/$DATE/$SLUG.md" \+ --slug "$SLUG"++echo+echo "==> o2b payment-report"+bun run "$ROOT/src/cli/main.ts" payment-report \+ --vault "$VAULT" \+ --date "$DATE" \+ --title "Mainnet Places E2E ($DATE)" \+ --task "Real Solana payment via pay.sh against Google Places searchText"++echo+echo "==> generated files"+find "$VAULT/AI Wiki" -type f | sort++echo+echo "==> done: vault preserved at $VAULT"+echo "Solscan: https://solscan.io/tx/${TX:-<none>}"diff --git a/tests/e2e/pay-memory-sandbox.sh b/tests/e2e/pay-memory-sandbox.shnew file mode 100755index 00000000..8f93dda5--- /dev/null+++ b/tests/e2e/pay-memory-sandbox.sh@@ -0,0 +1,116 @@+#!/usr/bin/env bash+#+# Manual end-to-end smoke test for Pay Memory against the real `pay` CLI in+# sandbox mode. Hits the free `https://debugger.pay.sh/mpp/quote/AAPL` endpoint+# (sandbox spends no real funds) and walks the full o2b pipeline:+#+# pay --sandbox curl β o2b init-pay-memory+# β o2b append-payment-receipt --raw-output-file+# β o2b capture-asset+# β o2b payment-report+#+# This script is NOT wired into `bun test` β running it requires the `pay`+# binary on PATH and outbound HTTPS to the pay.sh debugger and Surfpool RPC.+# See README "Pay Memory" and CHANGELOG 0.8.0 for context.+#+# Usage:+# bash tests/e2e/pay-memory-sandbox.sh [vault-dir]+#+# If no vault-dir is given, a fresh /tmp/o2b-e2e-vault-<ts> is used.++set -euo pipefail++ROOT=$(cd "$(dirname "$0")/../.." && pwd)+VAULT=${1:-/tmp/o2b-e2e-vault-$(date +%s)}+CONFIG=$(mktemp -t o2b-e2e-config-XXXXXX.yaml)+RAW_OUTPUT=$(mktemp -t pay-sandbox-output-XXXXXX.txt)++cleanup() {+ rm -f "$CONFIG" "$RAW_OUTPUT"+}+trap cleanup EXIT++if ! command -v pay >/dev/null 2>&1; then+ echo "error: \`pay\` CLI not found on PATH." >&2+ echo "Install with:" >&2+ echo " gh release download pay-v0.16.0 -R solana-foundation/pay \\" >&2+ echo " -p 'pay-x86_64-unknown-linux-gnu.tar.gz' -D /tmp" >&2+ echo " tar -xzf /tmp/pay-x86_64-unknown-linux-gnu.tar.gz -C /tmp" >&2+ echo " sudo install -m 0755 /tmp/pay /usr/local/bin/pay" >&2+ exit 1+fi++if ! command -v bun >/dev/null 2>&1; then+ echo "error: \`bun\` CLI not found on PATH (needed by \`o2b\`)." >&2+ echo "Install from https://bun.sh β e.g. \`curl -fsSL https://bun.sh/install | bash\`," >&2+ echo "then re-run this script. Open Second Brain requires Bun >= 1.1.0." >&2+ exit 1+fi++mkdir -p "$VAULT"+export OPEN_SECOND_BRAIN_CONFIG="$CONFIG"++echo "==> pay --version"+pay --version++echo "==> sandbox call to pay.sh debugger (free)"+# Endpoint per `solana-foundation/pay` README. The pay.sh docs site lists+# `https://payment-debugger.vercel.app/mpp/quote/AAPL` as a fallback β+# both deployments serve the same free MPP/x402 demo and either works+# with `pay --sandbox curl`. Using the README's branded host by default.+pay --sandbox curl https://debugger.pay.sh/mpp/quote/AAPL 2>&1 | tee "$RAW_OUTPUT"++echo+echo "==> o2b init"+bun run "$ROOT/src/cli/main.ts" init \+ --vault "$VAULT" \+ --name "Pay Memory E2E" \+ --agent-name "hermes-vps-agent" >/dev/null++echo "==> o2b init-pay-memory"+bun run "$ROOT/src/cli/main.ts" init-pay-memory --vault "$VAULT"++DATE=$(date -u +%Y-%m-%d)+TIME=$(date -u +%H:%M)++echo+echo "==> o2b append-payment-receipt"+bun run "$ROOT/src/cli/main.ts" append-payment-receipt \+ --vault "$VAULT" \+ --service "debugger.pay.sh/mpp" \+ --status success \+ --reason "Sandbox quote for AAPL via pay.sh debugger" \+ --category market_data \+ --endpoint "https://debugger.pay.sh/mpp/quote/AAPL" \+ --expected-cost '$0.00 (sandbox)' \+ --actual-amount "0" \+ --currency "USDC" \+ --raw-output-file "$RAW_OUTPUT" \+ --slug "aapl-quote-sandbox" \+ --date "$DATE" \+ --time "$TIME"++echo+echo "==> o2b capture-asset"+bun run "$ROOT/src/cli/main.ts" capture-asset \+ --vault "$VAULT" \+ --title "AAPL Quote (sandbox)" \+ --service "debugger.pay.sh/mpp" \+ --result-url "https://debugger.pay.sh/mpp/quote/AAPL" \+ --source-receipt "AI Wiki/payments/$DATE/aapl-quote-sandbox.md" \+ --slug "aapl-quote-sandbox"++echo+echo "==> o2b payment-report"+bun run "$ROOT/src/cli/main.ts" payment-report \+ --vault "$VAULT" \+ --date "$DATE" \+ --title "Pay Memory E2E Sandbox Demo" \+ --task "Verify Pay Memory pipeline against pay.sh sandbox debugger"++echo+echo "==> generated files"+find "$VAULT/AI Wiki" -type f | sort++echo+echo "==> done: vault preserved at $VAULT"diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 5e7c6055..f69c0aa7 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -129,7 +129,7 @@ describe("handshake", () => {});describe("tool listing", () => {- test("advertises all five tools", async () => {+ test("advertises the core and Pay Memory tools", async () => {const server = new MCPServer({ vault: tmp });await initialize(server);const r = (await server.handleRequest({@@ -145,6 +145,14 @@ describe("tool listing", () => {"second_brain_capture","event_log_append","vault_health",+ "payment_memory_init",+ "payment_receipt_append",+ "asset_capture",+ "payment_report_generate",+ "payment_policy_check",+ "payment_request_approval",+ "payment_request_status",+ "payment_request_consume",]),);for (const t of r.result.tools) {@@ -468,7 +476,7 @@ describe("stdio loop", () => {const list = JSON.parse(lines[1]!);expect(init.id).toBe(1);expect(list.id).toBe(2);- expect(list.result.tools.length).toBe(5);+ expect(list.result.tools.length).toBe(13);});test("returns parse error for invalid JSON", async () => {diff --git a/tests/mcp/pay-memory.test.ts b/tests/mcp/pay-memory.test.tsnew file mode 100644index 00000000..6cfa3386--- /dev/null+++ b/tests/mcp/pay-memory.test.ts@@ -0,0 +1,342 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";++let tmp: string;+let vault: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-pay-test-"));+ vault = join(tmp, "vault");+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+ // Pin OPEN_SECOND_BRAIN_CONFIG to a non-existent path inside this+ // run's tmpdir so `resolveTimezone` returns null instead of leaking+ // the developer's real config (which on this VPS sets Europe/Belgrade+ // and would shift the timestamp assertions by the local UTC offset).+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = join(tmp, "isolated-config.yaml");+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++async function initialize(server: MCPServer) {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "t", version: "0" } },+ });+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+}++async function call(server: MCPServer, name: string, args: Record<string, unknown> = {}) {+ return server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 99,+ method: "tools/call",+ params: { name, arguments: args },+ }) as any;+}++describe("payment_memory_init", () => {+ test("creates the layout, policy, and reports the resolved agent", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ const r = await call(server, "payment_memory_init");+ expect(r.result.isError).toBe(false);+ const s = r.result.structuredContent;+ expect(s.policy_path).toBe("AI Wiki/policies/spending.md");+ expect(s.policy_status).toBe("created");+ expect(s.created).toContain("AI Wiki/policies");+ for (const sub of ["policies", "payments", "assets", "drafts", "reports"]) {+ expect(existsSync(join(vault, "AI Wiki", sub))).toBe(true);+ }+ });++ test("idempotent re-run skips policy", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_memory_init");+ expect(r.result.structuredContent.policy_status).toBe("skipped");+ });++ test("overwrite=true rewrites the policy", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_memory_init", { overwrite: true });+ expect(r.result.structuredContent.policy_status).toBe("overwritten");+ });+});++describe("payment_receipt_append", () => {+ test("writes a receipt and redacts secrets in raw_output", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_receipt_append", {+ agent: "hermes-vps-agent",+ service: "paysponge/fal",+ status: "success",+ reason: "Generate one original blog header image",+ actual_amount: "0.05",+ currency: "USDC",+ result_ref: "https://fal-cdn.example/img.png",+ result_note: "AI Wiki/assets/blog-header.md",+ raw_output: 'Authorization: Bearer SECRET\n{"api_key": "sk_live_abc"}',+ date: "2026-05-10",+ time: "17:20",+ });+ expect(r.result.isError).toBe(false);+ const s = r.result.structuredContent;+ expect(s.path.startsWith("AI Wiki/payments/2026-05-10/")).toBe(true);+ expect(s.date).toBe("2026-05-10");+ expect(s.created).toBe("2026-05-10T17:20:00Z");+ const text = readFileSync(join(vault, s.path), "utf8");+ expect(text).toContain("***REDACTED***");+ expect(text).not.toContain("sk_live_abc");+ expect(text).not.toContain("Bearer SECRET");+ });++ test("missing required arg returns INVALID_PARAMS error", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_receipt_append", {+ service: "x/y",+ status: "success",+ // reason missing+ });+ expect(r.error).toBeDefined();+ expect(r.error.code).toBe(-32602);+ expect(r.error.message).toContain("reason");+ });++ test("overwrite=false on duplicate yields tool-level error", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const args = {+ agent: "h",+ service: "x/y",+ status: "success",+ reason: "dup",+ slug: "dup-1",+ date: "2026-05-10",+ time: "00:00",+ };+ const first = await call(server, "payment_receipt_append", args);+ expect(first.result.isError).toBe(false);+ const second = await call(server, "payment_receipt_append", args);+ expect(second.result.isError).toBe(true);+ expect((second.result.content[0] as { text: string }).text).toContain("already exists");+ });+});++describe("asset_capture", () => {+ test("writes an asset note linked to its source receipt", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "asset_capture", {+ title: "Blog Header: Pay Memory",+ service: "paysponge/fal",+ result_url: "https://fal-cdn.example/img.png",+ source_receipt: "AI Wiki/payments/2026-05-10/fal-blog.md",+ prompt: "A recursive technical illustration",+ used_in: "AI Wiki/drafts/blog-post.md",+ });+ expect(r.result.isError).toBe(false);+ const s = r.result.structuredContent;+ const text = readFileSync(join(vault, s.path), "utf8");+ expect(text).toContain("# Blog Header: Pay Memory");+ expect(text).toContain('source_receipt: "[[AI Wiki/payments/2026-05-10/fal-blog]]"');+ expect(text).toContain("> A recursive technical illustration");+ });+});++describe("payment_report_generate", () => {+ test("aggregates receipts and reports receipts_used", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ for (const slug of ["fal-1", "alpha-1"]) {+ await call(server, "payment_receipt_append", {+ agent: "h",+ service: slug.startsWith("fal") ? "paysponge/fal" : "alpha/translate",+ status: "success",+ reason: `reason-${slug}`,+ actual_amount: "0.03",+ currency: "USDC",+ slug,+ date: "2026-05-10",+ time: "17:20",+ });+ }+ const r = await call(server, "payment_report_generate", {+ date: "2026-05-10",+ title: "Demo Report",+ task: "test task",+ });+ expect(r.result.isError).toBe(false);+ const s = r.result.structuredContent;+ expect(s.receipts_used).toBe(2);+ const text = readFileSync(join(vault, s.path), "utf8");+ expect(text).toContain("### paysponge/fal");+ expect(text).toContain("### alpha/translate");+ });++ test("rejects bad date format with tool-level error", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_report_generate", { date: "2026.05.10" });+ expect(r.result.isError).toBe(true);+ expect((r.result.content[0] as { text: string }).text).toContain("YYYY-MM-DD");+ });+});++describe("payment_policy_check", () => {+ test("fail-open when policy.json absent", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_policy_check", { service: "x/y" });+ expect(r.result.isError).toBe(false);+ const s = r.result.structuredContent;+ expect(s.has_policy).toBe(false);+ expect(s.allowed).toBe(true);+ expect(s.status).toBe("allowed");+ });++ test("denies non-allowlisted service", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const { writeFileSync } = await import("node:fs");+ writeFileSync(+ join(vault, "AI Wiki", "policies", "spending.json"),+ JSON.stringify({ allowed_services: ["paysponge/fal"] }),+ "utf8",+ );+ const r = await call(server, "payment_policy_check", { service: "alpha/x" });+ expect(r.result.isError).toBe(false);+ const s = r.result.structuredContent;+ expect(s.allowed).toBe(false);+ expect(s.rule).toBe("allowed_services");+ });++ test("expected_amount accepts numeric string", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_policy_check", {+ service: "x/y",+ expected_amount: "0.05",+ });+ expect(r.result.isError).toBe(false);+ });++ test("rejects non-numeric expected_amount", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_policy_check", {+ service: "x/y",+ expected_amount: "abc",+ });+ expect(r.error).toBeDefined();+ expect(r.error.code).toBe(-32602);+ });+});++describe("approval workflow MCP tools", () => {+ test("payment_request_approval creates a pending artifact", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ const r = await call(server, "payment_request_approval", {+ service: "paysponge/fal",+ reason: "demo",+ expected_amount: "0.05",+ currency: "USDC",+ slug: "mcp-1",+ });+ expect(r.result.isError).toBe(false);+ const s = r.result.structuredContent;+ expect(s.id).toBe("mcp-1");+ expect(s.status).toBe("pending");+ expect(s.path).toBe("AI Wiki/payments/_pending/mcp-1.md");+ });++ test("payment_request_status surfaces metadata", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ await call(server, "payment_request_approval", {+ service: "x/y",+ reason: "demo",+ slug: "mcp-2",+ });+ const r = await call(server, "payment_request_status", { id: "mcp-2" });+ const s = r.result.structuredContent;+ expect(s.status).toBe("pending");+ expect(s.service).toBe("x/y");+ expect(s.reason).toBe("demo");+ });++ test("payment_request_consume requires approval first (tool-level error)", async () => {+ const server = new MCPServer({ vault });+ await initialize(server);+ await call(server, "payment_memory_init");+ await call(server, "payment_request_approval", {+ service: "x/y",+ reason: "demo",+ slug: "mcp-3",+ });+ const r = await call(server, "payment_request_consume", {+ id: "mcp-3",+ receipt: "AI Wiki/payments/2026-05-10/x.md",+ });+ expect(r.result.isError).toBe(true);+ expect((r.result.content[0] as { text: string }).text).toContain("cannot transition");+ });+});++describe("instructions include the Pay Memory paragraph", () => {+ test("initialize.instructions documents every Pay Memory tool", async () => {+ const server = new MCPServer({ vault });+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "t", version: "0" } },+ })) as any;+ const text = r.result.instructions as string;+ for (const name of [+ "payment_memory_init",+ "payment_policy_check",+ "payment_request_approval",+ "payment_request_status",+ "payment_request_consume",+ "payment_receipt_append",+ "asset_capture",+ "payment_report_generate",+ ]) {+ expect(text).toContain(name);+ }+ });+});diff --git a/tests/openclaw/bundle.test.ts b/tests/openclaw/bundle.test.tsindex e9b036d6..b6d8b909 100644--- a/tests/openclaw/bundle.test.ts+++ b/tests/openclaw/bundle.test.ts@@ -8,7 +8,7 @@* `package.json` extension entry actually points at it.*/-import { describe, expect, test } from "bun:test";+import { beforeAll, describe, expect, test } from "bun:test";import { existsSync, readFileSync, statSync } from "node:fs";import { join, dirname, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -16,6 +16,14 @@ import { fileURLToPath } from "node:url";const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");const BUNDLE = join(ROOT, "openclaw", "index.js");+let bundleText: string;++beforeAll(() => {+ // 128 KB bundle; read once and share across the substring-search tests+ // instead of re-reading on every assertion.+ bundleText = readFileSync(BUNDLE, "utf8");+});+describe("openclaw bundle", () => {test("file exists and is non-empty", () => {expect(existsSync(BUNDLE)).toBe(true);@@ -24,27 +32,34 @@ describe("openclaw bundle", () => {});test("declares the SDK import as external", () => {- const text = readFileSync(BUNDLE, "utf8");- expect(text).toContain('from "openclaw/plugin-sdk/plugin-entry"');+ expect(bundleText).toContain('from "openclaw/plugin-sdk/plugin-entry"');});- test("bundles all five tool registrations", () => {- const text = readFileSync(BUNDLE, "utf8");+ test("bundles every Open Second Brain tool registration", () => {for (const tool of [+ // core"second_brain_status","second_brain_query","second_brain_capture","event_log_append","vault_health",+ // Pay Memory+ "payment_memory_init",+ "payment_receipt_append",+ "asset_capture",+ "payment_report_generate",+ "payment_policy_check",+ "payment_request_approval",+ "payment_request_status",+ "payment_request_consume",]) {- expect(text).toContain(tool);+ expect(bundleText).toContain(tool);}});test("does NOT contain Python references", () => {- const text = readFileSync(BUNDLE, "utf8");- expect(text).not.toContain("python3");- expect(text).not.toContain("from open_second_brain");+ expect(bundleText).not.toContain("python3");+ expect(bundleText).not.toContain("from open_second_brain");});test("package.json points to ./openclaw/index.js", () => {@@ -53,8 +68,7 @@ describe("openclaw bundle", () => {});test("bundles before_prompt_build hook (per-turn identity reminder)", () => {- const text = readFileSync(BUNDLE, "utf8");- expect(text).toContain("before_prompt_build");- expect(text).toContain("prependContext");+ expect(bundleText).toContain("before_prompt_build");+ expect(bundleText).toContain("prependContext");});});