oficina / equipo Public

Plan 1: resolve round 1 findings and apply Paul's answers (Astra)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev f0bd85a285f7b4a7ff3b1647ab6d78b050c0f30a parent b8bfd57
1 file changed, +79 −54
  • docs/superpowers/plans/2026-11-01-equipo-plan-1-foundation.md +79 −54

No CI script — run details

diff --git a/docs/superpowers/plans/2026-11-01-equipo-plan-1-foundation.md b/docs/superpowers/plans/2026-11-01-equipo-plan-1-foundation.md
index 2adbe7ca..766d0fcb 100644
--- a/docs/superpowers/plans/2026-11-01-equipo-plan-1-foundation.md
+++ b/docs/superpowers/plans/2026-11-01-equipo-plan-1-foundation.md
@@ -38,19 +38,18 @@
## Grounding and scope decisions
-Sources were read at Equipo HEAD `5042a9e` on branch `design`, memoria `617eb2a`, Rastrillo checkout `9c1e14ef` and its `v0.28.0` tag. Prototype checkout HEAD is `cb280f7`; `git diff ceee7a67 -- internal/team internal/teamcontract` is empty. Use the pinned commit for the copy, not a moving checkout.
+Initial grounding used Equipo `5042a9e`, memoria `617eb2a` and Rastrillo `v0.28.0`. Round 1 revisions were checked at Equipo HEAD `b8bfd57`, against that same Rastrillo tag (`86dd77b`) and `/home/paulca/amadan.net/carlos/platform-team-service/internal/team`. Prototype HEAD is `cb280f7`; its package diff against `ceee7a67` is empty. Copy from `ceee7a67`.
-| Source | Reuse and correction |
+| Source | Decision |
|---|---|
-| Rastrillo `cmd/rastrillo/new.go` at `v0.28.0` | `new --theme day --shell sidebar equipo`; the generator refuses an existing directory. Generate under scratch, then select files for this repository. This tag has no `--auth` flag; HEAD does. Do not mix their recipes. |
-| Rastrillo `ui/ui.go`, `ui/funcs.go`, `ui/layouts/sidebar.html` at the tag | `ui.Layout("sidebar")`, `ui.ThemeCSS("day")`, `ui.VendoredAssets("day")`, `ui.Funcs(ui.WithIcons(...))`, `ui.Templates()`. Use `view`, `up`, `brand`, `nav`, `account` blocks and `aria-current`. No new rail framework. |
-| Rastrillo `DESIGN.md`, Navigation | Its generic disclosure description is older than the sidebar's implemented phone index. The verified sidebar and Equipo spec agree on index/page navigation below 800px. |
-| Rastrillo `cmd/rastrillo/migration.go:appPackage` | Requires exactly one immediate app directory under `internal/` excluding names ending in `test`. Put the core in `internal/equipo/team` and its contracts in `internal/equipo/teamcontract`, not alongside `internal/equipo`. |
-| memoria `cmd/memoria/main.go`, `internal/memoria/{app,auth,config,migrations,render}.go` | Reuse Resolve → `db.Open` → app → Serve, one `auth.Auth`, admission callback, fail-closed routes, SMTP refusal, and separate app `Schema` / merged `BootSchema`. Translate old `github.com/carlosframework/rastrillo` imports to the pinned `amadan.net/rastrillo/rastrillo` module. |
-| memoria `Makefile`, `.amadan/ci`, `.amadan/ci.d/` | One `make ci` definition and executable step wrappers; stamped release; flags before deploy binary. Keep the new scaffold's additional checks rather than weakening them to memoria's smaller gate. |
-| memoria `tools/drive/main.go`, README, `/home/paulca/memoriadrive/run.sh` | Separate local drive; explicit loopback; persistent local config; production binary retains auth. Read the external script without copying its secrets or addresses. README's “never deployed” paragraph contradicts its Live section; Makefile's release path is authoritative. |
-| Prototype `internal/team` and `internal/teamcontract` at `ceee7a67` | Production imports are standard library, `modernc.org/sqlite`, and `golang.org/x/sys/{unix,windows}`. Only the two contract tests import `github.com/carlosframework/platform/internal/team`; rewrite those to the nested Equipo package. No console or other platform-internal implementation must be extracted. |
-| estilo README; suite doctrine rulings 1, 5, 9 and §8 | `day`; lone roster; actual actor; no provider egress in this plan. The Equipo provider-egress amendment remains separate suite work. |
+| Rastrillo `cmd/rastrillo/new.go` at `v0.28.0` | Generate the day/sidebar scaffold in scratch; this tag has no `--auth` flag. |
+| Rastrillo `ui` sidebar and `DESIGN.md` | Use the shipped shell and its phone index; its implemented navigation takes precedence over the older generic disclosure prose. |
+| Rastrillo `auth/auth.go`, `ui/partials/signin.html`, `pow/guard.go` | Use `SigninScreen` with the shipped partial and a `NoProof` guard; keep token age and single-use checks. |
+| Rastrillo `cmd/rastrillo/migration.go` | Nest the execution core under `internal/equipo` so the CLI finds one app. |
+| memoria app, auth and release files | Reuse app composition, fail-closed admission and human deployment conventions, adapted to the pinned Rastrillo APIs. |
+| memoria drive and local startup script | Keep local tooling separate and loopback-only; copy no secrets, addresses or production auth bypass. |
+| Prototype `internal/team` and `internal/teamcontract` at `ceee7a67` | Copy the execution library and contracts; rewrite the two contract imports, without extracting console code. Keep call settlement intact and add separate attempt-time accounting. |
+| estilo README; suite doctrine rulings 1, 5, 9 and §8 | Use `day`, one roster and the actual actor; Foundation has no provider egress. |
**Boundary:** no task form, runner protocol, connections discovery, live counters, product ranking, coordinator, preference learning, evidence extensions or plan editor. Preserve prototype evidence, fencing and recovery tests. Add owner-only quarantine release in plan 2 before opening the execution store for live jobs; append/cancel-unstarted-step operations and plan revision events belong to plan 3. Neither is required for metadata-only Foundation. Removing the source packages from platform is separate work.
@@ -64,7 +63,7 @@ All paths below are relative to this repository unless absolute. Existing files
- `internal/equipo/{app,config,auth,render,models,migrations}.go`: composition, sign-in, embedded templates/assets, app schema.
- `internal/equipo/{roster,projects,specialists,authority,budgets}.go`: focused metadata services and prototype adapters. `store.go` holds shared transaction/error helpers.
- `internal/equipo/team/*.go`, `internal/equipo/teamcontract/*_test.go`: copied core and external contracts; the core keeps its own SQLite migrations, witness and lock protocol. They do not enter app `Models` or `BootSchema`.
-- `internal/equipo/templates/{layout,signin,index,empty,projects,project,project_form,team,specialist}.html`, `internal/equipo/static/equipo.css`, `internal/equipo/icons/icons.go`: shell, forms and icons; scaffold static assets stay byte-identical to the library.
+- `internal/equipo/templates/{layout,signin_page,index,empty,projects,project,project_form,people,settings,specialist}.html`, `internal/equipo/static/equipo.css`, `internal/equipo/icons/icons.go`: shell, forms and icons; `signin_page.html` wraps the framework `signin` partial without redefining it. Scaffold static assets stay byte-identical to the library.
- `internal/equipo/copy.go`: sole app-owned runtime copy source, with stable keys and copy-review status. Scaffold boilerplate, accessible names, errors and email text count too; framework-owned strings stay framework-owned.
- `internal/equipo/migrations/0001_init.sql`, subsequent additive migrations and `schema.sql`; `Models []any` describes app tables only.
- `internal/equipotest/`: HTTP, migration, asset, gate and browser tests. Core tests remain beside their packages.
@@ -79,21 +78,21 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
**Files:** Create the scaffold files listed above, `internal/equipotest/foundation_test.go`; modify `README.md` only with reviewed setup prose. Reserve `copy.go` for reviewed strings; keep unapproved scaffold copy out of shipping artifacts.
-**Interfaces:** Consume the pinned Rastrillo APIs. Produce `App(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (*http.ServeMux, error)`, `Config{Origin, InstanceKey string; Owners []string; AllowLoggedMail bool}`, `LoadConfig(getenv func(string) string) (Config, error)`, `Schema`, `BootSchema`, `Models`, and the `Store` contract above. Keep the scaffold decomposition with `Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.Router, error)`, `Mux(r http.Handler) *http.ServeMux` and `Configure(opts *rastrillo.Options, mux *http.ServeMux, started time.Time)`; update the generated HTTP/browser/performance harness callers together. Until Task 3, private routes return service unavailable rather than an unauthenticated scaffold page.
+**Interfaces:** Consume the pinned Rastrillo APIs. Produce `App(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (*http.ServeMux, error)`, `Config{Origin, InstanceKey string; Owners []string; AllowLoggedMail bool}`, `LoadConfig(getenv func(string) string) (Config, error)`, `Schema`, `BootSchema`, `Models`, and the `Store` contract above. Keep the scaffold decomposition with `Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.Router, error)`, `Mux(r http.Handler) *http.ServeMux` and `Configure(opts *rastrillo.Options, mux *http.ServeMux, started time.Time)`; update the generated HTTP/browser/performance harness callers together. Preserve `TestPerfScreens` and its `perftest.ScreenConfig.Signin` hook; Task 3 supplies a capturing-mailer sign-in helper, and Task 8 measures the private pages with its session cookie. Until Task 3, private routes return service unavailable rather than an unauthenticated scaffold page.
-- [ ] **Step 1: Write failing boot/gate tests.** `TestFoundationFailsClosed` requires an unauthenticated private request to fail, an empty key/owners or incomplete SMTP config to reject boot, and an invalid origin to reject boot. `TestFoundationMigratesTwice` applies `BootSchema` twice without losing a row. `TestCIGateSteps` checks executable CI wrappers call the same Make targets. Assertion examples:
+- [ ] **Step 1: Write failing boot/gate tests.** `TestFoundationFailsClosed` requires an unauthenticated private request to fail, an empty key, invalid origin or incomplete SMTP config to reject boot, and missing owners to reject first boot on an empty DB. `TestFoundationMigratesTwice` applies `BootSchema` twice without losing a row. `TestCIGateSteps` checks executable CI wrappers call the same Make targets. Assertion examples:
```go
// TestFoundationFailsClosed
if err == nil { t.Fatal("missing production configuration accepted") }
if response.Code == http.StatusOK { t.Fatal("private page served before auth") }
// TestFoundationMigratesTwice
- if second.Applied != 0 { t.Fatal("migration repeated on second boot") }
+ if len(second.Applied) != 0 { t.Fatal("migration repeated on second boot") }
```
- [ ] **Step 2: Establish the red result.** Run `go test ./internal/equipotest -run 'TestFoundation|TestCIGateSteps' -count=1`; before scaffold creation the missing module/package is the expected failure. Once a compileable scaffold exists, also observe the behavioral auth refusal fail before adding the guard.
- [ ] **Step 3: Generate and adapt the scaffold.** In a fresh directory made by `mktemp -d "$TMPDIR/equipo-scaffold.XXXXXX"`, run `go run amadan.net/rastrillo/rastrillo/cmd/rastrillo@v0.28.0 new --theme day --shell sidebar equipo`. Select its files into this existing checkout, preserving design documents; rewrite scaffold `equipo/internal/...` imports and module declaration to `amadan.net/oficina/equipo`. Set the Go floor to `1.25.0`, retain the pinned CLI tool dependency and run `go mod tidy`. Do not commit a local `replace`. Remove the example Note model before the first app migration ships. Before adding any new app-owned copy in this or later tasks, use the copy-review gate described in Task 8; its placement there does not postpone approval of earlier strings.
-- [ ] **Step 4: Wire configuration and gates.** Use `rastrillo.Resolve(rastrillo.Options{DBPath: "equipo.db", Logger: logger})`, `db.Open(opts.DBPath, logger)`, app construction, then `rastrillo.Serve(opts)` with `opts.DBPath = ""` after the app opens it. Require `EQUIPO_ORIGIN`, `EQUIPO_INSTANCE_KEY`, `EQUIPO_OWNERS`, plus both `CARLOS_SMTP_HOST` and `CARLOS_SMTP_FROM`, or explicit local-only `EQUIPO_ALLOW_LOGGED_MAIL=1`. Reject logged mail on a public production origin. This pinned release predates `carlos.InstanceKey`; do not call that HEAD-only function. Use `mail.FromEnv("CARLOS", logger)`. Keep `Schema = migrate.MustFromFS(migrationFS, "equipo")` and `BootSchema = migrate.Merge(sessions.Schema, auth.Schema, Schema)`; apply with `migrate.Apply`. CI includes build, vet, formatting, tests and `go run amadan.net/rastrillo/rastrillo/cmd/rastrillo migration check`, plus the scaffold's static/security checks. Update AGENTS to shared-team data, copy review, `make ci`, and no autonomous merge/deploy; remove its generic per-user `scope.Owned` instruction.
+- [ ] **Step 4: Wire configuration and gates.** Use `rastrillo.Resolve(rastrillo.Options{DBPath: "equipo.db", Logger: logger})`, `db.Open(opts.DBPath, logger)`, app construction, then `rastrillo.Serve(opts)` with `opts.DBPath = ""` after the app opens it. Require `EQUIPO_ORIGIN`, `EQUIPO_INSTANCE_KEY`, plus both `CARLOS_SMTP_HOST` and `CARLOS_SMTP_FROM`, or explicit local-only `EQUIPO_ALLOW_LOGGED_MAIL=1`. Reject logged mail on a public production origin. `EQUIPO_OWNERS` is required only to bootstrap an empty DB; after the team exists, ignore it, including changes or absence. Enforce that requirement in `Bootstrap`, where DB state is known. This pinned release predates `carlos.InstanceKey`; do not call that HEAD-only function. Use `mail.FromEnv("CARLOS", logger)`. Keep `Schema = migrate.MustFromFS(migrationFS, "equipo")` and `BootSchema = migrate.Merge(sessions.Schema, auth.Schema, pow.Schema, Schema)`; apply with `migrate.Apply`. CI includes build, vet, formatting, tests and `go run amadan.net/rastrillo/rastrillo/cmd/rastrillo migration check`, plus the scaffold's static/security checks. Update AGENTS to shared-team data, copy review, `make ci`, and no autonomous merge/deploy; remove its generic per-user `scope.Owned` instruction.
- [ ] **Step 5: Verify.** Run the targeted tests, `make migration-check`, and `make build`; expect PASS, no schema drift, and cgo-free compilation. Remove scaffold scratch. Prove a removed CI target fails `TestCIGateSteps`, then restore it.
- [ ] **Step 6: Commit during implementation.** Stage only Task 1 files; `git commit -m "feat: scaffold Equipo foundation"`.
@@ -109,13 +108,13 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
- [ ] **Step 4: Verify.** Run the two core packages and `go test ./internal/equipotest -run TestCoreHasNoPlatformDependency -count=1`; all original tests must pass. Run `make migration-check` to prove nested core directories do not confuse app discovery. Run `make budget` and the normal instrumented `make test` gate as well. No test run against the external repository is required.
- [ ] **Step 5: Commit with provenance.** Stage copied packages and module/import test changes. Use subject `feat: move the team prototype into Equipo`; body `Copied internal/team and internal/teamcontract from carlos/platform ceee7a67. Platform removal is separate work.` Supply the body as a separate `git commit -m` argument, producing a real blank line.
-## Task 3: Persist the roster and wire keymail sign-in
+## Task 3: Persist the roster and wire sign-in
-**Files:** Create `internal/equipo/{store,roster,auth}.go`, `internal/equipo/templates/signin.html`, `internal/equipotest/{auth,roster}_test.go`; modify app configuration, models, migrations and composition.
+**Files:** Create `internal/equipo/{store,roster,auth}.go`, `internal/equipo/templates/signin_page.html`, `internal/equipotest/{auth,roster}_test.go`; modify app configuration, models, migrations, rendering and composition. Keep the shared email-link helper in `internal/equipotest/auth_test.go` for HTTP, browser and performance callers.
**Interfaces:** Produce `(*Store).Bootstrap(ctx context.Context, owners []string) error`, `Member(ctx context.Context, address string) (Member, error)`, `SetMember(ctx context.Context, actor Actor, address string, role Role, active bool, revision int64) error`; `NewAuth(d *db.DB, cfg Config, mailer mail.Sender, store *Store, logger *slog.Logger) (*auth.Auth, error)`; middleware `requireMember(next http.Handler) http.Handler` on the app.
-- [ ] **Step 1: Write tests.** `TestRosterBootstrapOnce`: two boots yield one team and one normalized owner per unique address; subsequent boot does not resurrect a removed seed member. `TestRosterProtectsLastOwner`: last active owner cannot be removed/demoted, and a member cannot promote themselves. `TestRosterChangesAffectExistingSession`: real session remains a framework session after demotion but owner writes fail; removal denies every private page; a failed lookup yields 503 rather than admission. `TestSigninAdmission`: approved owner/member can complete sign-in; an outsider cannot; missing/invalid cookie is denied. `TestSigninCSRF`: foreign-origin POSTs to sign-in, signout and roster mutations fail. Assert:
+- [ ] **Step 1: Write tests.** `TestRosterBootstrapOnce` checks one team and normalized unique owners across two boots; changed or absent `EQUIPO_OWNERS` after first boot cannot add or resurrect members. `TestRosterProtectsLastOwner` tests store calls: last active owner cannot be removed/demoted, and a member cannot promote themselves. `TestRosterChangesAffectExistingSession` uses a test-only private handler behind the production middleware: demotion keeps the session but denies owner store mutations; removal deletes every session for that subject, and re-adding the member cannot revive an old cookie. A DB lookup failure on a still-valid session returns 503. `TestSigninAdmission` signs in owner/member through a capturing mailer, denies an outsider and invalid cookies, and checks that `Authorize` returns false on a DB error. `TestSigninCSRF` covers the mounted auth POST routes only; roster HTTP checks wait for Task 8. `TestAuthProductionConfig` applies `BootSchema` and calls the production `NewAuth`, requiring `auth.New` to succeed with its real guard and no `ProofOff`. `TestSigninNoProof` rejects missing, premature and replayed tokens and accepts a valid aged token without JavaScript. Assert:
```go
if !errors.Is(err, equipo.ErrForbidden) { t.Fatal("member changed roster") }
@@ -123,19 +122,25 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
if teamCount != 1 || memberCount != 2 { t.Fatal("bootstrap duplicated records") }
```
-- [ ] **Step 2: Run red tests.** `go test ./internal/equipotest -run 'TestRoster|TestSignin' -count=1`; expect missing interfaces or failed assertions before wiring admission.
-- [ ] **Step 3: Implement the roster.** Bootstrap in one transaction only when the team row is absent; persist monotonically increasing `RosterEpoch` on changes. Seed owners from the configured list, then use the DB as authority. Attribute the initial seed audit to `bootstrap`, not to a person who has not signed in. Roster changes use revision checks, preserve at least one owner, and refuse removal of a person still assigned a project decision until reassigned. Missing rows are `ErrNotFound`; DB errors remain `ErrUnavailable`.
-- [ ] **Step 4: Wire existing auth.** Create one `auth.New(auth.Config{...})` for the process, with non-nil `Authorize` checking current active membership, `SubjectFor` returning the normalized address, `KeymailServers: []string{"keymail.dev"}`, and the supplied mailer/key/origin. Preserve the framework's keymail flow, email fallback, rate limiting and session cookies. Mount `Begin` at POST `/auth/begin`, `Callback` at GET `/auth/callback`, `Verify` at GET and POST `/auth/verify`, and `Signout` at POST `/signout`; reuse the pinned sign-in behavior rather than constructing tokens. Protect all mutating routes with `csrf.Protect(cfg.Origin)`. Private routes use `Auth.RequireSession`, then `auth.From(r)` and a live roster lookup; `Authorize` alone does not recheck old sessions. Use the framework fake-keymail test pattern from `auth/keymailfake_test.go` to verify the keymail callback, and a capturing `mail.Sender` for email tests. Never log a link in production.
+- [ ] **Step 2: Run red tests.** `go test ./internal/equipotest -run 'TestRoster|TestSignin|TestAuthProductionConfig' -count=1`; expect missing interfaces or failed assertions before wiring admission.
+- [ ] **Step 3: Implement the roster.** Bootstrap in one transaction only when the team row is absent; persist monotonically increasing `RosterEpoch` on changes. Seed owners from the configured list, then use the DB as authority. Attribute the initial seed audit to `bootstrap`, not to a person who has not signed in. Roster changes use revision checks and preserve at least one owner. On removal, delete rows in the framework `sessions` table for the normalized subject in the same transaction as the roster update and audit; failure rolls back the removal. Keep the live roster check as well. Task 4 adds the assigned-decision-owner removal rule once projects exist. Missing rows are `ErrNotFound`; DB errors remain `ErrUnavailable`.
+- [ ] **Step 4: Wire existing auth.** After `BootSchema`, create `pow.New` with the instance key, `Nonces: pow.SQLNonces(d.Writer())`, `Difficulty: pow.NoProof` and `MinAge: pow.DefaultMinAge` (three seconds). Pass the guard as `Proof` to the process's single `auth.New`; leave `ProofOff` false. Set `Authorize` to return true only for current active members, false on missing rows or any DB error; `SubjectFor` returns the normalized address. Keep `KeymailServers: []string{"keymail.dev"}` and the supplied mailer/key/origin.
+
+ Choose `SigninScreen: true` and the shipped `ui` `signin`/`signin-title` partials in a stage-layout `signin_page.html` wrapper. Build the state with `Auth.SigninState(r)`, call `PrepareSigninResponse`, then render; wire `RenderConfirm` to that renderer. The partial includes `.State.Proof.Fields` on Begin forms and checks `NeedsScript`, so this `NoProof` configuration needs no `pow.Assets()` or script URLs. Verified at the tag in `ui/partials/signin.html`, `TestSigninNoProofRendersAnEnabledSubmit` and `TestBrowserNoProofWorksWithoutJavaScript`.
+
+ Mount GET `/signin`, POST `/auth/begin`, GET `/auth/callback`, GET and POST `/auth/verify`, POST `/auth/forget`, and POST `/signout`; set `BeginPath` and `ForgetPath` to those mounted paths. Protect mutating routes with `csrf.Protect(cfg.Origin)`. Private routes use `Auth.RequireSession`, then `auth.From(r)` and a live roster lookup. Preserve framework keymail, email fallback, rate limiting and cookies.
+
+ The shared test helper GETs `/signin?force=1`, keeps cookies, submits the rendered challenge fields after `MinAge` with a same-origin POST, captures the email link, GETs its confirmation page and POSTs its token to Verify. In HTTP/performance tests, resolve the link’s path and query against the test server base URL and send the configured Origin on POSTs. Use this forced email path without external DNS/provider calls, including browser and performance setup; never construct a session token or log a link in production. Keymail callback coverage remains in Rastrillo: its fake requires unexported `a.guard.base` and cannot be copied into an app test.
- [ ] **Step 5: Verify.** Run the targeted tests plus `make migration-check`; exercise both red and green cases for removal and nil-auth startup. A nil auth handle must never grant access.
- [ ] **Step 6: Commit.** Stage Task 3 files; `git commit -m "feat: add lone-instance membership and sign-in"`.
## Task 4: Store CARLOS labels, projects and decision owners
-**Files:** Create `internal/equipo/projects.go`, `internal/equipotest/projects_test.go`; modify models and additive migrations.
+**Files:** Create `internal/equipo/projects.go`, `internal/equipotest/projects_test.go`; modify `internal/equipo/roster.go`, `internal/equipotest/roster_test.go`, models and additive migrations.
-**Interfaces:** Produce `Account{ID int64; Label string; Revision int64}` and `Project{ID, AccountID int64; Name, Repository, AppName string; Revision int64}`, with unique team-wide repository binding. `DecisionOwner{ProjectID int64; Decision, Address string}` stores decision keys `work`, `merge`, `copy`, `design`, `product`. Produce `SaveAccount(ctx context.Context, actor Actor, account Account) (Account, error)`, `SaveProject(ctx context.Context, actor Actor, project Project, owners []DecisionOwner, requestID string) (Project, error)`, `Projects(ctx context.Context) ([]ProjectGroup, error)`, and `Project(ctx context.Context, id int64) (ProjectDetail, error)` on `Store`. `ProjectGroup{Account Account; Projects []ProjectDetail}`; `ProjectDetail{Project Project; Owners []DecisionOwner}`. ID zero creates; existing IDs require exact revisions.
+**Interfaces:** Produce `Account{ID int64; Label string; Revision int64}` and `Project{ID, AccountID int64; Name, Repository, AppName, DefaultBranch string; Kind ProjectKind; Revision int64}`. `ProjectKind` accepts only `app`, `website` or `repository`. Enforce team-wide uniqueness on canonical `(Repository, AppName)`, with absent app stored as an empty string, so one repository can host distinct apps. `DecisionOwner{ProjectID int64; Decision, Address string}` stores decision keys `work`, `merge`, `copy`, `design`, `product`. Produce `SaveAccount(ctx context.Context, actor Actor, account Account) (Account, error)`, `SaveProject(ctx context.Context, actor Actor, project Project, owners []DecisionOwner, requestID string) (Project, error)`, `Projects(ctx context.Context) ([]ProjectGroup, error)`, and `Project(ctx context.Context, id int64) (ProjectDetail, error)` on `Store`. `ProjectGroup{Account Account; Projects []ProjectDetail}`; `ProjectDetail{Project Project; Owners []DecisionOwner}`. ID zero creates; existing IDs require exact revisions.
-- [ ] **Step 1: Write tests.** `TestProjectsSharedAndGrouped` creates two account labels and three projects, one without an app; both members read all three in stable label/name order. `TestProjectRejectsUnsafeBinding` rejects non-Amadan hosts, userinfo, query/fragment, missing owner/repo, path traversal and encoded separators. `TestProjectOwnersAreMembers` rejects inactive/unknown addresses and duplicate decision keys; every project requires `work` and `merge` owners. `TestProjectRetryAndRevision` replays an identical request ID without duplication; different content under that ID conflicts; stale update preserves the saved record and owners. Test hostile HTML as a valid display name, not executable markup.
+- [ ] **Step 1: Write tests.** `TestProjectsSharedAndGrouped` creates two account labels and three projects spanning all kinds, one without an app; both members read all three in stable label/name order. `TestProjectRejectsUnsafeBinding` rejects non-Amadan hosts, userinfo, query/fragment, missing owner/repo, path traversal and encoded separators. `TestProjectOwnersAreMembers` rejects inactive/unknown addresses and duplicate decision keys; every project requires `work` and `merge` owners. `TestProjectRetryAndRevision` replays an identical request ID without duplication; different content under that ID conflicts; stale update preserves the saved record and owners. `TestProjectKindsAndDefaultBranch` accepts all three kinds, rejects unknown kinds and missing/invalid default branches, and persists an owner-entered branch across reopen. `TestProjectBindingUniqueness` permits two apps on one repository and rejects duplicate repository/app pairs, including blank-app duplicates. `TestRosterRemovalWhileAssigned` refuses removal while any decision assignment remains, then allows removal after reassignment; rollback preserves both roster and sessions. Test hostile HTML as a valid display name, not executable markup.
```go
if len(groups) != 2 { t.Fatal("account groups lost") }
@@ -143,18 +148,18 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
if before.ID != retried.ID { t.Fatal("retry created a second project") }
```
-- [ ] **Step 2: Run red tests.** `go test ./internal/equipotest -run 'TestProjects|TestProject' -count=1`.
-- [ ] **Step 3: Implement metadata transactions.** Only team owners configure account labels, repository/app bindings and decision owners; all active members can read. Accept `amadan.net/<owner>/<repo>` or its HTTPS spelling, canonicalize to an HTTPS URL with exactly those two non-empty path segments, and store no credential. Blank `AppName` is valid. Do not probe repositories or CARLOS. Validate owners within the same transaction as the project write, use allowlisted form DTOs later, and audit the actual person. Store idempotency keys with the actor, operation and input hash. A CARLOS label is display metadata, never a `team.AccountID` or authority boundary.
+- [ ] **Step 2: Run red tests.** `go test ./internal/equipotest -run 'TestProjects|TestProject|TestRosterRemovalWhileAssigned' -count=1`.
+- [ ] **Step 3: Implement metadata transactions.** Only team owners configure account labels, repository/app bindings and decision owners; all active members can read. Accept `amadan.net/<owner>/<repo>` or its HTTPS spelling, canonicalize to an HTTPS URL with exactly those two non-empty path segments, and store no credential. Blank `AppName` is valid. Require kind and owner-entered `DefaultBranch` in the record and create/edit form. Use one validated canonical branch-name spelling for saved branches and target refs. Do not probe repositories or CARLOS. Refuse roster removal while any project decision is assigned to that member; check this inside the removal transaction. Validate owners within the same transaction as the project write, use allowlisted form DTOs later, and audit the actual person. Store idempotency keys with the actor, operation and input hash. A CARLOS label is display metadata, never a `team.AccountID` or authority boundary.
- [ ] **Step 4: Verify.** Run the targeted tests and `make migration-check`; close/reopen the app DB and verify the same grouping and owner assignments. New form IDs are unique per rendered form; duplicate submit has one effect.
- [ ] **Step 5: Commit.** Stage Task 4 files; `git commit -m "feat: add projects and decision ownership"`.
## Task 5: Define and test team/project limits
-**Files:** Create `internal/equipo/budgets.go`, `internal/equipo/team/periodbudget.go`, `internal/equipo/team/periodbudget_test.go`, `internal/equipotest/budgets_test.go`; modify app models/migrations and core `model.go`, `jobs.go`, `budget.go`, `scheduler.go`, `store.go`.
+**Files:** Create `internal/equipo/budgets.go`, `internal/equipo/team/periodbudget.go`, `internal/equipo/team/periodbudget_test.go`, `internal/equipotest/budgets_test.go`; modify app models/migrations and core `model.go`, `jobs.go`, `budget.go`, `scheduler.go`, `store.go`, plus recovery/migration tests.
**Interfaces:** New core `ProjectID int64`; `PeriodLimits{Calls, InputTokens, OutputTokens, Seconds int64}`; `BudgetSet{Revision int64; Team PeriodLimits; Projects map[ProjectID]PeriodLimits}`; `PeriodUsage{Reserved, Spent PeriodLimits}`. Add `Project ProjectID` to `JobSpec`/`Job` and `ConfigureBudgets(ctx context.Context, account AccountID, expectedRevision int64, budgets BudgetSet) error`, `PeriodUsage(ctx context.Context, account AccountID, project ProjectID, at time.Time) (PeriodUsage, error)` to `team.Store`; project zero requests team totals. App `BudgetConfig{Revision int64; Team team.PeriodLimits; Projects map[team.ProjectID]team.PeriodLimits}` is persisted in the app DB; `(*Store).SaveBudgets(ctx context.Context, actor Actor, config BudgetConfig) error` and `Budgets(ctx context.Context) (BudgetConfig, error)` manage it.
-- [ ] **Step 1: Write budget tests.** `TestBudgetConfiguration` pins owner-only changes, positive explicit limits, project limits no larger than team limits, unknown project rejection, overflow refusal and revision conflict. `TestPeriodBudgetReservations` uses the fake clock: project A permits 2 calls, B permits 2, team permits 3; three one-call reservations succeed, fourth fails even across projects. Independently exhaust input tokens, output tokens and seconds. Concurrent last-slot requests yield exactly one success. `TestTimeChargeWaitsForContainment` reserves a 1,200-second attempt under a 1,500-second project ceiling: a second attempt is rejected; cancellation/lease expiry alone does not refund it; confirmed containment at 300 seconds settles 300, releasing 900 exactly once. `TestBudgetPeriodBoundary` advances from November to December UTC: settled November usage leaves December, unresolved usage remains charged, and a late receipt is counted once. `TestProjectBudgetMigration` opens a pre-extension DB and preserves existing jobs/ledger/witness behavior.
+- [ ] **Step 1: Write budget tests.** `TestBudgetConfiguration` pins owner-only changes, positive explicit limits, project limits no larger than team limits, unknown project rejection, overflow refusal and revision conflict. `TestBudgetLoweringBelowUsage` permits an otherwise valid lower limit below charged usage, preserves existing work/accounting, and blocks new reservations until headroom returns; test both app save and core configuration. `TestPeriodBudgetReservations` uses the fake clock: project A permits 2 calls, B permits 2, team permits 3; three one-call reservations succeed, fourth fails even across projects. Independently exhaust input tokens, output tokens and seconds. Concurrent last-slot requests yield exactly one success. `TestTimeChargeWaitsForContainment` reserves a 1,200-second attempt under a 1,500-second project ceiling: a second attempt is rejected; cancellation/lease expiry alone does not refund it; confirmed containment at 300 seconds settles 300, releasing 900 exactly once. `TestBudgetPeriodBoundary` advances from November to December UTC: settled November usage leaves December, unresolved usage remains charged, and a late receipt is counted once. `TestProjectBudgetMigration` opens a pre-extension DB and preserves existing jobs/ledger/witness behavior. `TestTimeReservationsDoNotChangeCallLedger` proves Claim/Contain do not create call reservations or alter `Ledger`, and receipt/audited settlement cannot touch time rows; repeat across cancellation, Release, Complete and reopen/Resume. Include containment retries, elapsed time above the reserve, and a period boundary. `TestConfiguredBudgetDropsAccountCostCap` isolates the old account cost ceiling from job/per-call limits and proves only the configured period hierarchy replaces it.
```go
if !errors.Is(err, team.ErrBudget) { t.Fatal("team ceiling bypassed") }
@@ -162,10 +167,14 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
if usage.Spent.Seconds != 300 { t.Fatal("contained time settled incorrectly") }
```
-- [ ] **Step 2: Run red tests.** `go test ./internal/equipo/team -run 'TestPeriodBudget|TestTimeCharge|TestBudgetPeriod|TestProjectBudget' -count=1` and `go test ./internal/equipotest -run TestBudgetConfiguration -count=1`.
+- [ ] **Step 2: Run red tests.** `go test ./internal/equipo/team -run 'TestPeriodBudget|TestTimeCharge|TestTimeReservations|TestBudgetPeriod|TestBudgetLowering|TestProjectBudget|TestConfiguredBudget' -count=1` and `go test ./internal/equipotest -run 'TestBudgetConfiguration|TestBudgetLoweringBelowUsage' -count=1`.
- [ ] **Step 3: Implement metadata limits.** Use calendar months in UTC as the explicit Foundation period choice; spec leaves period length to the builder. Start with no configured budget, represented as unavailable/unset, never unlimited or fictitious spend. The owner must supply team limits before project limits, and project limits before any future job. Persist no invented numeric production defaults. Account roll-ups sum their projects using checked integer arithmetic.
-- [ ] **Step 4: Extend the existing ledger, keeping its safeguards.** Map the prototype's `AccountID` to the stable Equipo team ID and its account ceiling to the team ceiling. In configured mode, require a known nonzero project on new jobs and prohibit parent/child project changes. Atomically check project and team period totals inside the existing `reserve`/`checkBudget` transaction. In configured mode these replace the lifetime account aggregate check, so a new month is not still blocked by a lifetime ceiling; preserve legacy account checks only in unconfigured fixture mode. Keep job/ancestor and per-call checks. Reserve `AttemptSeconds` at `Claim`; settle trusted elapsed time only in `Contain`, using the injected clock and attempt creation time. `Complete` and `Release` leave containment pending in this prototype and must not refund time. Unknown work stays reserved. Count every open reservation against the current period, regardless of creation month, and settled usage by its original reservation period; do not erase history at rollover. Time over the reserved maximum remains charged and blocks subsequent work. Update all finish/recovery paths consistently, using existing clock/fence/lock machinery and checked arithmetic. Increment the core schema version with additive migration steps; do not replace its witness protocol with GORM. `ConfigureBudgets` requires a matching revision and never permits lowering below current charged usage. With no configured hierarchy, retain legacy prototype fixture behavior; the later production adapter must always configure it before job creation.
-- [ ] **Step 5: Verify.** Run targeted tests, then both full core packages once after this core change. Verify unchanged evidence, cancellation, unknown-outcome and restore tests. App migrations still pass. The original positive `CostMicros` policy remains intact; subscription policy/currency relaxation is plan 2, not a fake currency value in this UI.
+- [ ] **Step 4: Add period checks and separate time reservations.** Map core `AccountID` to persisted `Team.ID`. Configured jobs require a known nonzero project; children keep their parent's project. Check team/project totals atomically at call reservation and Claim. Configured period limits replace the lifetime account aggregate check, including its account-level `CostMicros` ceiling: `PeriodLimits` has no currency field. Preserve job/ancestor, per-call, pricing and concurrency limits, and legacy account checks in unconfigured fixture mode. `ConfigureBudgets` uses revision checks and permits lowering below usage; new reservations then fail until they fit.
+
+ Add `time_reservations` keyed uniquely by attempt, recording team/project/job, original UTC period, reserved seconds, settled seconds and settlement state/time. Claim reserves `AttemptSeconds` atomically with the attempt. Only successful `Contain` settles elapsed time from attempt creation using the injected clock, once; overrun stays charged. Cancellation, lease expiry, Complete, Release and recovery leave uncontained time reserved. Count time only in period checks/`PeriodUsage`; leave `Usage`, call `reservations`, `Ledger`, receipt settlement and `SettleAudited` unchanged.
+
+ Both call and time period totals count every open row regardless of its age and settled usage in its original reservation month. Use checked arithmetic, preserve history and add core migrations without changing witness/fence/lock guarantees. Production must configure the hierarchy before future job creation.
+- [ ] **Step 5: Verify.** Run targeted tests and both full core packages once. Preserve these existing call-ledger regressions: `TestReservationLimitsAndOverflow`, `TestSettlementRules`, `TestLateUsageAfterCancelAndAuditedSettlement`, `TestEveryReplayClassRetainsUnknownUsage`, `TestAuditedUnknownUsageDoesNotQuarantineOtherJobs`, `TestConcludeRevokesUnusedIntents` and `TestFixture`. Keep evidence, cancellation, unknown-outcome and restore tests green; app migrations still pass. Positive `CostMicros` policy validation and job/per-call enforcement remain; only the configured account aggregate cap is dropped. Subscription-policy relaxation remains plan 2.
- [ ] **Step 6: Commit.** Stage Task 5 files; `git commit -m "feat: add team and project period limits"`.
## Task 6: Implement Authority from roster and project ownership
@@ -174,7 +183,7 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
**Interfaces:** `NewAuthority(store *Store, clock team.Clock) *RosterAuthority`; `(*RosterAuthority).Introspect(ctx context.Context, req team.AdmissionRequest) (team.Admission, error)`; `GrantRef(projectID int64, address string) string`. Grant refs use versioned JSON encoded with raw URL-safe base64, containing only project ID and canonical address; they are references, not credentials. `team.AccountID` must match persisted `Team.ID`. `Admission.Version` is the project's revision; `Admission.Epoch` is `RosterEpoch`; admissions last exactly five seconds.
-- [ ] **Step 1: Write tests.** `TestAuthorityUsesLiveRoster` admits a current `work` decision owner and a team owner, then rejects a removed member or reassigned work owner. `TestAuthorityRejectsMismatchedTarget` rejects unknown/malformed grants, wrong team, wrong repository, business targets, unknown operations and publishing to the default ref. `TestAuthorityFailureIsNotRevocation` injects a failed DB read and requires `team.ErrAuthorityUnavailable`, distinct from `team.ErrGrantRevoked`. `TestAuthoritySnapshotChanges` requires project revision/roster epoch changes and `ExpiresAt.Sub(IssuedAt) == 5*time.Second`.
+- [ ] **Step 1: Write tests.** `TestAuthorityUsesLiveRoster` admits a current `work` decision owner and a team owner, then rejects a removed member or reassigned work owner. `TestAuthorityRejectsMismatchedTarget` rejects unknown/malformed grants, wrong team, wrong repository, business targets, unknown operations, a mismatched app, a `DefaultRef` different from saved `Project.DefaultBranch`, and any `Ref` equal to that saved branch. Include a forged `DefaultRef="other"` with `Ref` set to the real default, across every allowed operation; a valid review branch with the saved default is admitted. `TestAuthorityFailureIsNotRevocation` injects a failed DB read and requires `team.ErrAuthorityUnavailable`, distinct from `team.ErrGrantRevoked`. `TestAuthoritySnapshotChanges` requires project revision/roster epoch changes and `ExpiresAt.Sub(IssuedAt) == 5*time.Second`.
```go
if !errors.Is(err, team.ErrGrantRevoked) { t.Fatal("wrong repository admitted") }
@@ -183,7 +192,7 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
```
- [ ] **Step 2: Run red tests.** `go test ./internal/equipotest -run TestAuthority -count=1`.
-- [ ] **Step 3: Implement a read-only Authority.** Resolve grant identity and current project/roster in one DB read transaction. Allow `OpJobContinue`, `OpAttemptContinue`, `OpProviderCall` and `OpForgePublish` only for a current team owner or the project's `work` owner. For `OpForgePublish`, additionally require a nonempty review ref different from `DefaultRef`; this grants review-branch publication, never merge. Reject `OpTrackerPublish` until its product contract exists. Other decision owners are routing records, not implicit execution permission. Return prototype errors with `errors.Is` compatibility. The later trusted job-creation adapter must derive `GrantRef` and requester from the authenticated person; possession of a ref never authorizes an HTTP request. No runner-facing endpoint is added here.
+- [ ] **Step 3: Implement a read-only Authority.** Resolve grant identity and current project/roster in one DB read transaction. Allow `OpJobContinue`, `OpAttemptContinue`, `OpProviderCall` and `OpForgePublish` only for a current team owner or the project's `work` owner. For every admission, match repository and app to the saved project, require `Target.DefaultRef == Project.DefaultBranch`, and reject an empty `Target.Ref` or one equal to the saved default. Compare validated canonical branch names; job-supplied `DefaultRef` is never the authority. `OpForgePublish` grants publication only to that review ref, never merge. Reject `OpTrackerPublish` until its product contract exists. Other decision owners are routing records, not implicit execution permission. Return prototype errors with `errors.Is` compatibility. The later trusted job-creation adapter must derive `GrantRef` and requester from the authenticated person; possession of a ref never authorizes an HTTP request. No runner-facing endpoint is added here.
- [ ] **Step 4: Verify integration.** In tests only, open `team.Open` with this Authority and fake adapters; call `Resume`, create a job, change ownership, and prove the next admission is stale or revoked. Run authority tests and the core contracts. Production `cmd/equipo` still opens only the app DB; execution-store persistence/replication and restore release must be resolved in plan 2 before enabling runners.
- [ ] **Step 5: Commit.** Stage Task 6 files; `git commit -m "feat: authorize core work from the instance roster"`.
@@ -208,11 +217,11 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
## Task 8: Build the rail, empty screens and Projects overview
-**Files:** Create the planned templates, `internal/equipo/{navigation,handlers}.go`, `internal/equipo/static/equipo.css`, `internal/equipotest/pages_test.go`; modify `render.go`, `copy.go`, `app.go`, icons.
+**Files:** Create the planned templates, `internal/equipo/{navigation,handlers}.go`, `internal/equipo/static/equipo.css`, `internal/equipotest/pages_test.go`; modify `internal/equipotest/perf_test.go`, `render.go`, `copy.go`, `app.go`, icons.
-**Interfaces:** Produce `NavItem{Key, Href, CopyKey, Icon string}` and `Navigation() []NavItem`; each handler has signature `(w http.ResponseWriter, r *http.Request)`. Use the Store interfaces from Tasks 3–7. `render(w http.ResponseWriter, name string, data any)` follows the pinned scaffold's buffered execution, not HEAD's newer `ui.Pages` API.
+**Interfaces:** Produce `NavItem{Key, Group, Href, CopyKey, Icon string}` and `Navigation() []NavItem`; each handler has signature `(w http.ResponseWriter, r *http.Request)`. Use the Store interfaces from Tasks 3–7. `render(w http.ResponseWriter, name string, data any)` follows the pinned scaffold's buffered execution, not HEAD's newer `ui.Pages` API.
-- [ ] **Step 1: Write route tests.** `TestRailRoutes` verifies the team link, all 11 destinations (four work pages, five specialists, Connections, Preferences), exactly one `aria-current` on each destination page (the `/work` index has no selected child), icon plus name, and no console Apps/Billing entries. `TestProjectsOverview` checks grouping, repository/app/decision owners, an add-project form, zero activity only after successful reads, and an unavailable CARLOS signal state. `TestOverviewFailureIsNotZero` forces a DB error and expects 503. `TestProjectForms` submits create/edit as owner, reads as member, rejects member writes, CSRF and tampered actor fields; HTML names are escaped. `TestEmptyScreensDoNotStartWork` requires no enabled composer/run/connect-provider action.
+- [ ] **Step 1: Write route tests.** `TestRailRoutes` verifies the team link, all 12 destinations in order (Conversation, Needs you, Journey, Projects; Specialists: Product, Design, Copy, Engineering, Review; Team: Connections, People, Settings), exactly one `aria-current` on each destination page (the `/work` index has no selected child), icon plus name, and no console Apps/Billing entries. `TestProjectsOverview` checks one account-grouped list spanning app/website/repository kinds, each card’s kind, repository/app/default branch/decision owners, an add-project form, zero activity only after successful reads, and an unavailable CARLOS signal state. `TestOverviewFailureIsNotZero` forces a DB error and expects 503. `TestProjectForms` submits create/edit as owner, reads as member, rejects member writes, CSRF and tampered actor fields; kind and default branch round-trip through create/edit, and HTML names are escaped. `TestRosterRouteCSRF` first succeeds with a same-origin owner POST to the mounted roster route, then requires a foreign-origin POST to return 403 without changing rows. `TestEmptyScreensDoNotStartWork` requires no enabled composer/run/connect-provider action.
```go
if response.Code != http.StatusServiceUnavailable { t.Fatal("failed count rendered as empty") }
@@ -220,11 +229,11 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
if currentCount != 1 { t.Fatal("ambiguous navigation position") }
```
-- [ ] **Step 2: Run red tests.** `go test ./internal/equipotest -run 'TestRail|TestProjectsOverview|TestOverviewFailure|TestProjectForms|TestEmptyScreens' -count=1`.
-- [ ] **Step 3: Review copy before inserting it.** No existing runtime copy convention exists at this HEAD; establish `internal/equipo/copy.go` as that single source. Follow the copy-review skill during implementation: index every app-owned string with context, including validation, empty states, email subject/body, titles, labels and accessible names; apply Paul's edits verbatim. Required navigation names come from the spec. Other keys include `projects.empty`, `projects.add`, `signals.unconnected`, `form.invalid`, `form.conflict`, `service.unavailable`, `conversation.empty` and specialist empty states. Keep draft wording short; mark the inventory `COPY REVIEW REQUIRED` until approved. Do not copy mockup sample activity or invent final prose in this plan. Add reviewed README copy through the same gate.
-- [ ] **Step 4: Implement the shell and routes.** Use the pinned sidebar template/attributes; customize its blocks, not its mechanics. `/` redirects to `/conversation`; `/work` is the phone index (`view=index`); content pages have parent links back to `/work#nav-<key>`. Routes: GET `/conversation`, `/needs-you`, `/journey`, `/projects`, `/connections`, `/preferences`, `/specialists/{key}`, `/team`, `/projects/new`, `/projects/{id}`, `/projects/{id}/edit`. POST `/accounts`, `/projects`, `/projects/{id}`, `/team/members`, `/team/budgets`, `/specialists/{key}` use the corresponding store mutators and redirect 303 after success. Render unknown IDs/keys as 404; invalid form as 422; stale revisions as 409; owner-only denial as 403. A single team appears at the rail top; its link opens the roster, with no nonfunctional team switcher.
-- [ ] **Step 5: Implement grouped cards and settings forms.** Projects overview uses account headings and project cards from `projects.html`; show saved metadata and actual project counts. With no jobs, activity areas have reviewed empty states, not sample work or percentages. Show configured limits and zero usage separately; missing limits are unset, not zero. Each project page is a metadata/settings detail, not the later product view. Team page exposes roster, label and budget forms; specialist pages expose their stored settings plus empty working/queued/finished sections. Connections/Preferences remain honest empty destinations. Use `html/template` escaping, icons from the vendored icon set, and only theme tokens in app CSS.
-- [ ] **Step 6: Verify.** Run page tests and `go test ./internal/equipotest -run TestVendoredAssetsMatchTheLibrary -count=1`; confirm `theme.css` and `shell.css` are linked and copied library bytes match `v0.28.0`. Navigation and every form work without scripts.
+- [ ] **Step 2: Run red tests.** `go test ./internal/equipotest -run 'TestRail|TestProjectsOverview|TestOverviewFailure|TestProjectForms|TestRosterRouteCSRF|TestEmptyScreens' -count=1`.
+- [ ] **Step 3: Review copy before inserting it.** No existing runtime copy convention exists at this HEAD; establish `internal/equipo/copy.go` as that single source. Follow the copy-review skill during implementation: index every app-owned string with context, including validation, empty states, email subject/body, titles, labels and accessible names; apply Paul's edits verbatim. Required navigation names use Paul’s revised rail in the Round 1 brief and `docs/mockups/nav.html`. Other keys include `projects.empty`, `projects.add`, `signals.unconnected`, `form.invalid`, `form.conflict`, `service.unavailable`, `conversation.empty` and specialist empty states. Keep draft wording short; mark the inventory `COPY REVIEW REQUIRED` until approved. Do not copy mockup sample activity or invent final prose in this plan. Add reviewed README copy through the same gate.
+- [ ] **Step 4: Implement the shell and routes.** Use the pinned sidebar template/attributes; customize its blocks, not its mechanics. `/` redirects to `/conversation`; `/work` is the phone index (`view=index`); content pages have parent links back to `/work#nav-<key>`. Routes: GET `/conversation`, `/needs-you`, `/journey`, `/projects`, `/connections`, `/people`, `/settings`, `/specialists/{key}`, `/projects/new`, `/projects/{id}`, `/projects/{id}/edit`. POST `/accounts`, `/projects`, `/projects/{id}`, `/team/members`, `/team/budgets`, `/specialists/{key}` use the corresponding store mutators and redirect 303 after success. Render unknown IDs/keys as 404; invalid form as 422; stale revisions as 409; owner-only denial as 403. Use a single team header linking to `/people`, followed by the four work pages, the five Specialists and the Team group (Connections, People, Settings), as in the revised mockup. The header is not a second selected nav item or a team switcher.
+- [ ] **Step 5: Implement grouped cards and settings forms.** Projects overview uses account headings and project cards from `projects.html`; show each project’s saved kind and metadata and actual project counts in one list, with no separate app/website lists. With no jobs, activity areas have reviewed empty states, not sample work or percentages. Show configured limits and zero usage separately; missing limits are unset, not zero. Each project page is a metadata/settings detail, not the later product view. People exposes the roster; Settings exposes account-label and budget forms; specialist pages expose their stored settings plus empty working/queued/finished sections. Connections remains an empty destination; personal preferences stay in plan 3. Use `html/template` escaping, icons from the vendored icon set, and only theme tokens in app CSS.
+- [ ] **Step 6: Verify.** Run page tests and `go test ./internal/equipotest -run TestVendoredAssetsMatchTheLibrary -count=1`; confirm `theme.css` and `shell.css` are linked and copied library bytes match `v0.28.0`. Navigation and every form work without scripts. Update `TestPerfScreens` with seeded concrete `Paths` for project and specialist routes. Its `ScreenConfig.Signin` calls Task 3’s email-link helper using the supplied client/cookie jar and base URL, with the configured Origin on POSTs; sign-in and the `MinAge` wait occur before timing. Require 200 plus a page-specific content assertion for each private page, and keep redirects explicit for `/`; never count a sign-in redirect as a measured private page. Run `make perf`.
- [ ] **Step 7: Commit.** Stage Task 8 files and approved copy; `git commit -m "feat: add the rail and grouped projects overview"`.
## Task 9: Exercise the finished app in a browser and provide local startup
@@ -233,9 +242,9 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
**Interfaces:** Keep production `App` from Task 1. The drive uses that app with a capturing mailer and a real framework session minted through its sign-in flow, not an auth-bypass flag. New drive flags: `-addr` (default `127.0.0.1:8824`), `-db` (required scratch DB path). `run.sh` consumes a local ignored environment file and executes the built binary with explicit `--db` and `--addr` flags, following memoria's script shape.
-- [ ] **Step 1: Add browser/startup assertions.** `TestFoundationBrowserWalk` uses Rastrillo `harness.New`, `rig.Run` and `rig.Screen` with `chromedp` as the pinned scaffold does: sign in, add account, create two projects, reopen, edit, sign out. At widths 1280 and 390, and with JavaScript disabled, assert no horizontal overflow; all rail/index destinations reachable; specialist back link returns to its index row; long project names wrap; project creation succeeds. `TestProductionDoesNotUseDriveAuth` starts the production handler with missing/invalid auth configuration and requires refusal. Browser screenshots are inspection evidence, not a substitute for assertions.
+- [ ] **Step 1: Add browser/startup assertions.** `TestFoundationBrowserWalk` uses Rastrillo `harness.New`, `rig.Run` and `rig.Screen` with `chromedp` as the pinned scaffold does: sign in through the capturing-mailer helper with the production `NoProof` guard and its `MinAge`, add account, create projects of all three kinds, reopen, edit, sign out. At widths 1280 and 390, and with JavaScript disabled, assert no horizontal overflow; all rail/index destinations reachable; specialist back link returns to its index row; long project names wrap; project creation succeeds. `TestProductionDoesNotUseDriveAuth` starts the production handler with missing/invalid auth configuration and requires refusal. Browser screenshots are inspection evidence, not a substitute for assertions.
- [ ] **Step 2: Run the browser test before fixes.** `go test -tags browser ./internal/equipotest -run TestFoundationBrowserWalk -count=1`; observe the missing flow or rendering assertion fail. A skipped browser is not a pass; use an installed Chromium or `RASTRILLO_CHROME` as the scaffold supports.
-- [ ] **Step 3: Implement local tooling and fix browser failures.** `run.sh` requires explicit owners, origin and persistent instance key, opts into logged mail only for loopback development, uses `exec`, and never contains production secrets. The drive creates synthetic account/project data through real store/HTTP interfaces, opens no inbound address except loopback, and removes its own scratch on shutdown. Do not copy memoria's auth bypass into production or its hard-coded home directory. Review setup prose before writing it.
+- [ ] **Step 3: Implement local tooling and fix browser failures.** `run.sh` requires origin and a persistent instance key, accepts owners for first-boot seeding only, opts into logged mail only for loopback development, uses `exec`, and never contains production secrets. The drive creates synthetic account/project data through real store/HTTP interfaces, opens no inbound address except loopback, and removes its own scratch on shutdown. Do not copy memoria's auth bypass into production or its hard-coded home directory. Review setup prose before writing it.
- [ ] **Step 4: Verify the complete slice.** Run `make ci`, then the browser command, once with script enhancements and once without. Inspect desktop and phone pages, keyboard focus, parent navigation and empty states. Run `go test -race ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipotest` once for the changed transactional core/auth boundaries. Check no test uses an external provider or CARLOS credential. Stop drive/review servers and remove only session-owned scratch.
- [ ] **Step 5: Commit.** Stage Task 9 files; `git commit -m "test: verify the foundation sign-in and project flow"`.
@@ -243,31 +252,47 @@ Shared app types: `Role string` with only `owner` and `member`; `Actor{Address s
**Files:** Modify `Makefile`, reviewed `README.md`; create `internal/equipotest/release_test.go`. Human deployment changes no source file.
-**Interfaces:** `make release` produces `releases/equipo-linux-arm64`; `RELEASE_GOARCH=amd64` is an explicit alternative. Stamp `amadan.net/rastrillo/rastrillo.BuildVersion` with `git rev-parse --short HEAD`. The human supplies `CARLOS_ACCOUNT`; there is no inferred default.
+**Interfaces:** `make release` produces `releases/equipo-linux-arm64`; `RELEASE_GOARCH=amd64` is an explicit alternative. Stamp `amadan.net/rastrillo/rastrillo.BuildVersion` with `git rev-parse --short HEAD`. The deployment target is the `oficina` account on the flagship console, [https://console.carloku.com/a/oficina](https://console.carloku.com/a/oficina), as confirmed by Paul. Project account labels do not change that target.
- [ ] **Step 1: Write a failing release check.** `TestReleaseStampContract` tests the Make recipe using a fake `go` executable to capture arguments: require `CGO_ENABLED=0`, Linux/arm64 defaults, correct output path and `-X amadan.net/rastrillo/rastrillo.BuildVersion=<commit>`. A dirty tracked file must make the recipe fail before building even with a supplied `VERSION`, and a supplied unrelated `VERSION` must not change the commit stamp. The recipe must include `-trimpath` and print `carlos deploy`, not the scaffold's `carlos ship`. Mutate the stamp/path deliberately, see failure, then restore it. No deploy command runs in this test or in CI.
- [ ] **Step 2: Run red check.** `go test ./internal/equipotest -run TestReleaseStampContract -count=1`; the unadapted scaffold permits a `VERSION` override and prints `carlos ship`; expect those assertions to fail. Its existing stamping and output path are not missing features.
-- [ ] **Step 3: Implement the memoria release pattern.** Use `-trimpath` and `-ldflags "-s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=$(git rev-parse --short HEAD)"` in the actual shell recipe, with Make's doubled dollar escaping. Reject dirty tracked files independently of the stamp variable, remove the arbitrary `VERSION` override, and replace the scaffold's printed ship command with the human deploy instruction. Document required origin, owners, stable instance key and platform SMTP configuration without secret values; provider credentials are not needed. Do not invent CARLOS configuration CLI flags: the human uses the supported account/app configuration surface, confirms the real HTTPS origin, and provisions these settings before startup.
+- [ ] **Step 3: Implement the memoria release pattern.** Use `-trimpath` and `-ldflags "-s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=$(git rev-parse --short HEAD)"` in the actual shell recipe, with Make's doubled dollar escaping. Reject dirty tracked files independently of the stamp variable, remove the arbitrary `VERSION` override, and replace the scaffold's printed ship command with the human deploy instruction. Document required origin, first-boot-only owners, stable instance key and platform SMTP configuration without secret values; provider credentials are not needed. Do not invent CARLOS configuration CLI flags: the human uses the supported account/app configuration surface, confirms the real HTTPS origin, and provisions these settings before startup.
- [ ] **Step 4: Verify and commit the release preparation.** Run the release test, `make ci`, and commit Task 10 files with `git commit -m "build: prepare the human-run CARLOS release"`. Then `make release`; expect the stamped Linux/arm64 artifact. This commit is an implementation step, not permission to merge or deploy.
-- [ ] **Step 5: Human deploys after choosing the account.** This step is performed by Paul or a human operator, never by the implementing agent. From the clean, reviewed revision, set the chosen account and run the verified memoria command shape:
+- [ ] **Step 5: Human deploys to oficina on the flagship console.** This step is performed by Paul or a human operator, never by the implementing agent. From the clean, reviewed revision, confirm the CLI targets the flagship console and run the verified memoria command shape with Paul’s chosen account:
```sh
- : "${CARLOS_ACCOUNT:?Set the Equipo deployment account}"
- carlos deploy --app equipo --account "$CARLOS_ACCOUNT" --channel edge --timeout 5m ./releases/equipo-linux-arm64
+ carlos deploy --app equipo --account oficina --channel edge --timeout 5m ./releases/equipo-linux-arm64
```
Flags precede the binary. Confirm the target's architecture before choosing the release override. Poll GET `/api/version` on the actual deployed origin until the process reports the stamped commit; the router's `X-Carlos-Version` is insufficient.
-- [ ] **Step 6: Human acceptance.** Sign in as a configured owner, add a second roster member, create an account label and two projects (one repo-only), refresh/restart and verify persistence. Sign in as the member and verify shared visibility and denied owner edits. Open every empty destination and the phone Work index. Confirm no runner is enrolled, no execution job exists, and no provider/CARLOS credential was requested. Record acceptance in the normal review record; do not claim deployment from a successful local build.
+- [ ] **Step 6: Human acceptance.** Sign in as a configured owner, add a second roster member, create an account label and projects spanning all three kinds (one repo-only), refresh/restart and verify persistence. Sign in as the member and verify shared visibility and denied owner edits. Open every empty destination and the phone Work index. Confirm no runner is enrolled, no execution job exists, and no provider/CARLOS credential was requested. Record acceptance in the normal review record; do not claim deployment from a successful local build.
## Questions for Paul
-1. Which CARLOS account should host the Equipo instance? Memoria uses `bds`, while mockups show `tito` and Personal project groups; neither establishes Equipo's deployment account. This blocks only Task 10's human deployment.
+Resolved: Paul chose `oficina` on the flagship console, [https://console.carloku.com/a/oficina](https://console.carloku.com/a/oficina). Task 10 uses that account; no deployment-account question remains. His project-kind and revised-rail answers are applied in Tasks 4 and 8.
## Self-review results
1. **Spec coverage:** §§2, 3.2, 3.3, 4.1, 4.5, 5.1, 6.7 and 8 map to Tasks 1–10. Roster/sign-in: 3; projects/owners: 4; team/project limits: 5; Authority: 6; specialists: 7; rail/overview/phone shell: 8–9; human deployment: 10. Coordinator/runtime/evidence extensions, provider connections, product ranking and routing are excluded according to the roadmap. Plan-edit operations are plan 3; quarantine release and execution-store deployment are plan 2 prerequisites. No Foundation requirement is silently delegated to a future UI.
-2. **Step scan:** Tasks name files, interfaces, assertions and red/green commands; no function bodies or invented final product copy. New APIs are explicitly planned interfaces. Future commits are described but none is made by this planning session. All proposed subjects are under 80 characters.
+2. **Dependency check:** Task 3 can finish with roster store operations, mounted auth routes and a private middleware test handler. Project-assignment removal checks belong to Task 4; roster HTTP CSRF checks belong to Task 8 and require a successful control POST. This prevents a missing route from passing as authorization protection.
3. **Type/source consistency:** Framework references use verified `v0.28.0` APIs and its `amadan.net` module path, not memoria's old path or newer HEAD-only auth/scaffold APIs. Nested core placement avoids the migration CLI's single-app scan. `team.AccountID` always means the Equipo team; CARLOS labels never scope execution. Project revisions and roster epochs invalidate admissions. App and core migration ownership remain separate.
4. **Review Focus:** All five failure classes have named tests in their owning tasks. Bootstrap and seeding preserve edits; session revocation is checked on requests; malformed bindings never become network requests; time and uncertain reservations remain charged; browser/layout and DB-failure tests prevent plausible empty results.
-5. **Proportion and validation:** Ten reviewable tasks cover Foundation. At about 6,400 words against the 4,270-word whole spec, the plan is longer because it includes source-grounded integration and red/green steps, but is not several times the spec; assertion blocks are a small minority. Tests and signatures specify decisions without implementing the application. The planning pass checked source files, tag-specific APIs, imports, the prototype diff and command definitions; it did not run application tests, build, deploy or claim future tests passed.
-6. **Conflicts found:** The mockup says the phone opens on Work, while spec §4.1 defaults to Conversation and later permits a personal choice; the spec wins. The mockup's console Apps/Billing hierarchy is superseded by the standalone Equipo rail. Roadmap row 4 mentions phone layout, but the Foundation brief explicitly requires its basic shell now. Spec §9's provider egress conflicts with the unamended suite §8; Foundation has no provider egress, and the separate amendment remains needed before later live use. Spec §§6.8/9 acknowledge subscriptions cannot enforce token/currency caps while also requiring token limits; this plan preserves recorded ceilings and the core's metered policy, leaving the runner plan to distinguish admission/reservation limits from what an unmodified subscription CLI can actually enforce. The prototype's distinct-provider review is stricter than the spec's distinct-family rule; preserve it here and resolve assignment behavior in plan 2. Memoria's deployment prose and Rastrillo's generic navigation prose are stale in the ways recorded above.
+5. **Accounting boundary check:** Time is keyed by attempt in its own table and settled only by Contain. It never enters call receipts or audited settlement. The named existing call-ledger tests must stay unchanged and pass alongside the configured-mode isolation test. Configured mode deliberately drops the account currency cap, while preserving job/per-call caps; lowering a budget blocks new reservations without rewriting prior usage. This planning pass checked source contracts, not execution of the future tests.
+6. **Conflicts found:** The mockup says the phone opens on Work, while spec §4.1 defaults to Conversation and later permits a personal choice; the spec wins. Paul’s revised rail supersedes the older spec’s Preferences entry: Foundation uses the Team group with Connections, People and Settings, with no console Apps/Billing. Roadmap row 4 mentions phone layout, but the Foundation brief explicitly requires its basic shell now. Spec §9's provider egress conflicts with the unamended suite §8; Foundation has no provider egress, and the separate amendment remains needed before later live use. Spec §§6.8/9 acknowledge subscriptions cannot enforce token/currency caps while also requiring token limits; this plan preserves recorded ceilings and the core's metered policy, leaving the runner plan to distinguish admission/reservation limits from what an unmodified subscription CLI can actually enforce. The prototype's distinct-provider review is stricter than the spec's distinct-family rule; preserve it here and resolve assignment behavior in plan 2. Use memoria’s release recipe over its stale “never deployed” README paragraph and the shipped sidebar over Rastrillo’s older disclosure prose.
+
+## Round 1 dispositions
+
+- P1-1: Added `pow.Schema`, a production `NoProof` guard with `MinAge`, the framework sign-in fields and startup/scriptless tests; this mode requires no pow assets.
+- P2-1: Specified attempt-keyed `time_reservations`, Contain-only settlement and period-only totals, excluded call settlement, and named the existing ledger regressions.
+- P2-2: Added owner-entered `Project.DefaultBranch`; Authority checks saved default/ref bindings for every admission, with forged-default tests.
+- P2-3: Replaced the inaccessible keymail fake with capturing-mailer email-link sign-in; framework tests retain keymail coverage.
+- P2-4: Moved assigned-owner removal to Task 4 and roster-route CSRF to Task 8 with a successful control request; Task 3 covers the store and auth.
+- P2-5: Corrected the repeated-migration assertion to `len(second.Applied) != 0`.
+- P3 (budgets): Made removal of configured account `CostMicros` explicit and allowed lowering below usage, with new reservations blocked.
+- P3 (auth): Made DB-error admission false, deleted removed members’ sessions transactionally, documented first-boot-only owners, and selected the shipped sign-in partial.
+- P3 (project uniqueness): Made canonical repository plus app unique, including the blank-app case.
+- P3 (speed tests): Specified `ScreenConfig.Signin` with the real email-link cookie flow before timing, seeded paths and private-page assertions.
+- P3 (proportion): Reduced the grounding table and Task 5 Step 4 to decisions and replaced self-review items 2 and 5 with dependency/accounting checks.
+- Paul’s deployment answer: Task 10 now targets `oficina` on the flagship console and the account question is resolved.
+- Paul’s project kinds: Added app/website/repository to the record, forms, tests and each card in one Projects list.
+- Paul’s rail: Task 8 now specifies the team header, four work pages, five Specialists and Team group with Connections, People and Settings.