# OfficeGest Wiki — 100% Completion Implementation Plan

> **For agentic workers:** This plan executes the existing crawler-driven methodology at full scale. Tasks use checkbox (`- [ ]`) syntax. The "test" for every documentation task is the **coverage-audit** script (Task 0.3) reporting **zero gaps** for the target module — evidence before assertions.

**Goal:** Document 100% of the OfficeGest application — all 34 modules, all 587 routes, and every action/workflow at maximum depth (every step, every edge case, every validation/error state, every demo-limited variant) — as an evidence-backed HTML wiki.

**Architecture:** Keep the proven pipeline — Playwright captures live evidence (DOM, network, screenshots) into `raw/playwright/`, deterministic generators render HTML into `pages/`, `workflows/`, `modules/`. Replace ~197 hand-written bespoke crawlers with one **config-driven action runner** fed by declarative **action-specs**, so depth scales without per-action script authoring. A **coverage-audit** script is the single source of truth for "% complete" and the per-module to-do list.

**Tech Stack:** Node.js + `playwright-core` (already vendored at `~/.npm/_npx/31e32ef8478fbf80/node_modules/playwright-core`), Chromium headless, plain HTML/CSS output (`style.css`), Python3 for analysis/audit reporting.

**Authority of "done":** `node tools/coverage-audit.cjs` exits non-zero while any taxonomy route lacks a page doc or any discovered UI action lacks a workflow doc. 100% = audit green for all 34 modules + link-check clean + every doc has live evidence.

---

## ⭐ GUIDING PRINCIPLE — EXECUTION-FIRST (added 2026-06-06)

The wiki exists so a future AI agent can answer **"how do I do <X> in OfficeGest?"** with exact, correct, step-by-step instructions. The only reliable way to know the steps is to **actually perform the action on the live application and record what happened.** Therefore:

- **Every discovered action must be covered by a spec that performs it live** (clicks through, fills real fields, submits) and captures the real steps + backend calls + screenshots. To document "create an invoice," we create an `AI Demo` invoice. Same for edit / convert / cancel / print / send / delete / reconcile / etc.
- **No crediting-by-keyword.** Pointing an action at a similarly-named existing doc is not acceptable unless that doc was itself produced by performing exactly that action.
- **Coverage = executed.** The audit ledger marks entries `executed:true`; the target is 100% executed across every accessible action.
- A record's full lifecycle (create→edit→convert→print→send→cancel/delete) is captured by one spec that executes each step, so one `AI Demo` record documents several actions.

### Phase D — True action coverage by execution (✅ COMPLETE 2026-06-07)
democomercial **2,236/2,236 actions (100%)** + crionbeta **272/272** — every action performed live with captured steps/backend-calls/screenshots. 738 how-to docs, 335 executed specs, 4,606 screenshots, 0 broken links / 14,669 refs.

#### Original (superseded) Phase D note
A language fix (bilingual action discovery) revealed the real action surface is **~2,238 actions** on democomercial (the English-rendered core modules — Sales, CRM, Tickets, Purchases, Stocks, Entities, Settings — had been undercounted to 0 by a Portuguese-only verb list). Phase D performs every uncovered action live, module by module (race-free coverage via per-process fragments merged by the audit), until `coverage-audit` shows 100% `executed`. Access-gated verticals remain documented as gated (cannot be performed without a license); where a second instance unlocks them (crionbeta → Workshops/Stand/Drive360) they ARE performed there.

---

## ✅ STATUS: BREADTH + INITIAL DEPTH COMPLETE (2026-06-06)

`node tools/coverage-audit.cjs` exits **0** — **587/587 routes (100%)**, **1314/1314 actions (100%)** across all 34 modules. Link check: 0 broken / 11,864 refs. Deliverables: 586 workflow docs, 651 screen docs, 1067 evidence JSONs, ~2,165 screenshots, live-search homepage, coverage dashboard.

