Skip to content

Planning entities on the server: one table map, lifecycle set and id rule - #2079

Merged
Kevinjohn merged 168 commits into
mainfrom
issue/2013-planning-entity-table-map
Nov 16, 2026
Merged

Kevinjohn merged 168 commits into
mainfrom
issue/2013-planning-entity-table-map

Conversation

@Kevinjohn

@Kevinjohn Kevinjohn commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

What and why

The server declared the planning table map, the lifecycle set and the entity id rule in several places.

  • apps/backend/app/services/product_tables.ts is the one AppData-to-table map (satisfies Record<AppDataKey, string>). The TABLE_NAMES copy in entity_policy.ts is removed; execute, restoration, the writer, the beta account transfer, example data and the tests import the map.
  • The policy and the writer use the shared isLifecycleEntityKey instead of local lifecycle lists.
  • ENTITY_ID_PATTERN is exported from validators/planning/fields.ts and used by entity_policy.ts, so both accept the colon that imported and Internal client ids carry (internal:<company>).
  • The beta transfer insert order and the schema-integrity scoped tables derive from the shared SCOPED_WRITE_ORDER.

Tests: an update of a client whose id contains a colon now commits (independent_operations.spec.ts); tests/functional/product_tables.spec.ts fails when the company snapshot read misses an AppData key. Both were mutation-checked.

Decisions made without the owner

  • Creates still require a UUID, so the widened id rule only reaches updates of imported or Internal client rows. Before this change such an update failed the stricter policy check.

Closes #2013

Gate evidence

  • pnpm run check:changed <predecessor branch>: passed (format, lint, type-check and the backend suite: 564 tests).
  • Pre-push check:push (format, type-check, lint): passed.
  • Validation workflow on this head: run 43868566283
  • Stack tip gate on issue/2015-service-dependencies, which contains this branch: e2e passed (309 tests). gate:all passed every step except one backend test, which failed while the machine was under heavy load; a rerun of the whole backend suite on the same commit passed all 572 tests.

Merge order

#2062 → #2063 → #2064 → #2065 → #2066 → #2067 → #2068 → #2069 → #2070 → #2071 → #2072 → #2073 → #2074 → #2075 → #2076 → #2077 → #2078 → #2079 → #2080 → #2081 → #2082 → #2083 → #2084 → #2085 → #2086

Merge predecessor for this PR: #2078.

