Skip to content

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

refactor!: remove the pay.sh integration and the Pay Memory layer (#83)

Sol Aitken618870e8ecf5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 12d5be7e..7d4ffd53 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,35 @@ 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).
+## [Unreleased]
+
+Removal of the Pay Memory layer. The pay.sh integration and the entire
+payment-memory subsystem it supported have been taken out of Open Second
+Brain. Brain (observing memory), schema, search, and the rest of the surface
+are unchanged. Historical records are preserved: this changelog, the dated
+`docs/plans/` and `docs/brainstorm/` design notes, and any existing
+`Brain/payments/` content in a vault are left untouched.
+
+### Removed
+
+- **BREAKING - Pay Memory MCP tools**: `payment_memory_init`,
+ `payment_receipt_append`, `asset_capture`, `payment_report_generate`,
+ `payment_policy_check`, `payment_request_approval`, `payment_request_status`,
+ and `payment_request_consume` are no longer advertised or callable on any
+ scope. The advertised full-surface tool count drops from 77 to 69.
+- **BREAKING - Pay Memory CLI verbs**: `init-pay-memory`,
+ `append-payment-receipt`, `capture-asset`, `payment-report`,
+ `check-payment-policy`, `request-payment-approval`, `approve-payment-request`,
+ `reject-payment-request`, `consume-payment-request`, `list-pending-payments`,
+ and `payment-digest` are removed from the `o2b` command surface.
+- **OpenClaw plugin**: the eight payment tool registrations are removed from the
+ native plugin entry; the bundle now exposes `second_brain_status`,
+ `second_brain_query`, and `vault_health` only.
+- **Core modules and docs**: `src/core/pay-memory/`, the payment CLI module, the
+ `docs/pay-memory.md` guide, the Hermes payment-digest example and cron
+ section, and the `payment` / `asset` surface-group prefixes are deleted. The
+ shared `vaultRelativePath` helper now imports from `core/path-safety`.
+
## [1.0.1] - 2026-06-07
Hermes registration fix. The memory provider now advertises its curated
@@ -4932,6 +4961,8 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[Unreleased]: https://github.com/itechmeat/open-second-brain/compare/v1.0.1...HEAD
+[1.0.1]: https://github.com/itechmeat/open-second-brain/compare/v1.0.0...v1.0.1
[1.0.0]: https://github.com/itechmeat/open-second-brain/compare/v0.45.0...v1.0.0
[0.45.0]: https://github.com/itechmeat/open-second-brain/compare/v0.44.0...v0.45.0
[0.44.0]: https://github.com/itechmeat/open-second-brain/compare/v0.43.1...v0.44.0
diff --git a/README.md b/README.md
index b74fcceb..c7526710 100644
--- a/README.md
+++ b/README.md
@@ -110,7 +110,6 @@ The capabilities you actually feel day to day:
| 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. |
| 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. |
| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open --evidence-pack --since 7d` β€” SQLite + FTS5 and an optional semantic layer, with CJK-aware token expansion for unspaced Chinese/Japanese/Korean text. Recall is sharpened by MMR diversity, link-graph traversal, entity boosting, structured query lanes, session focus, and header-anchored chunking; typed relations carry recall polarity (a `superseded_by` predecessor is demoted below its successor, `contradicts` warns without endorsing); `--since` / `--until` scope recall by time; `o2b search feedback` trains bounded, auditable learned weights; opt-in evidence packs show matched/missing terms, IDF-weighted coverage, per-token union records, a completeness verdict with a false-absence guard, abstention text, terminal-state downranks, and `why_retrieved` reasons. |
-| 10 | Pay Memory β€” audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |
These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_brief view=morning` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.
@@ -156,7 +155,7 @@ o2b mcp --probe --json --disable-tool second_brain_query # Capability-aware MCP
o2b update # Update across detected runtimes
```
-Full list (~50 verbs across `o2b`, `o2b brain`, `o2b vault`, `o2b discipline`, Pay Memory) in [`docs/cli-reference.md`](docs/cli-reference.md).
+Full list of verbs across `o2b`, `o2b brain`, `o2b vault`, and `o2b discipline` in [`docs/cli-reference.md`](docs/cli-reference.md).
## Safety
@@ -171,7 +170,7 @@ Full list (~50 verbs across `o2b`, `o2b brain`, `o2b vault`, `o2b discipline`, P
- Lifecycle review commands (`intent-review`, `retention`, `monthly`) are read-only. Retention emits recommendations only; it never deletes, moves, or edits Brain artifacts.
- Hooks (Claude Code, Codex) inject active context and capture explicit prompt markers / `brain_feedback` tool calls through the same signal dedup boundary; lifecycle observations are audited/logged and never block the runtime.
- `o2b brain watchdog` and `brain_watchdog` are probe-first. They recommend search-index repair and can create missing Brain directories only when remediation is explicit; snapshot restore is refused unless restore intent and force are both explicit.
-- Text written through Brain/Pay Memory redaction strips `<private>...</private>` regions before storage and masks secret-shaped assignments such as `api_key=...`.
+- Text written through Brain redaction strips `<private>...</private>` regions before storage and masks secret-shaped assignments such as `api_key=...`.
## Updating
@@ -195,7 +194,6 @@ change to hooks/launcher/install must keep) lives in
| MCP protocol, tools, lifecycle, writer split | [`docs/mcp.md`](docs/mcp.md) |
| Full CLI reference (every verb, every flag) | [`docs/cli-reference.md`](docs/cli-reference.md) |
| Update safety contract + hook/launcher invariants | [`docs/updating.md`](docs/updating.md) |
-| Pay Memory - audit for paid agent actions | [`docs/pay-memory.md`](docs/pay-memory.md) |
| Hermes cron jobs (daily digest, discipline report) | [`docs/hermes-cron.md`](docs/hermes-cron.md) |
| Cross-project pointer (multi-host vaults) | [`docs/cross-project-pointer.md`](docs/cross-project-pointer.md) |
| Architecture | [`docs/architecture.md`](docs/architecture.md) |
diff --git a/docs/architecture.md b/docs/architecture.md
index 9b0480e6..0bb20961 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -150,11 +150,11 @@ Recommended behavior:
## Vault layout
-The agent owns one directory in the vault: `Brain/`. Pay Memory nests
-under `Brain/payments/` so the write contract stays simple ("agent
-writes only under `Brain/`"). User-authored notes (daily journals,
-weekly notes) live wherever the operator names them; the agent reads
-those paths only when they are listed in `notes.read_paths`.
+The agent owns one directory in the vault: `Brain/`. The write
+contract stays simple ("agent writes only under `Brain/`").
+User-authored notes (daily journals, weekly notes) live wherever the
+operator names them; the agent reads those paths only when they are
+listed in `notes.read_paths`.
```text
Brain/
@@ -166,13 +166,6 @@ Brain/
preferences/ # active rules: pref-<slug>.md, status unconfirmed | confirmed
retired/ # ret-<slug>.md with retired_reason
log/ # YYYY-MM-DD.md, append-only event log (dream / apply-evidence / etc.)
- payments/ # Pay Memory (optional, paid-action audit)
- policies/spending.md # spending policy + optional spending.json
- <YYYY-MM-DD>/<slug>.md # dated receipts
- assets/ # generated-asset notes
- drafts/ # draft artefacts
- reports/ # daily reports
- _pending/ # approval workflow
.snapshots/ # <run_id>.tar.zst, pre-run snapshots for o2b brain rollback
```
@@ -195,7 +188,7 @@ Agent runtime
-> runtime adapter/plugin
-> skills and commands (brain-memory skill, open-second-brain skill)
-> CLI/core library (src/core/brain/*)
- -> vault files: Brain/ (observing memory) + Brain/payments/ (paid-action audit)
+ -> vault files: Brain/ (observing memory)
```
Full design: [`docs/plans/2026-05-15-brain-observing-memory.md`](plans/2026-05-15-brain-observing-memory.md).
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 98c0f265..8a3d113c 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -255,24 +255,6 @@ o2b discipline uninstall Remove the cron job; --weekly removes only the wee
See [`hermes-cron.md`](hermes-cron.md) for the cron envelope and Telegram delivery shape.
-## Pay Memory
-
-```text
-o2b init-pay-memory Bootstrap Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)
-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
-o2b reject-payment-request Mark a pending request as rejected
-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
-```
-
-Full Pay Memory walkthrough: [`pay-memory.md`](pay-memory.md).
-
## Search
```text
diff --git a/docs/hermes-cron.md b/docs/hermes-cron.md
index f50c1472..d6f42db8 100644
--- a/docs/hermes-cron.md
+++ b/docs/hermes-cron.md
@@ -1,8 +1,6 @@
-# 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.
+# Hermes cron β€” daily Brain digest
-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.
+`o2b brain digest` renders a short Markdown summary of what the `dream` pass did over a given window: new unconfirmed preferences, confirmations, retirements, confidence shifts, and contradictions. `--no-agent --script` ships the markdown verbatim, `--silent-if-empty` suppresses delivery when nothing changed.
## Prerequisites
@@ -11,69 +9,7 @@ The digest is produced by `o2b payment-digest` itself β€” pure TypeScript, no LL
- `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/Brain/payments/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`.
-
----
-
-# Hermes cron β€” daily Brain digest
-
-`o2b brain digest` renders a short Markdown summary of what the `dream` pass did over a given window: new unconfirmed preferences, confirmations, retirements, confidence shifts, and contradictions. The same wiring as the Pay Memory digest above β€” `--no-agent --script` ships the markdown verbatim, `--silent-if-empty` suppresses delivery when nothing changed.
-
-## Prerequisites
-
-Same as the Pay Memory digest: Hermes installed, the plugin enabled, `o2b` on `PATH`, vault path known, and a Telegram destination. Additionally, `o2b brain init --vault <path>` must have been run once on the target vault so `Brain/_brain.yaml` exists.
+- `o2b brain init --vault <path>` must have been run once on the target vault so `Brain/_brain.yaml` exists.
## Register the cron job
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 3957decf..fde53777 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -22,9 +22,8 @@ no surprise, no hallucinated memory.
## Vault layout
-The agent owns one top-level directory in the vault: `Brain/`. Pay
-Memory writes nest under `Brain/payments/`, so the agent's entire
-write contract is "I touch only `Brain/`".
+The agent owns one top-level directory in the vault: `Brain/`, so the
+agent's entire write contract is "I touch only `Brain/`".
```text
<vault>/
@@ -41,13 +40,6 @@ write contract is "I touch only `Brain/`".
β”‚ β”‚ └── ret-<slug>.md # retired_reason: stale-no-evidence | expired-unconfirmed | rebutted | user-rejected | quarantine-violated | superseded-by-context
β”‚ β”œβ”€β”€ log/ # daily event log
β”‚ β”‚ └── YYYY-MM-DD.md # append-only, typed events
-β”‚ β”œβ”€β”€ payments/ # Pay Memory (optional, paid-action audit)
-β”‚ β”‚ β”œβ”€β”€ policies/spending.md
-β”‚ β”‚ β”œβ”€β”€ <YYYY-MM-DD>/<slug>.md # dated receipts
-β”‚ β”‚ β”œβ”€β”€ assets/ # generated-asset notes
-β”‚ β”‚ β”œβ”€β”€ drafts/ # draft artefacts
-β”‚ β”‚ β”œβ”€β”€ reports/ # daily reports
-β”‚ β”‚ └── _pending/ # approval workflow
β”‚ └── .snapshots/ # pre-dream snapshots
β”‚ └── dream-<run-id>.tar.zst
β”‚
@@ -72,7 +64,6 @@ flowchart LR
end
Agent -- "brain_* (read + write)" --> Brain
- Agent -- "payment_* (read + write)" --> Brain
Agent -- "scan-inline (read-only)" --> Notes
```
@@ -607,7 +598,7 @@ fresh `_brain.yaml`. The full multi-device walkthrough is in
Two cheap, deterministic layers keep the data clean.
**Input sanitisation** (v0.9.1). Every Brain writer routes text fields
-through `src/core/redactor.ts` (promoted from Pay Memory) plus a
+through `src/core/redactor.ts` plus a
`normaliseTextField` / `sanitiseTextField` pair:
- C0 control characters are stripped (except `\t` and `\n`); `U+2028`
diff --git a/docs/mcp.md b/docs/mcp.md
index ff0e1666..5b889c3f 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -18,10 +18,10 @@ in Open Second Brain depends on the MCP server being running.
## Tool Highlights
-The full server currently advertises 65 tools; 18 further names stay callable
+The full server currently advertises 57 tools; 18 further names stay callable
through `tools/call` as hidden deprecated aliases (see "Consolidated views and
deprecated aliases" below). The table highlights the operator-facing core,
-schema, agent-source, health, recovery, and Pay Memory tools; the full surface
+schema, agent-source, health, and recovery tools; the full surface
also includes Brain writer, review, query, temporal, link-graph, and search
tools. In Claude Code, the full schema can push MCP definitions beyond 10% of
the context window, causing `MCPSearch` tool-search deferral; use the writer
@@ -57,14 +57,6 @@ flags for a narrower per-process full server.
| `schema_apply_mutations` | Apply audited, locked schema mutations to `Brain/_brain.yaml`. | `mutations` |
| `brain_watchdog` | Probe Brain config, required dirs, and search-index health; optionally apply safe directory remediation. | β€” |
| `brain_switch_vault` | Activate a named vault profile; the change takes effect on the next server launch. | `name` |
-| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` 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 `Brain/payments/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` |
### Consolidated views and deprecated aliases
@@ -113,37 +105,9 @@ recall DAG populated by CLI `import-session --recall` or the core API.
`brain_recall_gate` accepts optional `previous_prompt` and
`explicit`; `explicit: true` always returns `retrieve: true`.
-`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.** Brain and Pay Memory tools use ISO 8601
-> `YYYY-MM-DD` throughout; the `Brain/log/<date>.md` and
-> `Brain/payments/<date>/` subdirectory layouts share that convention.
-
-`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.
+> **Date format note.** Brain tools use ISO 8601 `YYYY-MM-DD`
+> throughout; the `Brain/log/<date>.md` subdirectory layout shares that
+> convention.
All tool results contain both an unstructured `content` text block (a JSON
serialization of the structured payload) and a `structuredContent` object so
@@ -334,20 +298,11 @@ mcp_servers:
timeout: 30
tools:
include:
+ # Drop any line below to disable a specific tool, or remove the
+ # whole `tools.include` block to expose every advertised tool.
- second_brain_status
- second_brain_query
- 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,
@@ -426,7 +381,7 @@ server to your Codex MCP config the same way as Hermes.
The plugin's `.mcp.json` ships **two** MCP-server entries:
-- `open-second-brain` - the full surface: 56 advertised tools (including the consolidated `brain_brief`, `brain_analytics`, and `schema_inspect`, plus `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_recall_gate`, `brain_pinned_context`, `brain_pre_compress_pack`, `brain_audit`, `brain_sources`, and `brain_switch_vault`) and 18 hidden deprecated aliases listed under "Consolidated views and deprecated aliases" above; subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
+- `open-second-brain` - the full surface: 48 advertised tools (including the consolidated `brain_brief`, `brain_analytics`, and `schema_inspect`, plus `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_recall_gate`, `brain_pinned_context`, `brain_pre_compress_pack`, `brain_audit`, `brain_sources`, and `brain_switch_vault`) and 18 hidden deprecated aliases listed under "Consolidated views and deprecated aliases" above; subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.
- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.
Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).
diff --git a/docs/pay-memory.md b/docs/pay-memory.md
deleted file mode 100644
index 743eb1e3..00000000
--- a/docs/pay-memory.md
+++ /dev/null
@@ -1,133 +0,0 @@
-# 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. It never executes payments and never holds wallet keys.
-
-## Bootstrap
-
-```bash
-o2b init-pay-memory --vault /path/to/vault
-# -> Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs) and policies/spending.md
-```
-
-## Recording a paid call
-
-After running `pay --sandbox curl ...` and capturing the output:
-
-```bash
-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 "Brain/payments/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 "Brain/payments/2026-05-10/<receipt-slug>.md"
-
-o2b payment-report --vault /path/to/vault --date 2026-05-10
-```
-
-The `--raw-output-file` of a receipt 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.
-
-The spending policy at `Brain/payments/policies/spending.md` is read by the agent before each paid call; the MVP does not enforce policy at runtime.
-
-## Machine-readable spending policy (optional)
-
-To enable runtime enforcement, drop a JSON companion at `Brain/payments/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 check before each paid call:
-
-```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.
-
-## Approval workflow (optional)
-
-For paid calls that should not happen until a human signs off, Pay Memory ships a pending-payment-request artifact under `Brain/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
-# -> Brain/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 "Brain/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`.
-
-## Daily Telegram digest via Hermes cron (optional)
-
-`o2b payment-digest --vault <vault> --date <YYYY-MM-DD>` renders a 4-line summary suitable for delivery via Hermes cron `--script --no-agent` jobs. See [`hermes-cron.md`](hermes-cron.md) for the ready-to-paste `hermes cron create` command. The same command can be wrapped by any other scheduler that pipes its stdout to a chat destination - the digest itself is runtime-neutral.
-
-## 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.
-
-## MCP tool surface
-
-Eight Pay Memory tools, all on the full MCP scope:
-
-| Tool | Purpose |
-| --- | --- |
-| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)`. |
-| `payment_receipt_append` | Save a redacted Markdown receipt for one paid API call. |
-| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. |
-| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. |
-| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json`. |
-| `payment_request_approval` | Create a pending-payment-request the user must approve. |
-| `payment_request_status` | Look up a pending request by id (agent uses this to poll). |
-| `payment_request_consume` | Mark an approved request as consumed and link the resulting receipt. |
-
-See [`mcp.md`](mcp.md) for the protocol envelope and lifecycle.
diff --git a/examples/hermes-payment-digest.sh b/examples/hermes-payment-digest.sh
deleted file mode 100755
index c51e601c..00000000
--- a/examples/hermes-payment-digest.sh
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/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 silent
diff --git a/openclaw/index.js b/openclaw/index.js
index 3a357b63..ad0c587e 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1554,84 +1554,13 @@ var require_proper_lockfile = __commonJS((exports, module) => {
// src/openclaw/index.ts
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
-import { existsSync as existsSync6 } from "node:fs";
-import { resolve as resolvePath } from "node:path";
+import { existsSync as existsSync4 } from "node:fs";
// src/core/config.ts
-import { mkdirSync as mkdirSync2, readFileSync } from "node:fs";
+import { mkdirSync, readFileSync } from "node:fs";
var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
import { homedir } from "node:os";
-import { dirname as dirname2, join as join2 } from "node:path";
-
-// src/core/fs-atomic.ts
-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");
- let written = 0;
- while (written < buf.byteLength) {
- written += writeSync(fd, buf, written, buf.byteLength - written);
- }
- fsyncSync(fd);
- closeSync(fd);
- fd = null;
- commit(tmpPath);
- committed = true;
- try {
- const dfd = openSync(dir, "r");
- try {
- fsyncSync(dfd);
- } finally {
- closeSync(dfd);
- }
- } catch {}
- } catch (err) {
- if (fd !== null) {
- try {
- closeSync(fd);
- } catch {}
- }
- if (!committed) {
- try {
- unlinkSync(tmpPath);
- } catch {}
- }
- throw err;
- }
-}
+import { dirname, join } from "node:path";
// src/core/fs-utils.ts
import { existsSync, statSync } from "node:fs";
@@ -1664,8 +1593,8 @@ function defaultConfigPath() {
return expandTilde(override);
const xdg = process.env["XDG_CONFIG_HOME"];
if (xdg)
- return join2(expandTilde(xdg), "open-second-brain", "config.yaml");
- return join2(homedir(), ".config", "open-second-brain", "config.yaml");
+ return join(expandTilde(xdg), "open-second-brain", "config.yaml");
+ return join(homedir(), ".config", "open-second-brain", "config.yaml");
}
function parseSimpleYaml(text) {
const data = {};
@@ -1699,23 +1628,6 @@ function discoverConfig(path) {
return { path: resolved, exists: false, data: {} };
}
}
-function validateTimezoneName(name) {
- try {
- new Intl.DateTimeFormat("en-US", { timeZone: name });
- return { ok: true, error: null };
- } catch (exc) {
- return { ok: false, error: exc.message ?? String(exc) };
- }
-}
-function resolveTimezone(configPath) {
- let name = process.env["VAULT_TIMEZONE"];
- if (!name) {
- name = discoverConfig(configPath).data["timezone"];
- }
- if (!name)
- return null;
- return validateTimezoneName(name).ok ? name : null;
-}
function resolveAgentName(configPath) {
const env = process.env["VAULT_AGENT_NAME"];
if (env)
@@ -1742,25 +1654,25 @@ function expandTilde(p) {
if (p === "~")
return homedir();
if (p.startsWith("~/"))
- return join2(homedir(), p.slice(2));
+ return join(homedir(), p.slice(2));
return p;
}
// src/core/doctor.ts
import {
existsSync as existsSync3,
- mkdirSync as mkdirSync3,
- openSync as openSync2,
+ mkdirSync as mkdirSync2,
+ openSync,
readFileSync as readFileSync2,
rmSync,
- writeSync as writeSync2,
- closeSync as closeSync2
+ writeSync,
+ closeSync
} from "node:fs";
-import { dirname as dirname4, join as join4 } from "node:path";
+import { dirname as dirname3, join as join3 } from "node:path";
// src/core/partner/codegraph.ts
import { existsSync as existsSync2, readdirSync, statSync as statSync2 } from "node:fs";
-import { dirname as dirname3, join as join3, resolve } from "node:path";
+import { dirname as dirname2, join as join2, resolve } from "node:path";
var CODE_MANIFESTS = [
"package.json",
"pyproject.toml",
@@ -1784,9 +1696,9 @@ function isCodeProject(dir) {
try {
if (!existsSync2(dir))
return false;
- if (!isDir(join3(dir, ".git")))
+ if (!isDir(join2(dir, ".git")))
return false;
- return CODE_MANIFESTS.some((m) => existsSync2(join3(dir, m)));
+ return CODE_MANIFESTS.some((m) => existsSync2(join2(dir, m)));
} catch {
return false;
}
@@ -1810,7 +1722,7 @@ function findCodeProjects(opts) {
found.push(path);
};
consider(opts.cwd);
- const vaultParent = dirname3(resolve(opts.vault));
+ const vaultParent = dirname2(resolve(opts.vault));
if (isDir(vaultParent)) {
let entries = [];
try {
@@ -1822,7 +1734,7 @@ function findCodeProjects(opts) {
for (const name of entries) {
if (scanned >= limit)
break;
- consider(join3(vaultParent, name));
+ consider(join2(vaultParent, name));
}
}
for (const extra of opts.scanExtraPaths ?? []) {
@@ -1878,7 +1790,7 @@ function checkCodegraph(opts, deps) {
if (!cliPath) {
return null;
}
- const indexDir = join3(project, ".codegraph");
+ const indexDir = join2(project, ".codegraph");
if (!isDir(indexDir)) {
return {
name: "code_graph",
@@ -1916,10 +1828,10 @@ function checkVaultWriteable(vault) {
if (!existsSync3(vault)) {
return { name: "vault_writeable", ok: false, message: `vault directory missing: ${vault}` };
}
- const probe = join4(vault, ".open-second-brain-doctor-test");
+ const probe = join3(vault, ".open-second-brain-doctor-test");
try {
- const fd = openSync2(probe, "w");
- closeSync2(fd);
+ const fd = openSync(probe, "w");
+ closeSync(fd);
rmSync(probe);
} catch (exc) {
return {
@@ -1933,12 +1845,12 @@ function checkVaultWriteable(vault) {
function checkConfigWriteable(config) {
let createdForCheck = false;
try {
- mkdirSync3(dirname4(config), { recursive: true });
+ mkdirSync2(dirname3(config), { recursive: true });
if (!existsSync3(config))
createdForCheck = true;
- const fd = openSync2(config, "a");
- writeSync2(fd, "");
- closeSync2(fd);
+ const fd = openSync(config, "a");
+ writeSync(fd, "");
+ closeSync(fd);
if (createdForCheck)
rmSync(config);
} catch (exc) {
@@ -2123,7 +2035,7 @@ function checkOpenclawManifest(path) {
}
function checkOpenclawInstallability(repoRoot) {
const results = [];
- const pkgPath = join4(repoRoot, "package.json");
+ const pkgPath = join3(repoRoot, "package.json");
const { result, data } = loadJsonManifest(pkgPath, "openclaw_package_json");
results.push(result);
if (!data)
@@ -2152,7 +2064,7 @@ function checkOpenclawInstallability(repoRoot) {
});
continue;
}
- const entryPath = join4(repoRoot, entry);
+ const entryPath = join3(repoRoot, entry);
if (isFile(entryPath)) {
results.push({
name: `openclaw_entry_${entry}`,
@@ -2176,10 +2088,10 @@ function doctor(opts) {
results.push(checkConfigWriteable(opts.config));
if (opts.repoRoot) {
const root = opts.repoRoot;
- results.push(checkClaudeManifest(join4(root, ".claude-plugin", "plugin.json")));
- results.push(checkCodexManifest(join4(root, ".codex-plugin", "plugin.json")));
- results.push(checkHermesManifest(join4(root, "plugins", "hermes", "plugin.yaml")));
- results.push(checkOpenclawManifest(join4(root, "openclaw.plugin.json")));
+ results.push(checkClaudeManifest(join3(root, ".claude-plugin", "plugin.json")));
+ results.push(checkCodexManifest(join3(root, ".codex-plugin", "plugin.json")));
+ results.push(checkHermesManifest(join3(root, "plugins", "hermes", "plugin.yaml")));
+ results.push(checkOpenclawManifest(join3(root, "openclaw.plugin.json")));
results.push(...checkOpenclawInstallability(root));
}
const cg = checkCodegraph({
@@ -2195,9 +2107,9 @@ function doctor(opts) {
// src/core/identity-reminder.ts
import { readFileSync as readFileSync3 } from "node:fs";
-import { dirname as dirname5, resolve as resolve2 } from "node:path";
+import { dirname as dirname4, resolve as resolve2 } from "node:path";
import { fileURLToPath } from "node:url";
-var TEMPLATE_PATH = resolve2(dirname5(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
+var TEMPLATE_PATH = resolve2(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
var KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"];
function isRuntimeTarget(value) {
return typeof value === "string" && KNOWN_RUNTIME_TARGETS.includes(value);
@@ -2216,7 +2128,7 @@ function loadReminderTemplate() {
});
}
}
-var TEMPLATES_DIR = resolve2(dirname5(fileURLToPath(import.meta.url)), "..", "..", "templates");
+var TEMPLATES_DIR = resolve2(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates");
var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve2(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));
var TEMPLATE_CACHE = new Map;
function tryReadTargetTemplate(target) {
@@ -2258,403 +2170,11 @@ function buildReminder(agent, target) {
return loadReminderTemplate().replace(/\{agent\}/g, agent);
}
-// src/core/pay-memory/paths.ts
-import { join as join6, posix as posix3 } from "node:path";
-
-// src/core/brain/paths.ts
-import { join as join5, posix as posix2 } from "node:path";
-
-// src/core/path-safety.ts
-import { existsSync as existsSync4, realpathSync } from "node:fs";
-import { dirname as dirname6, posix, relative, resolve as resolve3, sep } from "node:path";
-function ensureInsideVault(target, vault) {
- const resolvedTarget = resolve3(target);
- const resolvedVault = resolve3(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 = dirname6(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(resolve3(vault), resolve3(target));
- return rel.split(/[\\/]/).filter((p) => p.length > 0).join(posix.sep);
-}
-
-// src/core/brain/paths.ts
-var BRAIN_ROOT_REL = "Brain";
-var BRAIN_INBOX_REL = posix2.join(BRAIN_ROOT_REL, "inbox");
-var BRAIN_PROCESSED_REL = posix2.join(BRAIN_INBOX_REL, "processed");
-var BRAIN_PREFERENCES_REL = posix2.join(BRAIN_ROOT_REL, "preferences");
-var BRAIN_RETIRED_REL = posix2.join(BRAIN_ROOT_REL, "retired");
-var BRAIN_SKILL_PROPOSALS_REL = posix2.join(BRAIN_ROOT_REL, "skill-proposals");
-var BRAIN_SKILL_PROPOSALS_PENDING_REL = posix2.join(BRAIN_SKILL_PROPOSALS_REL, "pending");
-var BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix2.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");
-var BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix2.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");
-var BRAIN_PROCEDURES_REL = posix2.join(BRAIN_ROOT_REL, "procedures");
-var BRAIN_PROCEDURAL_MEMORY_REL = posix2.join(BRAIN_ROOT_REL, "procedural-memory");
-var BRAIN_ATTENTION_REL = posix2.join(BRAIN_ROOT_REL, "attention");
-var BRAIN_LOG_REL = posix2.join(BRAIN_ROOT_REL, "log");
-var BRAIN_ENTITIES_REL = posix2.join(BRAIN_ROOT_REL, "entities");
-var BRAIN_SNAPSHOTS_REL = posix2.join(BRAIN_ROOT_REL, ".snapshots");
-var BRAIN_ARTIFACTS_REL = posix2.join(BRAIN_ROOT_REL, ".artifacts");
-var BRAIN_INDEX_FILE = "_INDEX.md";
-var BRAIN_INDEX_REL = posix2.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);
-
-// src/core/pay-memory/paths.ts
-var PAY_MEMORY_ROOT_REL = posix3.join(BRAIN_ROOT_REL, "payments");
-var PAY_MEMORY_POLICIES_REL = posix3.join(PAY_MEMORY_ROOT_REL, "policies");
-var PAY_MEMORY_ASSETS_REL = posix3.join(PAY_MEMORY_ROOT_REL, "assets");
-var PAY_MEMORY_DRAFTS_REL = posix3.join(PAY_MEMORY_ROOT_REL, "drafts");
-var PAY_MEMORY_REPORTS_REL = posix3.join(PAY_MEMORY_ROOT_REL, "reports");
-var PAY_MEMORY_PENDING_REL = posix3.join(PAY_MEMORY_ROOT_REL, "_pending");
-var PAY_MEMORY_SPENDING_MD_REL = posix3.join(PAY_MEMORY_POLICIES_REL, "spending.md");
-var PAY_MEMORY_SPENDING_JSON_REL = posix3.join(PAY_MEMORY_POLICIES_REL, "spending.json");
-var ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
-var HHMM_RE = /^(\d{2}):(\d{2})$/;
-function payMemoryDirs(vault) {
- return {
- policies: join6(vault, PAY_MEMORY_POLICIES_REL),
- payments: join6(vault, PAY_MEMORY_ROOT_REL),
- assets: join6(vault, PAY_MEMORY_ASSETS_REL),
- drafts: join6(vault, PAY_MEMORY_DRAFTS_REL),
- reports: join6(vault, PAY_MEMORY_REPORTS_REL),
- pending: join6(vault, PAY_MEMORY_PENDING_REL)
- };
-}
-function policyPath(vault) {
- return join6(vault, PAY_MEMORY_SPENDING_MD_REL);
-}
-function paymentsDateDir(vault, date) {
- return join6(payMemoryDirs(vault).payments, validateIsoDate(date));
-}
-function receiptPath(vault, date, slug) {
- return join6(paymentsDateDir(vault, date), `${validateSlug(slug)}.md`);
-}
-function assetPath(vault, slug) {
- return join6(payMemoryDirs(vault).assets, `${validateSlug(slug)}.md`);
-}
-function reportPath(vault, slug) {
- return join6(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/redactor.ts
-var PLACEHOLDER = "***REDACTED***";
-var PRIVATE_REGION_PLACEHOLDER = "***PRIVATE***";
-var MAX_REDACTOR_INPUT = 256 * 1024;
-var TRUNCATION_MARKER = `
-
-[…truncated for size; original exceeded 256 KB. Inspect raw output before sharing.]
-`;
-var PRIVATE_OPEN_TAG_RE = /<private\b[^>]*>/gi;
-var PRIVATE_CLOSE_TAG_RE = /<\/private>/gi;
-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 stripPrivateRegions(text) {
- if (!text)
- return text;
- let output = "";
- let cursor = 0;
- PRIVATE_OPEN_TAG_RE.lastIndex = 0;
- PRIVATE_CLOSE_TAG_RE.lastIndex = 0;
- while (cursor < text.length) {
- PRIVATE_OPEN_TAG_RE.lastIndex = cursor;
- const openMatch = PRIVATE_OPEN_TAG_RE.exec(text);
- if (!openMatch) {
- output += text.slice(cursor);
- break;
- }
- output += text.slice(cursor, openMatch.index);
- output += PRIVATE_REGION_PLACEHOLDER;
- let depth = 1;
- let scan = PRIVATE_OPEN_TAG_RE.lastIndex;
- while (depth > 0) {
- PRIVATE_OPEN_TAG_RE.lastIndex = scan;
- PRIVATE_CLOSE_TAG_RE.lastIndex = scan;
- const nextOpen = PRIVATE_OPEN_TAG_RE.exec(text);
- const nextClose = PRIVATE_CLOSE_TAG_RE.exec(text);
- if (!nextClose)
- return output;
- if (nextOpen && nextOpen.index < nextClose.index) {
- depth += 1;
- scan = PRIVATE_OPEN_TAG_RE.lastIndex;
- } else {
- depth -= 1;
- scan = PRIVATE_CLOSE_TAG_RE.lastIndex;
- }
- }
- cursor = scan;
- }
- return output;
-}
-function redactRawOutput(text, opts = {}) {
- if (!text)
- return text;
- let out = text;
- for (const literal of opts.literals ?? []) {
- if (literal.length === 0)
- continue;
- out = out.split(literal).join(PLACEHOLDER);
- }
- const maxInput = opts.maxInput ?? MAX_REDACTOR_INPUT;
- if (out.length > maxInput)
- out = out.slice(0, maxInput) + TRUNCATION_MARKER;
- out = stripPrivateRegions(out);
- 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 readFileSync4 } from "node:fs";
-import { dirname as dirname7 } 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 \`${PAY_MEMORY_ROOT_REL}/<date>/\`
-- daily event log entry referencing the receipt
-`;
-function writePolicyIfMissing(vault, opts = {}) {
- const target = policyPath(vault);
- const overwrite = opts.overwrite ?? false;
- mkdirSync4(dirname7(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 { mkdirSync as mkdirSync5, readFileSync as readFileSync5, readdirSync as readdirSync2, writeFileSync } from "node:fs";
-import { dirname as dirname8, join as join7, relative as relative2 } from "node:path";
+import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync } from "node:fs";
+import { dirname as dirname5, join as join4, relative } 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_./-])?$/;
-var SLUG_INVALID_RE = /[^a-z0-9]+/g;
-var SLUG_MAX_LEN = 64;
var MEDIA_EXTENSIONS = new Set([
".png",
".jpg",
@@ -2683,7 +2203,7 @@ var DEFAULT_SKIP_FILES = ["index.md", "log.md"];
function parseFrontmatter(path) {
let text;
try {
- text = readFileSync5(path, "utf8");
+ text = readFileSync4(path, "utf8");
} catch {
return [{}, ""];
}
@@ -2716,44 +2236,6 @@ function parseFrontmatterText(text) {
}
return [metadata, body];
}
-function formatFrontmatter(metadata, body) {
- const lines = ["---"];
- for (const [key, value] of Object.entries(metadata)) {
- lines.push(`${key}: ${formatYamlValue(value)}`);
- }
- lines.push("---");
- if (body) {
- lines.push("");
- lines.push(body);
- }
- return lines.join(`
-`) + `
-`;
-}
-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}`, { cause: err });
- }
- throw err;
- }
-}
-function slugify(value) {
- const lowered = value.trim().toLowerCase();
- let slug = lowered.replace(SLUG_INVALID_RE, "-").replace(/^-+|-+$/g, "");
- if (!slug)
- slug = "note";
- slug = slug.slice(0, SLUG_MAX_LEN).replace(/-+$/, "");
- return slug || "note";
-}
function listVaultPages(vaultDir, opts = {}) {
const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);
const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));
@@ -2770,7 +2252,7 @@ function walk(root, dir, skipDirs, skipFiles, out) {
return;
}
for (const entry of entries) {
- const full = join7(dir, entry.name);
+ const full = join4(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name))
continue;
@@ -2783,7 +2265,7 @@ function walk(root, dir, skipDirs, skipFiles, out) {
continue;
if (skipFiles.has(entry.name.toLowerCase()))
continue;
- const rel = relative2(root, full);
+ const rel = relative(root, full);
const parts = rel.split(/[\\/]/);
if (parts.some((p) => skipDirs.has(p)))
continue;
@@ -2851,813 +2333,6 @@ function splitInlineArray(inner) {
}
return out;
}
-function formatYamlScalar(value) {
- const text = typeof value === "string" ? value : String(value);
- if (text && PLAIN_SCALAR_RE.test(text) && !text.includes(": ") && !text.includes(" #")) {
- return text;
- }
- const escaped = text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
- return `"${escaped}"`;
-}
-function formatYamlValue(value) {
- if (Array.isArray(value)) {
- return "[" + value.map((item) => formatYamlScalar(item)).join(", ") + "]";
- }
- return formatYamlScalar(value);
-}
-
-// 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/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 \`${PAY_MEMORY_SPENDING_JSON_REL}\` 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: [[${PAY_MEMORY_PENDING_REL}/${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:",
- "",
- `[[${stripMarkdownExt(PAY_MEMORY_SPENDING_MD_REL)}]]`,
- "",
- ...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 readdirSync3 } from "node:fs";
-import { join as join8 } from "node:path";
-var REPORT_FRONTMATTER_TYPE = "payment-report";
-function aggregateReceipts(vault, date) {
- const dir = paymentsDateDir(vault, date);
- let entries;
- try {
- entries = readdirSync3(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 = join8(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 readFileSync6 } from "node:fs";
-import { join as join9 } from "node:path";
-var POLICY_SCHEMA_VERSION = 1;
-function policyJsonPath(vault) {
- return join9(payMemoryDirs(vault).policies, "spending.json");
-}
-function loadPolicyRules(vault) {
- const target = policyJsonPath(vault);
- let text;
- try {
- text = readFileSync6(target, "utf8");
- } catch (err) {
- if (err?.code === "ENOENT")
- return null;
- throw new Error(`failed to read ${target}: ${err.message ?? String(err)}`, {
- cause: err
- });
- }
- let parsed;
- try {
- parsed = JSON.parse(text);
- } catch (err) {
- throw new Error(`${target} is not valid JSON: ${err.message ?? String(err)}`, {
- cause: 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 join10 } from "node:path";
-var PENDING_REQUEST_FRONTMATTER_TYPE = "pending-payment-request";
-function pendingDir(vault) {
- return join10(vault, PAY_MEMORY_PENDING_REL);
-}
-function pendingRequestPath(vault, id) {
- return join10(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.ts
var PLACEHOLDER_AGENT_VALUES = new Set([
@@ -3696,25 +2371,11 @@ function normalizeAgentArgument(value) {
return cleaned;
}
-// src/core/validate.ts
-function parseOptionalFiniteNumberInput(raw) {
- if (raw === undefined || raw === null)
- return { value: null, error: null };
- if (typeof raw === "number") {
- if (!Number.isFinite(raw))
- return { value: null, error: "finite-number" };
- return { value: raw, error: null };
- }
- if (typeof raw === "string") {
- const trimmed = raw.trim();
- if (trimmed === "")
- return { value: null, error: null };
- const parsed = Number(trimmed);
- if (!Number.isFinite(parsed))
- return { value: null, error: "number-or-numeric-string" };
- return { value: parsed, error: null };
- }
- return { value: null, error: "number-or-numeric-string" };
+// src/core/path-safety.ts
+import { dirname as dirname6, posix, relative as relative2, resolve as resolve3, sep } from "node:path";
+function vaultRelative(target, vault) {
+ const rel = relative2(resolve3(vault), resolve3(target));
+ return rel.split(/[\\/]/).filter((p) => p.length > 0).join(posix.sep);
}
// src/openclaw/index.ts
@@ -3722,43 +2383,6 @@ function resolveVaultPath(api) {
const cfg = api.pluginConfig ?? {};
return cfg.vault || process.env["VAULT_DIR"] || ".";
}
-function resolveOpenclawTimezone(api) {
- const cfg = api.pluginConfig ?? {};
- const candidate = cfg.timezone || process.env["VAULT_TIMEZONE"] || null;
- if (!candidate)
- return null;
- return validateTimezoneName(candidate).ok ? candidate : null;
-}
-function resolveOpenclawAgent(api, argAgent) {
- const normalized = normalizeAgentArgument(argAgent);
- if (normalized)
- return normalized;
- const cfg = api.pluginConfig ?? {};
- return cfg.agentName ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();
-}
-function coerceExpectedAmount(value) {
- const parsed = parseOptionalFiniteNumberInput(value);
- if (parsed.error === "finite-number") {
- throw new Error("expected_amount must be a finite number");
- }
- if (parsed.error === "number-or-numeric-string") {
- throw new Error("expected_amount must be a number or numeric string");
- }
- return parsed.value;
-}
-function strOrNull(value) {
- if (value === undefined || value === null)
- return null;
- if (typeof value !== "string")
- return null;
- const trimmed = value.trim();
- return trimmed ? trimmed : null;
-}
-function asJson(payload) {
- return {
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]
- };
-}
var openclaw_default = definePluginEntry({
register(api) {
api.on("before_prompt_build", () => {
@@ -3785,7 +2409,7 @@ var openclaw_default = definePluginEntry({
config_keys: Object.keys(discovery.data).toSorted(),
config: redactMapping(discovery.data),
vault_path: vault,
- vault_exists: existsSync6(vault)
+ vault_exists: existsSync4(vault)
};
return {
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
@@ -3813,7 +2437,7 @@ var openclaw_default = definePluginEntry({
},
async execute(_id, params) {
const vault = resolveVaultPath(api);
- if (!existsSync6(vault))
+ if (!existsSync4(vault))
throw new Error(`vault directory missing: ${vault}`);
const pattern = params["pattern"] ?? null;
const limit = typeof params["limit"] === "number" ? params["limit"] : 50;
@@ -3870,399 +2494,6 @@ var openclaw_default = definePluginEntry({
};
}
});
- 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 = existsSync6(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 ${PAY_MEMORY_REPORTS_REL}/.`,
- 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 ${PAY_MEMORY_SPENDING_JSON_REL}. 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/skills/open-second-brain/SKILL.md b/skills/open-second-brain/SKILL.md
index 773d65fb..1432630b 100644
--- a/skills/open-second-brain/SKILL.md
+++ b/skills/open-second-brain/SKILL.md
@@ -1,6 +1,6 @@
---
name: open-second-brain
-description: Use Open Second Brain to read, write, and maintain an agent-owned second brain in an Obsidian-compatible Markdown vault. The agent owns one top-level directory (`Brain/`); Pay Memory nests under `Brain/payments/`. User-authored notes live wherever the operator names them and are read-only inputs when listed in `notes.read_paths`.
+description: Use Open Second Brain to read, write, and maintain an agent-owned second brain in an Obsidian-compatible Markdown vault. The agent owns one top-level directory (`Brain/`). User-authored notes live wherever the operator names them and are read-only inputs when listed in `notes.read_paths`.
---
# Open Second Brain
@@ -12,13 +12,12 @@ Use this skill when a user asks an agent to use, configure, inspect, or maintain
Open Second Brain owns one top-level directory in the vault: `Brain/`. Everything the agent writes lives under it.
- **`Brain/`** - agent-writable observing memory. Taste signals, accreted preferences (unconfirmed β†’ confirmed β†’ retired), evidence log, snapshots. Operations go through MCP tools `brain_feedback`, `brain_apply_evidence`, `brain_dream`, `brain_brief`, `brain_query`, `brain_doctor` - see the `brain-memory` skill for the calling protocol. CLI counterparts: `o2b brain *`.
-- **`Brain/payments/`** - Pay Memory subtree (optional). Receipts, generated-asset notes, drafts, reports, policies, pending-approval requests. Agents use `payment_*` MCP tools when they make paid API calls. Same write contract as the rest of `Brain/` - one root.
- **User-authored notes** - the operator's daily journal, weekly notes, project notes, etc. Folder names are operator-chosen. The agent reads these paths only when they appear under `notes.read_paths` in `Brain/_brain.yaml`; the agent never writes to them.
## Core principles
- Treat the vault as user-owned durable knowledge.
-- Write only into `Brain/` (covers both the observing-memory layer and the optional Pay Memory subtree). Never write to user-authored note folders.
+- Write only into `Brain/`. Never write to user-authored note folders.
- Keep raw operational evidence separate from synthesized knowledge: per-event records go to `Brain/log/`, preferences live in `Brain/preferences/`.
- Never write secrets, tokens, passwords, private keys, or credential-bearing connection strings.
- Prefer deterministic CLI commands (`o2b brain ...`, `o2b doctor`, `o2b status`) over guessing file paths.
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 62ed7cb1..43025b0c 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -225,17 +225,6 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("uninstall", "Remove discipline cron"),
],
),
- command("init-pay-memory", "Bootstrap Pay Memory folders"),
- command("append-payment-receipt", "Save a payment receipt"),
- command("capture-asset", "Save an asset note"),
- command("payment-report", "Aggregate payment receipts"),
- command("check-payment-policy", "Evaluate paid-call policy"),
- command("request-payment-approval", "Create payment approval request"),
- command("approve-payment-request", "Approve payment request"),
- command("reject-payment-request", "Reject payment request"),
- command("consume-payment-request", "Consume approved payment request"),
- command("list-pending-payments", "List payment requests"),
- command("payment-digest", "Render payment digest"),
],
});
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 4101faaa..07c4e6d6 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -36,19 +36,6 @@ import {
sortedReplacer,
} from "./helpers.ts";
import { wantsJsonFlag, withJsonFallback } from "./json-helpers.ts";
-import {
- cmdInitPayMemory,
- cmdAppendPaymentReceipt,
- cmdCaptureAsset,
- cmdPaymentDigest,
- cmdRequestPaymentApproval,
- cmdApprovePaymentRequest,
- cmdRejectPaymentRequest,
- cmdConsumePaymentRequest,
- cmdListPendingPayments,
- cmdCheckPaymentPolicy,
- cmdPaymentReport,
-} from "./pay-memory/index.ts";
import {
installCli,
renderInstallResult,
@@ -682,19 +669,6 @@ Commands:
help Print this help text; --json prints command metadata
completions Print shell completions for bash, zsh, fish, elvish, nushell, powershell
-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)
-
Brain (observing memory):
brain init Bootstrap <vault>/Brain/ skeleton (idempotent)
brain feedback Record a taste signal into Brain/inbox/
@@ -782,17 +756,6 @@ const COMMANDS_WITH_INTERNAL_JSON: ReadonlySet<string> = new Set([
"search",
"vault",
"discipline",
- "init-pay-memory",
- "append-payment-receipt",
- "capture-asset",
- "payment-report",
- "check-payment-policy",
- "request-payment-approval",
- "approve-payment-request",
- "reject-payment-request",
- "consume-payment-request",
- "list-pending-payments",
- "payment-digest",
]);
async function dispatchCommand(command: string, rest: string[]): Promise<number> {
@@ -826,28 +789,6 @@ async function dispatchCommand(command: string, rest: string[]): Promise<number>
return cmdHelp(rest);
case "completions":
return cmdCompletions(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);
case "brain":
return await handleBrainSubcommand(rest);
case "discipline":
diff --git a/src/cli/pay-memory/index.ts b/src/cli/pay-memory/index.ts
deleted file mode 100644
index 00ace1ac..00000000
--- a/src/cli/pay-memory/index.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export { cmdInitPayMemory } from "./verbs/init.ts";
-export { cmdAppendPaymentReceipt } from "./verbs/append-receipt.ts";
-export { cmdCaptureAsset } from "./verbs/capture-asset.ts";
-export { cmdPaymentDigest } from "./verbs/digest.ts";
-export { cmdRequestPaymentApproval } from "./verbs/request-approval.ts";
-export { cmdApprovePaymentRequest } from "./verbs/approve.ts";
-export { cmdRejectPaymentRequest } from "./verbs/reject.ts";
-export { cmdConsumePaymentRequest } from "./verbs/consume.ts";
-export { cmdListPendingPayments } from "./verbs/list.ts";
-export { cmdCheckPaymentPolicy } from "./verbs/check-policy.ts";
-export { cmdPaymentReport } from "./verbs/report.ts";
diff --git a/src/cli/pay-memory/verbs/append-receipt.ts b/src/cli/pay-memory/verbs/append-receipt.ts
deleted file mode 100644
index 081700a7..00000000
--- a/src/cli/pay-memory/verbs/append-receipt.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-import { readFileSync } from "node:fs";
-
-import { defaultConfigPath, resolveAgentName, resolveTimezone } from "../../../core/config.ts";
-import { loadPendingRequest, writeReceipt } from "../../../core/pay-memory/index.ts";
-import type { ReceiptPolicyStatus } from "../../../core/pay-memory/types.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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;
- }
- }
-
- 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;
-}
diff --git a/src/cli/pay-memory/verbs/approve.ts b/src/cli/pay-memory/verbs/approve.ts
deleted file mode 100644
index 4a1ad261..00000000
--- a/src/cli/pay-memory/verbs/approve.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { defaultConfigPath } from "../../../core/config.ts";
-import { approvePendingRequest } from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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;
-}
diff --git a/src/cli/pay-memory/verbs/capture-asset.ts b/src/cli/pay-memory/verbs/capture-asset.ts
deleted file mode 100644
index 31248a47..00000000
--- a/src/cli/pay-memory/verbs/capture-asset.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { readFileSync } from "node:fs";
-
-import { defaultConfigPath } from "../../../core/config.ts";
-import { writeAsset } from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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;
-}
diff --git a/src/cli/pay-memory/verbs/check-policy.ts b/src/cli/pay-memory/verbs/check-policy.ts
deleted file mode 100644
index ed847787..00000000
--- a/src/cli/pay-memory/verbs/check-policy.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { defaultConfigPath, resolveTimezone } from "../../../core/config.ts";
-import { checkPolicy } from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseOptionalNumberFlag } from "../../coerce.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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
- ? decision.policyPath.slice(vault.length).replace(/^\/+/, "")
- : 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`);
- }
- if (decision.allowed) return 0;
- if (decision.approvalRequired) return 3;
- return 1;
-}
diff --git a/src/cli/pay-memory/verbs/consume.ts b/src/cli/pay-memory/verbs/consume.ts
deleted file mode 100644
index b5c7e895..00000000
--- a/src/cli/pay-memory/verbs/consume.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { defaultConfigPath } from "../../../core/config.ts";
-import { consumePendingRequest } from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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;
-}
diff --git a/src/cli/pay-memory/verbs/digest.ts b/src/cli/pay-memory/verbs/digest.ts
deleted file mode 100644
index a894c901..00000000
--- a/src/cli/pay-memory/verbs/digest.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { defaultConfigPath, resolveTimezone } from "../../../core/config.ts";
-import { buildPaymentDigest, renderPaymentDigestTelegram } from "../../../core/pay-memory/index.ts";
-import { requireVault } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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,
- },
- null,
- 2,
- ) + "\n",
- );
- } else {
- const text = renderPaymentDigestTelegram(digest, {
- emptyMode: emptyMode as "silent" | "empty" | "summary",
- });
- if (text) process.stdout.write(text + "\n");
- }
- return 0;
-}
diff --git a/src/cli/pay-memory/verbs/init.ts b/src/cli/pay-memory/verbs/init.ts
deleted file mode 100644
index b96bbc01..00000000
--- a/src/cli/pay-memory/verbs/init.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * `o2b init-pay-memory` β€” bootstrap pay-memory directory layout.
- */
-
-import { existsSync, mkdirSync } from "node:fs";
-
-import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
-import {
- payMemoryDirs,
- vaultRelativePath,
- writePolicyIfMissing,
-} from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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;
-}
diff --git a/src/cli/pay-memory/verbs/list.ts b/src/cli/pay-memory/verbs/list.ts
deleted file mode 100644
index 40db3782..00000000
--- a/src/cli/pay-memory/verbs/list.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { defaultConfigPath } from "../../../core/config.ts";
-import { listPendingRequests } from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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) {
- 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;
-}
diff --git a/src/cli/pay-memory/verbs/reject.ts b/src/cli/pay-memory/verbs/reject.ts
deleted file mode 100644
index 0e1fc09a..00000000
--- a/src/cli/pay-memory/verbs/reject.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { defaultConfigPath } from "../../../core/config.ts";
-import { rejectPendingRequest } from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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;
-}
diff --git a/src/cli/pay-memory/verbs/report.ts b/src/cli/pay-memory/verbs/report.ts
deleted file mode 100644
index 2db7c9c3..00000000
--- a/src/cli/pay-memory/verbs/report.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { defaultConfigPath } from "../../../core/config.ts";
-import { writeReport } from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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;
-}
diff --git a/src/cli/pay-memory/verbs/request-approval.ts b/src/cli/pay-memory/verbs/request-approval.ts
deleted file mode 100644
index 6c881507..00000000
--- a/src/cli/pay-memory/verbs/request-approval.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { defaultConfigPath, resolveAgentName, resolveTimezone } from "../../../core/config.ts";
-import { writePendingRequest } from "../../../core/pay-memory/index.ts";
-import { normalizeFlagString, requireVault, sortedReplacer } from "../../helpers.ts";
-import { parseOptionalNumberFlag } from "../../coerce.ts";
-import { parseFlags } from "../../argparse.ts";
-
-export 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 explicitAgent = normalizeFlagString(flags["agent"]);
- if (flags["agent"] !== undefined && explicitAgent === null) {
- process.stderr.write("error: --agent must be a non-empty string when provided\n");
- return 2;
- }
- const agent = explicitAgent ?? 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;
-}
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 99764ba6..3bf485f5 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -20,8 +20,7 @@
* Every constructor here funnels through `ensureInsideVault` (re-exported
* from `../path-safety`) so a malformed slug or a `..` traversal cannot
* land a file outside the vault root. Slug validation rejects empties,
- * path separators, traversal sequences, and Windows-reserved basenames
- * β€” same contract as the Pay Memory layer.
+ * path separators, traversal sequences, and Windows-reserved basenames.
*/
import { existsSync } from "node:fs";
@@ -364,8 +363,7 @@ export function artifactPath(vault: string, runId: string, artifactId: string):
/**
* Reject slugs that could escape their intended subdirectory or hit a
- * Windows-incompatible filename. Same shape rules as Pay Memory's
- * `validateSlug`, copied here to avoid coupling the two layers.
+ * Windows-incompatible filename.
*/
export function validateSlug(slug: string): string {
const trimmed = slug.trim();
diff --git a/src/core/brain/sync-lockfile.ts b/src/core/brain/sync-lockfile.ts
index fc7dd3d0..59ad1a07 100644
--- a/src/core/brain/sync-lockfile.ts
+++ b/src/core/brain/sync-lockfile.ts
@@ -1,11 +1,11 @@
/**
* Synchronous lockfile primitive for the brain write path.
*
- * Pay Memory locks through `proper-lockfile` (async). The brain write
- * path is sync end-to-end (`writePreference`, `dream`, `moveToRetired`,
- * `writeFrontmatterAtomic`) and migrating it to async would touch every
- * caller signature for one async-only ingredient. Instead, this module
- * provides a tiny single-attempt sync lock built on `fs.openSync(target
+ * The brain write path is sync end-to-end (`writePreference`, `dream`,
+ * `moveToRetired`, `writeFrontmatterAtomic`) and migrating it to async
+ * would touch every caller signature for one async-only ingredient.
+ * Instead, this module provides a tiny single-attempt sync lock built
+ * on `fs.openSync(target
* + '.lock', 'wx')`. EEXIST surfaces as `Error` with
* `.code === 'ELOCKED'`; the brain txn layer maps that to a
* `BrainCollisionError({ kind: 'SourceLock' })`.
diff --git a/src/core/brain/templates/_BRAIN.md.tpl b/src/core/brain/templates/_BRAIN.md.tpl
index 615fd5aa..31bccf7f 100644
--- a/src/core/brain/templates/_BRAIN.md.tpl
+++ b/src/core/brain/templates/_BRAIN.md.tpl
@@ -116,9 +116,7 @@ Schedule it on a cron with confidence β€” duplicate runs do not pollute.
- Do not edit files in `retired/` to undo a retirement. The reason is
preserved on purpose; a rule that should return becomes a new
preference with `supersedes: [[ret-...]]`.
-- Brain operations stay scoped to `Brain/`. Pay Memory writes under
- `Brain/payments/` (receipts, policies, assets, drafts, reports) -
- the same root, different subtree. User-authored notes (daily
+- Brain operations stay scoped to `Brain/`. User-authored notes (daily
journals, etc.) are read-only inputs whose folders are listed in
`_brain.yaml:notes.read_paths`; the agent never writes there.
- Do not invent topics. Reuse an existing topic slug if the rule space
diff --git a/src/core/pay-memory/_md.ts b/src/core/pay-memory/_md.ts
deleted file mode 100644
index bdbad50e..00000000
--- a/src/core/pay-memory/_md.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * 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.ts
deleted file mode 100644
index 31f3b496..00000000
--- a/src/core/pay-memory/approval.ts
+++ /dev/null
@@ -1,498 +0,0 @@
-/**
- * Approval workflow for paid agent actions (spec Β§17.6).
- *
- * Adds a `pending-payment-request` artifact under `Brain/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,
- PAY_MEMORY_PENDING_REL,
- 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(vault, PAY_MEMORY_PENDING_REL);
-}
-
-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.ts
deleted file mode 100644
index 983652b7..00000000
--- a/src/core/pay-memory/asset.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * 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.ts
deleted file mode 100644
index c99ab813..00000000
--- a/src/core/pay-memory/digest.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * 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.ts
deleted file mode 100644
index ce6dc26a..00000000
--- a/src/core/pay-memory/index.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * 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 {
- PAY_MEMORY_ASSETS_REL,
- PAY_MEMORY_DRAFTS_REL,
- PAY_MEMORY_PENDING_REL,
- PAY_MEMORY_POLICIES_REL,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_ROOT_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
- PAY_MEMORY_SPENDING_MD_REL,
- 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.ts
deleted file mode 100644
index 7ddf465a..00000000
--- a/src/core/pay-memory/paths.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-/**
- * Filesystem paths and date utilities for the Pay Memory layout.
- *
- * The layout sits inside `<vault>/Brain/payments/`:
- * - policies/spending.md
- * - YYYY-MM-DD/<slug>.md (receipts go directly under the root)
- * - assets/<slug>.md
- * - drafts/<slug>.md (written by other tools)
- * - reports/<slug>.md
- * - _pending/<id>.md (approval workflow)
- *
- * Date subdirectories use the hyphenated `YYYY-MM-DD` form (ISO 8601
- * calendar date).
- */
-
-import { join, posix } from "node:path";
-
-import { BRAIN_ROOT_REL } from "../brain/paths.ts";
-
-export { ensureInsideVault, vaultRelative } from "../path-safety.ts";
-
-// ----- Canonical Pay Memory path constants ----------------------------------
-//
-// Every path the Pay Memory layer writes to is named here. Other
-// modules (receipt, report, approval, policy, MCP tool descriptions,
-// CLI help text) import these instead of repeating the literal so a
-// future rename cascades from one edit.
-
-/** Vault-relative root of Pay Memory under the Brain layer. */
-export const PAY_MEMORY_ROOT_REL = posix.join(BRAIN_ROOT_REL, "payments");
-
-/** Vault-relative Pay Memory subdirectory names. */
-export const PAY_MEMORY_POLICIES_REL = posix.join(PAY_MEMORY_ROOT_REL, "policies");
-export const PAY_MEMORY_ASSETS_REL = posix.join(PAY_MEMORY_ROOT_REL, "assets");
-export const PAY_MEMORY_DRAFTS_REL = posix.join(PAY_MEMORY_ROOT_REL, "drafts");
-export const PAY_MEMORY_REPORTS_REL = posix.join(PAY_MEMORY_ROOT_REL, "reports");
-export const PAY_MEMORY_PENDING_REL = posix.join(PAY_MEMORY_ROOT_REL, "_pending");
-
-/** Spending-policy file paths (vault-relative). */
-export const PAY_MEMORY_SPENDING_MD_REL = posix.join(PAY_MEMORY_POLICIES_REL, "spending.md");
-export const PAY_MEMORY_SPENDING_JSON_REL = posix.join(PAY_MEMORY_POLICIES_REL, "spending.json");
-
-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;
- readonly pending: string;
-}
-
-export function payMemoryDirs(vault: string): PayMemoryDirs {
- return {
- policies: join(vault, PAY_MEMORY_POLICIES_REL),
- payments: join(vault, PAY_MEMORY_ROOT_REL),
- assets: join(vault, PAY_MEMORY_ASSETS_REL),
- drafts: join(vault, PAY_MEMORY_DRAFTS_REL),
- reports: join(vault, PAY_MEMORY_REPORTS_REL),
- pending: join(vault, PAY_MEMORY_PENDING_REL),
- };
-}
-
-export function policyPath(vault: string): string {
- return join(vault, PAY_MEMORY_SPENDING_MD_REL);
-}
-
-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.ts
deleted file mode 100644
index a0587cd1..00000000
--- a/src/core/pay-memory/policy-rules.ts
+++ /dev/null
@@ -1,328 +0,0 @@
-/**
- * Machine-readable spending policy (`Brain/payments/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 `Brain/payments/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)}`, {
- cause: 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)}`, {
- cause: 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.ts
deleted file mode 100644
index 9e86df56..00000000
--- a/src/core/pay-memory/policy.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * 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 { PAY_MEMORY_ROOT_REL, 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 \`${PAY_MEMORY_ROOT_REL}/<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.ts
deleted file mode 100644
index 6c9f683c..00000000
--- a/src/core/pay-memory/receipt.ts
+++ /dev/null
@@ -1,267 +0,0 @@
-/**
- * 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,
- PAY_MEMORY_PENDING_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
- PAY_MEMORY_SPENDING_MD_REL,
- 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 \`${PAY_MEMORY_SPENDING_JSON_REL}\` 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: [[${PAY_MEMORY_PENDING_REL}/${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:",
- "",
- `[[${stripMarkdownExt(PAY_MEMORY_SPENDING_MD_REL)}]]`,
- "",
- ...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.ts
deleted file mode 100644
index 04712812..00000000
--- a/src/core/pay-memory/redactor.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Pay Memory redactor β€” thin re-export of the shared `src/core/redactor.ts`.
- *
- * The implementation lives in `src/core/redactor.ts` so the Brain
- * writers (`writeSignal`, `appendApplyEvidence`) can share the same
- * secret-key list and assignment shapes without depending on the Pay
- * Memory subtree. This file remains as the import path Pay Memory
- * code historically used; new callers should import from
- * `src/core/redactor.ts` directly.
- */
-
-export { MAX_REDACTOR_INPUT, SECRET_KEYS, redactRawOutput } from "../redactor.ts";
diff --git a/src/core/pay-memory/report.ts b/src/core/pay-memory/report.ts
deleted file mode 100644
index 6a8d8b94..00000000
--- a/src/core/pay-memory/report.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-/**
- * Daily payment report aggregator.
- *
- * `aggregateReceipts` walks `<vault>/Brain/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>/Brain/payments/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.ts
deleted file mode 100644
index 4ff3c5a0..00000000
--- a/src/core/pay-memory/types.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * 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/redactor.ts b/src/core/redactor.ts
index d9724655..84d0866b 100644
--- a/src/core/redactor.ts
+++ b/src/core/redactor.ts
@@ -1,6 +1,6 @@
/**
* Best-effort secret redactor + text-field normaliser shared across
- * Pay Memory and Brain writers.
+ * the Brain writers.
*
* The redactor catches six secret-bearing keys in four assignment
* shapes:
diff --git a/src/core/surface/descriptor.ts b/src/core/surface/descriptor.ts
index 086b62ce..19e884c1 100644
--- a/src/core/surface/descriptor.ts
+++ b/src/core/surface/descriptor.ts
@@ -43,12 +43,7 @@ export function firstLine(text: string): string {
return "";
}
-const GROUP_PREFIXES: ReadonlyArray<string> = Object.freeze([
- "brain",
- "schema",
- "payment",
- "asset",
-]);
+const GROUP_PREFIXES: ReadonlyArray<string> = Object.freeze(["brain", "schema"]);
/**
* Derive a coarse group from a tool name. Prefix families map to their
diff --git a/src/core/vault.ts b/src/core/vault.ts
index a09f8117..712c315c 100644
--- a/src/core/vault.ts
+++ b/src/core/vault.ts
@@ -125,8 +125,8 @@ export function formatFrontmatter(metadata: FrontmatterMap, body: string): strin
* 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.
+ * re-emitted). For 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 });
@@ -156,7 +156,7 @@ export interface WriteFrontmatterAtomicOptions {
/**
* Atomic frontmatter writer with optional exclusive-create semantics.
*
- * Used by Pay Memory writers (receipt, asset, report, policy) where:
+ * Used by the Brain writers 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
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 8b1db6e4..730899da 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -735,7 +735,6 @@ async function toolBrainApplyEvidence(
if (exc instanceof BrainPreferenceNotFoundError) {
// Re-throw as a non-MCPError so `server.handleToolsCall` packs it
// into a `toolError` envelope (isError: true, single-text content).
- // This matches the pay-memory "pending request not found" pattern.
throw new Error(exc.message, { cause: exc });
}
throw exc;
@@ -1695,8 +1694,8 @@ function serializeLogEntry(e: BrainLogEntry): Record<string, unknown> {
// ----- Misc ----------------------------------------------------------------
/**
- * Produce a vault-relative path, swallowing errors (Pay Memory uses the
- * same defensive pattern for output rendering). Exported for unit tests
+ * Produce a vault-relative path, swallowing errors (a defensive pattern
+ * for output rendering). Exported for unit tests
* β€” internal callers stay inside this module.
*
* @internal
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index bf381151..24bde871 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -8,7 +8,6 @@
* the deferred full server.
*/
-import { PAY_MEMORY_SPENDING_JSON_REL } from "../core/pay-memory/paths.ts";
import type { ToolScope } from "./tools.ts";
export interface BuildInstructionsOpts {
@@ -40,10 +39,10 @@ preserved for backward compatibility with existing client configs):
hook (Cursor, Aider, raw Claude API). Runtimes that
already inject active.md via a hook can skip this.
-The remaining Brain surface (digest, query, doctor, backlinks, search,
-Pay Memory tools, vault_health, second_brain_status, second_brain_query,
-and the scheduled learning pass) lives on the sibling
-"open-second-brain" MCP server (deferred). Use ToolSearch to reach it.
+The remaining Brain surface lives on the sibling "open-second-brain"
+MCP server (deferred), including additional read-only, analytics,
+maintenance, and workflow tools beyond the always-loaded writer set.
+Use ToolSearch to discover and reach it.
Prefer the writer-server copies of brain_feedback / brain_apply_evidence /
brain_note / brain_pinned_context over any duplicate exposed by the full server β€” both call the same
@@ -99,13 +98,6 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): string
"Preview budget: a large result may arrive as a JSON envelope with " +
"`preview_truncated: true` and an `artifact_id`; fetch the full " +
"payload with brain_artifact_get only when the preview is not " +
- "enough.\n\n" +
- "Pay Memory tools persist payment memory, never execute payments. " +
- "payment_memory_init bootstraps once per vault; approval sequence: " +
- "payment_policy_check (against " +
- `\`${PAY_MEMORY_SPENDING_JSON_REL}\`) β†’ payment_request_approval β†’ ` +
- "poll payment_request_status β†’ run `pay` β†’ payment_receipt_append β†’ " +
- "asset_capture β†’ payment_request_consume; payment_report_generate " +
- "aggregates a date's receipts."
+ "enough."
);
}
diff --git a/src/mcp/pay-memory-tools.ts b/src/mcp/pay-memory-tools.ts
deleted file mode 100644
index 16c11a6c..00000000
--- a/src/mcp/pay-memory-tools.ts
+++ /dev/null
@@ -1,575 +0,0 @@
-/**
- * MCP tool registry slice for Pay Memory.
- *
- * Exposes the eight Pay Memory tools (`payment_*`, `asset_capture`)
- * that record paid agent actions as inspectable Markdown inside the
- * vault. None of these handlers run a real payment β€” they only
- * persist memory (policy decisions, approval state, receipts, assets,
- * reports). The actual payment rail (`pay.sh`) is invoked separately
- * by the agent harness.
- *
- * Layout mirrors `./brain-tools.ts` and `./search-tools.ts`: each
- * handler is a local async function; one frozen `PAY_MEMORY_TOOLS`
- * array is consumed by `buildToolTable()` in `./tools.ts` via
- * spread.
- */
-
-import { existsSync, mkdirSync } from "node:fs";
-import { resolve } from "node:path";
-
-import { resolveAgentName, resolveTimezone } from "../core/config.ts";
-import { normalizeAgentArgument } from "../core/agent-identity.ts";
-import {
- checkPolicy,
- consumePendingRequest,
- loadPendingRequest,
- payMemoryDirs,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
- vaultRelativePath,
- writeAsset,
- writePendingRequest,
- writePolicyIfMissing,
- writeReceipt,
- writeReport,
-} from "../core/pay-memory/index.ts";
-import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";
-import { INVALID_PARAMS, MCPError } from "./protocol.ts";
-import type { ServerContext, ToolDefinition } from "./tools.ts";
-import { coerceOptionalNumber, coerceStr } from "./coerce.ts";
-
-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 MCPError(INVALID_PARAMS, `from_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 MCPError(INVALID_PARAMS, `id 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,
- };
-}
-
-export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
- {
- 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` and the receipt says so explicitly.",
- },
- 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 ${PAY_MEMORY_SPENDING_JSON_REL}. 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 ${PAY_MEMORY_REPORTS_REL}/.`,
- 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,
- },
-]);
diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.ts
index fccd2499..239d6173 100644
--- a/src/mcp/registry-guard.ts
+++ b/src/mcp/registry-guard.ts
@@ -88,14 +88,6 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr
brain_switch_vault: "write; returns a small profile ack",
brain_write_session: "lifecycle ops return one fixed-shape envelope; prompts are kernel-bounded",
schema_apply_mutations: "write; returns a bounded mutation receipt",
- payment_memory_init: "write; returns a bootstrap receipt",
- payment_receipt_append: "write; returns a single receipt path",
- asset_capture: "write; returns a single asset note path",
- payment_request_approval: "write; returns one pending-request descriptor",
- payment_request_status: "read of one request; fixed-shape status",
- payment_request_consume: "write; returns a small link receipt",
- payment_policy_check: "fixed-shape policy verdict",
- payment_report_generate: "write; returns one report path plus totals",
// Bounded-by-construction reads.
second_brain_capabilities: "fixed-size capability report",
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index f5adc6b6..749abcd4 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -16,8 +16,6 @@
* (`SCHEMA_TOOLS`).
* - Brain watchdog recovery probes (`brain_watchdog`) β€”
* `./watchdog-tools.ts` (`WATCHDOG_TOOLS`).
- * - Pay Memory tools (`payment_*`, `asset_capture`) β€”
- * `./pay-memory-tools.ts` (`PAY_MEMORY_TOOLS`).
*
* Each slice owns its own handlers and tool definitions; this file
* only assembles them in a stable order and applies scope filtering.
@@ -33,7 +31,6 @@ import { BRAIN_TOOLS } from "./brain-tools.ts";
import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";
import { SCHEMA_TOOLS } from "./schema-tools.ts";
import { WATCHDOG_TOOLS } from "./watchdog-tools.ts";
-import { PAY_MEMORY_TOOLS } from "./pay-memory-tools.ts";
import { SKILL_TOOLS } from "./skill-tools.ts";
import { buildHydrateTool, TOOL_HYDRATE_NAME } from "./hydrate-tool.ts";
import { normalizeAgentArgument, PLACEHOLDER_AGENT_VALUES } from "../core/agent-identity.ts";
@@ -415,7 +412,6 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
},
...SCHEMA_TOOLS,
...WATCHDOG_TOOLS,
- ...PAY_MEMORY_TOOLS,
...SKILL_TOOLS,
];
if (scope === "writer") return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));
diff --git a/src/openclaw/index.ts b/src/openclaw/index.ts
index 664b2bd7..8b065a03 100644
--- a/src/openclaw/index.ts
+++ b/src/openclaw/index.ts
@@ -5,42 +5,19 @@
* shares the same source of truth as the CLI and MCP server.
*
* Exposes the current tool surface: `second_brain_status`,
- * `second_brain_query`, `vault_health`, plus the eight Pay Memory tools.
+ * `second_brain_query`, and `vault_health`.
* No subprocess creation; passes the OpenClaw security scanner.
*/
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
import { existsSync } from "node:fs";
-import { resolve as resolvePath } from "node:path";
-import {
- discoverConfig,
- redactMapping,
- resolveAgentName,
- resolveTimezone,
- validateTimezoneName,
-} from "../core/config.ts";
+import { discoverConfig, redactMapping, resolveAgentName } from "../core/config.ts";
import { doctor } from "../core/doctor.ts";
import { buildReminder } from "../core/identity-reminder.ts";
-import {
- checkPolicy,
- consumePendingRequest,
- loadPendingRequest,
- vaultRelativePath,
- writeAsset,
- writePendingRequest,
- writePolicyIfMissing,
- writeReceipt,
- writeReport,
- payMemoryDirs,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
-} from "../core/pay-memory/index.ts";
-import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";
-import { mkdirSync } from "node:fs";
import { listVaultPages } from "../core/vault.ts";
import { normalizeAgentArgument } from "../core/agent-identity.ts";
-import { parseOptionalFiniteNumberInput } from "../core/validate.ts";
+import { vaultRelative as vaultRelativePath } from "../core/path-safety.ts";
interface PluginConfig {
vault?: string;
@@ -54,58 +31,6 @@ function resolveVaultPath(api: { pluginConfig?: Record<string, unknown> }): stri
return cfg.vault || process.env["VAULT_DIR"] || ".";
}
-function resolveOpenclawTimezone(api: { pluginConfig?: Record<string, unknown> }): string | null {
- const cfg = (api.pluginConfig ?? {}) as PluginConfig;
- const candidate = cfg.timezone || process.env["VAULT_TIMEZONE"] || null;
- if (!candidate) return null;
- return validateTimezoneName(candidate).ok ? candidate : null;
-}
-
-function resolveOpenclawAgent(
- api: { pluginConfig?: Record<string, unknown> },
- argAgent: string | null,
-): string {
- const normalized = normalizeAgentArgument(argAgent);
- if (normalized) return normalized;
- const cfg = (api.pluginConfig ?? {}) as PluginConfig;
- return cfg.agentName ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();
-}
-
-/**
- * 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 {
- const parsed = parseOptionalFiniteNumberInput(value);
- if (parsed.error === "finite-number") {
- throw new Error("expected_amount must be a finite number");
- }
- if (parsed.error === "number-or-numeric-string") {
- throw new Error("expected_amount must be a number or numeric string");
- }
- return parsed.value;
-}
-
-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({
register(api): void {
// Per-turn identity reminder via OpenClaw's `before_prompt_build` hook.
@@ -240,417 +165,5 @@ 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 ${PAY_MEMORY_REPORTS_REL}/.`,
- 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 ${PAY_MEMORY_SPENDING_JSON_REL}. 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.ts
deleted file mode 100644
index 0731099e..00000000
--- a/tests/cli/pay-memory.test.ts
+++ /dev/null
@@ -1,622 +0,0 @@
-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 {
- PAY_MEMORY_ASSETS_REL,
- PAY_MEMORY_DRAFTS_REL,
- PAY_MEMORY_PENDING_REL,
- PAY_MEMORY_POLICIES_REL,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_ROOT_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
- PAY_MEMORY_SPENDING_MD_REL,
-} from "../../src/core/pay-memory/paths.ts";
-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");
- expect(existsSync(join(vault, PAY_MEMORY_ROOT_REL))).toBe(true);
- for (const sub of ["policies", "assets", "drafts", "reports"]) {
- expect(existsSync(join(vault, PAY_MEMORY_ROOT_REL, sub))).toBe(true);
- }
- expect(existsSync(join(vault, PAY_MEMORY_SPENDING_MD_REL))).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, PAY_MEMORY_SPENDING_MD_REL);
- 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, PAY_MEMORY_SPENDING_MD_REL);
- 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(PAY_MEMORY_SPENDING_MD_REL);
- expect(payload.policy_status).toBe("created");
- expect(payload.created).toContain(PAY_MEMORY_POLICIES_REL);
- });
-});
-
-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",
- `${PAY_MEMORY_ASSETS_REL}/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: ${PAY_MEMORY_ROOT_REL}/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",
- `${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-blog.md`,
- "--prompt-file",
- promptFile,
- "--used-in",
- `${PAY_MEMORY_DRAFTS_REL}/blog-post.md`,
- ],
- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
- );
- expect(r.returncode).toBe(0);
- expect(r.stdout).toContain(`asset: ${PAY_MEMORY_ASSETS_REL}/`);
- 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: "[[${PAY_MEMORY_ROOT_REL}/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: ${PAY_MEMORY_REPORTS_REL}/`);
- 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, PAY_MEMORY_SPENDING_JSON_REL),
- 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, PAY_MEMORY_SPENDING_JSON_REL),
- 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, PAY_MEMORY_SPENDING_JSON_REL),
- 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: ${PAY_MEMORY_PENDING_REL}/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",
- `${PAY_MEMORY_ROOT_REL}/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, PAY_MEMORY_PENDING_REL, "demo-1.md"), "utf8");
- expect(text).toContain("status: consumed");
- expect(text).toContain("approved_by: sergey");
- expect(text).toContain(`receipt: ${PAY_MEMORY_ROOT_REL}/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).toSorted()).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/path-constants.test.ts b/tests/core/path-constants.test.ts
index fead403f..849a69bb 100644
--- a/tests/core/path-constants.test.ts
+++ b/tests/core/path-constants.test.ts
@@ -2,43 +2,16 @@
* Canonical vault-relative path constants. Everywhere the codebase
* builds a path inside the vault, it imports a constant from this
* test's covered modules instead of repeating the literal. Future
- * renames (Brain β†’ Memory, Brain/payments β†’ Payments, ...) are a
- * one-line change in the constants module.
+ * renames (Brain β†’ Memory, ...) are a one-line change in the
+ * constants module.
*/
import { describe, expect, test } from "bun:test";
-import { posix } from "node:path";
import { BRAIN_ROOT_REL } from "../../src/core/brain/paths.ts";
-import {
- PAY_MEMORY_ASSETS_REL,
- PAY_MEMORY_DRAFTS_REL,
- PAY_MEMORY_PENDING_REL,
- PAY_MEMORY_POLICIES_REL,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_ROOT_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
- PAY_MEMORY_SPENDING_MD_REL,
-} from "../../src/core/pay-memory/paths.ts";
describe("BRAIN_ROOT_REL", () => {
test("names the Brain-layer root directory", () => {
expect(BRAIN_ROOT_REL).toBe("Brain");
});
});
-
-describe("PAY_MEMORY_*_REL constants", () => {
- test("compose under BRAIN_ROOT_REL so a Brain rename cascades", () => {
- expect(PAY_MEMORY_ROOT_REL).toBe(posix.join(BRAIN_ROOT_REL, "payments"));
- expect(PAY_MEMORY_POLICIES_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "policies"));
- expect(PAY_MEMORY_ASSETS_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "assets"));
- expect(PAY_MEMORY_DRAFTS_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "drafts"));
- expect(PAY_MEMORY_REPORTS_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "reports"));
- expect(PAY_MEMORY_PENDING_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "_pending"));
- });
-
- test("spending policy file constants compose under policies", () => {
- expect(PAY_MEMORY_SPENDING_MD_REL).toBe(posix.join(PAY_MEMORY_POLICIES_REL, "spending.md"));
- expect(PAY_MEMORY_SPENDING_JSON_REL).toBe(posix.join(PAY_MEMORY_POLICIES_REL, "spending.json"));
- });
-});
diff --git a/tests/core/pay-memory.approval.test.ts b/tests/core/pay-memory.approval.test.ts
deleted file mode 100644
index ab2fe29b..00000000
--- a/tests/core/pay-memory.approval.test.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-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";
-
-import {
- PAY_MEMORY_ASSETS_REL,
- PAY_MEMORY_DRAFTS_REL,
- PAY_MEMORY_PENDING_REL,
- PAY_MEMORY_POLICIES_REL,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_ROOT_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
- PAY_MEMORY_SPENDING_MD_REL,
-} from "../../src/core/pay-memory/paths.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(`${PAY_MEMORY_PENDING_REL}/`)).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: [`${PAY_MEMORY_DRAFTS_REL}/post.md`, `${PAY_MEMORY_ASSETS_REL}/header.md`],
- });
- const text = readFileSync(out.path, "utf8");
- expect(text).toContain("expected_amount: 0.05");
- expect(text).toContain("currency: USDC");
- expect(text).toContain(`- \`${PAY_MEMORY_DRAFTS_REL}/post.md\``);
- expect(text).toContain("PNG image, 1024Γ—512");
- });
-
- test("records the policy decision when policies/spending.json is present", () => {
- mkdirSync(join(tmp, PAY_MEMORY_POLICIES_REL), { 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, PAY_MEMORY_POLICIES_REL), { 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: `${PAY_MEMORY_ROOT_REL}/2026-05-10/x.md`,
- });
- expect(out.status).toBe("consumed");
- const reloaded = loadPendingRequest(tmp, "t-3")!;
- expect(reloaded.metadata["receipt"]).toBe(`${PAY_MEMORY_ROOT_REL}/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).toSorted()).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.ts
deleted file mode 100644
index c3342f59..00000000
--- a/tests/core/pay-memory.asset.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-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("Brain/payments/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: "Brain/payments/2026-05-10/fal-blog.md",
- usedIn: "Brain/payments/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: "[[Brain/payments/2026-05-10/fal-blog]]"');
- expect(text).toContain('used_in: "[[Brain/payments/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: "Brain/payments/2026-05-10/fal[v2].md",
- });
- const text = readFileSync(out.path, "utf8");
- expect(text).toContain('source_receipt: "[[Brain/payments/2026-05-10/falv2]]"');
- expect(text).toContain("Receipt: [[Brain/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.ts
deleted file mode 100644
index 29dc5b07..00000000
--- a/tests/core/pay-memory.digest.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-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: "Brain/payments/reports/payment-report-2026-05-10.md",
- });
- expect(text).toContain("πŸ’³ ΠžΠΏΠ»Π°Ρ‡Π΅Π½ΠΎ сСрвисов: **2**");
- expect(text).toContain("πŸ’° Π‘ΡƒΠΌΠΌΠ°: **0.08 USDC**");
- expect(text).toContain("πŸ“ Π€Π°ΠΉΠ»Ρ‹ Ρ‡Π΅ΠΊΠΎΠ²: **3**");
- expect(text).toContain("πŸ”— ΠžΡ‚Ρ‡Ρ‘Ρ‚: `Brain/payments/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.ts
deleted file mode 100644
index e9285994..00000000
--- a/tests/core/pay-memory.paths.test.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import { join } from "node:path";
-
-import {
- assetPath,
- isoDateNow,
- isoTimeNow,
- isoTimestampZ,
- PAY_MEMORY_ASSETS_REL,
- PAY_MEMORY_DRAFTS_REL,
- PAY_MEMORY_POLICIES_REL,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_ROOT_REL,
- PAY_MEMORY_SPENDING_MD_REL,
- payMemoryDirs,
- paymentsDateDir,
- policyPath,
- receiptPath,
- reportPath,
- validateIsoDate,
- validateIsoTime,
- validateSlug,
-} from "../../src/core/pay-memory/paths.ts";
-
-describe("payMemoryDirs", () => {
- test("composes the canonical Brain/payments layout", () => {
- const dirs = payMemoryDirs("/vault");
- expect(dirs.policies).toBe(join("/vault", PAY_MEMORY_POLICIES_REL));
- expect(dirs.payments).toBe(join("/vault", PAY_MEMORY_ROOT_REL));
- expect(dirs.assets).toBe(join("/vault", PAY_MEMORY_ASSETS_REL));
- expect(dirs.drafts).toBe(join("/vault", PAY_MEMORY_DRAFTS_REL));
- expect(dirs.reports).toBe(join("/vault", PAY_MEMORY_REPORTS_REL));
- });
-
- test("policyPath, receiptPath, assetPath, reportPath", () => {
- expect(policyPath("/v")).toBe(join("/v", PAY_MEMORY_SPENDING_MD_REL));
- expect(receiptPath("/v", "2026-05-10", "fal-x")).toBe(
- join("/v", PAY_MEMORY_ROOT_REL, "2026-05-10", "fal-x.md"),
- );
- expect(assetPath("/v", "header")).toBe(join("/v", PAY_MEMORY_ASSETS_REL, "header.md"));
- expect(reportPath("/v", "demo")).toBe(join("/v", PAY_MEMORY_REPORTS_REL, "demo.md"));
- });
-
- test("paymentsDateDir validates date", () => {
- expect(paymentsDateDir("/v", "2026-05-10")).toBe(join("/v", PAY_MEMORY_ROOT_REL, "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.ts
deleted file mode 100644
index 4668c4a3..00000000
--- a/tests/core/pay-memory.policy-rules.test.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-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";
-
-import {
- PAY_MEMORY_ASSETS_REL,
- PAY_MEMORY_DRAFTS_REL,
- PAY_MEMORY_PENDING_REL,
- PAY_MEMORY_POLICIES_REL,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_ROOT_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
- PAY_MEMORY_SPENDING_MD_REL,
-} from "../../src/core/pay-memory/paths.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, PAY_MEMORY_POLICIES_REL), { 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, PAY_MEMORY_POLICIES_REL), { 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.1 },
- { 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.ts
deleted file mode 100644
index 1791ca20..00000000
--- a/tests/core/pay-memory.policy.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-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("Brain/payments/<date>/");
- });
-});
diff --git a/tests/core/pay-memory.receipt.test.ts b/tests/core/pay-memory.receipt.test.ts
deleted file mode 100644
index 095bcca6..00000000
--- a/tests/core/pay-memory.receipt.test.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-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("Brain/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("[[Brain/payments/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: "Brain/payments/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("Brain/payments/assets/blog-header.md");
- expect(body).toContain("[[Brain/payments/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: "Brain/payments/assets/blog [draft].md",
- });
- const text = readFileSync(out.path, "utf8");
- expect(text).toContain("[[Brain/payments/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("[[Brain/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.ts
deleted file mode 100644
index c1aa527c..00000000
--- a/tests/core/pay-memory.redactor.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-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.ts
deleted file mode 100644
index f6cb1c90..00000000
--- a/tests/core/pay-memory.report.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-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: "Brain/payments/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("Brain/payments/assets/img1.md");
- });
-
- test("ignores files without the receipt frontmatter type", () => {
- writeReceipt(tmp, { ...baseReceipt, slug: "real-1" });
- const dir = join(tmp, "Brain", "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: "Brain/payments/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("Brain/payments/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("[[Brain/payments/2026-05-10/fal-1]]");
- expect(body).toContain("[[Brain/payments/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/core/search/entities.test.ts b/tests/core/search/entities.test.ts
index f08fcf4b..9084f0f8 100644
--- a/tests/core/search/entities.test.ts
+++ b/tests/core/search/entities.test.ts
@@ -16,9 +16,9 @@ test("extracts a capitalized multi-word run", () => {
});
test("extracts wikilink target and alias display text", () => {
- const e = extractEntities("See [[Pay Memory]] and [[notes/ledger.md|Receipt Ledger]].");
- expect(e).toContain("pay memory");
- expect(e).toContain("receipt ledger");
+ const e = extractEntities("See [[Vector Store]] and [[notes/ledger.md|Recall Ledger]].");
+ expect(e).toContain("vector store");
+ expect(e).toContain("recall ledger");
});
test("extracts CamelCase identifiers", () => {
diff --git a/tests/core/search/entity-alias.test.ts b/tests/core/search/entity-alias.test.ts
index a70534c0..e52f833d 100644
--- a/tests/core/search/entity-alias.test.ts
+++ b/tests/core/search/entity-alias.test.ts
@@ -105,11 +105,11 @@ describe("alias-aware search boost", () => {
mkdirSync(join(tmp.vault, "notes"), { recursive: true });
writeFileSync(
join(tmp.vault, "notes", "a.md"),
- "---\ntitle: A\n---\n\nThe payment flow runs through Pay Memory to pay memory costs.\n",
+ "---\ntitle: A\n---\n\nThe vector flow runs through Vector Store to store vector data.\n",
);
const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath, maxHops: 0 });
await indexVault(config, {});
- const out = await search(config, { query: "payment Pay Memory", limit: 5 });
+ const out = await search(config, { query: "vector Vector Store", limit: 5 });
expect(out.results.length).toBeGreaterThan(0);
expect(out.results[0]!.reasons.some((x) => x.includes("ent-"))).toBe(false);
});
diff --git a/tests/core/search/entity-boost-recall.test.ts b/tests/core/search/entity-boost-recall.test.ts
index c6c630cc..d315b539 100644
--- a/tests/core/search/entity-boost-recall.test.ts
+++ b/tests/core/search/entity-boost-recall.test.ts
@@ -16,17 +16,17 @@ let tmp: ReturnType<typeof createTempVault>;
beforeEach(async () => {
tmp = createTempVault("entity-boost");
mkdirSync(join(tmp.vault, "notes"), { recursive: true });
- // Both notes contain the keyword tokens (payment, pay, memory) so the
+ // Both notes contain the keyword tokens (vector, store) so the
// FTS AND-query retrieves both equally. Only with-entity names the
- // capitalized entity "Pay Memory"; plain uses the same words in lower
+ // capitalized entity "Vector Store"; plain uses the same words in lower
// case, so only with-entity carries the entity the query also names.
writeFileSync(
join(tmp.vault, "notes", "with-entity.md"),
- "---\ntitle: With Entity\n---\n\nThe payment flow runs through Pay Memory to pay memory costs.\n",
+ "---\ntitle: With Entity\n---\n\nThe vector flow runs through Vector Store to store vector data.\n",
);
writeFileSync(
join(tmp.vault, "notes", "plain.md"),
- "---\ntitle: Plain\n---\n\nThe payment system will pay memory fees generically on demand.\n",
+ "---\ntitle: Plain\n---\n\nThe vector system will store vector data generically on demand.\n",
);
const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath, maxHops: 0 });
await indexVault(config, {});
@@ -39,7 +39,7 @@ afterEach(() => {
test("a doc naming the query entity ranks above an equal keyword-only doc", async () => {
// maxHops 0 isolates the entity signal from traversal.
const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath, maxHops: 0 });
- const out = await search(config, { query: "payment Pay Memory", limit: 10 });
+ const out = await search(config, { query: "vector Vector Store", limit: 10 });
const withEntity = out.results.findIndex((r) => r.path === "notes/with-entity.md");
const plain = out.results.findIndex((r) => r.path === "notes/plain.md");
expect(withEntity).toBeGreaterThanOrEqual(0);
diff --git a/tests/core/surface/descriptor.test.ts b/tests/core/surface/descriptor.test.ts
index fef62403..e0ba7f74 100644
--- a/tests/core/surface/descriptor.test.ts
+++ b/tests/core/surface/descriptor.test.ts
@@ -41,7 +41,6 @@ test("descriptions are first-line only", () => {
test("surfaceGroup derives a group from the name prefix", () => {
expect(surfaceGroup("brain_feedback")).toBe("brain");
expect(surfaceGroup("schema_inspect")).toBe("schema");
- expect(surfaceGroup("payment_policy_check")).toBe("payment");
expect(surfaceGroup("second_brain_status")).toBe("core");
expect(surfaceGroup("vault_health")).toBe("core");
});
diff --git a/tests/e2e/pay-memory-factchecktools.sh b/tests/e2e/pay-memory-factchecktools.sh
deleted file mode 100755
index 51c4171d..00000000
--- a/tests/e2e/pay-memory-factchecktools.sh
+++ /dev/null
@@ -1,130 +0,0 @@
-#!/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 "Brain/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/Brain/payments" -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.sh
deleted file mode 100755
index 802650e7..00000000
--- a/tests/e2e/pay-memory-mainnet-places.sh
+++ /dev/null
@@ -1,173 +0,0 @@
-#!/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 "Brain/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/Brain/payments" -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.sh
deleted file mode 100755
index eb87310d..00000000
--- a/tests/e2e/pay-memory-sandbox.sh
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/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 "Brain/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/Brain/payments" -type f | sort
-
-echo
-echo "==> done: vault preserved at $VAULT"
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 19705c72..cbc01500 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -155,7 +155,7 @@ describe("handshake", () => {
});
describe("tool listing", () => {
- test("advertises the core, Brain, and Pay Memory tools (v0.10.8+)", async () => {
+ test("advertises the core and Brain tools (v0.10.8+)", async () => {
const server = new MCPServer({ vault: tmp });
await initialize(server);
const r = (await server.handleRequest({
@@ -230,15 +230,6 @@ describe("tool listing", () => {
// names above stay registered as deprecated aliases.
"brain_brief",
"brain_analytics",
- // Pay Memory (unchanged).
- "payment_memory_init",
- "payment_receipt_append",
- "asset_capture",
- "payment_report_generate",
- "payment_policy_check",
- "payment_request_approval",
- "payment_request_status",
- "payment_request_consume",
// Search (added in v0.10.0; recall gate added in v0.27.0).
"brain_recall_feedback",
"brain_recall_gate",
@@ -502,34 +493,34 @@ describe("stdio loop", () => {
// brain_stale_scan / brain_daily_brief / brain_weekly_synthesis
// added v0.10.18; brain_agent_query / brain_agent_diff added in
// v0.15.0; brain_pinned_context added in v0.16.0; lifecycle review
- // tools added in v0.17.0) + 8 Pay Memory + 1 Search
- // + brain_artifact_get (v0.18.0) = 40.
- // + brain_mcp_landscape (typed graph semantics) = 41.
- // + brain_pre_compress_pack (v0.20.0) = 42.
- // + brain_audit (v0.21.0) = 43.
- // + brain_morning_brief (v0.21.0) = 44.
- // + brain_sources + brain_switch_vault (v0.22.0) = 46.
- // + second_brain_capabilities (v0.23.0) = 47.
- // + 9 schema admin tools + brain_watchdog = 57.
- // + brain_recall_gate (v0.27.0) = 58.
- // + 7 context continuity/session recall tools (v0.29.0) = 65.
- // + 3 procedural-learning tools (v0.30.0) = 68.
- // + brain_procedural_graph (v0.31.0) = 69.
- // + brain_attention_flows (v0.31.0) = 70.
- // + brain_recall_feedback (recall-trust-suite) = 71,
- // + brain_brief / brain_analytics / schema_inspect (token-diet) = 74
+ // tools added in v0.17.0) + 1 Search
+ // + brain_artifact_get (v0.18.0) = 32.
+ // + brain_mcp_landscape (typed graph semantics) = 33.
+ // + brain_pre_compress_pack (v0.20.0) = 34.
+ // + brain_audit (v0.21.0) = 35.
+ // + brain_morning_brief (v0.21.0) = 36.
+ // + brain_sources + brain_switch_vault (v0.22.0) = 38.
+ // + second_brain_capabilities (v0.23.0) = 39.
+ // + 9 schema admin tools + brain_watchdog = 49.
+ // + brain_recall_gate (v0.27.0) = 50.
+ // + 7 context continuity/session recall tools (v0.29.0) = 57.
+ // + 3 procedural-learning tools (v0.30.0) = 60.
+ // + brain_procedural_graph (v0.31.0) = 61.
+ // + brain_attention_flows (v0.31.0) = 62.
+ // + brain_recall_feedback (recall-trust-suite) = 63,
+ // + brain_brief / brain_analytics / schema_inspect (token-diet) = 66
// - 18 predecessors hidden as deprecated aliases (callable via
- // tools/call, not advertised) = 56 (+1 capability diagnostic = 57).
+ // tools/call, not advertised) = 48 (+1 capability diagnostic = 49).
// + list_skills / get_skill / skills_attach / tool_hydrate /
- // brain_intention (Agent Surface Suite) = 62.
+ // brain_intention (Agent Surface Suite) = 54.
// + brain_trigger / brain_deep_synthesis / brain_idea_discovery
- // (Workspace Insight Suite) = 65.
- // + brain_write_session (Agent Write Contract Suite) = 66.
+ // (Workspace Insight Suite) = 57.
+ // + brain_write_session (Agent Write Contract Suite) = 58.
// + brain_truth / brain_dead_ends / brain_foresight
- // (Entity Truth & Self-Improving Dream Suite) = 69.
+ // (Entity Truth & Self-Improving Dream Suite) = 61.
// + brain_labels / brain_tiers / brain_secrets / brain_maintenance
- // (Write-Time Integrity & Governance Suite) = 73.
- expect(list.result.tools.length).toBe(77);
+ // (Write-Time Integrity & Governance Suite) = 65.
+ expect(list.result.tools.length).toBe(69);
});
test("returns parse error for invalid JSON", async () => {
@@ -616,7 +607,6 @@ describe("buildInstructions writer mode", () => {
expect(text).toContain("brain_feedback");
expect(text).toContain("brain_apply_evidence");
expect(text).toContain("open-second-brain"); // points at sibling server
- expect(text).not.toMatch(/payment_/i);
expect(text).not.toMatch(/brain_dream/);
});
});
diff --git a/tests/mcp/pay-memory.test.ts b/tests/mcp/pay-memory.test.ts
deleted file mode 100644
index 1eafda2c..00000000
--- a/tests/mcp/pay-memory.test.ts
+++ /dev/null
@@ -1,363 +0,0 @@
-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";
-
-import {
- PAY_MEMORY_ASSETS_REL,
- PAY_MEMORY_DRAFTS_REL,
- PAY_MEMORY_PENDING_REL,
- PAY_MEMORY_POLICIES_REL,
- PAY_MEMORY_REPORTS_REL,
- PAY_MEMORY_ROOT_REL,
- PAY_MEMORY_SPENDING_JSON_REL,
- PAY_MEMORY_SPENDING_MD_REL,
-} from "../../src/core/pay-memory/paths.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("Brain/payments/policies/spending.md");
- expect(s.policy_status).toBe("created");
- expect(s.created).toContain("Brain/payments/policies");
- // Receipts go DIRECTLY under Brain/payments/ (no nested payments subdir).
- expect(existsSync(join(vault, PAY_MEMORY_ROOT_REL))).toBe(true);
- for (const sub of ["policies", "assets", "drafts", "reports"]) {
- expect(existsSync(join(vault, "Brain", "payments", 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: "Brain/payments/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("Brain/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: "Brain/payments/2026-05-10/fal-blog.md",
- prompt: "A recursive technical illustration",
- used_in: "Brain/payments/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: "[[Brain/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, PAY_MEMORY_SPENDING_JSON_REL),
- 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("Brain/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: "Brain/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/mcp/profiles.test.ts b/tests/mcp/profiles.test.ts
index 86bce4c2..bb0e0d7f 100644
--- a/tests/mcp/profiles.test.ts
+++ b/tests/mcp/profiles.test.ts
@@ -49,7 +49,6 @@ test("recall profile keeps the memory surface and withholds admin tools", () =>
expect(names).toContain("brain_context_pack");
expect(names).toContain("brain_feedback");
expect(names).not.toContain("schema_apply_mutations");
- expect(names).not.toContain("payment_memory_init");
const withheld = evaluated.report.withheld.map((w) => w.name);
expect(withheld).toContain("schema_apply_mutations");
});
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
index ed71deab..295a552e 100644
--- a/tests/mcp/removed-tools.test.ts
+++ b/tests/mcp/removed-tools.test.ts
@@ -138,5 +138,5 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn
method: "tools/list",
params: {},
})) as { result: { tools: Array<{ name: string }> } };
- expect(list.result.tools.length).toBe(77);
+ expect(list.result.tools.length).toBe(69);
});
diff --git a/tests/mcp/scope-filter.test.ts b/tests/mcp/scope-filter.test.ts
index f0508813..b1898d92 100644
--- a/tests/mcp/scope-filter.test.ts
+++ b/tests/mcp/scope-filter.test.ts
@@ -8,7 +8,6 @@ describe("buildToolTable scope filter", () => {
expect(names).toContain("brain_feedback");
expect(names).toContain("brain_apply_evidence");
expect(names).toContain("brain_dream");
- expect(names).toContain("payment_memory_init");
expect(names).toContain("vault_health");
expect(full.length).toBeGreaterThanOrEqual(15);
});
diff --git a/tests/openclaw/bundle.test.ts b/tests/openclaw/bundle.test.ts
index 0a3a899a..a3e5c80d 100644
--- a/tests/openclaw/bundle.test.ts
+++ b/tests/openclaw/bundle.test.ts
@@ -41,15 +41,6 @@ describe("openclaw bundle", () => {
"second_brain_status",
"second_brain_query",
"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(bundleText).toContain(tool);
}