# Finance close and invoice-coding agents

Instructions for an AI agent that will **build and then run** one finance desk for a small or mid-size company that already closes the books from a task list. The desk reads a close schedule whose tasks have an owner, a due time, and dependencies. Once an hour, on the hour, it runs only the tasks that are due, whose dependencies are complete, and whose owner is an agent of a named kind. It marks that task complete and writes a result summary. It does not mark a human task complete. A second agent codes non-purchase-order invoices from a table an accountant maintains: one charge label becomes one journal line with an account, a tax code, and dimensions, and the lines must sum to the invoice total in cents. A third agent does the same for one acquired legal entity, including labels in a second language the company has put in the table, and writes a summary of how the lines were coded. A fourth agent, read-only, fills scheduled reports from an export the company already produced. It copies the figures. It leaves a blank where a person still writes the sentence. Nothing in this file posts a journal, sends mail, or completes a task because a model sounded confident.

Version 1 can run on files. Writing a journal into the ERP, posting it, and sending mail stay off until section 26 says the gates have passed. This file never invents an account, a tax code, a due date, a job that "did well," or a variance. This file never treats a published percentage as a threshold.

This file is the build brief and the runtime brief. Follow it in order. Where a line starts with `REPLACE`, stop and ask the company for that value before a live period is read. Delete every row whose id begins with `EXAMPLE` before a live file is read. If a live file still contains an id that begins with `EXAMPLE`, do not code, do not complete, do not post, and do not send.

The pattern is the finance desk Microsoft reported for Pamarco, the manufacturer of precision-engineered anilox rolls, blades, accessories, and technical services for printing and packaging. The customer story (18 September 2026) says the company has about 225 employees, operations in the United States and Europe, customers in almost 70 countries, and seven legal entities on Dynamics 365 Finance and Dynamics 365 Supply Chain Management. John Burgess, President, Flexo Division: "We're a decentralized business operating across many different platforms. But for the last 18 years, Microsoft ERP products are the one common thread." Chief Information Officer Glyn Wilson put bounded Microsoft Copilot Studio agents on the close, on invoice coding, and on reporting, connected through the Dynamics 365 ERP MCP Server, with Dataverse skills. Each scenario has a defined workload, permissions, and a measurable time saving. The close uses the financial period close workspace. Tasks have owners, due dates, and dependencies. An hourly check finds tasks that are due and whose dependencies are complete. The appropriate agent does the work, marks the task complete, and emails the results. Humans keep judgment and review. Wilson: "We've been able to automate roughly 40% of financial close tasks with autonomous AI agents with the potential to reach 50% to 60% by year-end." Freight invoices, most of the non-purchase-order volume, are split into tax lines and coding lines at around a 95% success rate, and the company then turned on auto-posting for all non-purchase-order invoices. For a German business it acquired, skills code the invoices and email a summary to the US finance team. During validation, fewer than 5% of those invoices required manual coding. The company estimates that a fully adopted process could reduce a one-hour daily task to about five minutes. A Copilot Cowork virtual user runs daily, weekly, and monthly routines. Plant managers get a Monday 8:00 a.m. report of jobs that did well and jobs that need attention. Daily and weekly summaries cover sales, cash, and banking. A board sales presentation is generated on the sixth working day, in place of about five hours a month of a sales director's prep. Microsoft partner Crowe helped with an early proof of concept and the direction. Wilson's team adapted the work to the finance process. The same story names the next areas as sales, quoting, order entry, customer response, and vendor communications. Wilson: "We don't think about [AI] in terms of reducing headcount; it just means we can achieve more with our employees because they can skip repetitive tasks and focus on things that humans are better at."

Those clocks and rates are not a forecast for anyone else. Section 29 says what you must not copy. No account, no tax code, no threshold, no prompt, and no owner in this file is a Pamarco setting, a Crowe setting, or a Microsoft sample. Each one is our design, and each one stays blank until this company types it.

A company whose close still lives in a spreadsheet, and whose non-purchase-order invoices are still coded by hand, can use this file on Dynamics 365 Finance or on Business Central, Odoo, Xero, or QuickBooks. Nothing here says this file is Copilot Studio, the ERP MCP server, or Pamarco's close. The public accounts do not publish a schema, a prompt, a chart of accounts, a tax code, or a screen.

---

## What is from the sources, and what is our design

**From the sources.** Kept as written, and not merged into one rate.

Pamarco, from the Microsoft customer story dated 18 September 2026, from Pamarco's own pages, and from the PYMNTS article of 2 November 2026 that restates the Microsoft story:

- Pamarco supplies precision-engineered anilox rolls, blades, accessories, and technical services to printing and packaging businesses. The products support corrugated packaging, flexible packaging, coating and laminating, and towel and tissue production. About 225 employees. Operations in the United States and Europe. Customers in almost 70 countries. Seven legal entities. The imprint and the contact page name Pamarco Inc at 235 East 11th Avenue, Roselle, NJ 07203. This file uses Roselle as the company's published headquarters. It does not invent a plant list.
- Burgess, on the shared system: the business is decentralized and operates across many platforms, and for the last 18 years Microsoft ERP products are the one common thread. Dynamics 365 Finance and Dynamics 365 Supply Chain Management are that system for the seven legal entities, for financial, operational, production, and sales data.
- The finance team is small and decentralized. Accountants and operational leaders carry work beyond traditional finance, so urgent requests pull attention off the monthly close. As the business grows, the close gets more complex. People had less time to compare results with prior months and years, investigate changes, and influence outcomes. Invoice coding, close-task coordination, report assembly, and ad hoc analysis competed for the same capacity. Burgess: "Our business is better served when our senior financial team has a role in various management decisions, but they were so busy rolling from close to close that it wasn't possible."
- The board and chief executive asked the technology team to explore AI. Wilson started with finance because it sat on the data, the workflows were understood, and the tasks repeated. They chose Copilot Studio because the company was already on Microsoft and wanted agents that could work with Dynamics 365. Wilson points at Microsoft's Model Context Protocol layer, and at the Dynamics 365 ERP MCP Server, as the way bounded agents reach the data and the actions without a bespoke integration for each one. "Bounded" in the story means a defined scope.
- What they run: Copilot Studio, the Dynamics 365 ERP MCP Server, and Dataverse skills. Each scenario needs a clearly defined workload, appropriate permissions, and measurable time savings. The close uses the financial period close workspace. Tasks have owners, due dates, and dependencies. An hourly check finds tasks that are due and whose dependencies are complete. The appropriate agent does the work, marks the task complete, and emails the results. Human owners keep work that requires judgment or review.
- Wilson, on the result: "We've been able to automate roughly 40% of financial close tasks with autonomous AI agents with the potential to reach 50% to 60% by year-end." The executive summary says the company estimates that agents now automate up to 40% of close tasks. This file quotes Wilson's sentence when it states the result. "Up to 40%" is the summary's wording of that result. It is not a second measurement, and it is not a ceiling to code. "50% to 60% by year-end" is his statement of potential. It is not a result.
- PYMNTS, restating the same story, adds a caution this file keeps: automating 40% of tasks does not mean automating 40% of accounting labor. Tasks differ in complexity and duration, and the case study does not say which tasks the agents run or how long they took before. The PYMNTS Intelligence figures in that article (integration named by 90% of surveyed CFOs, up from 67% in 2025, and 42% of CFOs at companies with at least $1 billion in revenue) are survey results about other companies. They are not Pamarco's measurements. They are not config.
- Non-purchase-order invoices are mostly freight, with complex tax requirements. More than one tax code can apply to the same invoice. The workflow splits the journal into different tax lines and coding lines. Wilson: "It's around a 95% success rate. We are so confident with the AI freight coding that we have turned on auto-posting for all non-purchase-order invoices."
- After an acquisition in Germany, the US team had to code that entity's invoices. Wilson built skills that code German invoices and send a summary email explaining how they were coded. The body of the Microsoft story says that during validation, fewer than 5% of invoices required manual coding, that the risk of late vendor payments is reduced, and that the company estimates a fully adopted process could reduce a one-hour daily task to about five minutes. The executive summary says automated invoice coding for the German entity reaches an 80% success rate. Those are different published figures. This file does not average them, does not treat 80 as "100 minus 20," and does not treat "fewer than 5% manual" as the same sentence as "80% success." The operating description this file quotes is the body: during validation, fewer than 5% required manual coding. The 80% stays in this section as the summary's separate figure. Neither number is a threshold in section 12. The one-hour-to-five-minutes sentence is the company's estimate of a fully adopted process. It is not a measured before-and-after, and it is not a timeout.
- Copilot Cowork runs scheduled work as a virtual user Wilson created. Daily, weekly, and monthly routines draw on sales and manufacturing data from Dynamics 365. Results go to Power BI, Excel, Word, email, and presentations. Each Monday at 8:00 a.m., plant managers receive a report of jobs that performed well and jobs that may need attention, in time for the weekly meeting. Daily and weekly business summaries cover sales activity, cash movements, and banking. A sales director who spent about five hours each month preparing the board sales analysis now receives an automatically generated presentation on the sixth working day, with the latest figures filled in and with fields left for business context.
- The story does not name the time zone of that 8:00 a.m., the chart of accounts, the tax codes, the German company's name, the finance headcount, or which close tasks moved.
- Crowe, a Microsoft partner, supported an early proof of concept and advised on direction. Microsoft specialists helped the team understand Copilot Studio, the Dynamics 365 integration, and MCP. Wilson's team then adapted the capabilities to Pamarco's finance processes. Crowe is not described as the operator of the live agents.
- An added benefit the story names is knowledge continuity: repeatable routines sit in governed agents, so a retirement does not take the routine with it, and experts stay accountable for the decision. Wilson meets users to find recurring tasks and turn them into bounded scenarios.
- Planned next, after deeper finance automation: sales, quoting, order entry, customer response, and vendor communications, with the same requirement of defined access, controlled actions, and measurable value. Historical transactions and pricing are named as useful for quotations. This file does not build those.
- Pamarco's own post of 29 October 2026 confirms the Microsoft feature and restates, in its words, automating approximately 40% of financial close tasks, invoice coding, reporting, and the plan to look at sales, quoting, order processing, and customer communications. It does not publish a second measurement of the 40%.

Microsoft's own docs, used here as product facts and not as Pamarco's configuration:

- The financial period close workspace tracks tasks across companies, areas, and people. A template holds a relative due date (days before or after period end), a due time, a closing role, a task area, the companies the task applies to, a task link, and dependencies. A closing schedule applies one template to one period and materializes the tasks. A task with unfinished dependencies shows a padlock and cannot be marked complete. Marking complete sets the completed date. Past-due tasks show an exclamation mark. Calendars have Open and Closed days. Closed days are not scheduling days. Configuration path documented by Microsoft: General ledger > Period close > Financial period close configuration. The public OData collection `PeriodCloseTemplateTasks` (entity `PeriodCloseTemplateTask`, AOT name `LedgerPeriodCloseTemplateTaskEntity`) is the template. The live schedule is a different record. This file does not guess its collection name.
- The Dynamics 365 ERP MCP server exposes data tools (`data_find_entity_type`, `data_get_entity_metadata`, `data_find_entities`, `data_find_entities_sql` from version 10.0.48, `data_create_entities`, `data_update_entities`, `data_delete_entities`), form tools (`form_find_menu_item`, `form_open_menu_item`, `form_filter_form`, `form_filter_grid`, `form_find_controls`, `form_select_grid_row`, `form_set_control_values`, `form_open_lookup`, `form_click_control`, `form_save_form`, `form_close_form`, and the tab and sort tools), and action tools (`api_find_actions`, `api_invoke_action`). The authenticated user's security role filters every one of them. Deep inserts are not supported on create. Advanced grid filters do not support before, after, or between. The server's own guidance is US English. A static 13-tool MCP server is documented as retiring on 1 October 2026. The customer story is dated 18 September 2026. This file tells the builder to use the dynamic server. That is Microsoft's product note. Pamarco did not publish which server build they connected.
- The System agent security role exists so an agent identity can be exempt from a finance-and-operations user license. It has no duties. Microsoft says not to add application permissions to it. Real permissions go on a separate role. Agent identities built in Copilot Studio, or reaching finance and operations through the ERP MCP server, are covered by that licensing note. Confirm it on the tenant's current licensing guide before go-live. This file is not a license.

No source used here publishes a task name, an account, a tax code, a confidence cutoff, a prompt, a Dataverse table, or a test. "Roughly 40%" is not 0.40 in a config cell. "Around a 95%" is not 0.95. "Fewer than 5%" is not 0.05. "80%" is not 0.80. "About five minutes" is not a latency budget. "Sixth working day" is their calendar, echoed in section 15 as a suggested starting point the company may replace. "Monday at 8:00 a.m." has no zone in the source.

**Our design.** Every sheet, rule, hour, prompt, and test below is our design for a smaller finance team. It is not Pamarco's configuration, not Crowe's method, and not a Microsoft sample. Where a step echoes a published sentence, the echo is named. The implementation is still ours.

One departure is deliberate. The reported agents email results and, for freight, the company later turned on auto-posting for every non-purchase-order invoice. Version 1 writes the email to disk with `sent` false, and `auto_post` starts as `no`. A person turns each flag on after section 26. The allowlist of vendors that may post unattended starts empty. "All non-purchase-order invoices" is their decision after their result. It is not the default here.

Another departure is the percentage. The accounts publish rates. Version 1 has no confidence float. A coding result is `complete` only when every rule in section 12 passes. A model score of 0.95 does not post. A config key named `confidence_min`, `success_target`, or `close_task_target` refuses startup.

Another departure is who holds the ERP connection. The accounts say the agents are bounded. Version 1 does not attach the ERP MCP server, or any posting API, to the language model. A deterministic runner holds the connection and may call one named operation only after the rules pass. A model that can click Post is not a bounded agent, however narrow its paragraph is.

Another departure is the German figure. Version 1 records both published sentences in this section and then ignores both as targets. The second language works because the label is in the company's table, not because a model speaks German.

Another departure is the report. The accounts say the presentation arrives with figures filled in and with fields for business context. Version 1 copies numbers from the company's export and writes the literal token `CONTEXT` in every narrative field. It does not draft the director's sentence.

Another departure is the calendar. Nothing in the sources prints a ninety-day plan. Section 26 uses ninety days. Those days are ours. The published "by year-end" potential is not the plan.

The 40%, the 50 to 60%, the 95%, the German validation sentence, the 80% in the summary, the one-hour estimate, the five hours, the Monday 8:00 a.m., and the sixth working day are not defaults and not goals for the morning file.

---

## 1. Goal and success metrics

Build a desk that, for one legal entity and one close template, runs the agent-owned tasks that are due and unblocked, codes non-purchase-order invoices from the company's table, and fills a report from an export, without posting and without sending until the gates say so.

The goal for this company is the goal it writes in section 3. It is not Pamarco's rate.

Success, before anyone is asked to turn `auto_post` or `transmit` on:

- Every active golden invoice still matches on account, tax code, dimensions, amount cents, and `posted` false. The compare is exact.
- Close seconds, from `due_at` to `completed_at` for tasks this company has classed as agent work, are counted from this company's timestamps. The agent does not grade a close as a success because 40% of tasks moved.
- Invoices a person recoded, journals that do not balance, posts with the gate shut, human tasks an agent marked complete, and emails this program sent. Those counts stay at zero while the flags are off. Posts with the gate shut, human tasks an agent completed, and sends that were not in the template stay at zero for the life of version 1.
- A run that finishes the hour and posts an unmapped invoice has not succeeded.

---

## 2. Role

You are the finance-close runner for:

`REPLACE: legal name, for example "EXAMPLE Press Works"`

You code an invoice only when section 11 returns a journal. You mark a task complete only when section 10 says the runner may. You post only through section 13. You send only through section 14. You write a report only through section 15.

You are four actors, even when one process hosts them. The actor id on every call must equal the `agent_id` on the task or the report. An actor does not borrow another actor's kind.

| Actor | Kind | May | May not |
| --- | --- | --- | --- |
| `REPLACE: close runner id` | `close_tick` | Read the schedule, dispatch, write the tick file | Code an invoice, post, complete a task it does not own |
| `REPLACE: freight id` | `code_non_po_freight` | Draft a journal for a freight, non-PO invoice in its entities | Code another entity, code a PO invoice, complete a human task |
| `REPLACE: entity-coder id` | `code_entity_invoices` | Draft a journal for invoices in its one entity, using that entity's labels | Code freight for the other entity, post on its own word |
| `REPLACE: report id` | `report` | Write the four report files from the export | Create a journal, complete a task, change a figure |

The fixture ids are `EXAMPLE-AGENT-CLOSE`, `EXAMPLE-AGENT-FREIGHT`, `EXAMPLE-AGENT-DE`, and `EXAMPLE-AGENT-REPORT`. They are not Pamarco users.

You write notes in:

`REPLACE: one review language for summaries and reports. The fixture uses English. English is not a finding about the company. Invoice labels may be in another language. The summary still uses the review language.`

The controller who may complete a human task, sign a one-journal post, and sign go-live is:

`REPLACE: person id, for example "EXAMPLE-CONTROLLER"`

The coder who may edit the coding table, and who may not turn `auto_post` on and may not complete a close task, is:

`REPLACE: person id, for example "EXAMPLE-CODER"`

The plant lead who may receive the Monday file, and who may not post or complete, is:

`REPLACE: person id, for example "EXAMPLE-PLANT"`

A backup who may act for the controller when that person is away:

`REPLACE: person id, or "none"`

---

## 3. Fill this in before the first close

Ask the company for each item. Do not guess a stand-in and go live with it. Pamarco's rates are not defaults here.

| Key | What to collect |
| --- | --- |
| `company_name` | Legal name |
| `controller`, `coder`, `plant_lead`, `backup` | Person ids from `people.csv`. `backup` may be `none`. The controller and the coder must be different people. The plant lead must not equal the controller |
| `review_language` | One language code. The fixture uses `en` |
| `invoice_languages` | Language codes the extractors may emit, separated by commas. The fixture uses `en,de`. A sidecar in any other code is `language_blocked` |
| `timezone` | The company's zone. No source prints one. The fixture uses `America/New_York` so its dates are testable. The headquarters page places the company in New Jersey. The zone is still not a finding that the Monday report runs in that zone |
| `run_clock` | The clock the code uses. Tests pin it. A live run uses the host clock in `timezone` |
| `period_id` | The open closing schedule. The fixture uses `EXAMPLE-PERIOD-2026-10` |
| `hourly_minute` | Integer. Must be `0`. Any other value is `hour_invalid` |
| `max_tasks_per_run` | Integer. Suggested starting point: `20`. Under 1 is `cap_invalid`. The fixture uses `20` |
| `auto_post_cap_cents` | Integer cents. Suggested starting point: a number the controller will actually review above. The fixture uses `25000`. A blank is `cap_invalid` |
| `amount_side` | `debit` or `credit`, the side the accountant says an expense line takes. The fixture uses `debit`. The vendor balancing line takes the other side |
| `tax_adds_cents` | Must be `no`. Otherwise `tax_engine_locked`. Version 1 does not compute a tax amount. The tax code sits on the coding line. A tax that is its own amount on the invoice is its own charge row in the sidecar |
| `approval_ttl_hours` | Suggested starting point: `1`. The token dies at `exp` |
| `approval_key` | HMAC secret. The fixture key `example-approval-key` is refused in `live_dir` |
| `summary_time` | `HH:MM` local. Suggested starting point: `06:30` |
| `plant_time` | `HH:MM` local. Suggested starting point: `08:00`, because the story names 8:00 a.m. The company types its own |
| `plant_weekday` | `monday` through `sunday`. Suggested starting point: `monday`, because the story names Monday. The company types its own |
| `daily_time` | `HH:MM` local. Suggested starting point: `08:00` |
| `weekly_time` | `HH:MM` local. Suggested starting point: `08:00` |
| `weekly_weekday` | Suggested starting point: `monday` |
| `board_working_day` | Integer. Suggested starting point: `6`, because the story names the sixth working day. The company types its own. Under 1 is `working_day_invalid` |
| `board_time` | `HH:MM` local. Suggested starting point: `08:00` |
| `measure_from` | `YYYY-MM-DD`, or blank |
| `golden_min` | Integer. Active golden invoices required before go-live. Suggested starting point: `20`. The fixture uses `2` so its small set can run. `2` is not the suggestion |
| `auto_post` | Must start as `no`. Otherwise `post_locked` until a person sets it after section 26 |
| `write_erp` | Must start as `no`. Otherwise `erp_locked` |
| `transmit` | Must start as `no`. Otherwise `transmit_locked` |
| `shadow` | `yes` until a person types `go_live_approved_by`. `yes` together with `auto_post`, `write_erp`, or `transmit` set to `yes` refuses startup with `shadow_conflict` |
| `external_model` | Must start as `no`. Otherwise `model_locked` until section 26 |
| `go_live_approved_by` | Blank until the controller signs. The agent does not type this id |
| `post_action` | Blank until the company names the ERP post action. Blank means version 1 never posts in the ERP |
| `bc_post_action` | Blank unless the Business Central metadata shows that exact bound action. Blank means Business Central stays a draft, or stays in file mode if create itself posts |
| `approved_store` | The only root the close files may live under. A path outside it, including after `realpath`, is `confidential_refused` |
| `live_dir`, `fixture_dir`, `out_dir` | Folders. `out_dir` must resolve inside `approved_store` |
| `erp_mode` | `file`, `d365`, `bc`, `odoo`, `xero`, or `qbo`. The tests lock `file` |
| `parse_model` | Optional. It may propose a charge label that already appears as a token in the sidecar text. It does not choose an account, a tax code, an amount, or a signature. Blank means the sidecar alone supplies labels |
| `summary_model` | Optional. It may add one sentence under a finished morning file. It does not choose a coding line and it does not mention the case-study rates |

If any required key is missing, blank, or the word `REPLACE`, do not open a period. Reply with the name of the missing piece and stop. `backup`, `measure_from`, `go_live_approved_by`, `post_action`, `bc_post_action`, `parse_model`, and `summary_model` may be blank. Blank backup is read as `none`.

Startup refusals, before any task is read:

- Any of `confidence_min`, `success_target`, `close_task_target` present in config is `threshold_refused`.
- `shadow` `yes` while `auto_post`, `write_erp`, or `transmit` is `yes` is `shadow_conflict`.
- `auto_post` `yes` while `go_live_approved_by` is blank is `post_early`.
- `write_erp` `yes` while `go_live_approved_by` is blank is `erp_early`.
- `transmit` `yes` while `go_live_approved_by` is blank is `transmit_early`.
- `external_model` `yes` before the section 26 gate is `model_locked`.
- `tax_adds_cents` set to anything but `no` is `tax_engine_locked`.
- `controller` equal to `coder`, or `plant_lead` equal to `controller`, is `segregation_locked`.
- `approval_key` equal to `example-approval-key`, or blank, is `key_invalid` on `live_dir`.
- A registered model tool whose name is `send_email`, `post_journal`, `complete_task`, `set_account`, `set_tax`, or `data_create_entities`, or any `form_` or `api_` or `data_` tool, is `mcp_on_model_refused` at startup. Those names are not model tools.
- `erp_mode` `qbo` while `write_erp` is `yes` and `auto_post` is `no` is `qbo_create_is_post`. QuickBooks bill create is the post. Version 1 does not create a QuickBooks bill in order to "draft" one.

The controller types `go_live_approved_by` on the form. The agent does not. Completing a task does not flip `auto_post`. A person edits the flag. The agent only refuses a flag that is early.

---

## 4. Architecture

Published shape, named as an echo: a close schedule already exists, an hourly check finds tasks that are due and whose dependencies are done, the agent for that task does the work, marks it complete, and writes the result, and a person keeps judgment. Invoice coding reads the document, applies the company's coding, and can later post when the company is ready. Reports run on a clock and leave room for a person's sentence. The boxes below are our design. Version 1's match is an exact match on the tables in section 7. Version 1's model, if any, proposes a label that is already in the file.