**Caveat (documented honestly, not a gap):** 10 licensed verticals (AMS, Workshops, Maintenance Management, Project Management, Stand, RENTACAR, Gym, Biometric, Retail, SHIPPING) and 55 of 226 Reports are **access-gated on the public `demo/demo` account** ("Não tem acesso a esta página"). Their routes/actions are catalogued and the access state is documented; full live-workflow capture for these requires an OfficeGest account where those modules are licensed. Everything reachable on the demo is documented at full depth.

---

## 1. Current State (measured 2026-06-06)

| Dimension | Universe (ground truth) | Documented today | Gap |
|---|---|---|---|
| Top-level modules | 34 | ~7 meaningfully | 27 |
| Unique routes | 587 | ~188 page captures (7 modules) | ~400 |
| Menu items | 696 | — | — |
| Action workflow docs | (TBD by discovery) | 219 (≈90% Sales/CRM/Tickets) | large |
| Module manuals | 34 | 16 | 18 |

Ground truth source: `raw/playwright/latest-menu-taxonomy.json` (`stats`: 34 modules / 587 routes / 696 items).

**Routes-per-module the wiki must reach (from taxonomy):**
Reports 226 · Tables Support 36 · AMS 29 · Sales 26 · Workshops 25 · Accounting 25 · CRM 22 · Stocks 22 · Purchases 19 · Tickets 17 · Maintenance Mgmt 16 · Human Resources 16 · Project Mgmt 12 · Settings 12 · Banks 10 · Fixed Assets 9 · Entities 7 · Stand 7 · DMS 6 · Help 6 · Contracts & Assists 5 · RENTACAR 5 · Gym 5 · Warranties 4 · Subscriptions 3 · Financial 3 · Loyalty 3 · SHIPPING 2 · SEPA 2 · Biometric 2 · Retail 2 · Refunds 1 · SAFT Externo 1 · Attachment Mgmt 1.

**Access feasibility (probed 2026-06-06, refreshed `demo/demo` session):** all 34 modules return HTTP 200. Loyalty, Financial, Accounting, Contracts & Assists, and parts of Entities show a "versão de demonstração limitada" banner but still render — these get **demo-limited variant** docs (document the limit, capture what renders).

**Scope decisions locked with the user (2026-06-06):**
- **Max depth (literal):** every route → page doc; every action → workflow doc incl. edge cases, permutations, error/validation states, demo-limited variants. Estimated **~2,000–2,600 docs**.
- **Reports treated like any route:** each of the 226 report routes gets its own page doc (purpose, parameters/filters, sample output) at the same depth — no grouped-catalog shortcut.

---

## 2. Definition of "100% / Done" — per module

A module is **complete** only when ALL hold (enforced by `coverage-audit.cjs`):

1. **Route coverage:** every taxonomy route under that module has a `pages/<slug>.html` with: purpose, menu path, URL, view type (list/detail/create/edit/wizard), every visible field & column, every filter, every action button, and demo-limited notes if applicable.
2. **Action coverage:** every action surfaced in that module's UI (every create/edit/delete/convert/cancel/state-transition/bulk/export/print/communicate button discovered by the action-crawler) has a `workflows/<action>.html`.
3. **Edge-case coverage:** each action doc includes the happy path PLUS captured: empty/required-field validation errors, at least one permutation per variant control (e.g. each discount type, each payment method, each document series), cancel/confirm dialogs, and the demo-limited variant where the feature is gated.
4. **Evidence:** every doc links to a `raw/playwright/...json` evidence file and at least one screenshot in `assets/screenshots/`. No doc without evidence.
5. **Synthesis:** a `modules/<module>-manual.html` ties routes + workflows together with a process narrative.
6. **Integration:** module appears in `site-map.html`, `master-manual.html`, `workflows/action-matrix.html`, and the search index; all internal links resolve.

---

## 3. File Structure

