Skip to content

docs: card of step 5, Duas empresas - #50

Merged
leandrotcawork merged 11 commits into
mainfrom
feat/conexus-e05-card2
Oct 17, 2026
Merged

leandrotcawork merged 11 commits into
mainfrom
feat/conexus-e05-card2

Conversation

@leandrotcawork

@leandrotcawork leandrotcawork commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Etapa 5: Duas empresas, cartão

The card docs/steps/e05-duas-empresas.md and the step 5 row of docs/roadmap.md. Documents only. No approval line yet: as 4.2 did, it goes in the step 5 build PR with the approved commit.

What it follows

The founder's answers of 2026-10-16, pre-approved with "2A" on that condition:

  • A: mandatory typed context plus native RLS.
  • B: the nine proofs.
  • Q6: only Conexus deletes, in the Central, with the typed name and the revision; a repeat gets the uniform 404.
  • H: two phases, v0.5.0 then v0.5.1.
  • I, J, L: as answered.
  • 4.2: the operator scope.

Units

  • U1: the proof (decision record 0039, then the proof locally and on Neon).
  • U2: the phase 1 roles and grants (own PR, D11).
  • U3: the scoped transaction and the policies.
  • U4: delete client on the server.
  • U5: the confirmation dialog.
  • U6: the two-company journey.
  • U7: phase 2, which revokes the Hub login's reach (own PR, D11).

Budget: 3,150 changed lines, with a split if it goes past that.

Critical reader

One reader, Claude Sonnet at medium effort, read the card at b8ef8b6. It found no Bloqueia. Its fixes are in d59e1e7:

  • Lock order: delete locks the client before the company, the same order as correction.
  • Operator scope: sees the person, the operators and the owners, and every member of the company being deleted.
  • B6 and B8: stated in full.
  • Name: the typed name is the display name.
  • Out of scope: hostile SQL run with the Hub login's own credentials.

For firstmate to confirm

Deleting the client also deletes its operations.client row, so the same CNPJ can be registered again. Firstmate's steering message 001 put operations.client inside the approved deletion; the founder's page says so explicitly. The reader called the CNPJ reuse a possible new decision. Its options were A, delete and allow re-registration; B, keep a tombstone; C, forbid the CNPJ for good. The card follows A.

CI

npm run docs fails with second-card until 4.2's card leaves docs/steps/ at its closing. This is delivery L5. npm run verify passed lint, typecheck, deps and knip and stopped at that check.

Ceiling trims (explanatory prose only, at the commit after 5faadd3)

The acceptance criteria are back to their full wording: 2, 3, 10, 11, 12, 13 and 16. To stay under the 4,000-word ceiling, these explanatory passages were shortened instead:

  • Opening sentence: "o banco recusa" and "de Operação" removed.
  • Decision A: the "Exemplo:" lead-in removed.
  • 4.2 seams F1–F8: one sentence each.
  • The transplant measure: "Basejump e Supabase são só referência" removed.
  • The debt line: the v0.5.1 note removed.
  • The state matrix intro: "Dono: Hub" and "Q6" removed.
  • The budget: the note on U1 shortened.
  • U1 step 3: the B5 address sentence shortened.
  • U3 step 2: the e-mail sentence shortened.
  • U3 step 4: the FORCE reason shortened to "(D9)". Decision 0039 states the full reason.
  • Founder-confirmed trim (a69cda1): removed the two words "enquanto isso" from "a construção segue local enquanto isso" on the founder's page; the founder confirms this trim.
  • Founder's B on replay after deletion (2026-10-17), 76af620 and the next commit: one sentence after "Apagar não deixa estado": "Repetir o cadastro com a chave antiga após apagar é cadastro novo (fundador, 2026-10-17: B)." Explanatory prose trimmed to offset it:
    • 4.2 seams: NotFound dropped from F6.
    • The debt line: "Fechamento (L19)" reworded.
    • The transplant line: shortened to "Transplante. Zero linhas."
    • The status row of U3's change radius: shortened.
    • U1 step 2: "fora de transação" and "do operador" dropped.
    • U3 step 2: the e-mail sentence shortened.

@leandrotcawork