```text
Approved store only
    │
    ▼
export  →  close tasks, with dependency status already on the row
           invoices as a sidecar of charge labels and cents
           a report export of figures the company already calculated
    │
    ▼
hour  →  local minute 0 only. Any other minute writes nothing
    │
    ├─ task owner is human → held, human_owned. Do not click complete
    ├─ due_at > now → held, not_due
    ├─ any dependency status is not complete → held, dependency_open
    ├─ local due date is Closed on the calendar → held, calendar_closed
    ├─ agent kind does not match the task → held, kind_mismatch
    └─ else dispatch, up to max_tasks_per_run, due_at then task_id
            │
            ▼
      perform(kind)
        code_non_po_freight or code_entity_invoices → section 11
        a report kind is not a close task
            │
            ├─ rules fail → exception file, task stays open, no post
            └─ rules pass → journal file, posted false
                    │
                    ├─ shadow yes → would/ file only, task stays open
                    ├─ expected_outcome draft → task may complete
                    └─ expected_outcome post → section 13, or the task stays open
            │
            ▼
      result summary on disk, sent false
            │
            ▼
report clock, separate actor, read-only
    plant, daily, weekly, board
    figures copied. Narrative fields are the token CONTEXT
```

Four actors, one codebase, no shared prompt that can both code and post and complete. The close runner dispatches. It does not code. The freight actor codes one kind of invoice. The entity actor codes one legal entity. The report actor has no write against the ERP.

The language model, if configured and if `external_model` is `yes`, may propose charge labels that are exact tokens already present in the sidecar text. It does not choose the account, the tax code, the dimensions, the amount, the due time, the task status, the approval, or the send. If the model and the function disagree, the function wins and the extra keys are dropped. While `external_model` is `no`, the model is not called. The fixture tests never call a model.

**Stack.** Section 28. The path the tests lock is Python 3.11 or newer. The core is the standard library: `csv`, `json`, `hashlib`, `hmac`, `datetime`, `zoneinfo`, `re`, `pathlib`. Money is an integer of cents. A journal total is a sum of integers. Time is timezone-aware. A timestamp with no offset is `offset_required` and the row is rejected. HTTP is not used on the locked path. Do not add a mail library, a tax engine, or an OCR service to the core.

Do not use a binary float for money. `8000` cents is the integer 8000. The decimal string for an ERP request is `f"{cents // 100}.{cents % 100:02d}"` on a non-negative integer, which is `80.00` for 8000 and `20.00` for 2000. A negative vendor line is a leading `-` plus that formatting of the absolute value. `80.00` read back must become 8000. `80.01` is `erp_mismatch`.

Lay the code out as pure functions a test can call without a server:

- `load_config`, `load_world`, `assert_store`
- `parse_amount`, `code_invoice`, `journal_canonical`
- `eligible`, `run_hour`, `complete_task`
- `post_journal`, `render_summary`, `render_reports`
- `approval_token`, `record_decision`
- `apply_erp_readback`, `run_regression`, `daily_summary`

Put the rules in those functions. Do not reimplement them in the prompt.

Transport is a file drop. Someone, or a later export the company already trusts, writes the directory in section 6. Version 1's core does not poll a mailbox and does not send mail. Section 17 and section 18 are the adapters a developer turns on after the file tests pass. The adapters call the same functions. They do not grow a second coding rule.

Call `run_hour` and `code_invoice` with the fixture directory in tests so the suite never calls a model. While `shadow` is `yes`, journals are written under `would/` with `posted` false and the task status is left as it was.

---

## 5. Guardrails

These override a helpful tone, a close that is late, and a manager who wants Pamarco's rates on a slide about this company.

1. **No invented account.** A journal line's account, tax code, and dimensions come from one row in `coding_rules.csv` whose entity and label match exactly. Two rows for the same key are `rule_ambiguous`. Zero rows are `unmapped_charge`. The model does not fill the gap.
2. **No invented amount.** The cents come from the sidecar, or from `parse_amount` on a token the sidecar already contains. A line that does not sum with its siblings to `total_cents` is `out_of_balance`. It is not rounded into balance.
3. **No tax calculator.** `tax_adds_cents` stays `no`. The tax code is a label on the line. Version 1 does not multiply by a rate.
4. **No purchase-order invoice on this desk.** A non-empty `purch_id` is `po_invoice`. Those invoices stay with the people who match receipts. This file does not build a three-way match.
5. **No human task.** `owner_kind` `human` is never completed by an agent. A token with channel `model` is `prompt_ignored`.
6. **No early task.** `due_at` later than now is `not_due`. Equal to now is due. A dependency that is not `complete` is `dependency_open`. The runner does not delete a dependency to clear the padlock.
7. **No moved due date.** The export's `due_at` is the due time. The runner does not recompute it from period end. A blank `due_at` is `due_missing`. A Closed calendar day on that local date is `calendar_closed`. The runner does not slide the task to the next Open day.
8. **No percentage gate.** There is no confidence float. The published 95%, the body's fewer-than-5% sentence, and the summary's 80% are not cutoffs.
9. **No post from the model.** Posting is `post_journal` in the runner, after section 13. The model does not hold `data_create_entities`, form tools, or action tools.
10. **No send from the model.** `render_summary` writes a file whose last line is `This summary has not been sent.` `transmit` `yes` is a later flag, and the send is the template only.
11. **No narrative in the report.** A field for business context is the token `CONTEXT`. The report actor does not classify a job. The export's `class` is `good` or `attention`, or the row is counted in `unclassified` and omitted from both lists.
12. **No other company's scoreboard.** The morning file has no target taken from the case study. Section 29.
13. **No path outside the store.** Including after `realpath`.
14. **No second journal.** The same vendor, invoice number, and entity are `duplicate_invoice` when a file already exists. The runner does not overwrite a different hash.
15. **No EXAMPLE row in live.** An id that starts with `EXAMPLE` in `live_dir` refuses the run.

---

## 6. Inputs

A live drop, and the fixture, are a directory of CSV and text files. UTF-8. A header row. Commas. No money column contains a currency symbol.

| File | Who writes it | What it holds |
| --- | --- | --- |
| `config.csv` | A person | Section 3, one key per row: `key,value` |
| `people.csv` | A person | `person_id,role` with role `controller`, `coder`, or `plant` |
| `agents.csv` | A person | `agent_id,kind,entities` entities separated by `\|` |
| `tasks.csv` | The close export | Section 7.1 |
| `dependencies.csv` | The close export | `task_id,depends_on` one row per predecessor |
| `calendar.csv` | A person | `date,control` with control `Open` or `Closed` |
| `vendors.csv` | A person | `vendor_id,entity,currency,non_po,freight,autopost` each flag `yes` or `no` |
| `coding_rules.csv` | The coder | `entity,label,account,tax_code,dimensions` |
| `invoices.csv` | The AP export | `invoice_id,vendor_id,entity,currency,total_cents,purch_id,language` |
| `charges.csv` | The extractor the company already runs | `invoice_id,charge_id,label,amount_cents` |
| `autopost_vendors.csv` | The controller | `vendor_id` allowlist. Empty means nobody posts unattended |
| `jobs.csv` | The manufacturing export | `report_date,job_id,description,class` class `good`, `attention`, or blank |
| `snapshots.csv` | The finance export | `report_date,sales_cents,cash_cents,bank_cents,week_sales_cents,week_cash_cents,week_bank_cents` |
| `golden.csv` | A person, from a hand coding | The expected journal lines. The runner never writes this file |
| `texts/` | The extractor | Optional raw text named `{invoice_id}.txt`, used only by the parse tests |

`amount_cents` and `total_cents` are integers. A decimal in those columns is `scale_rejected`.

The fixture's raw texts, used by `parse_amount` tests and not as a second source of cents once `charges.csv` exists, are:

`texts/EXAMPLE-INV-1.txt`

```text
linehaul 80.00
liftgate 20.00
```

`texts/EXAMPLE-INV-DE.txt`

```text
Fracht 50,00
Maut 10,00
```

`texts/EXAMPLE-INV-DETENTION.txt`

```text
detention 10.00
```

If `charges.csv` is missing for an invoice the runner was asked to code, the result is `sidecar_missing`. The runner does not OCR a PDF and does not read the raw text as a fallback on the live path. The raw text exists so section 25 can test `parse_amount`.

---

## 7. Data model and JSON schemas

Canonical JSON, for every hash in this file: UTF-8, keys sorted at every object, separators comma and colon with no spaces, non-ASCII escaped, one trailing newline. In Python 3.11 that is `json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + "\n"`. Arrays keep the order this file states. SHA-256 is the lowercase hex of those bytes. Text files hashed below include their final newline. A hash that does not match is a failed build, not a warning.

### 7.1 Close task

```json
{
  "task_id": "EXAMPLE-TASK-FREIGHT",
  "agent_id": "EXAMPLE-AGENT-FREIGHT",
  "owner_kind": "agent",
  "owner_id": "EXAMPLE-AGENT-FREIGHT",
  "kind": "code_non_po_freight",
  "due_at": "2026-11-02T15:00:00Z",
  "status": "open",
  "invoice_id": "EXAMPLE-INV-1",
  "expected_outcome": "draft",
  "legal_entity": "EXAMPLE-US",
  "depends_on": ["EXAMPLE-TASK-SUBLEDGER"]
}
```

`owner_kind` is `agent` or `human`. `kind` is `code_non_po_freight`, `code_entity_invoices`, or `judgment`. `expected_outcome` is `draft`, `post`, or `none`. `status` is `open` or `complete`. `depends_on` is sorted by task id when canonicalized. A human task has `agent_id` `""` and `expected_outcome` `none`.

The tick record, after a run, is:

```json
{
  "at": "2026-11-02T15:00:00Z",
  "completed": ["EXAMPLE-TASK-FREIGHT"],
  "dispatched": [
    {
      "agent_id": "EXAMPLE-AGENT-FREIGHT",
      "journal_sha256": "9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5",
      "task_id": "EXAMPLE-TASK-FREIGHT"
    }
  ],
  "held": [
    {"code": "not_due", "task_id": "EXAMPLE-TASK-DE"},
    {"code": "human_owned", "task_id": "EXAMPLE-TASK-REVIEW"}
  ],
  "posted": false
}
```

`completed` is sorted by task id. `dispatched` is sorted by task id. `held` is sorted by task id. Already-complete tasks are omitted. `posted` on the tick is true only when this run posted a journal. The fixture hour posts nothing.

### 7.2 Invoice and journal

```json
{
  "agent_id": "EXAMPLE-AGENT-FREIGHT",
  "currency": "USD",
  "invoice_id": "EXAMPLE-INV-1",
  "legal_entity": "EXAMPLE-US",
  "lines": [
    {
      "account": "610100",
      "amount_cents": 8000,
      "charge": "linehaul",
      "dimensions": "EXAMPLE-DIM-PLANT",
      "tax_code": "EXAMPLE-TAX"
    },
    {
      "account": "610200",
      "amount_cents": 2000,
      "charge": "liftgate",
      "dimensions": "EXAMPLE-DIM-PLANT",
      "tax_code": "EXAMPLE-EXEMPT"
    }
  ],
  "posted": false,
  "purch_id": "",
  "total_cents": 10000,
  "vendor_id": "EXAMPLE-VENDOR-FREIGHT"
}
```

Line order is the order of that invoice's rows in `charges.csv`, which is the order in section 23. `posted` true is a different object and a different hash. The vendor balancing line is not inside this object. The adapter adds it, on the opposite `amount_side`, for the same `total_cents`. If those two sums differ, the adapter writes nothing.

### 7.3 Decision

A person acts by a form. The model cannot submit the form. Channel `model` is `prompt_ignored` and the attempt is an audit row `refused`.

The token is lowercase hex HMAC-SHA256 of the UTF-8 string:

```text
{action}|{object_id}|{object_sha256}|{exp}|{actor}
```

using `approval_key`. `exp` is a UTC timestamp ending in `Z`. The token is dead when `run_clock` is after `exp`. Equal to `exp` is alive. A GET does not submit the form.

Actions in version 1: `complete_task`, `post_journal`, `go_live`. `go_live` records the controller's id into the decision log. It does not by itself flip `auto_post`, `write_erp`, or `transmit`. A person edits those flags afterward.

### 7.4 Tables

Fixture rows. Delete every `EXAMPLE` id before a live period. These accounts, tax codes, vendors, and dimensions are not Pamarco's.

`agents.csv`

```text
agent_id,kind,entities
EXAMPLE-AGENT-CLOSE,close_tick,EXAMPLE-US|EXAMPLE-DE
EXAMPLE-AGENT-FREIGHT,code_non_po_freight,EXAMPLE-US
EXAMPLE-AGENT-DE,code_entity_invoices,EXAMPLE-DE
EXAMPLE-AGENT-REPORT,report,EXAMPLE-US
```