Conflicts: none. This PR test-merges cleanly into its base branch, the stack is linear so no pair of open PRs conflicts, and the stack tip (#2086) test-merges cleanly into main at 6e54407d3.

Closes #2013. The AppData-to-table map now lives only in
services/product_tables.ts; entity_policy's TABLE_NAMES copy is gone
and every caller imports the one map. The lifecycle set comes from the
shared LIFECYCLE_ENTITY_KEYS in both the policy and the writer. The
validators and the write policy share ENTITY_ID_PATTERN, which accepts
the colon in generated Internal client ids, so updating a row with such
an id no longer fails the stricter policy check.

The beta transfer insert order and the schema integrity scoped tables
derive from the shared SCOPED_WRITE_ORDER; a new spec fails when the
company snapshot read misses an AppData key.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2014. app/exceptions/http_error_mapping.ts now holds the
central handler's mapping for every known error family, including the
masquerade and password-confirmation refusals that handler.ts mapped
inline. handle() sends what it returns, and report() derives the
expected-error list from it: a mapped outcome below 500 is not logged
unless the mapping marks it (database constraints, Account Kit server
faults). Mapped masquerade and admission refusals are therefore no
longer logged as unexpected 500s.

IdentityAuthorityError and AdmissionRequiredError keep their per-surface
wording, now declared once with the reason beside it, and the planning
and admission adapters call the same functions. A unit test pins each
surface's body and the reporting rule.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2012. Only services/planning/restoration.ts now names
deleted_groups, deleted_rows and planning_mutations in queries (the
schema integrity checks excepted). Callers use named functions that
take the transaction:

- discardRestorationGroups: planning invalidation, beta import and
  anonymisation;
- ownsUnconsumedGroup: the writer's retained-id reuse check;
- isMutationCommitted, recordCommittedMutation and
  committedMutationRevision: the planning mutation marker.

PlanningOperationError moves to planning/errors.ts, so the writer can
import the restoration module without an import cycle; the writer and
execute modules still export it.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2008. writer.ts's writeRow now only inserts or updates a
prepared row and applies it to the company snapshot. writeEntity in
planning/entity_write.ts runs the steps it used to hold, each now kept
with the rule it belongs to:

- the restricted-field refusal and the create defaults move to
  entity_policy.ts; the defaults are declared once there, and the
  duplicate resource defaults in assertRequired are gone;
- the allocation working-day gate moves to entity_validation/domain.ts;
- retained-id reuse moves to restoration.ts as reclaimRetainedId;
- the validation lookup adapter moves with writeEntity.

The order of checks and every refusal are unchanged; no test assertion
changed.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2009. services/planning.ts now orchestrates the read, lookup
and mutation flows. Authority resolution moves to
planning/authority.ts (resolvePlanningAuthority), and the before/after
comparison, patch projection and privacy triggers move to
planning/mutation_changes.ts. The idempotency marker already lives in
the restoration module since #2012.

The privacy trigger fields (client and project isPrivate and codeName,
activity kind) are declared once in PRIVACY_TRIGGER_FIELDS;
requiresRefetch and invalidatesRestoration both read it. The
transaction, authorization, audit and failure order is unchanged.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2010. planning/restricted_fields.ts declares, per entity, the
fields a role without the capability may neither see nor change: the
time-off note, and the client and project private-name fields (with the
name hidden only on a private row). Every path now derives from it:
the write refusal, the stored-value pinning, the validation view, the
undefined-field allowance and the preserved values in entity_policy.ts,
the private-row skip in normalization.ts, and the read projection in
state_transformer.ts.

One stricter outcome: the read projection now clears a code name left
on a row that is not private, which the redaction previously passed
through; normal writes never store one.

The table map already moved out of the policy file in #2013. A new spec
walks the declaration and fails when any declared field's stored value
reaches the read projection or a restricted write is accepted.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
…ository

Closes #2011. state_repository.ts keeps the company snapshot read and
row encoding. Fixture seeding moves to services/fixture_seed.ts, the
database health check to services/database_health.ts, and the
disposable demo company creation into services/disposable_demo.ts, its
only caller. The code moves unchanged.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
…ository-split

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
…services

For #2015. The planning read, archive, mutation and lookup services and
the ownership transfer take the transaction and verified actor from
their controllers, which open withActor. effectiveReadPrincipal takes
the company instead of reading route params; the masquerade start, end
and status helpers take the context token and company their controllers
read; parseAccountCommand takes the two header values.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2015. Member sign-in tracking changes now run in
changeMemberSignInTracking, and the member-resource link and unlink
audits are written by setMemberResourceLink and clearMemberResourceLink,
as member mutations already were. The sign-in identity check and the
invitation preview's company name move from their controllers into
installation_company.ts.

writeAudit, the restoration save, consume and count, the sign-in
tracking writes, the member-resource link and the first company's
defaults take `now`, defaulting to the current time.

docs-src/reference/code-standards.md now says how request services
receive the actor and transaction, and exempts boot-time and operator
services (commands and services/operations, readiness and schema
checks, fixture, demo and development bootstrap seeding, storage
maintenance, the transaction helper) from the no-singleton rule.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2019. createTypedPlanningActions now takes requireAccount from
the store guards instead of its own copy, so catalogue, time-off and
resource writes accept a company known from the account summaries, as
allocation writes already did, and refuse with the same messages. The
ExternalForm test expects the shared guard's wording for a missing
company. A new test writes while the company is known only from the
summaries: the guard admits it and the command builder stops it before
anything is sent.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2016. A new planningSessionSlice owns the planning cache
controller, context changes and auth-loss clearing, refresh and
reconciliation, command suspension, replacement readiness, undo/redo
and sendPlanningCommand, together with the publication that resets the
scheduler view and renames account summaries. The allocation slice keeps
only the allocation rules and actions and writes through
sendPlanningCommand like every other entity. Store keys and action names
are unchanged. The architecture reference names the new file.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Part of #2019. An active id with no row and no summary is refused with
the shared guard's not-loaded wording. A switched company known only
from the summaries now reaches the role check, which blocks the write
under the fail-closed viewer role instead of the old guard throwing.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2017. MasqueradeController now reads and writes the store only
through injected readState and writes the context proof only through
injected setContextToken; projection recovery adopts a confirmed proof
through the same writer. The production instance, its bootstrap read
through the store transport seam and the import-time registrations move
to masqueradeControllerInstance.ts.

The data layer no longer imports the proof: the planning cache
controller takes readMasqueradeContextToken and captures it into every
read and write context, the planning transport sends only the proof its
caller captured (an empty one when none was), and apiFetch reads it
through a reader registered with setMasqueradeContextReader. Masquerade
stays a read-only projection; the server still refuses every write
under it.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #1973.

The docs build, navigation check, lightbox runtime and screenshot
publication check now live together in scripts/docs/. Repository-root
lookups gain one level, and the docs workflow path filters, pnpm
commands, ESLint ignores, VitePress config and lightbox test point at
the new paths. Command names and the generated site are unchanged.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2025.

The sidebar, the command palette and the document title each kept their
own list of routes and repeated the disciplines, capacity overview and
diagnostics visibility decisions. navLinks.ts now holds APP_ROUTES, one
table in sidebar and palette order where each route carries its sidebar
placement and visibility rule. useVisibleRoutes builds the visibility
context from the member's role, permission status and company settings
and lists the visible routes; AppShell and the palette read from it and
the document title looks labels up in the same table.

Which routes each role sees is unchanged, and a new test pins the visible
routes per role, capacity overview setting and disciplines flag. Route
guards and server authorization in route_access.ts are untouched and stay
independent of what the client shows.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
…tion

Closes #2020.

Import, company-wide anonymisation, resource anonymisation and example data
each repeated the replacement protocol: check readiness, suspend planning
writes, send, then refresh or require a reload. The copies differed in small
ways and lived mostly in view code.

runSuspendedReplacement in data/planning/suspendedReplacement.ts now owns that
protocol and returns a typed outcome: blocked, departed, refused, committed or
uncertain, with reloadRequired when writes stay suspended. Refused requests
resume writes so the message stays visible and the action can be retried; an
uncertain result reconciles with a fresh read, or keeps writes suspended for a
page reload when that read fails or the caller recovers by reloading.

The transfer preview, transfer apply and both anonymise requests moved to
data/companyDataRequests.ts with unchanged URLs, methods and bodies, so no
component calls apiFetch, suspendPlanningCommands or
planningReadyForReplacement. The two hard-coded "finish loading" notices are
now catalogue messages with the same text, and the never-produced "refresh
skipped" lifecycle message is removed.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2023.

The schedule, the capacity overview and the Resources list each carried
their own copy of the Studio/Supplementary fallback bands and the
placeholder-last resource order, and seven open-coded checks decided
whether a resource kind was switched on for the company.

apps/frontend/src/lib/resourceGrouping.ts now owns:
- isResourceKindEnabled, the one answer to whether a kind is enabled;
  the palette, allocation and time-off resource pickers, the schedule
  filter, the person schedule, the time-off list and the capacity
  overview use it;
- buildResourceBand and buildEngagementGroups, with every band title
  (Resources, Overall, Unassigned, Unassigned demand, External / 3rd
  party, Studio, Supplementary) read from the message layer;
- createResourceComparator, the one resource order, which the schedule,
  the capacity overview and the Resources list all sort with.

Owner decisions: both placeholder avatar colours stay as they are. The
schedule gives a placeholder its discipline colour (its own colour when
it has none), while the capacity overview gathers placeholders into the
uncoloured Unassigned demand band so they show their own colour; comments
in SchedulerGridRow and CapacityOverviewTableGrid state this as
intended. The Resources list uses the shared order; placeholders and
externals are always Studio, so its order is unchanged.

English is the only locale, so the new titles are added to en.json only.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2022.

The in-flight guard, the stale-edit check and the handling of a cancelled
save were copied into each entity form, and the forms disagreed on where the
current rows came from: seven read the store singleton at submit time while
the resource form took them as a parameter.

useEditSubmit now owns that protocol. It takes the current rows as an input
(each form subscribes to its slice), refuses a stale edit, saves, closes on
success, keeps the draft open on a blocked create, and shows any other failure
on the form. The activity, client, discipline, external, project, closure,
time-off and resource forms all prepare a validated save and hand it to the
hook; the time-off and resource forms keep their own accepted-submission and
company-switch guards around it.

A save the user cancels in the Restore cleanup dialog now leaves every form
open without an error. The activity, client and project forms already did
this; the discipline, external, closure, time-off and resource forms showed
"The planning save was cancelled." as a form error.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2018. planningCacheController.ts is now the request state
machine only. Its port and state types move to planningCacheTypes.ts,
PlanningControllerError and errorDetails to planningErrors.ts, and the
UI notice predicates isShownByPlanningState and readPlanningProblem to
planningNotices.ts; importers now use those modules directly.

planningReadiness.ts holds the one readiness rule,
isPlanningReadyForChange, used by begin, the send check, undo/redo
through isPlanningHistoryReady and the session slice's replacement
check, which each kept their own copy before. The PlanningTransport
port now documents its error contract: the controller acts on
uncertain and restoration-confirmation failures only when they arrive
as PlanningControllerError.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2035.

The allocation and time-off forms each kept a copy of the repeat and
repeat-until state, and they disagreed about a repeat switched on before
the start date was valid: time off marked the end date as suggested and
filled it once a valid start date arrived, while allocations left it empty.

Owner decision: both forms follow the time-off behaviour. Switching repeat on
always marks the end date as suggested, and it is filled from the form's
default once a valid start date exists.

useRepeatUntil now holds the repeat choice, the repeat-until date and the
suggestion flag, and takes the default-date function as a parameter. The
allocation form passes defaultRepeatUntilDate and the time-off form passes
defaultTimeOffRepeatUntilDate. A new allocation modal test covers repeat
switched on before a valid start; the existing time-off form test covers the
same case for time off.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Refs #2022.

The shared edit-submit hook made every form stay silent when the user
cancels the Restore cleanup dialog. Before it, the discipline, external,
closure, time-off and resource forms showed "The planning save was
cancelled." as the form error, while the activity, client and project
forms stayed open with no error.

useEditSubmit now takes an optional cancelledMessage. The five forms that
showed the message pass resolveErrorMessage, which produced it before, and
the other three omit it, so every form behaves as it did before the hook.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
…-until-hook

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #1974.

The port registry, lane claims, launcher, demo and full-stack runners and
the port guard now live together in scripts/dev/. Imports from Vite,
VitePress, Playwright, the backend test runner, end-to-end support and
the remaining scripts follow the new paths, as do the port guard's file
list and messages, the docs workflow path filter, package scripts and
the user story source links. Repository-root lookups gain one level.
Command names and behaviour are unchanged.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2024.

Gesture helpers now take their inputs instead of reading the store:
gestureWorkingWeeks takes a GestureCalendar (resources and the company
working week), and gestureAnnouncements splits the visible-window
over-capacity count (buildVisibleOverCapacity) from its message
(formatCapacityAnnouncement). useAllocationGestureController is the one
place that reads the live store, at the moment of each call, so commits
and keyboard actions still see the current calendar and a preview frame
for a known lane still reads nothing.

The inline Add activity path in useAllocationModalState no longer
serialises the whole data slice to decide whether its draft may follow
the new revision. isSoleAcknowledgedAdvance in planningCacheController
answers it from planning metadata: same context, revision exactly one
past the draft's, and that revision acknowledged. Each committed change
advances the company revision by one, so this admits the same cases as
the old row comparison.

Shared pieces leave the scheduler folder so person-schedule, time off and
the capacity overview no longer import scheduler internals:
useCalendarToday moves to hooks/, buildAllocationAttribution to lib/, and
the renderable date-range checks to lib/renderableDateRanges.ts. The
Draft and Patch types move from store/entityDrafts.ts to
lib/entityDrafts.ts, so lib/ no longer imports from store/. No behaviour
changes.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2021.

The single accountClient object covered sessions, companies, diagnostics,
example data, members, avatars, invitations, masquerade, admission and
invitation sign-up, and handed raw responses to screens that then read status
codes and decoded bodies themselves.

The raw requests now live in one module per concern: sessionRequests,
memberRequests, invitationRequests, admissionRequests, masqueradeRequests and
invitationSignupRequests, plus companyDataRequests for example data. Every
URL, method, header and body is unchanged, and createInvitation keeps its
masquerade-context race check. Each module is read only by its typed client:
teamAccessClient, ownershipTransferAccess, masqueradeApi, fetchAuthStatus and
the company directory reader.

Screens that read responses themselves now call typed readers instead:
invitationSignupClient returns preview and sign-up results, the getting-started
client returns the dismissed flag, readServerDiagnostics returns one
observation, readSoleCompanyOwnership answers the setup-conflict check, and
readImportSummary decodes a committed import. No component inspects a
response status or parses a body.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Closes #2026.

Backend:
- executePlanningIntent takes one ExecutePlanningIntentOptions object
  instead of six positional parameters. Its body is unchanged, so the
  write-access refusal, the company check, the writes and the caller's
  revision and audit steps in mutatePlanning keep their order.
- PlanningCapabilities drops canAnonymise, which was computed for every
  operation and never read, and takes its role type from the shared Role
  instead of re-listing the four roles. PlanningAuthority extends it, so
  authority.ts no longer repeats the capability fields.

Frontend:
- sendPlanningCommand no longer accepts an `original` argument; the
  planning session never read it, and typedPlanningActions stops
  passing it.
- createTypedPlanningActions takes a getter typed to the two store
  fields it reads (data and sendPlanningCommand) rather than the whole
  StoreState.
- SchedulerGrid calls useSchedulerGridVirtualization with the four
  values it needs instead of a wrapper that took three whole hook
  results, and its modal boundary and footer take the modal state and
  the visible closures instead of the whole interactions and
  virtualization results.

useMembersOrchestration's return stays as it is: its one consumer,
MembersSection, uses nearly every key and already hands each child a
Pick of it. SchedulerGridRow's props are all read by the row or the
header and lane it renders.

Signed-off-by: Kevinjohn Gallagher <kevinjohngallagher@hotmail.com>
Move application build tooling into scripts/build/
Move local development and port management into scripts/dev/
Move documentation tooling into scripts/docs/
…unt-request-tests

Tests: split the account request tests by module
…uerade-controller-tests

Tests: split the masquerade controller tests by concern
…ning-cache-tests

Tests: split the planning cache controller tests by concern
…-provider-tests

Tests: split the AuthProvider tests by concern
Split smaller files that hold a second unrelated job
Narrow contracts that are wider than their consumers
Repeat end date: one hook for the allocation and time-off forms
Scheduler: pure gesture helpers, planning-owned revision checks, no feature cycle
Resource grouping and kind rules: one module for schedule and capacity overview
…ults

Account client: typed results and a split by concern
Whole-company replacement: one suspended-replacement function
Planning cache controller: split types, errors, notices and readiness
Masquerade controller: inject the store and context token
…lice

Store: give the planning session its own slice
Backend services: take actor, transaction and clock as parameters
…plit

State repository: move seeding, health check and demo creation out
Entity policy: declare restricted fields once and move the table map out
…plit

Planning service: separate authority, diffing and idempotency from orchestration
Planning writer: reduce writeRow to persistence
…access

Restoration tables: route all access through the restoration module
Error responses: one mapping per error class
@Kevinjohn
Kevinjohn merged commit 08bacd7 into main Nov 16, 2026
21 checks passed
@Kevinjohn
Kevinjohn deleted the issue/2013-planning-entity-table-map branch November 16, 2026 23:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

polish-done Polish review complete

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Planning entities on the server: one table map, lifecycle set and id rule

1 participant