Copy link
Copy Markdown
Collaborator Author

Reviewer: Claude Sonnet 5.5

Verdict: request changes (two Bloqueia, card text only).

Reviewer: Claude Sonnet 5.5 (medium effort), card docs/steps/e05-duas-empresas.md at origin/feat/conexus-e05-card2 (PR #50), read against the study (data/conexus-e05-study/report.md), the founder's answers in data/captain.md, the operator-console study (Q6), docs/guides/{data,delivery}.md, docs/reference/checklist.md, the conexus-scope skill and template, decision 0012, and the 4.2 build branch origin/feat/conexus-e042-build (head 14d6a27). Nothing in the repository was changed.

Verdict: request changes (two Bloqueia, both one-paragraph card edits; no new founder decision found that stops the build)

The card follows every answer A, B, H, I, J, L and Q6 in substance. Two things stop me from approving it as "exactly his answers": a process hole that makes his "2A" cover a grant list that does not exist yet (B-1), and one unguarded door in the "by construction" claim (B-2). The CNPJ choice is a consequence of his answers, not a new decision, but the page words it as if he had said it (F-5).

What I checked and how

4.2 seams F1–F8 (all exist as the card says)

Seam Evidence on origin/feat/conexus-e042-build
F1 identity/admission.ts:9-32 ACTIONS with by; :112 mayOperate; :189 admitOperator; union proof :109
F2 platform/database.ts:152-159 read/command/libraryCommand through inTransaction; :158 libraryOrm on the pool
F3 identity/auth.ts:214-218 organizationAdapter(auth) = getOrgAdapter
F4 migration 20261017010336_operations_client/migration.sql: revision, no FK; ...0337_operations_grants: SELECT, INSERT, UPDATE only; /api/clients routes in operations/client-reads.test.ts
F5 operations/clients.ts:121-127 .for('update') on the client, then identity/clients.ts:85 lockCompany; invitations invitation-management.ts:39 lock the company only
F6 apps/web/src/hub/operations/client.tsx:13 route /_app/operations/clients/$companyId
F7 hub-api/src/operations.ts:32,56 revision; failures.ts:241-244 CLIENT_STALE 412
F8 auth.ts:201 allowUserToCreateOrganization: false
Library facts the card cites also hold at the installed 1.7.8: organization/adapter.mjs:370-390 deletes members, then invitations, then the company inside runWithTransaction; crud-org.mjs:255 disableOrganizationDeletion answers NOT_FOUND; :263- the native route needs the caller's membership (so auth.api.deleteOrganization is rightly avoided).

RLS by construction (the brief's checklist)

  • Policies on every company table plus auth.user: yes (criterion 1, table in U3).
  • Runtime role not owner, not BYPASSRLS: yes (D10; roles NOLOGIN NOINHERIT NOBYPASSRLS; hub_runtime already NOBYPASSRLS in database-grants.sql:43).
  • Context per transaction: SET LOCAL ROLE and set_config(…, true) with bound values (U3 contract); consistent with PostgREST SqlFragment.hs:604-624 and D25. Pool leak: criterion 5 (A→B→none, commit, rollback, library nested transaction). Good.
  • Missing context: criterion 1 says zero rows and no write. Correct intent; see F-3 for the one implementation trap.
  • FORCE: the card chooses none ("o dono só roda o migrate", D9). Acceptable, see F-2.
  • Deletion grant: names exactly DELETE on auth.company, auth.member, auth.invitation, operations.client for hub_operator only, plus UPDATE (active_organization_id) on auth.session. That is exactly the four deletes the brief names; the session grant is questioned in F-4.
  • Operator crosses companies without membership: hub_operator has no INSERT policy on auth.member (table row in U3), so "Conexus never a member" is enforced by the database, not by code. Good.
  • Nine proofs: B1–B9 map to criteria 1–17; B7 was correctly re-worded to "only Conexus deletes" with the concurrency part kept (criteria 8–12). Mutation proofs exist as npm run removals entries (rls-company-policy, scope-role-set, client-delete-revision, client-delete-operator-only), so a removed protection fails a test (T10, B8). I found no proof that survives removal of its protection, except the phase-1 blind spot F-1.
  • Budget: 3,150 against the 4,000 ceiling (L2) with a stated 5a/5b split. U3's 1,500 is the one number with no census behind it; the split rule covers it. No finding.
  • Stacking logic on logic: one new union (Scope), one role per scope, policies in Drizzle pgPolicy; no AsyncLocalStorage, no SECURITY DEFINER (U1 step 4 sends one back to the card), no wrapper. The exception is within (B-2).

Findings

Bloqueia

B-1. The grant lists of U2 and U7 are approved by a quote that predates them (D11).
Card, U2 "Os contratos": verbs are "os que o censo de U1 achou", and the global tables get "só os verbos que a biblioteca usa naquele fluxo". U2 and U7 say "PR próprio, citando esta página e a 2A". The page says "No começo: nada" is asked of the founder. D11 (data.md:40) requires the founder's word on the role and grant list; in 4.2 he gave it on the concrete list (PR 48, "1A"). Here the list will exist only after U1.
Cost if left: a role and grant list reaches production on "2A", which was given before the list existed, so the condition of his approval ("follows exactly his answers") is silently stretched to cover verbs he never saw.
Fix (card text only): either put the full role-by-table-by-verb table in the card now, or state on the page and in U2/U7 that those two PRs wait for his explicit word on the exact list, exactly as PR 48 did. Recommended: the second, since the census is the point of U1.

B-2. The widest role is reachable by anyone who holds a transaction, and the database cannot tell an operator from a non-operator.
Card U3 contracts: Scope includes {kind:'OPERATOR', personId, companyId|null}, built freely, and within(tx, scope, work) "troca o escopo na mesma transação" to any Scope. The hub_operator policies key only on conexus.person_id/company_id set by the caller (table in U3), not on the person actually being the installation administrator. Admission (admitOperator, admission.ts:189) runs inside the already-OPERATOR transaction. So a route that opens OPERATOR, or any code that calls within(tx, {kind:'OPERATOR'…}), sees every company, and RLS does not object. That is the "exception that becomes unrestricted access" the study warned about (§7, "Desenho candidato de C"), and it is the founder's "intrínseco no software" standing words: whoever writes the query.
Cost if left: the isolation guarantee holds for company, person and invitation scopes but has one door that any future query author can open, and the only thing between them and every company is code review.
Fix (card text only, small): (a) hub_operator policies require the person to be the installation administrator (exists on auth.user for conexus.person_id with the admin role; the auth.user policy for hub_operator already lets it read "a pessoa", so there is no recursion), proved in U1; (b) within is not a general scope switch: it takes a closed set (the pace check's PERSON) or becomes a named function in platform/; (c) add a removal entry operator-policy-admin-only to B8.

Fechamento (fix in the card or at the build, none blocks)

F-1. Phase 1 cannot detect an uncontained caller. Until U7, hub_runtime keeps transition policies on the four tables, so a query that forgot its scope still passes the whole suite; the first test that would fail is U7's, after v0.5.0 is live. Fix: U3's CI also runs the full suite against the phase-2 state (apply the U7 migration in a second test database), so v0.5.0 ships with no uncontained caller and v0.5.1 is only the revoke. This does not change H.

F-2. FORCE. No FORCE ROW LEVEL SECURITY is acceptable: the owner only runs migrate (D9), and with FORCE the owner's own data migrations (4.2's P6 B deletes) would silently touch zero rows. Close it by saying so in decision 0039 and by having catalog.test.ts assert (i) relforcerowsecurity as chosen, (ii) hub_runtime is a member of no role except the four scope roles (so it cannot SET ROLE to the owner), and (iii) the four roles own nothing. Criterion 1 covers only part of this.

F-3. Empty context is '', not NULL. After a first set_config(…, true) on a connection, current_setting('conexus.company_id', true) returns an empty string in later transactions. A policy that casts it, or compares without nullif(…, ''), can raise 22P02 instead of returning zero rows, which would turn "deny" into a 500/503. Ids here are text, so equality would deny, but the card should say the policies read the setting as nullif(current_setting(…, true), '') and criterion 1/5 test the second use of a connection.

F-4. The session grant has no reader, and the page attributes it to Q6. Page, "O grant": "…e limpa a empresa ativa das sessões (Q6; 4.2)". Q6 (operator-console study, report line 22) says delete company, links and invitations and keep people; it says nothing about sessions. activeOrganizationId is written by the library on accept (crud-invites.mjs:330) but no Hub code reads it (git grep on the 4.2 branch: only identity/tables.ts:50 and tests). The checklist item 5 (D18, written and never read) applies, and it costs a column-level UPDATE grant on auth.session to hub_operator. An UPDATE … WHERE active_organization_id = … also needs SELECT on that column, which the card does not list. Recommendation: drop the clearing, the grant and the clause of criterion 9, unless U1's census finds a reader; if kept, cite it as 4.2 P6 precedent and list the SELECT. This is a technical choice, not a founder decision.

F-5. The page words the CNPJ reuse as already decided. "Decisões já dadas … Q6 … o CNPJ pode ser cadastrado de novo." His Q6 words say nothing about the registration row or the CNPJ; operations.client entered the deletion through firstmate's steering message 001 (PR body). See "Choices the answers do not settle" below. Reword the line as a consequence and keep the ask in the use script.

F-6. Scope narrowing relies on a relayed correction not in the ledger. The ledger (captain.md, "Tenant isolation must be intrinsic") records the reframing "for the Hub's database and for the apps the Builder generates". The study (§7) says the founder corrected that to the Hub only in firstmate's message 003, which I cannot find in captain.md. The card puts "Apps e bancos das empresas (etapas 7 e seguintes)" in "Fica de fora" and the founder will read it, and decision 0021 already isolates apps by a Neon project per company, so the risk is low. Firstmate should confirm message 003 is his word and record it; if not, it is a narrowing he must see (options in the table below).

F-7. U1 on Neon. (a) "Um banco novo e vazio num branch do Hub": a branch of the production project carries the parent's data by copy-on-write and its roles; the card should say the proof creates the empty database, never reads a company table, and deletes the branch at the end (it does say "sem ler linha de empresa" and "apagado no fim"). (b) Neon cannot create BYPASSRLS roles for the app and adds roles of its own, so catalog equality stays CI-only (D11 already says so); the Neon Result should state which assertions ran. (c) Run B5 on the address the Hub's runtime really uses; SET LOCAL/set_config(true) are safe through a transaction pooler, a session SET ROLE is not (D25 already forbids it). Not found in the repository which address production uses; U1 should record it.

Issue futura

  • Data isolation of the apps the Builder generates (step 7 onward); the card already defers it.
  • A future plugin or library route that reaches company tables through libraryOrm on the pool: after v0.5.1 it fails loudly with 42501, which is the right behaviour, but the libraryOrm census (B1) should be a catalog test that lists the tables the pool's role can reach.

Choices the card makes that the answers do not settle

# Choice Direct consequence of an answer, or new? Options Recommendation
1 Re-registering the same CNPJ after a deletion (the card follows "delete and allow") Consequence, one inference removed. Q6 A deletes company, links, invitations and keeps people; "no trash, no receipt" was his (study D/G, Q6 A: no durable record of who deleted). Deleting the registration row is needed for the uniform 404 (operations.client has no FK, so a surviving row would point at a missing company). A tombstone would be the durable record he declined. The page must not call it "already given". A. Delete the row, CNPJ free again. B. Keep a tombstone (CNPJ, legal name, deleted date), CNPJ stays blocked. C. Forbid the CNPJ for good. A. Not a stop for the build; show it on the page as a consequence, and he confirms it when he runs the roteiro step 5. B and C are additive later; A is not harmful to switch.
2 Typed name is the display name, not the legal name or the CNPJ Consequence of "nome digitado" (Q6) plus 4.2's name being the company's name. Mild ambiguity. A. Display name. B. Legal name. C. CNPJ. A. Same string the operator sees on the screen.
3 hub_operator can read every member row of the company being deleted (policy "com companyId, todos dela, para apagar") Consequence of Q6 plus deleting members; invisible on screens (4.2 P7 still shows owners only). A. As in the card. B. Delete members through the owner list only. A, once B-2(a) anchors the role to the administrator.
4 Clearing the active company of every session Not an answer (F-4). A. Drop it. B. Keep with the SELECT grant listed. A unless a reader appears.
5 Version numbers v0.5.0/v0.5.1 and "volta anterior à v0.5.0 deixa de funcionar" Direct from H; the card already asks him before v0.5.1. – –
6 Apps/Builder data excluded Needs the ledger line (F-6). A. Hub only now, apps proved at step 7 on decision 0021. B. Design the Builder's data path now. A, if message 003 is his.
7 Exact grant verbs per role Not settled by any answer (B-1). A. Table in the card now. B. His word at the U2/U7 PRs. B.

Nothing else in the card is a product rule outside his answers: the 412/422/404 codes, the dialog texts (he approves the texts at the end), lock order, disableOrganizationDeletion, Notice strings and the 5a/5b split are consequences of Q6, 4.2 and the guides.

Process notes

  • CI fails second-card by delivery L5 until 4.2's card leaves docs/steps/ (as the PR says); not a card defect.
  • The card is 358 lines against 4.2's 370; I did not run npm run docs, so the L24 ceiling is not measured here.
  • I did not run the proof. Every claim marked "verified" above was read at the cited line; claims about PostgreSQL behaviour (FOR SHARE/UPDATE needing UPDATE privilege and the UPDATE policy, '' after set_config(true)) are the PostgreSQL docs' behaviour and are exactly what U1's proof must show, as the card says.

Recommendation

Fix B-1 and B-2 in the card (about ten lines), reword F-5, and take F-1 to F-4 as card amendments or build notes. After those, approve: the card then follows his answers exactly, and the only item to put in front of him is the CNPJ consequence, at the roteiro, not before the build.

…perator policies need the administrator, closed scope switch, no session clearing, CNPJ as consequence)
@leandrotcawork

Copy link
Copy Markdown
Collaborator Author

Reviewer: Claude Sonnet 5.5 (delta)

Step 5 card, delta reading (PR #50)

Read: git diff d59e1e7 e1af8a8 (only docs/steps/e05-duas-empresas.md, 58+/60-; docs/roadmap.md unchanged in the delta), against the whole reading data/conexus-e05-card-reader2/report.md. Nothing in the repository was changed. I did not run the proof or npm run docs.

Verdict: request changes (1 Bloqueia, small; the rest is fixed or Fechamento)

Findings of the whole reading, one by one

Item State Evidence in the card at e1af8a8
B-1 grant word Fixed "O que você faz": he gives his word on the exact role/table/verb list "antes de U2 e de U7", as PR 48 (D11), construction stays local meanwhile; U2 "A ordem do trabalho": own PR with the exact list that waits for his word. U7 only drops policies and revokes (no new verb), and its PR (D11) carries his H confirmation.
B-2(a) operator needs administrator Stated, not provable yet (see N-1, N-2) U3 contracts: "Toda política de hub_operator exige também que conexus.person_id seja uma pessoa com o papel admin em auth.user"; U1 step 2 lists "a exigência de administrador do operador". admin is INSTALLATION_ADMINISTRATOR (admission.ts:43 on the 4.2 build), role column identity/tables.ts:31.
B-2(b) closed switch Fixed within(tx, scope, work) replaced by asPerson(tx, work): COMPANY→PERSON of the same person and back, "só para checkPace; nenhuma outra troca". It narrows, takes no scope, so it cannot reach OPERATOR. Scope.COMPANY gained personId for it: a consequence of the closed switch, not a decision.
B-2(c) removal entry Named, no test behind it (N-1) U3 raio: operator-policy-admin-only; criterion 15 lists the removal.
F-1 Fixed Criterion 17 "a suíte passa também com a fase 2 desde U3"; U3 "Como se prova": CI runs the suite on a second database with U7 applied.
F-2 Fixed Criterion 1 "sem FORCE", "não são donos de nada", "hub_runtime só é membro deles"; U1 contracts and U3 step 4 say why (D9).
F-3 Fixed U3: policies read nullif(current_setting(…, true), ''); criterion 1 "também no segundo uso da conexão".
F-4 Fixed Session clearing, grant and criterion 9 clause removed; U4 step 1: "A empresa ativa das sessões não é lida pelo Hub e fica (D18), salvo leitor achado em U1". U1's census list does not name that reader search (N-3).
F-5 Fixed Page: "Consequência, não palavra sua: sem o cadastro, o CNPJ fica livre (roteiro, passo 4)"; the use script step 4 now shows it.
F-6 Not a card matter Card now says "etapa 7, decisão 0021". The ledger line for the founder's Hub-only word (2026-10-16 quote in the task brief) is still firstmate's to record in captain.md.
F-7 Fixed U1 step 3: empty DB created on a branch, no company table read, branch deleted; B5 on the address the Hub uses, recorded; Result says which assertions ran on Neon (catalog equality CI-only).

New founder decision introduced by the fixes: none. Logic on logic: none; one new function (asPerson) replaces one general one.

Findings of this reading

Bloqueia

N-1. Nothing observable proves the administrator requirement, so its removal entry would pass vacuously.
Criteria 1-4 and 8 say nothing about OPERATOR with a person who is not the installation administrator; criterion 8 is the HTTP 404 (code admitOperator), which still passes if the policy loses the clause. Criterion 15 says removing the clause "faz o teste do critério falhar", but no criterion owns that test. rg admin in the card finds it only in the contract line, U1 step 2, criterion 15 and the U3 raio.
Cost if left: the B-2 door (any code that opens OPERATOR sees every company) can reopen with the whole suite and npm run removals green, because the entry has no test to turn red.
Fix (one clause in the card): add to criterion 3 or 4 (or a new row): "em OPERATOR, a pessoa que não é administradora, ou sem pessoa, lê zero linhas de empresa e não grava; a administradora lê todas", test isolation.test.ts "operador sem papel", and name that test as the one operator-policy-admin-only breaks.

Fechamento

N-2. The administrator check on auth.user itself may recurse. The contract says every hub_operator policy requires the person to have role admin in auth.user, while the matrix gives hub_operator on auth.user "a pessoa, os operadores, os donos". A policy on auth.user whose predicate selects from auth.user raises PostgreSQL "infinite recursion detected in policy" (42P17); the escape hatch, SECURITY DEFINER, is sent back to the card by U1 step 4. The card already stops the build there, so this is not a decision hole, but say now that the predicate on auth.user itself reads the row's own role (or equivalent, no subquery on the same table) and that other tables use exists on auth.user; U1 then proves it. I did not run PostgreSQL to confirm; this is documented PostgreSQL behaviour U1 is built to show.
N-3. U1's census does not list the session reader. U4 keeps the session column alone "salvo leitor achado em U1", but U1 step 2 has no item looking for it. Add "leitor de active_organization_id" to that list (or drop the exception).
N-4. Not a card matter: firstmate should still record the Hub-only word in the ledger (F-6).

Issue futura

Unchanged from the whole reading (apps' data isolation from step 7; catalog test listing tables the pool role reaches).

Process notes

Page growth is small: the diff is net -2 lines (356 lines now; 4.2's card was 370). second-card CI stays red by L5 until 4.2's card leaves docs/steps/, as before.

Recommendation

Request changes for N-1 (one criterion row). N-2 and N-3 can ride in the same commit (two sentences). After that, approve; no founder decision is open besides the grant-list words the card now schedules.

@leandrotcawork
leandrotcawork merged commit 6ff7319 into main Oct 17, 2026
13 checks passed
leandrotcawork pushed a commit that referenced this pull request Oct 17, 2026
…#51) into feat/conexus-e05-build

The card, roadmap and decision 0039 take main's approved text.
leandrotcawork pushed a commit that referenced this pull request Oct 17, 2026
…conexus-e05-build

Its tree is already main's; the merge makes the approved card commit 3fa4793 an ancestor for the
approval check.
leandrotcawork pushed a commit that referenced this pull request Oct 17, 2026
…conexus-e05-removal-rows

No file changes; the approved card commit 3fa4793 becomes an ancestor for the approval check.
@leandrotcawork
leandrotcawork deleted the feat/conexus-e05-card2 branch November 12, 2026 20:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants