# Run it locally

Editable source: [just-every/run-willow](https://github.com/just-every/run-willow).
For the no-Node installer and per-terminal PATH step, start with [README.md](README.md#run-it-locally).
For adapting an installation, also read [AGENTS.consumer.md](AGENTS.consumer.md).

```sh
rer install
rer setup --owner-email you@example.com
rer dev
```

Enter the real owner mailbox through the setup prompt or `--owner-email` (or a
private answers file inside the checkout: `--answers exports/answers.json
--non-interactive`). `dev` prints `RER_OPEN`, which opens Willow signed in as
the owner; `dev --as hr|payroll|it|manager|employee` prints one for a persona
(real local members at `<as>@dev.localhost`, defined in `src/dev-personas.ts`);
the legacy `dev --login` flag uses the same automatic sign-in. No external mail is
sent and no provider account is needed. Stop servers with
`rer dev --stop` or `rer preview --stop`
before build, verification or deployment dry runs.

```sh
rer verify
rer reset --yes
rer export --output exports/installation.rer
rer import --input exports/installation.rer --yes
rer deploy --dry-run
rer describe
```

`verify` checks the source lock and Base copy record, builds, typechecks and
runs `tests/email-link.mjs` and `tests/willow/flows.mjs`. The browser journey
runs only in a disposable fresh clone: `WILLOW_TEST_CHECKOUT=1 pnpm run
test:journey` (it runs setup, dev, build, preview, export and import itself).
Reset is destructive local cleanup; import needs an empty destination. Read
`README.md` for the product and `SEED-COMMAND-CONTRACT.md` for the full
command contract.

## Product contract

[CONTRACT.md](CONTRACT.md) holds clauses WIL-01 to WIL-21 and
[ACCEPTANCE.md](ACCEPTANCE.md) the release scope, verification and owner trials.
Keep them true: a change to a guarantee changes its clause and its proof in
the same commit.

Rules that hold everywhere:

- Private data is read only through `personView` (`src/willow/profile.ts`) and
  the facets in `src/willow/access.ts`. Never select private contact fields
  (`wl_person_private`), pay (`wl_term_pay`), confidential reasons
  (`wl_leave_reasons`) or end reasons into a response by another route. Never
  infer a permission from managerial rank.
- Every GET door is listed in `src/willow/doors.ts`; `http.ts` and `views.ts`
  dispatch only through it and WIL-03 crawls every entry. Add a door there.
- Employment is effective-dated: terms rows are complete versions, never
  edited (database triggers refuse it); corrections are new versions or
  cancellations. Ending employment is an end date, never an archive flag.
- The leave ledger is append-only (triggers refuse UPDATE and DELETE). Balance
  checks and the entries they guard commit in one batch through `guard()` in
  `src/willow/core.ts`.
- Payroll calculation, tax and payments stay with the payroll provider; Willow
  hands off changes. External account and device work is never claimed done
  without the assignee's evidence.
- WIL-20 model calls use only the structural context in `model-drafts.ts`. Separately owner-enabled policy answers use HR-included approved policy clauses and permitted numeric leave inputs; assistant workflow calls use normalized structural requests. Raw questions and requests never leave Willow. Never pass a person projection, free-form prompt, template or task name, pay, document, absence reason or evidence. No simulated output in application code.
- Connection secrets live only in runtime bindings. Fixed email notices never include free text. Provider failures must not roll back committed business work.
- Payroll exports require a complete owner mapping and preview; preserve both source and mapping transaction fences and freeze reviewed file bytes. See WIL-18–21 and CONNECTIONS.md.

## Layout

- `src/willow/` — the product. `core.ts` (errors, D1 helpers, audited commits,
  in-batch guards), `input.ts` (one reader for forms and JSON), `actor.ts`
  (session → member, permissions, the people they manage), `access.ts`
  (facets), `profile.ts` (the person projection and directory), one module per
  area (`employer`, `members`, `people`, `lifecycle`, `documents`, `leave`,
  `payroll`, `reports`, `proposals`), `actions.ts` (every write by name),
  `views.ts` and `doors.ts` (every read), `http.ts` (the doors), `ui/`
  (server-rendered pages, no client script), `movein/` (BambooHR kit on Base's
  import kit: `bamboohr.ts` mapping, `target.ts` native targets, `tables.ts`
  CSV/XLSX/ZIP readers).
- `migrations/core/` — numbered D1 migrations: 0001–0005 Base auth, outbox,
  portability, first-run and identity providers; 0006 Willow; 0007 the original import
  kit schema and 0008 Connections. Forward migrations 0009–0018 adopt token
  health and current Base auth/import schemas (generated by `scripts/willow/import-kit-migration.mjs`). Never
  edit an applied migration; add the next number.
- `src/modules/` and `src/base/` — current Base runtime, operator auth, mail
  and import kit, recorded byte-for-byte in `base-copies.json`. Applied
  migrations retain their original provenance in `migrations/base-copies.json`,
  verified separately because their historical bytes must not be refreshed. The maintained CLI is the exact
  `@runeditrun/rer` package in `package.json`; there is no vendored CLI.
  `scripts/edition-authoring/` verifies copies and `sources.lock.json`.
  Re-run `node scripts/edition-authoring/cli.mjs lock` after intentional edits.
  `src/base/font-head.ts` is Willow's own font preload (Figtree).
- `tests/willow/` — `flows.mjs` (one check per clause against the built
  Worker), `journey.mjs` and `restore.mjs` (browser and recovery from a fresh
  clone), `fixtures.mjs` (documented-shape BambooHR fixtures, invented people).

## Agents operating Willow

Every page action has a JSON twin, so an agent can run Willow with a
signed-in session cookie and sees exactly what that member may see. Reads are
`GET /api/willow/` plus a path from `src/willow/doors.ts` (`me`, `progress`, `people`,
`people/:id`, `context/:id`, `organization`, `cases/:id`, `tasks`, `leave/:id`, `approvals`,
`quote?account&startDate&endDate`, `payroll`, `payroll/:id`, `reports`,
`proposals`, `proposals/:id`, `change-requests`, `change-requests/:id`, `upcoming-dates`, `imports`, `audit`, `settings`, `policies`,
`templates`, `members`, `preview?member&person`, `permissions`). Writes are
`POST /api/willow/ACTION` with a JSON body and an `Origin` header equal to the
app origin; the action names are the keys of `src/willow/actions.ts`. Files go
as `{ "filename": "...", "base64": "..." }`.

Managers request dated title, department, location, manager, schedule, employment-type or pay changes for a direct report with `change.request` (FLOW-004); `change.decide` (approve, return with a comment, decline) and `change.edit` follow HR's chain from `change.chain`. HR defines date alerts with `dateAlert.define` (PEOPLE-004); the scheduler fires them and `upcoming-dates` lists them within the reader's access.

To prepare a joiner or mover for HR, `POST /api/willow/proposal.create` with
`{ kind: "joiner" | "mover", summary, agent, plan }`, where `plan` holds the
same fields as `joiner.start` or `mover.schedule`. The response lists missing
information and the exact changes; HR approves it on `/app/proposals/:id`, and
it is refused if the records changed meanwhile. To explain a record, read
`GET /api/willow/context/:personId` (with `me` as the id for yourself): it holds only what the
member may read, names what is withheld, and cites the leave policy versions —
answer from it, cite the version, and say what is withheld rather than guess.

Named access levels (partial ROLE-001/003, DONE ROLE-002) are reviewed by the owner or explicit employer-wide HR access administrators on `/app/access`: `level.preview` creates an immutable review, `level.apply` consumes it once, and `levels`/`level-reviews/:id` require that administration right. ROLE-003 uses explicit access.admin plus employer-wide people.manage, never implied by HR alone. access.admin may be owner-assigned for Everyone or a structural group; group delegates may change only currently in-group targets and structurally contained definitions, never a shared definition with out-of-group assignees. Level lists and pickers use the administrative projection, while internal review validation uses complete levelData so hidden assignees cannot bypass the ceiling. API credentials still require employer-wide access.admin. levels/delegation.ts bounds every permission, personal mode and about-others field and rejects self/owner/re-delegation/EEO changes; pay/payroll/compensation approvals need the owner or a distinct eligible administrator. Native grant and Base role changes share the guarded batch, preserving Base version and last-owner triggers. All permission SQL reads use `wl_effective_permissions`, the union of explicit direct grants and assigned level grants. Keep actor, picker, import and restored-identity authority on that same view. `member.permissions` replaces every source; ending access clears assignments too. Personal self-write modes for seven fields (including legal name, whose default is HR approval) use `levels/personal.ts`; explicit assigned modes union as edit > approval > view, and absent rules preserve existing self-service rights. The explicit employer-wide compensation.approve permission also requires people.manage and pay.read for COMP-001 budget and publication; compensation/authority.ts fences the current rights and live session and cycles.ts still refuses own proposals and own compensation. Approval routes through the SELF-001 immutable queue; current mode and native revision are checked again at HR approval. Scoped personal fields about others use `levels/other-personal.ts`: `otherFields` in level.preview maps the same seven field names to none/view/approval/edit, with native form inputs otherMode.FIELD. No additional access contributes nothing and never denies another source. `person.field` edits exactly one permitted other-person field with its revision, while `self.request` kind personal accepts an optional person and reuses immutable HR approval. Actor otherPersonal grants remain separate from broad permissions; personView selects each readable private field, and visibilityPreview intersects both readers. Document-category reads use levels/documents.ts: documentCategories {self:{CATEGORY: none|view|approval|edit},others:{CATEGORY: none|view|approval|edit}} on level.preview. Self rights are independent of a level scope; others follow it. readsCategory is shared by metadata, preview, files and bundles; document-write.ts alone applies native Edit and document.propose routes approval-required uploads and revisions to SELF-001. Pending versions share existing native native document and object storage custody, stay out of ordinary projections and use document-publication.ts for current published versions. Only current proposal participants or category-authorized HR inspect pending bytes; decisions recheck current actor, category, scope and revision and never permit self approval. Selected saved reports use levels/reports.ts and wl_level_reports; level.preview reports lists IDs and native forms include reportSelection. reportAdmission is only for admitting selected people; the actual actor still governs fields and work. Saved-report-only holders gain no summary, general export, profile, editing, schedule configuration or other recipient authority; the scheduler rechecks selected grants before its fixed authenticated link. Other section rights remain unimplemented.

## Tests

Keep tests to flows a person would notice breaking, through public doors, one
check per clause, with fakes only at provider edges. Private-field access, effective dating, the leave ledger and import undo
are high-stakes: they keep their real proofs. No pin tests (hashes, versions,
file lists, UI copy, thresholds). Prove a one-off fix with before/after
evidence instead of a new permanent test.

People records and agent contexts accept `?asOf=YYYY-MM-DD` with current reader permissions. The directory accepts the same date plus `q`, `name`, `location`, `department`, `role` and `status`; `GET /api/willow/organization?asOf=YYYY-MM-DD` returns directory-only manager/report links and its active count. Manager changes and cancellations refuse effective-date cycles, including through BambooHR move-in.

Lifecycle templates save as drafts through `template.create`. Review with `template.preview` and publish the returned review through `template.publish`; any intervening audited event requires a fresh review. Conditional task rules use the same planner for joiners, approved employee-change movers, leavers and reviewed case upgrades (`case.upgrade.preview`, then `case.upgrade`). External steps remain assigned work requiring evidence; `task.fail` leaves them open.

Native move-in uses only Base's shared import door (`src/willow/movein/door.ts`).
The signed-in owner's forms call that same handler; `import.preview`,
`import.apply` and `import.job` no longer exist. Read IMPORTING.md for the
upload envelope, owner/Business authority, reviewed plans and reversible catch-up.
Migration 0021 adds current kit evolutions and the door without rewriting
applied migrations. DATA-002's future erasure inventory includes all door custody.

HIRING-003's partial manual pipeline has native forms at `/app/hiring`, `/app/hiring/openings/:id` and `/app/hiring/applications/:id`, using the same actions as its API: `hiring.opening` (HR creates initial name/stages/members), `hiring.team` (HR replaces members with opening/revision), `hiring.candidate` (opening/name/contactEmail/source), `hiring.move` (application/revision/stage) and `hiring.scorecard` (application/version/evidence; author is always the current member). Reads: `hiring`, `hiring/openings/:id`, `hiring/applications/:id`. HR or the current explicit opening team alone can read or act. Contact email is not verified identity; never use it for automatic merging or cross-opening disclosure. Calendar/email and ct's approved verified/reversible merge flow remain unimplemented.

ROLE-002 bulk assignments reuse `level.preview` with `kind: "bulk-assignment"`, `members` and `levels`, then the same one-use `level.apply`. Current owner administration, immutable per-member impact and the audited snapshot fence are shared with single assignments. The batch replaces assigned levels only; direct grants survive. Filter selection uses `selection: "filter"` and existing directory filters at today's employer-local date; the review fixes the resolved member list. `kind: "revert", batch: "<applied-review-id>"` reviews restoring each captured prior assignment, preserving direct grants. Related later business work, ended/changed access and edited level definitions refuse revert; unrelated work and read/download/export audits do not. Revert consumes one immutable review with the same transaction fence. A level's scope rides `level.preview` `kind: "level"` as `scope: {kind: "everyone"|"direct"|"indirect"|"group", dimensions?: {location|department|division|legal_entity|employment_type|field:<id>: [values]}}` (forms: `scopeKind`, `scopeLocation`, `scopeDepartment`, `scopeDivision`, `scopeLegalEntity`, `scopeEmploymentType`, `scopeField`, `scopeFieldValue`). A division groups departments (`division.create`, `department.division`); a legal entity belongs to an employment period (`entity.create`, `period.entity`); omitted keeps the level's scope. Rights of a scoped level are never in `actor.permissions` or `wl_effective_permissions`: read them per person with `canAbout`/`permissionsAbout` (`src/willow/actor.ts`), never `can`, and use `scopeFence` for a per-person write. Only the permissions in `SCOPEABLE` (`src/willow/levels/scope.ts`) may sit in a scoped level; a new per-person door that should follow a scope must use those helpers, and a door that uses `can` stays employer-wide.

ROLE-001 subject-follow is the default-off `followOwnChanges` level setting, reviewed through `level.preview`/`level.apply`. `change-requests/status.ts` is the sole minimal projection for subject-only list/detail reads, used only after existing full-read precedence. It grants no work, attachment or decision authority; direct permissions cannot grant it.

HIRING-003 resumes use `hiring.resume` with application, prior version and file. The candidate page lists immutable versions; its `?resume=<id>` download checks the current opening team/HR and application/version pair, then serves a checked attachment. Resume bytes share FILES custody; they never become employee documents. Include this table/blob custody in future DATA-002 erasure.

EEO-003 uses HR `preboarding.send` / `preboarding.withdraw` and `/app/preboarding`; scoped bearer mail links reach only `/preboarding/:token`. `joiner.start` accepts `preboardingPacket` and copies immutable EEO answers atomically without exposing them to HR's response. HR `hiring.selfId.invite` / `hiring.selfId.withdraw` send/revoke `/applicant-self-id/:token`; `hiring.close` records explicit closure with application/opening revisions. Only unscoped `eeo.individual` opens `eeo/preboarding/:id` or closed `eeo/applicants/:id`, and an opening-team member cannot read that opening's applicant answers. The invitation HTTP door accepts JSON with the same scoped authority; it creates no employee session. DATA-002 request/preview/confirm also accept `preboarding` for expired or withdrawn packets. Keep future HIRING-003 merges per application and keep HIRING-004 proposals free of applicant EEO.


## Contract document synchronization

CONTRACT.md is the acceptance and status source. After changing a clause, run
`node scripts/willow/contract-docs.mjs write CLAUSE...` and the same command with
`check`; include each changed clause ID. This synchronizes its existing acceptance
entry and the generated delivery register in docs/CLAIMS.md. Regenerate the
edition lock last with `node scripts/edition-authoring/cli.mjs lock`.

Lander-Regenerate: node scripts/willow/contract-docs.mjs write BASE-AGENT-001 BASE-AGENT-002 BASE-AGENT-003 BASE-AGENT-004 BASE-AGENT-005 BASE-AGENT-006 BASE-AGENT-007 BASE-AGENT-008 BASE-AGENT-009 BASE-AGENT-010 BASE-AGENT-011 BASE-AGENT-012 BASE-AGENT-013