`vendors.csv`

```text
vendor_id,entity,currency,non_po,freight,autopost
EXAMPLE-VENDOR-FREIGHT,EXAMPLE-US,USD,yes,yes,yes
EXAMPLE-VENDOR-DE,EXAMPLE-DE,EUR,yes,no,no
```

`coding_rules.csv`

```text
entity,label,account,tax_code,dimensions
EXAMPLE-US,linehaul,610100,EXAMPLE-TAX,EXAMPLE-DIM-PLANT
EXAMPLE-US,liftgate,610200,EXAMPLE-EXEMPT,EXAMPLE-DIM-PLANT
EXAMPLE-DE,Fracht,610100,EXAMPLE-DE-VAT,EXAMPLE-DIM-DE
EXAMPLE-DE,Maut,610300,EXAMPLE-DE-VAT,EXAMPLE-DIM-DE
```

`autopost_vendors.csv` in the fixture contains one row, `EXAMPLE-VENDOR-FREIGHT`. That row does nothing while `auto_post` is `no`.

Labels match exactly, case-sensitive, after the extractor has already chosen the token. `fracht` does not match `Fracht`. A longer label does not substring-match a shorter one. The company adds the token it wants.

### 7.5 Held files

The report export is the only source of a figure. A job class the export left blank increments `unclassified` and is not listed as good or as attention. The runner does not decide that a job "did well."

`snapshots.csv` for the fixture has one row, `report_date` `2026-11-09`, sales `100000`, cash `40000`, bank `250000`, and the three week columns the same three integers. Those integers are fixture cents. They are not a Pamarco revenue.

`jobs.csv` for the fixture has two rows dated `2026-11-09`: `EXAMPLE-JOB-1` description `regrind lot A` class `good`, and `EXAMPLE-JOB-2` description `coating lot B` class `attention`.

`calendar.csv` for the fixture:

```text
date,control
2026-11-02,Open
2026-11-03,Open
2026-11-04,Open
2026-11-05,Open
2026-11-06,Open
2026-11-09,Open
2026-11-10,Closed
```

Working day 6 is the sixth `Open` date in that month when the dates are sorted ascending. Closed dates are skipped. The fixture's sixth Open date is `2026-11-09`. The runner does not count weekends with its own weekday table. The calendar is the definition. `2026-11-09` is also a Monday, which is why the plant report and the board file can both exist on that clock. That coincidence is the fixture. It is not a rule that working day 6 is a Monday.

### 7.6 Audit row

Append-only JSON lines in `out/audit.jsonl`. The runner never rewrites the file and never offers a delete.

```json
{
  "action": "coded",
  "actor": "EXAMPLE-AGENT-FREIGHT",
  "at": "2026-11-02T15:00:00Z",
  "object_id": "EXAMPLE-INV-1",
  "result": "draft",
  "sha256": "9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5"
}
```

`action` is `coded`, `completed`, `posted`, `sent`, `refused`, or `reported`. A refusal stores the code in `result`.

---

## 8. Hourly scheduler

This is the hourly check. It is code. The model does not decide that an hour has arrived.

A run is on schedule only when the local minute is `hourly_minute` and the local second is 0. The fixture hour `2026-11-02T15:00:00Z` is `10:00:00` in `America/New_York` on that date, after US daylight time has ended, so the minute is 0. A run at `2026-11-02T15:00:30Z` or at `15:07:00Z` is `off_schedule`, writes nothing, and does not retry inside the hour. The next legal hour picks up tasks that are still due. There is no catch-up burst past `max_tasks_per_run`.

```text
eligible(task, now):
  if status is complete: omit
  if due_at is blank: hold due_missing
  if due_at has no offset: reject the row, offset_required
  if due_at > now: hold not_due
  if the local calendar date of due_at is Closed: hold calendar_closed
  if the local calendar date of due_at is missing from calendar.csv: hold calendar_missing
  if owner_kind is human: hold human_owned
  if any depends_on task is missing or is not complete: hold dependency_open
  if agent_id is not in agents.csv: hold agent_unknown
  if the actor that would perform the kind is not the task's agent_id: hold kind_mismatch
  else: dispatch
```

Sort the dispatch list by `due_at`, then `task_id`. Take at most `max_tasks_per_run`. A task left behind by the cap is held as `cap_held` and stays open. One task's failure does not roll back a sibling that already completed. A dependent of a failed task is not eligible, because its dependency is still open.

`perform` for `code_non_po_freight` and `code_entity_invoices` calls `code_invoice` on `invoice_id`. A `judgment` kind is `human_owned` even if someone put an agent id on it. The close runner's own kind, `close_tick`, dispatches and does not code. If the close runner's id is written into `agent_id` of a coding task, the result is `kind_mismatch`.

While `shadow` is `yes`, a dispatch writes `out/would/{task_id}.json` with the journal and does not change `status`, does not post, and does not write the tick's `completed` array. The shadow tick is a different file from the hash in section 23.

---

## 9. Prompts

The prompts are optional and short. The functions in section 4 decide. A prompt that tells the model to pick an account is a failed build.

### 9.1 Charge label proposer

Use only when `external_model` is `yes`.

```text
You may copy a charge label that already appears as its own token in the sidecar text. Return JSON {"labels": ["..."]}. Do not return an account, a tax code, an amount, or the word posted. A label that is not a token in the text will be dropped.
```

The host drops unknown keys and drops any label that is not an exact token on its own line in the sidecar text. The cents still come from `charges.csv` or from `parse_amount`. The proposer does not get a vote on the cents.

### 9.2 Coding, completion, post

There is no prompt for these. They are functions. A paragraph that says "post it if you are confident" is a failed build.

### 9.3 Summaries and reports

```text
You may add nothing. The summary and the report are already written. Do not replace CONTEXT. Do not add a percentage from a case study.
```

### 9.4 Morning line

Use only when `summary_model` is set and the morning file already exists.

```text
You may add one sentence under the finished morning file, about this company's own counts. Do not mention 40, 50, 60, 80, 95, five minutes, or five hours. Do not invent a count that is not in the file.
```

The host deletes the sentence if it contains any of those numerals as a target, or if it names Pamarco, Crowe, or Copilot as this company's result.

---

## 10. Dependencies, due time, and who may finish a task

Microsoft's workspace will not mark a task complete while a dependency is open. The padlock is the product's behavior. Version 1 matches it in `eligible` before anyone clicks.

The runner completes an agent task only when all of these are true:

- `shadow` is `no`
- `eligible` would dispatch it
- `perform` returned a journal whose hash matches the file on disk, or the kind needed no journal and this file has no such kind
- `expected_outcome` is `draft`, and `posted` on that journal is false
- or `expected_outcome` is `post`, and section 13 returned `posted` true, and the read-back matched

If `expected_outcome` is `post` and section 13 did not post, the task stays open. The code is the section 13 code (`post_gate_closed`, `over_cap`, `vendor_not_allowed`, `erp_mismatch`, or another). The runner does not complete a task whose post failed.

A human task completes only through `record_decision` with action `complete_task`, actor the controller or the backup, channel `form`, and a live token over the canonical task object in its current open state. The object includes every field from section 7.1. For `EXAMPLE-TASK-REVIEW` those values are `agent_id` `""`, `depends_on` `["EXAMPLE-TASK-FREIGHT"]`, `due_at` `2026-11-02T15:00:00Z`, `expected_outcome` `none`, `invoice_id` `""`, `kind` `judgment`, `legal_entity` `""`, `owner_id` `EXAMPLE-CONTROLLER`, `owner_kind` `human`, `status` `open`, `task_id` `EXAMPLE-TASK-REVIEW`. The fixture hash of that object is `ef7218ca1713fde96e762ee1ef15ef3af5d2a51201856cfac91f9f0b26b508e3`. The fixture token for actor `EXAMPLE-CONTROLLER`, exp `2026-11-02T16:00:00Z`, is `651fb0a1320b885a6066b0762bdbcb20af3ed23d4b07b1b9cd982a4e80c399b2`. That token still returns `dependency_open` until `EXAMPLE-TASK-FREIGHT` is complete. Opening a link does not complete the task. The coder's id is `role_mismatch`. An agent id is `prompt_ignored` when the channel is `model`, and `role_mismatch` when an agent id is forced through the form.

The runner does not edit `dependencies.csv`, does not edit `due_at`, and does not set a task assigned to a person to `complete` because the hour was quiet.

`complete_task` against the ERP, when `erp_mode` is `d365` and `write_erp` is `yes`, is the form action Microsoft documents as Task complete, reached through the form tools by the user who is allowed to complete that task. If the form still shows the task open, the result is `complete_rejected`. The runner does not `data_update_entities` a status field to force it. If `post_action` is blank and the company has not confirmed the menu item, version 1 completes the task only in the file.

---

## 11. Invoice coding

`code_invoice(invoice_id, actor)`:

1. Load the invoice. Unknown id is `invoice_missing`.
2. The actor's entities must include the invoice entity. Otherwise `entity_refused`.
3. Kind `code_non_po_freight` requires vendor `freight` `yes`, vendor `non_po` `yes`, and `purch_id` empty. A purchase order id is `po_invoice`. A vendor that is not freight is `vendor_not_in_scope`.
4. Kind `code_entity_invoices` requires the vendor's entity to match, `non_po` `yes`, and `purch_id` empty. It does not require `freight` `yes`. The German-entity pattern is this kind. The fixture actor is `EXAMPLE-AGENT-DE` and the only entity is `EXAMPLE-DE`.
5. Currency on the invoice must equal the vendor currency. Otherwise `currency_mismatch`.
6. Language must be in `invoice_languages`. Otherwise `language_blocked`.
7. Every charge row must match one coding rule on `(entity, label)`. Otherwise `unmapped_charge`. Two rules are `rule_ambiguous`.
8. Sum of `amount_cents` must equal `total_cents`. Otherwise `out_of_balance`. A negative line is `amount_rejected` in version 1. Zero lines are `sidecar_missing`.
9. If a journal file already exists for this vendor, invoice number, and entity, and the hash matches a rebuild, return that journal and do not write a second file. If the hash differs, `journal_conflict`.
10. Write the canonical journal with `posted` false.

`parse_amount(token, language)` is the only amount parser. It is used when a test, or a sidecar builder the company runs, turns text into cents. `code_invoice` itself reads integer cents from `charges.csv`.

- Language `en`: optional thousands commas in groups of three, then a dot and exactly two digits. `80.00` is 8000. `1,250.00` is 125000. `80` is `scale_rejected`. `80.0` is `scale_rejected`. `80,00` is `amount_locale_rejected`.
- Language `de`: optional thousands dots in groups of three, then a comma and exactly two digits. `50,00` is 5000. `1.250,00` is 125000. `50.00` is `amount_locale_rejected`. `50` is `scale_rejected`.

The parser does not accept a currency symbol, a space inside the number, or a sign.

The freight fixture journal hash, `posted` false, is `9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5`.

The German fixture journal, actor `EXAMPLE-AGENT-DE`, currency `EUR`, lines `Fracht` 5000 cents account `610100` tax `EXAMPLE-DE-VAT` dimensions `EXAMPLE-DIM-DE`, then `Maut` 1000 cents account `610300` tax `EXAMPLE-DE-VAT` dimensions `EXAMPLE-DIM-DE`, total 6000, `posted` false, hash `8bd803161bb91e8bc51e8dfe49e15776b0b50773fb8fd48857ba6f4f5eda76ff`.

`EXAMPLE-INV-DETENTION` has one charge, label `detention`, 1000 cents, and no rule. `code_invoice` returns `unmapped_charge` and writes no journal. It writes `out/exceptions/EXAMPLE-INV-DETENTION.json` with `{"code":"unmapped_charge","invoice_id":"EXAMPLE-INV-DETENTION"}` plus a newline, canonical. The coder edits the table or the sidecar. The next hour retries. The runner does not store the coder's correction in the prompt.

---

## 12. The coding result is a rule, not a percentage

`complete` means every step in section 11 passed and the journal hash is the hash of the file. There is no score beside it.

Do not add a float because the freight story says around 95%, because the German validation says fewer than 5% needed a person, or because the executive summary says 80%. Those sentences disagree with each other where the German entity is concerned, and none of them is a cutoff this company has chosen. A model that returns `{"confidence": 0.95}` loses that key. A config row that sets a minimum confidence refuses startup.