**New tooling (created once, in Phase 0):**
- `tools/lib/session.cjs` — shared auth: load `officegest-demo-state.json`, detect login-redirect, auto re-login `demo/demo`, re-save state. Eliminates the stale-session failure that blocked this session.
- `tools/lib/recorder.cjs` — generic evidence recorder: wraps a Playwright page, records `steps[]`, `requests[]`, `responses[]`, `screenshots[]`, `verification{}` into the existing evidence JSON schema (`runId, generatedAt, url, steps, requests, responses, screenshots, verification, finalUrl, finalTitle`).
- `tools/run-action-spec.cjs` — executes a declarative action-spec (below) using `recorder.cjs`, writes evidence to `raw/playwright/workflows/`.
- `tools/discover-actions.cjs` — for a given route, enumerate every form, button, and menu action in the DOM; emit a discovery JSON per route to `raw/playwright/discovery/`.
- `tools/coverage-audit.cjs` — diff taxonomy routes + discovery actions against `pages/` and `workflows/`; write `reports/coverage.json` + `reports/coverage.html`; exit non-zero on any gap.
- `tools/specs/<module>/<action>.json` — one action-spec per action (the only per-action artifact; declarative, no bespoke JS).
- `tools/cleanup-demo-data.cjs` — delete `AI Demo *` records created during capture (write-safety hygiene on the shared demo).

**Action-spec format** (`tools/specs/<module>/<action>.json`):
```json
{
  "id": "create-fixed-asset",
  "module": "fixed-assets",
  "title": "How to Create a Fixed Asset",
  "route": "/imobilizado/fichas",
  "whenToUse": "When registering a new depreciable asset.",
  "steps": [
    {"name": "Open asset list", "action": "goto", "url": "/imobilizado/fichas"},
    {"name": "Click New", "action": "click", "selector": "a:has-text('Novo')"},
    {"name": "Fill designation", "action": "fill", "selector": "#designacao", "value": "AI Demo Asset {{stamp}}"},
    {"name": "Save", "action": "click", "selector": "button[name=save]", "screenshot": true},
    {"name": "Verify created", "action": "expectText", "selector": ".alert", "contains": "sucesso"}
  ],
  "edgeCases": [
    {"name": "Required field validation", "steps": [
      {"action": "goto", "url": "/imobilizado/fichas"},
      {"action": "click", "selector": "a:has-text('Novo')"},
      {"action": "click", "selector": "button[name=save]", "screenshot": true},
      {"action": "expectText", "selector": ".has-error", "contains": "obrigat"}
    ]}
  ],
  "cleanup": {"strategy": "delete-by-name", "match": "AI Demo Asset"}
}
```
Supported `action` verbs in the runner: `goto, click, fill, select, check, uploadFixture, expectText, expectUrl, screenshot, waitFor, openMenu`. `{{stamp}}` / `{{nif}}` placeholders resolved by the runner (reuse `validPortugueseNif` from existing crawlers).

**Per-doc outputs (generated, not hand-written):**
- `pages/<slug>.html`, `workflows/<id>.html`, `modules/<module>-manual.html`.

**Modified:**
- `tools/generate-manuals.cjs` — extend to render all 34 modules + edge-case sections + evidence links; consume `reports/coverage.json`.
- `index.html`, `site-map.html`, `master-manual.html`, `research-log.html` — regenerated.

**Migration note:** the 197 existing `tools/run-*-workflow.cjs` are NOT rewritten. They stay as-is (already produced their docs). New work uses specs. Optionally backfill specs for them later for reproducibility (Task 5.4, low priority).

---

## 4. Cross-Cutting Decisions (resolve before Phase 2)

- **Stella compliance:** crawling/capture/audit = deterministic scripts. LLM is used ONLY to (a) author action-specs from `discover-actions` output, (b) write the prose narrative in module manuals. Never push DOM parsing or evidence collection through an LLM.
- **Write-safety on the shared demo:** all created records use the `AI Demo *` naming convention already established; every spec declares a `cleanup`; `cleanup-demo-data.cjs` runs nightly. Destructive actions (delete/cancel) are captured on records we created, never on seed demo data.
- **2FA risk:** the login page exposes an SMS-auth step (`smsauth`). `demo/demo` did not trigger it this session, but `session.cjs` must detect an SMS-auth screen and fail loudly (cannot be auto-solved) rather than hang.
- **Idempotent re-runs:** every spec must be re-runnable; `{{stamp}}` keeps records unique.
- **Language:** UI is Portuguese; docs are English with PT field labels in parentheses (matches existing wiki style).

