fairwire-core 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kurt Francisco
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,284 @@
1
- # Temporary Holding Version
1
+ # fairwire-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The shared core for the **Fairwire IT and network agents** (Mythos Machines): small MCP agents that each own one IT job and cannot act outside it. Forked from lodestar-core (with its Windows fixes of 18 November 2026) and extended with:
4
+
5
+ - **Personal-data masking** (`pii.js`): names, sign-in names, e-mail addresses, phone numbers, device ids and client addresses become stable HMAC pseudonyms before any result reaches the model; files written for the team keep the real values. `--pii mask|strict|off`; off is recorded on every audit line.
6
+ - **IT helpers** (`it.js`): IPv4/IPv6, CIDR ranges, private and public addresses, port lists and coverage, MAC addresses, version comparison, dates, counts and sorts that do not depend on row order.
7
+ - **The agent builder** (`agent.js`, `wireAgent`): check, explain, report, a draft note with a one-click request, accepted exceptions (`known_exception` memory) and refused live actions, from one short description per agent.
8
+
9
+ The parts below come from lodestar-core unchanged in behaviour:
10
+
11
+ - **Pack manifest** — name, version, a declared model pin, the tool allowlist and the policy. `defineManifest()` fails closed: an unpinned model (`latest`), a tool without a rule, a write marked `allow`, or a one-click action marked `allow` are rejected at load time.
12
+ - **Talos-style policy** — every tool call gets `allow`, `ask` or `block`. Unknown tools are blocked. The default is block.
13
+ - **Modes**
14
+ - **Review**: read and report tools only. Everything else is blocked.
15
+ - **Assist** (default): the policy as written. `ask` returns an `approval_id` and waits for a named human.
16
+ - **Auto**: off by default and **opt-in per action** (`--auto tool_a,tool_b`). Only opted-in `ask` actions run without a click. Step and spend caps and a kill switch always apply.
17
+ - **Always one-click, even in Auto**: `go_live`, `revoke_access`, `delete_personal_data`, `move_money`, `binding_send`, `production_deploy`, and `accept_learning` (changing what an agent remembers). Trying to put one of these on Auto throws an error. Auto prepares the work; a person clicks.
18
+ - **Audit log** — append-only JSONL (`.fairwire/audit.jsonl`), one line per decision, hash-chained so edits and removed lines show up. Arguments are stored as a SHA-256 hash, not in full. Field names follow Alethea's record vocabulary (`id`, `type`, `date`, `requirements`) so logs sit cleanly next to an Alethea `.decisions/` folder; this package does not write into `.decisions/`.
19
+ - **Stdio MCP server** — zero-dependency, newline-delimited JSON-RPC 2.0 (`initialize`, `ping`, `tools/list`, `tools/call`, `prompts/list`, `prompts/get`), protocol versions up to `2025-11-25`, tool annotations (`readOnlyHint`, `destructiveHint`, …) derived from each tool's kind, plus a built-in `fairwire_info` tool that reports usage and pending approvals.
20
+ - **Input validation** — every call is checked against the tool's `inputSchema` before anything runs or reaches a human. Errors carry JSON-pointer paths (`/vendors/3/tin expected string`).
21
+ - **Signed audit log (opt-in)** — with `--signing-key`, every line is also signed with Ed25519. A re-chained file fails `verify-log --pubkey`. Key rotation is recorded as a signed entry.
22
+ - **Approvals people can actually use** — CLI, a local approvals page on 127.0.0.1, or an HMAC-signed webhook callback. Approvals are single-use, bound to the exact arguments, expire after 24 h by default, and can be rejected.
23
+ - **Caps that survive restarts** — per session, per day and per tool, persisted in `.fairwire/usage.json`.
24
+ - **Domain memory (opt-in per agent)** — an agent can remember facts about one customer's setup in its own specialty (a column name, an extra privileged role). Learning only proposes; a fact applies after a named person accepts it, every result says which facts it used, and the file is hash-chained like the audit log. See [Domain memory](#domain-memory).
25
+ - **Private evals** — fixture-based, deterministic test cases, with an offline HTML report and regression highlighting against a baseline.
26
+ - **Shared helpers** — JSON Schema validation, iCalendar, SARIF 2.1.0, unified diff/patch, Jaro-Winkler and name/address normalisation, entropy, a small ZIP/DOCX reader, and a self-contained HTML page template.
27
+
28
+ MIT, Node ≥ 20, no runtime dependencies.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ npm install fairwire-core
34
+ ```
35
+
36
+ ## A pack in 30 lines
37
+
38
+ ```js
39
+ import { defineManifest, main } from 'fairwire-core';
40
+
41
+ const manifest = defineManifest({
42
+ name: 'my-pack', version: '0.1.0', description: 'One process, nothing else.',
43
+ model: { provider: 'anthropic', id: 'claude-sonnet-4-5-20250929' },
44
+ tools: [
45
+ { name: 'my_check', kind: 'read', description: 'Read a CSV and report.',
46
+ inputSchema: { type: 'object', required: ['path'], properties: { path: { type: 'string' } } },
47
+ handler: async (args, ctx) => { const rows = ctx.records(args.path); return { summary: `${rows.length} rows`, rows: rows.length }; } },
48
+ { name: 'my_fix', kind: 'write', description: 'Change something (needs a human).', handler: async () => ({ summary: 'done' }) },
49
+ { name: 'my_go_live', kind: 'action', category: 'go_live', description: 'Never by an agent.' },
50
+ ],
51
+ policy: { rules: [
52
+ { tool: 'my_check', decision: 'allow' },
53
+ { tool: 'my_fix', decision: 'ask', reason: 'writes need a human' },
54
+ { tool: 'my_go_live', decision: 'block' },
55
+ { tool: '*', decision: 'block' },
56
+ ] },
57
+ });
58
+
59
+ main(manifest); // gives you: mcp | tools | call | demo | eval | approve | reject | approvals | usage | keygen | verify-log | kill | unkill
60
+ ```
61
+
62
+ `ctx.records(path)` reads CSV, JSON or JSONL; `ctx.path()` refuses paths outside `--root`; `ctx.outDir()` creates an output folder inside it.
63
+
64
+ ## Scaffold a new agent
65
+
66
+ ```bash
67
+ npx -y -p fairwire-core fairwire-new-agent fairwire-example-checks --dir packages
68
+ ```
69
+
70
+ The generated package passes `npm test`, `eval` and `npm pack --dry-run` as is. Name it after its job (`fairwire-<what it does>`, 1 to 4 words); the tool prefix is the same words in snake_case. The 31 agents in `packages/` of the monorepo are full examples built with `wireAgent`.
71
+
72
+ ## Approvals
73
+
74
+ When a call is `ask`, the result contains an `approval_id` bound to that exact tool and arguments. A person approves it once:
75
+
76
+ ```bash
77
+ npx -y -p fairwire-core fairwire-approve 3f2a9c1d0b7e6a55 --as "Your Name" --dir .fairwire
78
+ ```
79
+
80
+ Then the same call runs and the log records who approved it.
81
+
82
+ Other ways to decide:
83
+
84
+ - `npx <pack> approvals serve` opens a local page (127.0.0.1 only, strict CSP, no scripts, a per-start form token, Host and Origin checks) that lists pending approvals with a short, non-sensitive preview of the arguments. Type your name and approve once, or reject.
85
+ - `--approval-webhook https://…` POSTs each new pending approval to your endpoint, signed with `FAIRWIRE_WEBHOOK_SECRET` (HMAC-SHA256, header `x-fairwire-signature: t=<unix>,v1=<hex>`). Your system answers by POSTing `{ "id", "decision": "approve"|"reject", "by": "Person Name" }`, signed the same way, to the approvals page's `/callback`. A bad signature, a timestamp older than 5 minutes or a missing name is refused and audited.
86
+ - `npx <pack> reject <id> --as "Name"` refuses a pending action.
87
+
88
+ Approvals expire 24 hours after a person approves (`--approval-ttl HOURS`). Names like "agent" or "claude" are refused as approvers. One-click categories can be approved by a person through any of these routes, but never by Auto.
89
+
90
+ **Honest limit:** approvals are a file. If the agent also has a shell in the same folder, it could write that file itself. For approvals to mean something, give the agent the MCP server only, not a shell, or keep `--state-dir` somewhere the agent cannot write.
91
+
92
+ ## Domain memory
93
+
94
+ An agent can remember facts about one customer's setup in its own specialty, so the next run does not have to be told again: "their key column is `legacy_id`", "Vault Keeper is a privileged role here". The agent declares which kinds of fact it can learn and what each one changes. Nothing else can be learned.
95
+
96
+ ```js
97
+ import { defineManifest, memoryTools } from 'fairwire-core';
98
+
99
+ const KINDS = {
100
+ privileged_role: {
101
+ description: 'A role this customer treats as privileged, e.g. {"role": "Vault Keeper"}.',
102
+ effect: 'adds the role to the privileged list (more findings, never fewer)',
103
+ schema: { type: 'object', additionalProperties: false, required: ['role'], properties: { role: { type: 'string', minLength: 2, maxLength: 100 } } },
104
+ check: (v) => null, // optional: return a reason to refuse a value
105
+ },
106
+ };
107
+ const mem = memoryTools('acme', KINDS); // acme_recall, acme_learn, acme_accept_learning, acme_retire_memory
108
+
109
+ export const manifest = defineManifest({
110
+ name: 'fairwire-example-checks', /* … */
111
+ memory: { prefix: 'acme', kinds: KINDS },
112
+ tools: [
113
+ { name: 'acme_review', kind: 'read', description: '…', handler: async (a, ctx) => {
114
+ const extra = ctx.memoryFacts('privileged_role').map((f) => f.value.role); // accepted facts only
115
+ /* … use them to add checks … */
116
+ } },
117
+ ...mem.tools,
118
+ ],
119
+ policy: { rules: [{ tool: 'acme_review', decision: 'allow' }, ...mem.rules, { tool: '*', decision: 'block' }] },
120
+ });
121
+ ```
122
+
123
+ | Tool | Kind | Policy | What it does |
124
+ |---|---|---|---|
125
+ | `<prefix>_recall` | read | allow | Search what the agent has learned: accepted facts, facts waiting for a person, and their history. Says whether the file verifies. |
126
+ | `<prefix>_learn` | report | allow | Propose one fact. It is stored as waiting and changes nothing. Records the hash of any `source_files` it came from. |
127
+ | `<prefix>_accept_learning` | action | ask · one-click (`accept_learning`) | A named person accepts or rejects a waiting fact. Never on Auto. |
128
+ | `<prefix>_retire_memory` | action | ask · one-click (`accept_learning`) | A named person stops an accepted fact. The history stays. |
129
+
130
+ What is enforced in code, not left to the model:
131
+
132
+ - **One file per agent**: `.fairwire/memory/<agent>.jsonl`. The runtime picks it from the manifest name; no tool argument names a file or another agent. Lines written for another agent are ignored and reported.
133
+ - **Only declared kinds**, each checked against its JSON Schema (which must set `additionalProperties: false`) and its optional `check`. A built-in `note` kind is for people and changes no check. Policy, caps, Auto opt-ins and one-click categories are not memory and cannot be learned.
134
+ - **Learning only proposes.** A fact applies from the next call after a named person accepts it. Accepting is the one-click category `accept_learning`, so it always asks, even in Auto.
135
+ - **Each acceptance is checked against the approvals file**: the approval must be by the same person, given before the line was written, for exactly that fact and decision (the approval id is a hash of the tool and its arguments). A properly chained "accepted" line with no such approval is shown as `unverified` and not used. The same check applies to retiring a fact.
136
+ - **Tamper-evident**: the file is hash-chained like the audit log, and signed with the same key when `--signing-key` is set. A fact's id is a hash of its content, so a value edited in place (even in a re-chained file) no longer matches its id or its approval and is ignored. If it does not verify, no accepted fact is used and every result says so. `<pack> memory verify` also cross-checks the audit log: an acceptance the audit log says ran but the memory file lacks (lines cut from the end) is reported.
137
+ - **Refused values**: private keys, AWS/Stripe/GitHub/Slack tokens, `password: …` patterns, long random-looking strings, US social security numbers, and text that reads like instructions to an AI. At most 200 facts can wait for a person and 5,000 facts are kept.
138
+ - **Every result says what it used**: `memory_applied` on the call result (id, kind, value, who accepted it) and the ids in the audit line. `--no-memory` (or `memory: false`) runs without learned facts; recall and learn still work.
139
+
140
+ From the command line:
141
+
142
+ ```bash
143
+ npx <pack> memory list # accepted and waiting facts
144
+ npx <pack> memory accept MEM-1a2b3c4d5e6f --as "Your Name" --reason "Checked with the controller"
145
+ npx <pack> memory reject MEM-1a2b3c4d5e6f --as "Your Name"
146
+ npx <pack> memory retire MEM-1a2b3c4d5e6f --as "Your Name" --reason "Role removed in March"
147
+ npx <pack> memory verify [--pubkey public.pem]
148
+ ```
149
+
150
+ `memory accept` takes the same path as the agent: the call asks, the named person approves, the call runs. Whoever approves sees the fact itself (kind, value, note and what it changes), not just its id: in the `needs_approval` result (`approving`), on the approvals page and in `approvals list`. Any tool can offer this with an `approvalPreview(args, ctx)` function.
151
+
152
+ **Honest limits:** the same as approvals. If the agent also has a shell in the same folder, it could write the memory and approvals files. Without a signing key, someone with write access to both the memory file and the approvals file could forge a fact and its approval together; with `--signing-key` (key kept outside `--root`) a rewritten memory file fails `memory verify --pubkey`. Removing lines from the end of an unsigned file is only caught by the audit-log cross-check. Learned facts are what a person accepted, not proof that they are right.
153
+
154
+ ## Kill switch and caps
155
+
156
+ - `npx <pack> kill` creates `.fairwire/KILL`; every call is then blocked until `unkill`. `FAIRWIRE_KILL=1` does the same.
157
+ - `--max-steps N` and `--max-spend USD` stop a session and report. Spend counts each tool's declared `costUsd` (the wave-1 packs are local and declare $0), plus any `costUsd` a handler returns.
158
+
159
+ - Caps persist in `.fairwire/usage.json`: `--session ID` keeps a session's count across restarts, `--max-steps-per-day` and `--max-spend-per-day` cap a whole day, and a manifest can set `caps.perTool.<tool>.maxSteps` so one tool cannot use the whole budget. A cap hit returns `{ status: "blocked", cap: { cap, scope, limit, used } }` and is audited. `npx <pack> usage` shows the counters.
160
+
161
+ ## Verify a log
162
+
163
+ ```bash
164
+ npx -y -p fairwire-core fairwire-verify-log .fairwire/audit.jsonl
165
+ ```
166
+
167
+ Unsigned, the chain is tamper-evident, not tamper-proof: someone with write access can rewrite the whole file. To close that gap, sign it:
168
+
169
+ ```bash
170
+ npx <pack> keygen --out ~/.fairwire-keys/my-pack # keep this outside --root
171
+ npx <pack> mcp --signing-key ~/.fairwire-keys/my-pack/private.pem --audit-mirror /backup/my-pack-audit.jsonl
172
+ npx <pack> verify-log --pubkey ~/.fairwire-keys/my-pack/public.pem
173
+ npx <pack> rotate-key --signing-key OLD.pem --new-key NEW.pem --as "Your Name"
174
+ ```
175
+
176
+ The key is refused if it sits under `--root`, and it is never logged. With `--pubkey`, every line must carry a valid signature from a trusted key (or a key introduced by a signed rotation). Old unsigned logs still verify as "chained, unsigned". Signing proves the lines came from whoever holds the key; it cannot stop that holder from writing a false line.
177
+
178
+ ## Untrusted data and broken arguments
179
+
180
+ Agents read files that other people wrote: vendor names, memos, email bodies, page content. The runtime treats that text as hostile until shown otherwise, for every pack built on it.
181
+
182
+ - **Spreadsheets.** `toCsv` puts an apostrophe in front of a cell that a spreadsheet would run as a formula (it starts with `=`, or with `+`, `-` or `@` and is not a plain number, a phone-style value or a bare `@handle`). Pass `{ formulas: 'keep' }` for a file only a program reads.
183
+ - **Markdown.** `ctx.writeFile` passes `.md` output through `safeMarkdown`: raw HTML outside code becomes literal text (`\<script>`), and remote or reference-style images become plain text, so a Markdown preview shows what a data cell contained instead of rendering it or fetching an image for it. Links are left as they are. Pass `{ raw: true }` when the file is a copy of the person's own document. If you store a hash of Markdown you write, hash `safeMarkdown(text)` or the file itself.
184
+ - **File names.** `ctx.writeFile(dir, name, …)` refuses a name that leaves `dir`. Use `safeFileName(id)` when a name comes from data.
185
+ - **HTML.** `htmlPage` wraps every table so a wide one scrolls inside the page on a phone, adds `scope` to header cells for screen readers, and right-aligns the header of a numeric column. `bodyHtml` must still be escaped with `escapeHtml` by the pack.
186
+ - **Instructions aimed at the model.** When a result quotes text that reads like instructions to an AI ("ignore previous instructions", fake chat markup, "do not tell the user", hidden or direction-flipping characters), the result carries a `warnings` entry and the audit line an `injection_signals` list. The data is returned unchanged. This is a short, high-precision heuristic (`injectionSignals`): it catches common shapes and misses others. The MCP `initialize` instructions also tell the host model that tool results are data. One-click actions still need a named human whatever the model was told.
187
+ - **Arguments.** A misspelled argument that is one or two letters from a real one (`receipt` for `receipts`, `outdir` for `out_dir`) is refused with the right name. An unrelated extra argument is refused by tools that set `additionalProperties: false`, and otherwise ignored with a `warnings` entry and an `ignored_args` audit field. A required argument given as an empty string counts as missing.
188
+ - **Errors.** File errors are plain sentences with paths relative to `--root` ("file not found: data/vendors.csv"); the absolute root never appears in an error, and long messages are clipped at about 1,200 characters.
189
+
190
+ `node scripts/hostile-inputs.mjs` in the monorepo plants hostile values in every pack's fixtures, runs every eval case and inspects the output; `--args` also calls every tool with broken arguments.
191
+
192
+ ## Configs
193
+
194
+ A pack can declare `configSchemas: { playbook: { …JSON Schema… } }`. Handlers load configs with `ctx.readJson(path, 'playbook')`, which fails with JSON-pointer errors, and people can check a file before use with `npx <pack> validate-config playbook ./my-playbook.json`.
195
+
196
+ ## Prompts
197
+
198
+ A pack can ship MCP prompts (`prompts: [{ name, description, arguments, text }]`) that walk a host model through its workflow. `{{arg}}` placeholders are filled from the prompt arguments.
199
+
200
+ ## Eval reports
201
+
202
+ ```bash
203
+ npx <pack> eval --report eval-out/ # report.json + report.html (no scripts, no network)
204
+ npx <pack> eval --report eval-new/ --baseline eval-out/report.json # exits 1 on a regression
205
+ ```
206
+
207
+ ## Reading real exports
208
+
209
+ `ctx.records(path)` reads CSV, TSV, semicolon- or pipe-separated text, Excel `.xlsx` (first visible sheet unless one is named; formulas are never evaluated), JSON (an array, or an object holding one array such as `records`, `data` or `items`) and JSONL. `.xls` is refused with advice to save as `.xlsx` or CSV.
210
+
211
+ A pack can declare the files it reads under `sources`: its own columns (`fields`, with a type and a list of other names each column goes by) and `profiles` for named exports from real systems, built from the shared catalogue in `src/exports.js`:
212
+
213
+ ```js
214
+ import { exportProfile, fullName } from 'fairwire-core';
215
+ sources: {
216
+ access: {
217
+ label: 'Access export', args: ['access', 'previous'],
218
+ fields: { user: { aliases: ['Display Name'], required: true }, email: { type: 'email' }, last_login: { type: 'date', aliases: ['Last Sign In'] } },
219
+ profiles: [exportProfile('google_workspace_users', { user: fullName('First Name [Required]', 'Last Name [Required]'), email: 'Email Address [Required]', last_login: 'Last Sign In [READ ONLY]' })],
220
+ },
221
+ }
222
+ ```
223
+
224
+ What happens to a file:
225
+ - In the pack's own columns: returned untouched.
226
+ - Otherwise: the export is recognised by its column names (or by its first row, for a headerless bank download), a title block above the header row is skipped, columns are renamed in place, other columns pass through, dates become `YYYY-MM-DD` (month-first or day-first is inferred from the values; a guess is said aloud), amounts become plain decimals (`$1,200.00`, `(45.10)`, `1.234,56 €`), yes/no columns become `yes`/`no`, emails are lowercased.
227
+ - The tool result gets a `sources` list (export recognised, columns mapped and not used, rows skipped, the date order read, notes about what the export lacks) and its `warnings` carry anything a person should check. The audit line records a compact version with no cell values.
228
+ - A file with none of a required column is read as it is and the result says which column was not found.
229
+
230
+ `<pack> sources` lists what a pack reads. `<pack> inspect <file>` (and the MCP tool `fairwire_inspect_input`) shows how one file would be read: format, sheets, header row, each column's name and shape (dates day-first, amounts, yes/no...), never a cell value. Column names that read like instructions to an AI are flagged.
231
+
232
+ When a file does not match, put `fairwire-sources.json` in the root (checked against a schema on every call):
233
+
234
+ ```json
235
+ {
236
+ "sources": { "access": { "date_order": "dmy" } },
237
+ "files": { "exports/okta.csv": { "profile": "okta_users_api", "columns": { "email": "Work E-mail" }, "set": { "system": "Okta" }, "skip_rows": 2, "sheet": "Users", "decimal": ",", "delimiter": ";" } }
238
+ }
239
+ ```
240
+
241
+ How far to trust the layouts: two (Procore RFIs, Ramp transactions) were compared with the vendor's documentation on 2026-11-15. The others were written from knowledge of each export and not checked. None was tested against a live account. `<pack> sources` marks which is which.
242
+
243
+ ## Files and reports from other markets
244
+
245
+ The core reads exports the way systems in Germany, France, Spain, Brazil, Italy, Japan, China, Korea and the English-speaking countries write them. These nine languages cover the largest business-software markets (sources in the ver 6 review).
246
+
247
+ - **Text encodings.** A file is decoded by the first of: the `encoding` set for it in `fairwire-sources.json`; a byte-order mark (UTF-8, UTF-16); strict UTF-8; UTF-16 without a mark; a scored guess among Shift_JIS, EUC-KR, GB18030, Big5 and Windows-1252 (known header words count most, and `--lang` breaks ties). A guessed encoding is named in the result's warnings with how to fix it. Names you can set: `utf-8`, `utf-16le`, `utf-16be`, `shift_jis`, `euc-jp`, `euc-kr`, `gb18030`, `gbk`, `big5`, `windows-1252`, `iso-8859-1`, `iso-8859-15` and common aliases (`sjis`, `cp932`, `cp949`, `cp936`, `latin1`...).
248
+ - **Amounts.** `1.234,56`, `1 234,56`, `1'234.56`, `12,5`, `R$ 1.234,56`, `1,200円`, `¥1,200`, `₩15,000`, Japanese negatives `△300` and `▲300`, `(45.10)`, a trailing minus and Indian grouping `12,34,567`. A whole column decides whether the comma is the decimal mark, so `1.234` in a column that also holds `2.500,50` reads as 1234. `toNumber("12,5")` is 12.5 (before ver 6 it was 125).
249
+ - **Dates.** Month names in English, German, French, Spanish, Portuguese, Italian and Dutch, also between slashes (`14/NOV/2026`, as Mexican and Brazilian bank exports write them); `2026年11月14日`, `2026년 11월 14일`, `2026. 11. 14.`; Japanese era years (`令和8年11月14日`, `R8.11.14`) and Taiwan 民國 years; 午前/午後 and 오전/오후 times.
250
+ - **Column names.** About 100 common columns are known in German, French, Spanish, Portuguese, Italian, Japanese, Chinese and Korean (`Betrag`, `Montant`, `Importe`, `Valor`, `Importo`, `金額`, `金额`, `금액`...). They fill only columns still unmatched after the English names and never take a column already used; the result lists them under `translated_columns`. A field can opt out with `translate: false` or point at another concept, for example `translate: 'ledger_debit'` so a general-ledger debit reads `Soll` or `借方` rather than a bank's money-out column.
251
+ - **Yes and no.** Yes/no columns read `ja`, `oui`, `sí`, `sim`, `sì`, `はい`, `有効`, `是`, `예`, `○` and their opposites.
252
+ - **Names.** `normalizeName`, `normalizeAddress`, `safeFileName` and the new `slugify` keep letters of every script (they used to drop them, so Japanese, Chinese and Korean names compared as empty). `normalizeName` and `stripLegalForms` remove legal forms such as GmbH, AG, KG, SARL, S.p.A., Ltda, 株式会社, (株), 有限公司, 주식회사, (주) and the half-width カ) of Japanese bank-transfer names. `stripLegalTail` removes forms that only count at the end of a name (S.L., S.L.U., S.A.U., S.A. de C.V., S/A, ME, EPP, S.n.c., SE), so a vendor called `SL Green` keeps its name.
253
+
254
+ ```json
255
+ { "files": { "exports/仕訳.csv": { "encoding": "shift_jis", "decimal": "." } } }
256
+ ```
257
+
258
+ **Output language.** `--lang de|fr|es|pt|it|ja|zh|ko` (or `FAIRWIRE_LANG`) sets the language of the pages and reports people read: the approvals page (which also has a language switcher), the Olympus readiness report, and the Ladon recertification summary and evidence page; a tool argument `language` overrides it per call where offered. Tool results, codes, CSV columns and JSON stay in English, so scripts and later runs read them the same. Any string not yet translated falls back to English. Use `makeText(catalog, lang)` and `coreText(lang)` for a pack's own pages.
259
+
260
+ **Limits.** The translations were written by Claude and have not been reviewed by native speakers; every translated page says so. The encoding guess can be wrong on very short files; set `encoding` when names look garbled. The column dictionaries cover common names, not every system's labels. The agents make no claim about any country's laws, tax rules or filing formats.
261
+
262
+ ## Paid tier (licence keys)
263
+
264
+ A tool marked `tier: 'pro'` (optionally with a `feature` name) runs only with a valid licence key. Without one it returns `status: 'needs_license'` with the reason; free tools keep working. The check runs after the policy, so a blocked tool stays blocked, an `ask` tool still asks, nothing is put on Auto and one-click categories are untouched; no approval is requested for a call that cannot run.
265
+
266
+ A key is `FAIRWIRE1.<payload>.<Ed25519 signature>` with licensee, plan, agents (`*` or package names), features, issue and expiry dates. It is checked offline against the public keys in `src/license-keys.js` (empty in this release, so nothing can be unlocked yet). There is no environment variable or config file that adds a trusted key.
267
+
268
+ - Customer: `<pack> license install key.txt` (copies it to `.fairwire/license.key`), `<pack> license status`, or set `FAIRWIRE_LICENSE` / `FAIRWIRE_LICENSE_FILE`. `fairwire_info` shows the plan, expiry and which tools are unlocked, never the key.
269
+ - Seller, on their own computer: `npx -p fairwire-core fairwire-license keygen --out ~/fairwire-licence-keys`, paste the printed public key into `LICENSE_PUBLIC_KEYS`, release, then `fairwire-license issue --key ~/fairwire-licence-keys/private.pem --licensee "Customer" --plan pro --days 365 [--agents fairwire-dns-records] --out customer.key` and `fairwire-license verify customer.key --pubkey ~/fairwire-licence-keys/public.pem`. Withdrawn licence ids go in `LICENSE_REVOKED_IDS` and take effect from the next release.
270
+ - `ctx.license` gives a handler `{ status, valid, plan, features, has(feature) }`.
271
+
272
+ This is not copy protection: the packages are MIT-licensed source and anyone can remove the check. It draws a clear line for honest customers.
273
+
274
+ ## What the model pin means
275
+
276
+ The manifest declares which host model a pack's prompts and evals target. An MCP server cannot force your MCP host to use that model; the pin is reported in `initialize` and `fairwire_info` so you can check it. The wave-1 packs' tools are deterministic and call no model at all.
277
+
278
+ ## Packs built on this core
279
+
280
+ All 31 Fairwire agents in the monorepo, from `fairwire-admin-roles` to `fairwire-wifi-health`. Source: <https://github.com/fpavia111-creator/fairwire-agents>.
281
+
282
+ ## License
283
+
284
+ MIT © 2026 Kurt Francisco
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ import { resolve, join } from 'node:path';
3
+ import { ApprovalStore } from '../src/approvals.js';
4
+ import { parseFlags } from '../src/cli.js';
5
+
6
+ const { flags, pos } = parseFlags(process.argv.slice(2));
7
+ if (!pos[0] || flags.help) {
8
+ process.stdout.write('Usage: fairwire-approve <approval_id> --as "Your Name" [--dir .fairwire] [--note "why"]\n');
9
+ process.exit(pos[0] ? 0 : 2);
10
+ }
11
+ try {
12
+ const dir = resolve(flags.dir || join(process.cwd(), '.fairwire'));
13
+ const rec = new ApprovalStore(dir).approve(pos[0], flags.as, flags.note || '');
14
+ process.stdout.write(`Approved ${rec.id} as ${rec.approved_by} (${dir}). It can be used once.\n`);
15
+ } catch (e) {
16
+ process.stderr.write(`fairwire-approve: ${e.message}\n`);
17
+ process.exit(1);
18
+ }
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ // Licence tools for the seller. Runs on the seller's own computer only.
3
+ // fairwire-license keygen --out DIR
4
+ // fairwire-license issue --key DIR/private.pem --licensee "Name" --plan pro [--days 365 | --expires YYYY-MM-DD]
5
+ // [--agents a,b] [--features x,y] [--seats N] [--id ID] [--out file]
6
+ // fairwire-license verify <file> --pubkey DIR/public.pem [--agent name]
7
+ // The private key never leaves DIR. The key it prints is the customer's licence text.
8
+ import { writeFileSync, readFileSync, existsSync } from 'node:fs';
9
+ import { resolve } from 'node:path';
10
+ import { parseFlags } from '../src/cli.js';
11
+ import { generateSigningKey, loadSigner } from '../src/signing.js';
12
+ import { issueLicense, checkLicense, licenseView } from '../src/license.js';
13
+
14
+ const { flags, pos } = parseFlags(process.argv.slice(2));
15
+ const out = (s) => process.stdout.write((typeof s === 'string' ? s : JSON.stringify(s, null, 2)) + '\n');
16
+ const USAGE = `Usage:
17
+ fairwire-license keygen --out DIR Make the licence signing key pair (keep DIR off every repo and shared drive)
18
+ fairwire-license issue --key DIR/private.pem --licensee "Name" --plan pro [--days N | --expires YYYY-MM-DD]
19
+ [--agents a,b] [--features x,y] [--seats N] [--id ID] [--out FILE]
20
+ fairwire-license verify FILE --pubkey DIR/public.pem [--agent NAME]`;
21
+ const list = (v) => (v === undefined || v === true ? undefined : String(v).split(',').map((x) => x.trim()).filter(Boolean));
22
+ try {
23
+ const cmd = pos[0];
24
+ if (cmd === 'keygen') {
25
+ if (!flags.out || flags.out === true) { out(USAGE); process.exit(2); }
26
+ const k = generateSigningKey(String(flags.out));
27
+ out(`Licence key pair ${k.keyId} written.\nPrivate: ${k.privateKeyFile} (never share, never commit; back it up offline)\nPublic: ${k.publicKeyFile}\nPaste this into packages/fairwire-core/src/license-keys.js, inside LICENSE_PUBLIC_KEYS, as a string:\n`);
28
+ out(readFileSync(k.publicKeyFile, 'utf8').trim());
29
+ process.exit(0);
30
+ }
31
+ if (cmd === 'issue') {
32
+ if (!flags.key || flags.key === true) { out(USAGE); process.exit(2); }
33
+ const signer = loadSigner(String(flags.key));
34
+ const token = issueLicense(signer, { licensee: flags.licensee === true ? '' : flags.licensee, plan: flags.plan === true ? '' : flags.plan, days: flags.days, expires: flags.expires, agents: list(flags.agents), features: list(flags.features), seats: flags.seats, id: flags.id });
35
+ if (flags.out && flags.out !== true) {
36
+ const f = resolve(String(flags.out)); if (existsSync(f)) throw new Error(`${f} already exists`);
37
+ writeFileSync(f, token + '\n', { mode: 0o600 });
38
+ out(`Licence written to ${f}. Send that file to the customer; they run "<agent> license install ${f.split(/[\\/]/).pop()}".`);
39
+ } else out(token);
40
+ process.exit(0);
41
+ }
42
+ if (cmd === 'verify') {
43
+ if (!pos[1] || !flags.pubkey || flags.pubkey === true) { out(USAGE); process.exit(2); }
44
+ const token = readFileSync(resolve(pos[1]), 'utf8').trim();
45
+ const st = checkLicense(token, { keys: [readFileSync(resolve(String(flags.pubkey)), 'utf8')], agent: flags.agent && flags.agent !== true ? String(flags.agent) : null });
46
+ out(licenseView(st)); process.exit(st.valid ? 0 : 1);
47
+ }
48
+ out(USAGE); process.exit(cmd ? 2 : 0);
49
+ } catch (e) { out(`Error: ${e.message}`); process.exit(1); }
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ // Scaffold a new Fairwire domain agent: fairwire-new-agent fairwire-<what-it-does> [--dir packages]
3
+ // Named after the job, 1 to 4 plain words (fairwire-dns-records); tools get the job words as prefix (dns_records_check).
4
+ // The output passes `npm test`, `eval` and `npm pack --dry-run` untouched.
5
+ import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
6
+ import { join, resolve } from 'node:path';
7
+
8
+ const name = process.argv[2];
9
+ const dirFlag = process.argv.indexOf('--dir');
10
+ const base = resolve(dirFlag > 0 ? process.argv[dirFlag + 1] : '.');
11
+ if (!name || !/^fairwire(-[a-z0-9]+){1,4}$/.test(name)) { process.stdout.write('Usage: fairwire-new-agent fairwire-<what-it-does> [--dir packages] (1 to 4 job words, e.g. fairwire-dns-records)\n'); process.exit(2); }
12
+ const root = join(base, name);
13
+ if (existsSync(root)) { process.stderr.write(`${root} already exists\n`); process.exit(1); }
14
+ const pre = name.replace(/^fairwire-/, '').replace(/-/g, '_');
15
+ const ACRONYMS = new Set(['ai', 'api', 'dns', 'dhcp', 'vpn', 'mfa', 'sla', 'it', 'ip', 'sso', 'voip']);
16
+ const Title = name.split('-').map((w) => (ACRONYMS.has(w) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1))).join(' ');
17
+ const coreVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
18
+ const files = {
19
+ 'package.json': JSON.stringify({ name, version: '0.1.0', description: `${Title}: describe the one process this agent owns.`, type: 'module', license: 'MIT', engines: { node: '>=20' }, main: 'src/index.js', exports: { '.': './src/index.js', './package.json': './package.json' }, bin: { [name]: `bin/${name}.js` }, files: ['src', 'bin', 'fixtures', 'evals', 'README.md', 'LICENSE'], scripts: { test: 'node scripts/run-tests.cjs', demo: `node bin/${name}.js demo`, eval: `node bin/${name}.js eval` }, dependencies: { 'fairwire-core': `^${coreVersion}` }, keywords: ['mcp', 'mcp-server', 'ai-agents', 'fairwire'] }, null, 2) + '\n',
20
+ [`bin/${name}.js`]: `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { main } from 'fairwire-core';\nimport { manifest } from '../src/manifest.js';\nimport { demo } from '../src/demo.js';\n\nmain(manifest, { bin: '${name}', demo, evalFile: fileURLToPath(new URL('../evals/cases.json', import.meta.url)) });\n`,
21
+ 'src/index.js': `export { manifest } from './manifest.js';\nexport * from './logic.js';\n`,
22
+ 'src/logic.js': `import { toNumber } from 'fairwire-core';\n\n/** Pure domain logic: no I/O. */\nexport function summarise(rows) {\n const total = rows.reduce((s, r) => s + (toNumber(r.amount) || 0), 0);\n return { rows: rows.length, total };\n}\n`,
23
+ 'src/manifest.js': `import { defineManifest } from 'fairwire-core';\nimport { readFileSync } from 'node:fs';\nimport { summarise } from './logic.js';\n\nconst pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));\n\nexport const manifest = defineManifest({\n name: '${name}', version: pkg.version,\n description: '${Title}: one process, nothing outside its lane.',\n model: { provider: 'anthropic', id: 'claude-sonnet-4-5-20250929', note: 'Declared host-model pin. The tools are deterministic and call no model.' },\n caps: { maxSteps: 60, maxSpendUsd: 0 },\n prompts: [{ name: '${pre}_workflow', description: 'Walk through the main workflow.', arguments: [{ name: 'file', description: 'Input CSV', required: true }], text: 'Call ${pre}_check with {"file":"{{file}}"} and summarise the result. Never call blocked tools.' }],\n tools: [\n { name: '${pre}_check', kind: 'read', title: 'Check the file', description: 'Read a CSV/JSON export and summarise it.',\n inputSchema: { type: 'object', required: ['file'], additionalProperties: false, properties: { file: { type: 'string', description: 'CSV/JSON/JSONL under --root' } } },\n handler: async (a, ctx) => { const r = summarise(ctx.records(a.file)); return { summary: \`\${r.rows} row(s), total \${r.total}\`, ...r }; } },\n { name: '${pre}_go_live', kind: 'action', category: 'go_live', description: 'Listed so agents can see it is refused.' },\n ],\n policy: { rules: [\n { tool: '${pre}_check', decision: 'allow' },\n { tool: '${pre}_go_live', decision: 'block', reason: 'A person goes live, not the agent.' },\n { tool: '*', decision: 'block', reason: 'Not on the allowlist.' },\n ] },\n});\n`,
24
+ 'src/demo.js': `import { fileURLToPath } from 'node:url';\nimport { demoRuntime, printStep } from 'fairwire-core';\n\nexport async function demo(manifest) {\n const rt = demoRuntime(manifest, fileURLToPath(new URL('../fixtures', import.meta.url)));\n printStep('Check the sample file', await rt.call('${pre}_check', { file: 'sample.csv' }));\n printStep('Agent tries to go live', await rt.call('${pre}_go_live', {}));\n}\n`,
25
+ 'fixtures/sample.csv': 'id,amount\nA1,10\nA2,32.5\n',
26
+ 'fixtures/README.md': '# Fixtures\n\n`sample.csv` is fictional.\n',
27
+ 'evals/cases.json': JSON.stringify({ suite: name, root: '..', cases: [
28
+ { id: 'check-sums', tool: `${pre}_check`, args: { file: 'fixtures/sample.csv' }, expect: { status: 'executed', equals: { 'result.total': 42.5 } } },
29
+ { id: 'go-live-blocked', tool: `${pre}_go_live`, mode: 'auto', args: {}, expect: { status: 'blocked' } },
30
+ ] }, null, 2) + '\n',
31
+ 'test/logic.test.js': `import { test } from 'node:test';\nimport assert from 'node:assert/strict';\nimport { fileURLToPath } from 'node:url';\nimport { AgentRuntime, runEvalFile } from 'fairwire-core';\nimport { manifest, summarise } from '../src/index.js';\n\ntest('summarise', () => { assert.deepEqual(summarise([{ amount: '1' }, { amount: '2.5' }]), { rows: 2, total: 3.5 }); });\ntest('invalid args are refused', async () => { const r = await new AgentRuntime(manifest, { audit: false }).call('${pre}_check', { file: 1 }); assert.equal(r.status, 'error'); });\ntest('evals pass', async () => { const r = await runEvalFile(manifest, fileURLToPath(new URL('../evals/cases.json', import.meta.url))); assert.equal(r.passed, r.total); });\n`,
32
+ 'scripts/run-tests.cjs': `#!/usr/bin/env node\n"use strict";\nconst { readdirSync } = require("node:fs");\nconst { join } = require("node:path");\nconst { spawnSync } = require("node:child_process");\nconst files = readdirSync("test").filter((f) => f.endsWith(".test.js")).sort().map((f) => join("test", f));\nconst r = spawnSync(process.execPath, ["--test", ...process.argv.slice(2), ...files], { stdio: "inherit" });\nprocess.exit(r.status ?? 1);\n`,
33
+ 'README.md': `# ${Title} (\`${name}\`)\n\n> Describe what it does, and nothing more.\n\nBuilt on [\`fairwire-core\`](https://www.npmjs.com/package/fairwire-core). MIT, Node >= 20.\n\n\`\`\`bash\nnpx ${name} demo\nnpx ${name} mcp\n\`\`\`\n`,
34
+ LICENSE: `MIT License\n\nCopyright (c) ${new Date().getUTCFullYear()}\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n`,
35
+ };
36
+ for (const [f, text] of Object.entries(files)) { const p = join(root, f); mkdirSync(join(p, '..'), { recursive: true }); writeFileSync(p, text); }
37
+ process.stdout.write(`Created ${root}. Add it to the root workspaces, run npm install, then npm test.\n`);
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { readAudit, verifyChain } from '../src/audit.js';
3
+ import { loadPublicKeys } from '../src/signing.js';
4
+ import { parseFlags } from '../src/cli.js';
5
+ const { flags, pos } = parseFlags(process.argv.slice(2));
6
+ if (!pos[0]) { process.stdout.write('Usage: fairwire-verify-log <audit.jsonl> [--pubkey public.pem[,old.pem]]\n'); process.exit(2); }
7
+ const r = verifyChain(readAudit(pos[0]), { publicKeys: flags.pubkey ? loadPublicKeys(String(flags.pubkey).split(',')) : null });
8
+ process.stdout.write(JSON.stringify(r, null, 2) + '\n');
9
+ process.exit(r.ok ? 0 : 1);
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "fairwire-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Family kit (names, reading rules, data and domain helpers) on fair-agent-core for the Fairwire IT and network agents: personal-data masking, IP, port and date helpers, the agent builder, pinned-model pack manifests, allow/ask/block policy, Review/Assist/Auto modes with caps and a kill switch, hash-chained JSONL audit logs, a zero-dependency stdio MCP server and fixture-based evals.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Kurt Francisco",
8
+ "engines": {
9
+ "node": ">=20"
10
+ },
11
+ "main": "src/index.js",
12
+ "exports": {
13
+ ".": "./src/index.js",
14
+ "./testkit": "./src/testkit.js",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "bin": {
18
+ "fairwire-approve": "bin/fairwire-approve.js",
19
+ "fairwire-verify-log": "bin/fairwire-verify-log.js",
20
+ "fairwire-new-agent": "bin/fairwire-new-agent.js",
21
+ "fairwire-license": "bin/fairwire-license.js"
22
+ },
23
+ "files": [
24
+ "src",
25
+ "bin",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "scripts": {
30
+ "test": "node scripts/run-tests.cjs"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/fpavia111-creator/fairwire-agents.git",
35
+ "directory": "packages/fairwire-core"
36
+ },
37
+ "homepage": "https://github.com/fpavia111-creator/fairwire-agents/tree/master/packages/fairwire-core#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/fpavia111-creator/fairwire-agents/issues"
40
+ },
41
+ "keywords": [
42
+ "mcp",
43
+ "mcp-server",
44
+ "model-context-protocol",
45
+ "ai-agents",
46
+ "guardrails",
47
+ "human-in-the-loop",
48
+ "audit-log",
49
+ "fairwire"
50
+ ],
51
+ "dependencies": {
52
+ "fair-agent-core": "^8.0.0"
53
+ }
54
+ }