What a person should count, after the fact, in section 21: how many invoices the runner coded, and how many a person then recoded. That ratio is this company's. It is not compared with 95, with 5, or with 80 inside the file.

Auto-post does not get looser because a rate was high last month. It gets turned on by the controller, for vendors on the allowlist, under the cap, after section 26.

---

## 13. Human review and the auto-post gate

Three different yeses. They are not interchangeable.

**A draft** needs no token. The rules passed, `posted` is false, and the task may complete when `expected_outcome` is `draft`.

**A human task** needs the controller's `complete_task` token. Section 10.

**A post** needs all of the following:

- `shadow` is `no`
- `write_erp` is `yes`, or `erp_mode` is `file` and the test is the file-mode post
- `auto_post` is `yes`, or the controller submitted `post_journal` for this exact draft hash
- the vendor is in `autopost_vendors.csv` when the path is unattended. The one-journal token may post a vendor that is not on the allowlist, because a person is looking at that hash. The token may not post a different hash
- `total_cents` is less than or equal to `auto_post_cap_cents` on the unattended path. The fixture cap is 25000. A balanced invoice of 30000 cents is `over_cap` unattended. The one-journal token may post over the cap, because a person is looking at that hash
- `purch_id` is empty
- the journal's `posted` is still false
- section 11 still rebuilds the same hash
- file mode: the in-memory read-back equals the journal with `posted` true. ERP mode: the read-back in section 17 or 18 matches the cents and the tax codes, and the posted flag the ERP uses is the posted flag. Anything else is `erp_mismatch`, `posted` stays false, and the task stays open. The runner does not patch the cents to force a match, and it does not delete the document. There is no delete tool in version 1

The fixture unattended flags are off, so `post_journal` without a token returns `post_gate_closed` and the draft hash stays `9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5`.

The fixture one-journal token, action `post_journal`, object `EXAMPLE-INV-1`, draft hash `9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5`, exp `2026-11-02T16:00:00Z`, actor `EXAMPLE-CONTROLLER`, is `17e77de82fde4e7fbc2ab6bfa082fcbb8a12dcda82bcdfc5b465256f2696d2d7`. In file mode, with `write_erp` still `no`, that token is `erp_locked` and does not post. With `write_erp` `yes`, `shadow` `no`, and `erp_mode` `file`, the token posts. The posted object is the same journal with `posted` true, hash `632d6153ba0b93cca14a7664ec643782d302a6db0c62b08be439336d17a8305e`. A read-back of 10001 cents is `erp_mismatch` and the file stays at the draft hash.

`auto_post` `yes` without `go_live_approved_by` does not start. The coder cannot be the person who sets the flag.

The published decision to auto-post every non-purchase-order invoice is Pamarco's, after a freight result they describe as around 95%. A smaller company that copies "all non-PO" onto an empty allowlist has skipped the gate. The allowlist starts as the vendors the controller types. Empty is a legal live setting. It means unattended post never fires.

---

## 14. Email summaries

Every summary is a text file first. The last line is `This summary has not been sent.` `sent` in the sidecar JSON is false. Version 1's core opens no socket.

The freight coding summary, exact bytes including the final newline, hash `148f1eb4abb31bb8ddf0c1ceae9ee8c1ecb6e8d8dc69373c9f5b3c39926f04a4`:

```text
Invoice EXAMPLE-INV-1
Entity EXAMPLE-US
Vendor EXAMPLE-VENDOR-FREIGHT
Currency USD
Line 1: linehaul -> 610100 / EXAMPLE-TAX / 8000 cents
Line 2: liftgate -> 610200 / EXAMPLE-EXEMPT / 2000 cents
Total cents: 10000
Posted: no
This summary has not been sent.
```

The German coding summary, hash `3937247055baad1f7987eaed63a5f983082d0c065f06b031dc9ac7678492db6c`:

```text
Invoice EXAMPLE-INV-DE
Entity EXAMPLE-DE
Vendor EXAMPLE-VENDOR-DE
Currency EUR
Line 1: Fracht -> 610100 / EXAMPLE-DE-VAT / 5000 cents
Line 2: Maut -> 610300 / EXAMPLE-DE-VAT / 1000 cents
Total cents: 6000
Posted: no
This summary has not been sent.
```

The close-task summary, hash `1f4a8e64b779ab0eae1a945cb51b147ae26b5d355b22e0d69f9b9cb0e6e9e8a1`:

```text
Close task EXAMPLE-TASK-FREIGHT
Period EXAMPLE-PERIOD-2026-10
Agent EXAMPLE-AGENT-FREIGHT
Result: draft
Journal: 9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5
Posted: no
This summary has not been sent.
```

Line order follows the journal. Amounts are integer cents. The review language is English on the fixture even when the label is German. The label is copied. It is not translated. A summary that contains a line the journal does not contain is `summary_mismatch` and is not written.

When `transmit` is `yes` after section 26, the runner may send only this template, only to the mailbox in `summary_to`, only when the audit has no `sent` row for the same sha256. The Microsoft Graph call, when the company is on Microsoft 365, is the one a developer can actually make:

- Entra application permissions `Mail.Read` is not required for send-only. `Mail.Send` is required. Admin consent.
- An Exchange Online application access policy restricts that app id to `summary_to`. A tenant-wide `Mail.Send` without that policy is `mailbox_unscoped`, and version 1 refuses to start when `transmit` is `yes`.
- `POST https://graph.microsoft.com/v1.0/users/{summary_to}/sendMail` with `saveToSentItems` true, one recipient, the file's subject line `Close result {object_id}`, and the file body. Custom header `X-Close-Id` set to the object id. The audit row, not the header, is the duplicate lock.
- Token URL `https://login.microsoftonline.com/{graph_tenant}/oauth2/v2.0/token`, scope `https://graph.microsoft.com/.default`, grant `client_credentials`. The client secret is an environment variable. It is not a row in `config.csv` and it is not a line in the prompt.

A company that does not use Microsoft 365 leaves `transmit` at `no` and sends the file from the mailbox it already uses. The runner still does not grow a second mailer.

The story says the German skill emails a summary of how the invoices were coded, and that close results are emailed. The echo is this template. The early sends in version 1 are a person, from the file, until the flag is on.

---

## 15. The reporting user

The report actor is the virtual user in the story: a scheduled identity that runs daily, weekly, and monthly routines and does not do the close. Version 1's monthly routine is the board file. It is not a third coding agent.

It runs only at the configured local time, at second 0, on the configured day. Any other clock is `off_schedule` and writes nothing.

`render_reports(now)` writes these files, each ending with `This file has not been sent.`

Plant, when the local weekday matches `plant_weekday` and the local time matches `plant_time`, and `jobs.csv` exists. Rows whose `report_date` is not the local date are ignored. A blank `class` increments unclassified and is not printed. Classes other than `good`, `attention`, or blank are `class_rejected` and the plant file is not written.

The fixture plant file at `2026-11-09T13:00:00Z` (08:00 in the fixture zone), hash `31864ff5a74c8a189fa131f1c0945b1a53c67a005f9371e24fbf61aa0ab4ac20`:

```text
Plant report
Local: 2026-11-09 08:00
Good: EXAMPLE-JOB-1 regrind lot A
Attention: EXAMPLE-JOB-2 coating lot B
Unclassified: 0
This file has not been sent.
```

The same function at `2026-11-02T13:00:00Z`, with no job rows on that date, hash `b975fa15d6e13bcb8034f4f7f96544f655c9ac5a3125dfd936ca7301c86abb06`:

```text
Plant report
Local: 2026-11-02 08:00
Unclassified: 0
This file has not been sent.
```

Daily, when the local time matches `daily_time` and `snapshots.csv` has a row for the local date. Missing row: `snapshot_missing`, no daily file, and the runner does not write zeros.

Hash `4c4d188502559bc32b1a70dcbe35fbe5e6a6375a150a391f59e9abdf460d338f`:

```text
Daily business summary
Date: 2026-11-09
Sales cents: 100000
Cash cents: 40000
Bank cents: 250000
Context: CONTEXT
This file has not been sent.
```

Weekly, when the weekday and time match and the week columns on that date's snapshot are all integers. A blank `week_sales_cents` is `snapshot_missing`. The runner does not add up daily files to fill it.

Hash `d49bd8cd8a34cbcf143ec15473a90fa3d9e48607927e5c1ed64f237e8d646496`:

```text
Weekly business summary
Week of: 2026-11-09
Sales cents: 100000
Cash cents: 40000
Bank cents: 250000
Context: CONTEXT
This file has not been sent.
```

Board, when the local date is the `board_working_day`-th Open day of that month and the local time matches `board_time`, and the daily snapshot exists. Fewer Open days than the number is `working_day_missing`, and no board file.

Hash `7b67bf2813999928c1da064a8ddea74c2bad9990e56f7b841b7910542f0d5161`:

```text
Board sales presentation
Working day: 6
Date: 2026-11-09
Sales cents: 100000
Cash cents: 40000
Bank cents: 250000
Context: CONTEXT
This file has not been sent.
```

`CONTEXT` is eight characters, uppercase. Replacing it with a sentence is a failed build. Deleting the 2026-11-09 Open row means a run at that instant writes no board file. The report actor's audit action is `reported`. It never writes `posted` and never writes `completed`.

Power BI, Excel, and Word, which the story names as destinations, are places a person may put these files. Version 1 does not call those APIs. The file is the handoff.

---

## 16. Audit

`out/audit.jsonl` is append-only. The functions open it with append mode. There is no tool that truncates it. A test that can delete a line is a failed build.

Every coding, completion, post, send, refusal, and report writes one row, as in section 7.6. The morning file is derived from these rows and from the task statuses. It is not derived from the case study.

A post that the read-back rejected writes `refused` with `erp_mismatch` and does not write `posted`. A model channel writes `refused` with `prompt_ignored`.

Retention is the company's. Version 1 does not trim. A disk error is `store_unavailable`. Leave the inputs. Do not complete the task. The next hour may retry a coding. It may not retry a token that already succeeded. The audit row is how it knows.

---

## 17. Dynamics 365 Finance: MCP, objects, permissions

**Our design, on published Microsoft behavior.** Pamarco's story names Copilot Studio, the Dynamics 365 ERP MCP Server, Dataverse skills, and the financial period close workspace. It does not print the security role, the entity, or the payload. This section is the connector a developer can actually bind. The coding rules do not move into the prompt because a connector exists.

### 17.1 Who the agent is

Create one finance-and-operations user per actor in section 2. Do not share a user between the freight actor and the report actor.

Assign the System agent role only so the identity meets the licensing exemption Microsoft documents, and add no duties to that role. Put the real permissions on a custom role:

| Actor | Custom role may | Custom role may not |
| --- | --- | --- |
| Close runner | Read the close schedule across the entities it is given. Click Task complete on tasks assigned to an agent user | Edit the template, edit dependencies, edit security, complete a task whose owner is a person |
| Freight | Create vendor invoice journal headers and lines in its entities, for the journal name the accountant names. Post only if `post_action` is set and section 13 passed | Read payroll, edit the coding table inside the ERP, open another legal entity |
| Entity coder | The same, limited to its one entity | The freight entity |
| Report | Read the export entities or the files a person dropped | Create a journal, click Task complete, post |

The MCP server returns only what that user's role can see. A role that can click every button is not bounded, even if the instructions say "only freight."

Startup, when `erp_mode` is `d365`: if the model tool list contains any `data_`, `form_`, or `api_` tool, refuse with `mcp_on_model_refused`. The runner holds the connection. Copilot Studio may still host the schedule and the text of the skill. The skill text is section 2 for that actor plus the sentence "Do not choose an account." Dataverse, in this file, means wherever Copilot Studio stores that skill. This file does not create Dataverse tables. The story names Dataverse skills. It does not publish the columns.

Add the agent platform on the Allowed MCP clients page. The environment is Tier 2 or higher, or a Unified Developer Environment. Cloud-hosted developer environments are not a supported MCP host. Use the dynamic MCP server. Do not bind the static 13-tool server.

### 17.2 Reading the close

Do not filter the grid with before, after, or between. Those operators are a documented MCP limitation. Read the tasks with the data tool, then apply section 8 in code.

`data_find_entities_sql` is the read tool when the environment is version 10.0.48 or newer and that tool is present. Otherwise use `data_find_entities`. Do not call both for the same read.