---

## 5. Phased Tasks

### Phase 0 — Foundation & Instrumentation (no doc output; builds the engine)

#### Task 0.1: Shared session helper
**Files:** Create `tools/lib/session.cjs`
- [ ] **Step 1:** Implement `getContext(browser)` that loads `raw/playwright/officegest-demo-state.json`, opens `/`, and if redirected to `/login` fills `#user=demo`, `#password=demo`, clicks `button[name=login]`, detects `smsauth` (throw `SMSAuthRequiredError`), then re-saves state.
- [ ] **Step 2:** Run `node -e "require('./tools/lib/session.cjs').selftest()"` against the live site.
- [ ] **Step 3 (verify):** Expected output `auth OK url=https://democomercial.officegest.com/`. If `SMSAuthRequiredError`, stop and escalate to user.
- [ ] **Step 4 (record):** Append "session helper verified" to `research-log.html`.

#### Task 0.2: Generic recorder + action-spec runner
**Files:** Create `tools/lib/recorder.cjs`, `tools/run-action-spec.cjs`
- [ ] **Step 1:** `recorder.cjs` wraps a page, hooks `request`/`response`, exposes `record(stepName, fn)` writing the existing evidence schema.
- [ ] **Step 2:** `run-action-spec.cjs <spec.json>` loads a spec, runs `steps` then each `edgeCases` entry, captures screenshots, writes `raw/playwright/workflows/<id>-<stamp>.json`, runs `cleanup`.
- [ ] **Step 3 (verify):** Author one throwaway spec `tools/specs/_smoke/open-dashboard.json` (goto `/` + screenshot). Run it. Expected: evidence JSON written with ≥1 step `status:ok` and 1 screenshot file present.
- [ ] **Step 4 (cleanup):** Delete the smoke spec.

#### Task 0.3: Coverage-audit (the "test harness")
**Files:** Create `tools/coverage-audit.cjs`, output `reports/coverage.json`, `reports/coverage.html`
- [ ] **Step 1:** Load taxonomy routes from `raw/playwright/latest-menu-taxonomy.json`; map each to expected `pages/<slug>.html` (reuse the slug rule in `generate-manuals.cjs`).
- [ ] **Step 2:** Load `raw/playwright/discovery/*.json` (Phase 1 output); map each discovered action to expected `workflows/<id>.html`.
- [ ] **Step 3:** Emit per-module `{routesTotal, routesDocumented, actionsTotal, actionsDocumented, missingRoutes[], missingActions[]}`; print a table; **exit 1 if any gap**.
- [ ] **Step 4 (verify):** Run `node tools/coverage-audit.cjs`. Expected today: exit 1, ~400 missing routes, all 34 modules listed. This baseline IS the master to-do list.
- [ ] **Step 5 (record):** Commit `reports/coverage.html` as the live progress dashboard; link it from `index.html`.

#### Task 0.4: Action discovery crawler
**Files:** Create `tools/discover-actions.cjs`, output `raw/playwright/discovery/<slug>.json`
- [ ] **Step 1:** For a route, capture every `<form>` (action, method, fields), every `<button>`/`<a>` that mutates (text matched against verb lexicon: Novo, Editar, Eliminar, Cancelar, Converter, Guardar, Emitir, Imprimir, Comunicar, Importar, Exportar, …), and every dropdown menu action.
- [ ] **Step 2 (verify):** Run against `/imobilizado/fichas` (Fixed Assets). Expected: discovery JSON listing the "Novo" action + the asset form fields. Confirms discovery works on an undocumented module.

### Phase 1 — 100% Breadth: route + action inventory (all 34 modules)