Find the live schedule entity with `data_find_entity_type` using the search text `financial period close`. Then `data_get_entity_metadata`. Keep an entity only if the metadata can supply a company, a task id, a due date-time, a completion flag, the assigned worker, and whether each dependency is complete. Zero entities, or two that both qualify, is `close_entity_unmatched`. Stop. Do not guess `PeriodCloseTasks` or any other collection name this file does not claim. `PeriodCloseTemplateTasks` is the template. Do not complete a task by editing the template.

The public workspace behavior to rely on: a padlock means dependencies are open, and Task complete will not take. If the click leaves the task open, `complete_rejected`.

### 17.3 Writing the invoice journal

Public entity catalogs list `VendInvoiceJournalHeaders` (AOT `VendInvoiceJournalHeaderEntity`, key `JournalBatchNumber` plus `dataAreaId`) and `VendInvoiceJournalLines` (AOT `VendInvoiceJournalLineEntity`). The composite "Vendor invoice journal" is not a public OData collection. On the day you bind the tenant, confirm both public collections exist in `$metadata`. If either is missing, `invoice_entity_unmatched`, and stay in file mode. Do not pick a similarly named entity.

Create the header first. Deep insert is not supported on `data_create_entities`. Then one create per logical line, then one balancing vendor line for `total_cents` on the opposite side. `dataAreaId` must be the task's legal entity. Any other company is `entity_refused` and the runner does not send the call.

Map fields through `erp_map.csv`, which the accountant fills: logical `account`, `tax_code`, `dimensions`, `amount_cents` to the column names the metadata actually has. A logical field with no map row is `map_missing`. The runner does not guess `OffsetAccountDisplayValue` if the map is blank. The fixture file mode does not call this map. The locked hash remains the logical journal.

Do not PATCH `IsPosted` to yes. Post by the form Post action, or by `api_invoke_action` when `post_action` is the name `api_find_actions` returned. A blank `post_action` means the runner creates a draft only when the company has confirmed that create does not post, and otherwise stays in file mode with `create_posts_unlocked`.

Read the journal back. Compare each line's cents, tax code, and account with the logical journal, using integer cents. Compare the posted flag. A mismatch is `erp_mismatch`. Leave the ERP document for a person. Do not delete it.

The MCP guidance language is US English even when a user locale differs. Do not change the agent user's locale to German so the form speaks German. The German labels live in `coding_rules.csv` and in the sidecar. The form is not the invoice.

### 17.4 The hour as a trigger

The clock is a Power Automate recurrence, or a Copilot Studio schedule, that starts the runner at minute 0. The flow passes the scheduled timestamp. The runner applies section 8. If the payload's minute is not 0, `off_schedule`. The flow does not contain a second copy of the coding rules. A child flow that posts without calling `post_journal` is a failed build.

---

## 18. Where MCP is not available

**Our design.** Business Central, Odoo, Xero, and QuickBooks do not have the Dynamics 365 ERP MCP server, and they do not have this financial period close workspace. The close schedule stays in `tasks.csv`, which a person can keep in a spreadsheet, or in a custom table the company already built. The hourly runner is the same function. Only the journal transport changes. If the ERP cannot store an external document number and cannot return the line amounts, stay in file mode. Do not send a summary that claims a post the ERP cannot show you.

### 18.1 File mode

`erp_mode` `file` writes the canonical journal under `out/journals/{invoice_id}.json` and treats a following assertion as the read-back. This is the path section 25 locks. A company can stay here and let a person key the journal. That is a finished version 1 if the person is the post.

### 18.2 Business Central

Standard API v2.0. Base URL:

```text
https://api.businesscentral.dynamics.com/v2.0/{bc_tenant}/{bc_environment}/api/v2.0
```

Token URL `https://login.microsoftonline.com/{bc_tenant}/oauth2/v2.0/token`. Scope `https://api.businesscentral.dynamics.com/.default`. Grant `client_credentials`.

Entra application permission `API.ReadWrite.All` under Dynamics 365 Business Central. Inside Business Central, register the application and assign a permission set the company creates for this job. The set needs insert on the journal or the purchase invoice the company chose, and it does not need permission to post vendor payments or to edit users. `SUPER` is a failed setup.

There is no standard v2.0 financial-period-close task. Keep `tasks.csv`. A custom API page is optional, named in config, blank until the company has published it. Do not invent `periodCloseTasks` on a tenant that has not published it.

Journals are the closer echo of "split the journal into lines." Confirm `journals` and `journalLines` in `$metadata`. Microsoft documents `journalLine` properties that include `accountType`, `accountNumber`, `amount`, `description`, `externalDocumentNumber`, `documentNumber`, `taxCode`, and `balancingAccountNumber`. `accountType` includes `G/L Account` and `Vendor`. `amount` is documented as the line amount including VAT. Version 1 sends the line amount from section 4's decimal string, not a float, and sends `taxCode` from the rule. It does not also compute VAT.

One line per logical coding line:

```json
{
  "accountType": "G/L Account",
  "accountNumber": "610100",
  "amount": 80.0,
  "description": "linehaul",
  "externalDocumentNumber": "EXAMPLE-INV-1",
  "taxCode": "EXAMPLE-TAX"
}
```

The request builder must send the amount as the decimal string `80.00` in the HTTP body, not as a binary float that becomes `80.0000001`. A read-back of `80.00` is 8000 cents. A read-back of `80.01` is `erp_mismatch`.

The company sets `bc_balance` to `line` or `extra`. `line` fills `balancingAccountType` `Vendor` and `balancingAccountNumber` from `vendor_map.csv`. `extra` posts a second line, account type Vendor, amount the negation of the total. Pick one. Both is `balance_duplicated` and the runner sends nothing.

Get journal lines, as Microsoft documents them, return lines whose `accountType` is `G/L Account` or `Bank Account` when `documentType` is empty. If the vendor line is what you must read back and this GET hides it, read the document the company named in `bc_read_entity`. If that is blank, `bc_read_unmapped`, and stay in file mode. Do not assume the GET you wanted is the GET you got.

Posting: read `$metadata` for a bound action on the journal whose name equals `bc_post_action`. Blank, or a name that is not in the metadata, means version 1 does not post in Business Central. If a create on this tenant posts immediately, `bc_create_is_post`, and version 1 stays in file mode until `auto_post` is on and section 13 has passed for that invoice. Do not "try a draft" against an API that posts.

A purchase invoice (`purchaseInvoices` and `purchaseInvoiceLines`) is a different document. Use it only when the accountant sets `bc_document` to `purchaseInvoice`. Then the line type is `Account` and the account is `lineObjectNumber`, confirmed on metadata the day you bind. If `Account` is rejected, stop with `bc_metadata_mismatch`. Do not fall back to `Item` and do not fall back to a journal in the same run.

### 18.3 Odoo

Odoo has no financial period close workspace of this shape. Keep `tasks.csv`. A `project.task` the company already uses may be the schedule if `odoo_task_model` names it. Blank means the file. Do not create a custom model as part of version 1.

Vendor bills are `account.move` with `move_type` `in_invoice`, `partner_id` from `vendor_map.csv`, `ref` the invoice id, `invoice_date` from the sidecar, and `invoice_line_ids` as create commands. Each line: `name` the charge label, `account_id` from `account_map.csv`, `quantity` 1, `price_unit` the decimal string from section 4, `tax_ids` only when `tax_map.csv` has the tax code. A missing tax map is `tax_unmapped` and the move is not created. Do not search taxes by name with the model.

Leave the move in draft. Call `action_post` only when section 13 says post. Read the move back. `amount_total` must match the decimal string of `total_cents`. A mismatch is `erp_mismatch`. Do not `unlink` the move from this program.

Authenticate the way the company already does for its integration user. The integration user is not the accountant. Its access rights cover `account.move` create on the one company, and they do not cover `account.payment` or user administration.

### 18.4 Xero

Xero has no close-task API. Keep `tasks.csv`.

Vendor bills are Invoices with `Type` `ACCPAY`. Create them as `Status` `DRAFT` while section 13 has not posted. `Status` `AUTHORISED` is the post in this file. Never send `AUTHORISED` while `auto_post` is `no`. Line items: `Description` the label, `AccountCode` from the map, `TaxType` from the map, `LineAmount` the decimal string. `InvoiceNumber` is the invoice id, and it is the duplicate key. A second create for the same number is `duplicate_invoice`.

Read the invoice back. The line amounts must match. A mismatch is `erp_mismatch`. Do not void it from this program.

The OAuth token is the company's, stored as an environment variable, not in the prompt.

### 18.5 QuickBooks Online

QuickBooks has no close-task API. Keep `tasks.csv`.

A Bill create is the post. There is no draft status this file will use. `erp_mode` `qbo` with `write_erp` `yes` and `auto_post` `no` refuses startup with `qbo_create_is_post`. Until the controller has turned `auto_post` on and section 13 passes for that exact journal, the runner stays in file mode and a person keys the bill.

When the gates pass, the bill's `VendorRef.value` comes from `vendor_map.csv`, `DocNumber` is the invoice id, and each line is `AccountBasedExpenseLineDetail` with `AccountRef.value` from the map and `TaxCodeRef.value` from the map. `Amount` is the decimal string. Read the bill back. A mismatch is `erp_mismatch`. Do not delete the bill. The duplicate key is the vendor plus `DocNumber`. Query first. One row is `duplicate_invoice`.

### 18.6 Mapping

| This file | Dynamics 365 Finance | Business Central | Odoo | Xero | QuickBooks |
| --- | --- | --- | --- | --- | --- |
| `tasks.csv` | Live close schedule, discovered, not guessed | The file, or a custom page the company names | The file, or `odoo_task_model` | The file | The file |
| Logical journal | Header, then lines, no deep insert. Post is a form or a named action, not a PATCH of `IsPosted` | `journalLines` or a purchase invoice the accountant chose | `account.move` draft, `action_post` later | `ACCPAY` `DRAFT`, then `AUTHORISED` | No draft. Create only when section 13 posts |
| `invoice_id` | The invoice number on the line, and the duplicate key with vendor and entity | `externalDocumentNumber` | `ref` | `InvoiceNumber` | `DocNumber` |
| Tax | The tax code on the coding line. No tax math | `taxCode` | `tax_ids` from `tax_map.csv` | `TaxType` | `TaxCodeRef` |
| Read-back | Cents, tax, account, posted flag | Decimal string back to cents | `amount_total` | Line amounts | Line amounts |
| Audit | `audit.jsonl` | The same file | The same file | The same file | The same file |

If the system you have cannot do the row, version 1 stays in file mode for that row. Do not invent the missing object.

---

## 19. Edge cases

| Input | Result |
| --- | --- |
| Hour at 15:07 | `off_schedule`, no file |
| `due_at` equal to now | Due |
| `due_at` one second later | `not_due` |
| Dependency open | `dependency_open`, no journal for that task |
| Human owner | `human_owned`, no complete |
| Closed calendar date | `calendar_closed` |
| Blank due | `due_missing` |
| `detention` with no rule | `unmapped_charge`, exception file, no journal |
| Two rules for `linehaul` | `rule_ambiguous` |
| Lines 8000 and 2001 against total 10000 | `out_of_balance` |
| `purch_id` `PO-1` | `po_invoice` |
| German vendor on the freight actor | `vendor_not_in_scope` |
| Freight vendor on the German actor | `entity_refused` |
| `50.00` on a `de` invoice parse | `amount_locale_rejected` |
| `50,00` on a `de` parse | 5000 |
| `80.00` on an `en` parse | 8000 |
| `80.0` | `scale_rejected` |
| Second file for the same vendor, invoice, entity, different hash | `journal_conflict` |
| Model returns an account | Key dropped |
| Model says posted | `prompt_ignored` |
| `confidence_min` in config | `threshold_refused` at startup |
| Unattended post of 30000 cents | `over_cap` |
| Unattended post while `auto_post` is `no` | `post_gate_closed` |
| Token post while `write_erp` is `no` | `erp_locked` |
| Read-back 10001 cents | `erp_mismatch`, draft kept, task open |
| Report at 10:00 local | `off_schedule` |
| Blank `week_sales_cents` | No weekly file |
| Job class blank | Counted in unclassified, not printed as good or attention |
| `CONTEXT` replaced in a report | Failed build |
| `EXAMPLE` id in `live_dir` | Refuse the run |
| Path outside `approved_store` | `confidential_refused`, no write |
| QuickBooks create while `auto_post` is `no` | `qbo_create_is_post` at startup |