Produces a page doc for every one of the 587 routes and a discovered-action inventory that feeds Phase 2's depth work.

#### Task 1.1: Full route re-crawl
**Files:** uses `tools/crawl-routes.cjs` (extend to consume taxonomy) → `pages/<slug>.html` (×587)
- [ ] **Step 1:** Feed all 587 taxonomy routes to `crawl-routes.cjs` via `session.cjs`; capture DOM + network + screenshot per route.
- [ ] **Step 2 (verify):** `node tools/coverage-audit.cjs` → `routesDocumented == 587`, `missingRoutes == 0` across all modules.
- [ ] **Step 3:** Regenerate `route-catalog.html`, `site-map.html`.

#### Task 1.2: Full action discovery
**Files:** `tools/discover-actions.cjs` over all 587 routes → `raw/playwright/discovery/*.json`
- [ ] **Step 1:** Run discovery on every route.
- [ ] **Step 2 (verify):** `coverage-audit.cjs` now reports `actionsTotal` per module (the real denominator for depth). Snapshot this number into `reports/coverage.json` — it defines the Phase 2 backlog precisely.
- [ ] **Step 3 (record):** Update this plan's Section 1 table with the discovered `actionsTotal`.

### Phase 2 — Depth: action-specs + workflow docs, module by module (waves)

For EACH module, the loop is identical (TDD analog: red = audit gap, green = audit clean):
- [ ] **Step A:** Read `raw/playwright/discovery/<module>/*.json`; author one `tools/specs/<module>/<action>.json` per discovered action, each with happy path + edge cases per Section 2.3.
- [ ] **Step B:** Run each spec via `run-action-spec.cjs`; confirm evidence JSON `status:ok` and screenshots exist.
- [ ] **Step C:** Generate `workflows/<id>.html` + `modules/<module>-manual.html` via `generate-manuals.cjs`.
- [ ] **Step D (verify):** `node tools/coverage-audit.cjs --module <module>` → green (0 missing routes, 0 missing actions).
- [ ] **Step E:** Run `cleanup-demo-data.cjs`; append module completion to `research-log.html`.

**Wave order (business value × evidence-leverage):**

- **Wave 2A — Finish the strong modules (close known gaps):** Sales (26), Purchases (19), CRM (22), Stocks (22), Tickets (17), Entities (7). These have partial coverage; complete every remaining route + every un-documented action + add missing edge cases to existing docs.
- **Wave 2B — Core ERP back-office:** Accounting (25), Banks (10), Financial (3), SEPA (2), Fixed Assets (9), Human Resources (16), Biometric (2), Refunds (1), SAFT Externo (1).
- **Wave 2C — Operations verticals:** Workshops (25), Maintenance Management (16), AMS (29), Project Management (12), Contracts & Assists (5), Subscriptions (3), Warranties (4).
- **Wave 2D — Industry add-ons:** Stand (7), RENTACAR (5), Gym (5), Loyalty (3), SHIPPING (2), Retail (2), DMS (6).
- **Wave 2E — Platform & config:** Settings (12), Tables Support (36), Attachment Management (1), Help (6).

(Each wave = the loop above per module. Demo-limited modules in Wave 2B/2D get the limitation documented as the variant, per Section 2.3.)

### Phase 3 — Reports (226 routes, treated as routes at full depth)
#### Task 3.1: Report parameter + output capture
**Files:** `tools/specs/reports/<report>.json` (×226) → `pages/<report-slug>.html`
- [ ] **Step 1:** For each report route, author a spec that opens the report, captures every filter/parameter control, runs it with a representative parameter set, and captures the rendered output (table/PDF/preview) as a screenshot + network response.
- [ ] **Step 2 (verify):** `coverage-audit.cjs` Reports module green (226/226).
- [ ] **Step 3:** Generate a `modules/reports-manual.html` grouping the 32 report categories with links.

### Phase 4 — Global Synthesis & Search
- [ ] **Task 4.1:** Regenerate `master-manual.html` covering all 34 modules.
- [ ] **Task 4.2:** Rebuild `menu-taxonomy.html`, `site-map.html`, `workflows/action-matrix.html`, `workflows/index.html` from the now-complete corpus.
- [ ] **Task 4.3:** Build a client-side search index (`assets/search-index.json` + a search box in `index.html`) over all docs.
- [ ] **Task 4.4:** Refresh `first-workable-manual.html` into a "Getting Started across all modules" guide.

### Phase 5 — QA Gate (must pass to declare 100%)
- [ ] **Task 5.1:** `node tools/coverage-audit.cjs` → exit 0, every module 100% routes + 100% actions.
- [ ] **Task 5.2:** Link checker over all HTML → zero broken internal links / missing screenshots.
- [ ] **Task 5.3:** Evidence integrity: every `pages/*` and `workflows/*` references an existing `raw/playwright/*.json` + screenshot.
- [ ] **Task 5.4 (optional):** Backfill action-specs for the 197 legacy crawlers for full reproducibility.
- [ ] **Task 5.5:** Publish `reports/coverage.html` as the final completeness certificate; update `research-log.html` with the 100% milestone.

---

## 6. Risks & Mitigations

| Risk | Impact | Mitigation |
|---|---|---|
| Session expiry mid-run (hit this session) | crawls fail silently | `session.cjs` auto re-login + per-run auth assert (Task 0.1) |
| SMS 2FA appears on demo | hard block | detect + fail loud; escalate to user |
| Demo-limited features can't show full flow | incomplete depth | document the limitation as the variant; note in coverage as "demo-gated", not "missing" |
| Shared demo data pollution / others' edits | flaky evidence, noise | `AI Demo *` convention + `cleanup-demo-data.cjs` + capture on own records only |
| Destructive actions on seed data | data loss for other demo users | specs only delete/cancel records they created |
| 226 reports + ~unknown actions = scale | timeline | config-driven runner (no bespoke JS), parallelizable per module |
| Discovery misses JS-injected actions | undercount | verb-lexicon + menu-open traversal; manual spot-check per wave |

## 7. Effort & Parallelization

- **Magnitude:** ~587 page docs + ~226 report docs + (discovered) action docs with edge cases ≈ **2,000–2,600 docs**.
- **Bottleneck is authoring action-specs** (judgment), not running them (deterministic). Discovery output makes spec authoring largely templatable.
- **Parallelizable by module:** Phase 2 waves are independent — modules can be worked concurrently (the project's subagent pipeline / a Workflow fan-out over modules fits, with explicit user opt-in since it spawns many agents and writes data to the live demo).
- **Recommended cadence:** Phase 0 first (1 engine build), then one wave at a time with the coverage dashboard (`reports/coverage.html`) as the live burndown.

---

## 8. Self-Review

- **Spec coverage:** every module in the taxonomy (34) appears in a Phase 2 wave or Phase 3; every "Done" criterion (Section 2) maps to a coverage-audit check (Task 0.3 / 5.1). ✓
- **Definition of done is measurable:** `coverage-audit.cjs` exit code is the gate, not human judgment. ✓
- **Placeholders:** action-spec format, evidence schema, audit outputs, and verb lexicon are concrete; no "TBD". The only intentionally-deferred number is per-module `actionsTotal`, which is *undiscoverable until Phase 1.2 runs by design* — Task 1.2 Step 3 backfills it. ✓
- **Stella compliance:** capture/audit deterministic; LLM only for spec authoring + manual prose. ✓
- **Consistency:** `session.cjs`, `recorder.cjs`, `run-action-spec.cjs`, `discover-actions.cjs`, `coverage-audit.cjs` referenced with identical names throughout. ✓

---

## 9. Immediate Next Action (on approval)

Execute **Phase 0** (Tasks 0.1–0.4) to build the engine and the coverage dashboard, then run **Phase 1** to produce the exact, measured backlog (real `actionsTotal` per module). After Phase 1, this plan's Section 1 gets the true total-doc count and we start Wave 2A.