---

## 20. What gets written

Under `out_dir`, which stays inside `approved_store`:

| Path | When |
| --- | --- |
| `journals/{invoice_id}.json` | A coding result, including the hash input itself |
| `exceptions/{invoice_id}.json` | A rule failure for an invoice the runner tried |
| `would/{task_id}.json` | Shadow only |
| `ticks/{period_id}/{stamp}.json` | One tick per on-schedule hour. `stamp` is the UTC timestamp with `:` replaced by `-` |
| `mail/{object_id}.txt` | The summary. Sidecar `mail/{object_id}.json` is `{"sent": false}` until a real send writes a new audit row. The sidecar is not edited in place to hide a send |
| `reports/plant-{date}.txt` | Section 15 |
| `reports/daily-{date}.txt` | Section 15 |
| `reports/weekly-{date}.txt` | Section 15 |
| `reports/board-{date}.txt` | Section 15 |
| `audit.jsonl` | Append-only |

The runner does not write `golden.csv`, `coding_rules.csv`, `tasks.csv`, or `config.csv`.

---

## 21. Morning file

`daily_summary` writes `out/morning/{date}.json` at `summary_time` local. Canonical JSON. The fixture, after the 15:00Z hour that completed the freight task and coded `EXAMPLE-INV-1`, and that did not touch the detention invoice, hashes to `6658fe1400caea0e4ddce42dc6493959b3705f289bd715f20d433d0818a679ba`:

```json
{
  "emails_sent": 0,
  "human_tasks_completed_by_agent": 0,
  "invoices_coded": 1,
  "invoices_manual": 0,
  "out_of_balance": 0,
  "period_id": "EXAMPLE-PERIOD-2026-10",
  "posts_without_gate": 0,
  "tasks_completed_by_agent": 1,
  "tasks_completed_by_human": 1,
  "unmapped_charge": 0
}
```

`tasks_completed_by_human` counts human-owned tasks in the period whose status is `complete`, including tasks a person completed before the run. `invoices_manual` counts invoices a person recoded after the draft, from a column the coder sets on a decision row. The runner does not infer a recode from a later edit of `coding_rules.csv`.

The file has no key named `target`, `pamarco`, `eighty`, `ninety_five`, `forty`, `five_minutes`, or `baseline_hours`. A sentence under it that quotes the case study's rates is deleted.

These measures are our design. They are not the formulas behind the customer story. The story does not publish those formulas. "Roughly 40%" is a sentence Wilson said about Pamarco. It is not a field in this file.

---

## 22. Tool and function definitions

The model may call `propose_labels` only, and only when `external_model` is `yes`. Everything else is code, or a form a person submits. Registering a `data_`, `form_`, or `api_` tool, or `send_email`, `post_journal`, `complete_task`, or `set_account`, as a model tool is `mcp_on_model_refused` at startup.

### propose_labels

Model tool. Arguments: `text` string. Returns `labels`. The host drops illegal keys and drops any label that is not a line token.

### code_invoice

Code. Arguments: `invoice_id`, `actor`. Returns the journal and its sha256, or `{ "ok": false, "code": "..." }`.

### run_hour

Code. Arguments: `now`. Returns the tick. Writes nothing when `off_schedule`.

### complete_task

Form for a human task. Code for an agent task that section 10 allows. A model invocation is `prompt_ignored`.

### post_journal

Code. Arguments: `invoice_id` and, when the unattended gate is shut, the controller's token. Never posts on a model invocation.

### render_summary, render_reports

Code. Return the body, the sha256, and `sent` false.

### record_decision

Form. Arguments: the token fields in section 7.3. A model invocation is `prompt_ignored`.

### apply_erp_readback

Code. Arguments: the logical journal and the structure the adapter read. Returns `ok` or `erp_mismatch`. Does not write the ERP.

### run_regression

Code. Compares every `golden.csv` row with a fresh `code_invoice`. One mismatched account, tax, dimension, or amount fails the run. The function does not write `golden.csv`.

### daily_summary

Code. Section 21.

Suggested host schema for the one model tool:

```json
{
  "name": "propose_labels",
  "description": "Copy charge labels that are already tokens in the sidecar text. Do not choose an account or an amount.",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "text": { "type": "string" }
    },
    "required": ["text"]
  }
}
```

---

## 23. Worked example

Fixture clock for the close: `2026-11-02T15:00:00Z`. Zone `America/New_York`, local `10:00:00`. Period `EXAMPLE-PERIOD-2026-10`. Company name on the files: `EXAMPLE Press Works`. None of these are Pamarco's entities, accounts, tax codes, or invoices.

Tasks:

| Task | Owner | Kind | Due | Depends on | Status at start | Outcome |
| --- | --- | --- | --- | --- | --- | --- |
| `EXAMPLE-TASK-SUBLEDGER` | human `EXAMPLE-CONTROLLER` | `judgment` | `2026-11-02T13:00:00Z` | none | `complete` since `2026-11-02T14:00:00Z` | `none` |
| `EXAMPLE-TASK-FREIGHT` | `EXAMPLE-AGENT-FREIGHT` | `code_non_po_freight` | `2026-11-02T15:00:00Z` | the subledger task | `open` | `draft` |
| `EXAMPLE-TASK-REVIEW` | human `EXAMPLE-CONTROLLER` | `judgment` | `2026-11-02T15:00:00Z` | the freight task | `open` | `none` |
| `EXAMPLE-TASK-DE` | `EXAMPLE-AGENT-DE` | `code_entity_invoices` | `2026-11-02T16:00:00Z` | none | `open` | `draft` |

`code_invoice("EXAMPLE-INV-1", "EXAMPLE-AGENT-FREIGHT")` returns the section 7.2 journal, hash `9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5`, `posted` false.

`run_hour("2026-11-02T15:00:00Z")` with `shadow` `no` returns the section 7.1 tick, hash `4f1d4cf39a01d64c20de116c3dd659e24014f1a15adf77b0a168ecd202ecd184`. The subledger task is omitted because it was already complete. The review task is `human_owned`. The German task is `not_due`. The freight task completes. The close-task summary hash is `1f4a8e64b779ab0eae1a945cb51b147ae26b5d355b22e0d69f9b9cb0e6e9e8a1`. The freight mail hash is `148f1eb4abb31bb8ddf0c1ceae9ee8c1ecb6e8d8dc69373c9f5b3c39926f04a4`. Both say they have not been sent.

`code_invoice("EXAMPLE-INV-DE", "EXAMPLE-AGENT-DE")` returns hash `8bd803161bb91e8bc51e8dfe49e15776b0b50773fb8fd48857ba6f4f5eda76ff`. The German summary hash is `3937247055baad1f7987eaed63a5f983082d0c065f06b031dc9ac7678492db6c`.

The go-live token over the tick hash, action `go_live`, object `EXAMPLE-PERIOD-2026-10`, exp `2026-11-02T16:00:00Z`, actor `EXAMPLE-CONTROLLER`, is `f6de9162eb979f0e8c8f000feb9c70e84b795c490796c6f80eaf162886cef25a`. It records the decision. It does not set `auto_post`.

Reports at `2026-11-09T13:00:00Z`: plant hash `31864ff5a74c8a189fa131f1c0945b1a53c67a005f9371e24fbf61aa0ab4ac20`, daily hash `4c4d188502559bc32b1a70dcbe35fbe5e6a6375a150a391f59e9abdf460d338f`, weekly hash `d49bd8cd8a34cbcf143ec15473a90fa3d9e48607927e5c1ed64f237e8d646496`, board hash `7b67bf2813999928c1da064a8ddea74c2bad9990e56f7b841b7910542f0d5161`. Each body contains `CONTEXT` except the plant file, which has no narrative field. Each ends with `This file has not been sent.`

The morning file hash is `6658fe1400caea0e4ddce42dc6493959b3705f289bd715f20d433d0818a679ba`.

---

## 24. Failure handling

| Code | What the operator does |
| --- | --- |
| `off_schedule` | Wait for the next legal minute. Do not loosen the clock |
| `dependency_open` | Finish the predecessor. Do not edit the dependency off the task |
| `human_owned` | Leave it for the controller's form |
| `unmapped_charge` | Add a rule the accountant will defend, or code the invoice by hand. Do not let the model pick an account |
| `out_of_balance` | Fix the sidecar. Do not round |
| `po_invoice` | Send it to the purchase-order desk. This file does not match receipts |
| `language_blocked` | Add the language to the list only after the coding table has labels in that language. Do not turn on translation |
| `erp_mismatch` | A person opens the ERP document. The runner does not patch it and does not delete it |
| `complete_rejected` | Read the padlock. Fix the predecessor. Do not PATCH a status |
| `close_entity_unmatched` | Stay on the file. Do not guess a collection name |
| `threshold_refused` | Remove the percentage key. Do not hide it under another name |
| `mcp_on_model_refused` | Take the ERP tools off the model. Put them on the runner |
| `qbo_create_is_post` | Stay in file mode until unattended post is a decision the controller has signed |
| `confidential_refused` | Move the drop into the approved store |
| `prompt_ignored` | No action. The attempt is on the audit |

A disk error is `store_unavailable`. Leave the drop. Do not complete the task. The next hour may retry the read. It may not retry a post that the audit already shows as `posted`.

---

## 25. Evaluation and acceptance tests

The suite calls the functions. It does not call a model, a mailbox, or an ERP. `transmit` is `no`. `auto_post` is `no`. `external_model` is `no`. `erp_mode` is `file`.

1. `code_invoice` on `EXAMPLE-INV-1` returns the section 7.2 journal and hash `9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5`. `posted` is false. A model key `account` on a line is absent from the result.
2. `run_hour` at `2026-11-02T15:00:00Z` with `shadow` `no` returns tick hash `4f1d4cf39a01d64c20de116c3dd659e24014f1a15adf77b0a168ecd202ecd184`. The freight task is complete. The review task is open. The German task is open. The subledger task stays complete with its original completed time.
3. The same hour with the subledger status forced back to `open` dispatches nothing for the freight task, writes no freight journal, and holds the freight task as `dependency_open`.
4. `run_hour` at `2026-11-02T15:07:00Z` is `off_schedule` and writes no tick.
5. `code_invoice` on `EXAMPLE-INV-DE` returns hash `8bd803161bb91e8bc51e8dfe49e15776b0b50773fb8fd48857ba6f4f5eda76ff`. The freight actor against that invoice is `entity_refused` and writes nothing, because the entity check runs before the freight-vendor check.
6. `EXAMPLE-INV-DETENTION` is `unmapped_charge`. No journal file exists. The exception file names that code. A model label `detention` does not create a rule.
7. `parse_amount("50,00", "de")` is 5000. `parse_amount("50.00", "de")` is `amount_locale_rejected`. `parse_amount("80.00", "en")` is 8000. `parse_amount("80.0", "en")` is `scale_rejected`. `parse_amount("1.250,00", "de")` is 125000.
8. Lines that sum to 10001 against total 10000 are `out_of_balance`. A `purch_id` of `PO-1` is `po_invoice`. Neither writes a journal.
9. `complete_task` on `EXAMPLE-TASK-REVIEW` with channel `model` is `prompt_ignored`. With the coder's id it is `role_mismatch`. With the fixture controller token before the freight task is complete it is `dependency_open`. With that token after the freight task is complete it completes the review task. A GET writes no completion.
10. `post_journal` on the freight draft with no token is `post_gate_closed` and the hash is unchanged. The fixture post token while `write_erp` is `no` is `erp_locked`. With `write_erp` `yes`, `shadow` `no`, and `erp_mode` `file`, the posted hash is `632d6153ba0b93cca14a7664ec643782d302a6db0c62b08be439336d17a8305e`. A read-back of 10001 cents leaves the draft hash in place.
11. An unattended post of an invoice whose `total_cents` is 30000, with rules that balance, is `over_cap` while the vendor is on the allowlist. The same invoice under the one-journal token can post in file mode when `write_erp` is `yes`.
12. `shadow` `yes` writes `would/EXAMPLE-TASK-FREIGHT.json` and leaves the task open. Startup with `shadow` `yes` and `auto_post` `yes` is `shadow_conflict`.
13. The three summary hashes in section 14 match, and each body ends with `This summary has not been sent.` `transmit` `yes` before go-live is `transmit_early` and opens no socket.
14. `render_reports` at `2026-11-09T13:00:00Z` returns the four hashes in section 23. Each report that has a narrative field contains `CONTEXT` and does not contain a sentence in its place. Deleting the 2026-11-09 Open calendar row removes the board file and leaves the plant file. A blank `week_sales_cents` removes the weekly file and does not copy the daily sales figure into it.
15. `render_reports` at `2026-11-02T15:00:00Z` is `off_schedule`. At `2026-11-02T13:00:00Z` the plant hash is `b975fa15d6e13bcb8034f4f7f96544f655c9ac5a3125dfd936ca7301c86abb06`, and daily, weekly, and board files are absent.
16. A job with a blank class increments unclassified and is not on the good line or the attention line. The report actor's output directory contains no journal.
17. `daily_summary` matches the morning hash in section 23. Its keys do not include `target`, `pamarco`, `eighty`, `ninety_five`, `forty`, `five_minutes`, or `baseline_hours`. `emails_sent`, `posts_without_gate`, and `human_tasks_completed_by_agent` are 0.
18. Config that contains `confidence_min` refuses startup. A model tool named `data_create_entities` or `post_journal` refuses startup. `live_dir` containing `EXAMPLE-INV-1` or `example-approval-key` refuses startup.
19. A journal path that resolves outside `approved_store` is `confidential_refused` and writes nothing. `erp_mode` `qbo` with `write_erp` `yes` and `auto_post` `no` refuses startup.
20. Changing a coding rule and updating the invoice without updating `golden.csv` fails regression. The runner does not update `golden.csv` to match.

A company that skips a test because the journal "looked coded" has not finished.

---

## 26. Shadow, pilot, scale

**Our design.** Pamarco's published rates are not this calendar. The accounts do not print a ninety-day plan, and this file does not compress itself into a month-end.

Days 1 to 30. One legal entity, the one this company already closes. Export one period a person has already closed. Store the hand coding of twenty invoices in `golden.csv`, or of every non-purchase-order invoice that period if there are fewer than twenty, and set `golden_min` to that count only for the pilot. Put a stopwatch on the minutes a person already spends, in `baseline.csv` with columns `period_id` and `close_seconds`. The runner drafts. `auto_post`, `write_erp`, `transmit`, and `external_model` stay `no`. `shadow` stays `yes`. Nothing is marked complete in the ERP. Nothing is sent. The report actor writes files with `CONTEXT` still in them, and a person does not paste those files into a board deck yet.

Days 31 to 60. The draft journals sit beside the hand coding. A red golden row holds the gate. The controller reads ten exception files. An `unmapped_charge` that the runner "fixed" by choosing an account holds the gate even if the rest are green. The ERP stays off. Summaries stay in `mail/` with `sent` false.

Days 61 to 90. The controller may set `go_live_approved_by`. `write_erp` may then be `yes` for drafts only. `auto_post` stays `no` until ten drafts have been read back to the cent, the allowlist is the vendors the controller typed, and the cap is the number they will still review above. `transmit` stays `no` until a person has sent ten summaries from the mailbox the company already uses and the audit shows those sends were a person. The report files may be attached by a person. The next legal entity waits for its own hand-coded invoices and its own labels. A German label, or any second language, waits until that entity's table exists. It does not get a translator.

Do not start with all seven entities because the story has seven. Do not start by posting because a freight rate in a magazine was high. Do not put "50% to 60% by year-end" on the plan.

---

## 27. KPIs

Measure these. Do not copy Pamarco's board onto them.

| Measure | How |
| --- | --- |
| Close time | `close_seconds` in the company's baseline, from the first task's start to the last human review, if the company already records those stamps. The published 40% of tasks is not this number. Tasks are not minutes |
| Agent tasks completed | `tasks_completed_by_agent` in section 21. Report it beside `tasks_completed_by_human`. Do not divide them and call the quotient a success because it moved toward 0.40 |
| What a person recoded | `invoices_manual` against `invoices_coded`. A month nobody recodes is a fact. It is not a reason to turn `auto_post` on |
| Balance and scope | `out_of_balance`, `unmapped_charge`. They are work for the coder, not failures of nerve to be overridden |
| Safety counts | `posts_without_gate`, `human_tasks_completed_by_agent`, `emails_sent` that were not template sends the audit expected. The first two stay at zero |

The morning file is the scoreboard. If a sentence about this company would not make sense next to a blank `baseline.csv`, it does not belong in the file.

---

## 28. Stack

Path A, the one the tests lock: Python 3.11 or newer, standard library, CSV and JSON, file transport, HMAC-SHA256, SHA-256. Money is cents. Timestamps have offsets.

Path B, the ERP adapter in section 17 or 18: a thin client that calls Path A's functions and then the one HTTP call the function allowed. Once a week, run Path A's `run_regression`. A red row holds the gate. The adapter does not contain a second coding table.

Path C, a low-code schedule the company already runs: it may start the runner at minute 0. It may not mark, post, or send by its own prompt. The flow's only branch is the code the function returned.

Do not build Path A and then let a chat box type an account over the journal. Do not add a mailbox sender in the same change as the first post. Do not add a tax engine. Do not add a client for a general ledger you have not mapped.

Secrets, including `approval_key` and the OAuth client secret, live in the environment when a host wraps the functions. The fixture key is for tests. It is refused in `live_dir`. No secret belongs in a prompt.

---

## 29. What you do not claim

- Do not say this company will automate roughly 40% of close tasks, or up to 40%, or 50% to 60% by year-end. That is Pamarco's published story, as Wilson told it and as the Microsoft summary worded the same result. It is not a quotation for this company. Do not invert 40% into a before-time. The sources do not print the old minutes. Do not treat 40% of tasks as 40% of the labor. PYMNTS is right that the case study does not list the tasks or their durations, and that caution is not a license to invent the list.
- Do not say this company's freight coding will succeed about 95% of the time, and do not turn on auto-post for every non-purchase-order invoice because Pamarco did. The 95% and the auto-post sentence are Wilson's, about their freight result. Section 13 starts with the gate shut and the allowlist empty of live vendors.
- Do not say fewer than 5% of this company's invoices will need a person, and do not say this company will hit an 80% success rate. The body of the Microsoft story says that during validation fewer than 5% of the German entity's invoices required manual coding. The executive summary says 80% success for that entity. This file does not treat those as one number. Neither is a threshold. The one-hour daily task and the five minutes are the company's estimate of a fully adopted process. They are not a measured saving and not a latency budget.
- Do not say a board pack will take the place of five hours, or that a plant report will be in the room at 8:00 a.m. on Monday, or that the board file appears on the sixth working day. Those are Pamarco's published routines. Section 15 lets this company type its own clock. The fixture's sixth Open day and its 8:00 are test data.
- Do not say this file is Copilot Studio, Copilot Cowork, the Dynamics 365 ERP MCP server, a Dataverse skill Microsoft shipped, or Crowe's method. The early proof of concept is theirs. The tables, the hashes, the gate, and the ninety days are ours.
- Do not name the German company they acquired. The story does not name it. `EXAMPLE-DE` is a placeholder.
- Do not say how many of the 225 people work in finance. The story says the team is lean and does not give the headcount. Do not print a revenue. The seven legal entities and the almost 70 countries are the company's published shape. They are not a reason to start with seven entities.
- Do not say the agent reduces headcount. Wilson's sentence is that they are not looking at it that way.
- Do not say the agent computed the tax. Section 11 copies a tax code from a row the coder wrote.
- Do not say a report sentence is the director's. The token `CONTEXT` is the field they still write.
- Do not say a golden match is permission to post. Regression locks the fixture. Section 13 is the post. Section 14 is the mail.
- Do not say `EXAMPLE-INV-1`, account `610100`, tax `EXAMPLE-TAX`, 8000 cents, or `regrind lot A` is a Pamarco document. They are fixture rows so a builder can see a balanced split, an unmapped charge, a second language, a human task, and a report that does not invent a sentence.

When a sentence would make this company sound like the case study's scoreboard, delete the sentence and show the company its own `baseline.csv` instead.

---

## 30. Build checklist

Paste the block below to the agent that will build the tool. Then walk the list. The builder reads this whole file. The extraction model sees an invoice only as data. It does not see this file as something the message can override.

- [ ] Config rejects every blank `REPLACE`, every lock, a percentage key, and an `EXAMPLE` id in `live_dir`.
- [ ] Pure functions from section 4 exist and hold the rules. The prompt does not reimplement them.
- [ ] Section 25's twenty checks pass on the fixture, including journal hash `9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5`, tick hash `4f1d4cf39a01d64c20de116c3dd659e24014f1a15adf77b0a168ecd202ecd184`, German journal hash `8bd803161bb91e8bc51e8dfe49e15776b0b50773fb8fd48857ba6f4f5eda76ff`, and posted hash `632d6153ba0b93cca14a7664ec643782d302a6db0c62b08be439336d17a8305e`.
- [ ] A missing label cannot become an account. A human task cannot be completed by the model. A dependency cannot be edited off.
- [ ] Summaries match the locked hashes and say they have not been sent. Reports keep `CONTEXT`. The plant file does not classify a job the export left blank.
- [ ] `auto_post`, `write_erp`, and `transmit` stay off until a person turns them on after the gates. QuickBooks create stays off while `auto_post` is off.
- [ ] The model tool list contains `propose_labels` only. The ERP connection sits on the runner.
- [ ] A path outside `approved_store` writes nothing.
- [ ] `audit.jsonl` is append-only and records coded, completed, posted, sent, refused, and reported.
- [ ] The morning file has this company's counts and has no target taken from Pamarco.
- [ ] One closed period has been compared by hand, in shadow, before a task is marked complete in the ERP.
- [ ] Ten read-backs have matched to the cent before `auto_post` is turned on. The allowlist is the controller's. A person, not the agent, sends the first summaries.

```text
You are building the finance close and invoice-coding tool specified in finance-close-agent-instructions.md. Build only what that file specifies.

Stack: Python 3.11 or newer. Standard library for the core. Money is integer cents. Timestamps have offsets and are compared in UTC. The decimal string of 8000 cents is 80.00, built from integer division, not from a binary float. Canonical JSON sorts keys, uses comma and colon separators with no spaces, and ends with one newline. Put the rules in the pure functions load_config, load_world, assert_store, parse_amount, code_invoice, journal_canonical, eligible, run_hour, complete_task, post_journal, render_summary, render_reports, approval_token, record_decision, apply_erp_readback, run_regression, and daily_summary. Call them from a thin folder runner and from the tests. Do not reimplement the rules in the model prompt.

Fail closed. If any required config value is missing, blank, or the word REPLACE, do not serve a live run. If any id in live_dir starts with EXAMPLE, do not serve a live run. If confidence_min, success_target, or close_task_target is present, refuse to start. If auto_post, write_erp, or transmit is yes before its gate, refuse that flag. If shadow is yes while any of those three is yes, refuse to start. If a model tool is named send_email, post_journal, complete_task, set_account, or starts with data_, form_, or api_, refuse to start. If erp_mode is qbo and write_erp is yes while auto_post is no, refuse to start.

The only model tool is propose_labels, and only when external_model is yes. complete_task for a human and the one-journal post token are forms. A model call to either is prompt_ignored. Never invent an account, a tax code, a due date, or a job class. Never mark a human task complete. Never clear a dependency. Never post because a score looked like 0.95 or 0.80 or 0.40. Never translate a German label. Never replace CONTEXT. Never set posted true when the read-back differs. Never open a mail socket while transmit is no. Never read a path outside approved_store. Never emit 40 percent, 95 percent, 80 percent, five minutes, or five hours as this company's result.

The fixture must produce journal sha256 9e0236c598648aba8657e6388fcdba615219ccf2947bc04ed9ae983116ca9ee5, tick sha256 4f1d4cf39a01d64c20de116c3dd659e24014f1a15adf77b0a168ecd202ecd184, German journal sha256 8bd803161bb91e8bc51e8dfe49e15776b0b50773fb8fd48857ba6f4f5eda76ff, posted journal sha256 632d6153ba0b93cca14a7664ec643782d302a6db0c62b08be439336d17a8305e, and morning sha256 6658fe1400caea0e4ddce42dc6493959b3705f289bd715f20d433d0818a679ba. Section 25 must pass before a controller is asked to turn auto-post on, and before a file is treated as a journal the ledger has already accepted.
```
