Interface, Integration And Effect Reconstruction Catalog¶
- Status:
CURRENT RECONSTRUCTION CATALOG - Purpose: define the information future application and migration work must preserve for commands, queries, events, provider calls, files and devices
- Current API owner:
.agents/rules/API_CONTRACTS.md - Current Runtime owner:
.agents/rules/ARCHITECTURE.md - Process sequence owner:
PROCESS_SEQUENCE_DIAGRAM_CATALOG.md - Capability template:
CAPABILITY_REBUILD_PACKET_TEMPLATE.md
1. Interface Layers¶
flowchart TB
User[User / External Consumer]
UI[React UI or current PHP/JS]
Adapter[Next.js Route Handler / Server Action / current API route]
Application[Application Command / Query]
Domain[Domain / Policy]
Repository[Repository / Transaction]
DB[(MySQL)]
Outbox[Outbox / Effect Intent]
Worker[Node Worker]
Provider[Provider / File / Device]
User --> UI
UI --> Adapter
Adapter --> Application
Application --> Domain
Application --> Repository
Repository --> DB
Application --> Outbox
Outbox --> Worker
Worker --> Provider
Layer responsibilities¶
| Layer | Owns | Does not own |
|---|---|---|
| UI | presentation, input, interaction, visible result and recovery guidance | SQL, transaction, role policy, provider retry |
| Web/API adapter | auth/session/tenant adaptation, parsing, validation envelope, HTTP mapping | business transition and persistence detail |
| Application command/query | use-case orchestration, authorization request, transaction intent, result/error contract | framework presentation or provider protocol detail |
| Domain/policy | state, validation, capability and invariants | HTTP, SQL and external SDK calls |
| Repository/transaction | SQL, mapping, conditional update and commit | UI and provider retry |
| Effect/outbox | durable intent and correlation | core state mutation after response unless explicitly owned |
| Worker/adapter | provider/file/device execution, retry and reconciliation | redefining business completion |
2. Common Request Context¶
Every target query/command/effect receives or derives:
tenantExecutionContext
actor / subject
operatingProfile
capabilityDecision
requestId / correlationId
sourceName / entrypoint
locale / timezone / unit context where needed
Do not accept browser-controlled tenant/module/role fields as authority.
Request identity¶
A stable request/command ID should allow:
- duplicate recognition;
- audit correlation;
- effect intent correlation;
- unknown-result readback;
- support investigation;
- retry without repeating an already committed command.
3. Query Contract Catalog¶
3.1 Platform and context queries¶
| Query | Purpose | Source | Required output |
|---|---|---|---|
GetCurrentSessionContext |
authenticated actor/subject/tenant/profile | session + tenant/profile/capability sources | safe actor, tenant, profile, capabilities, timezone/locale; no secrets |
GetNavigation |
role/capability-aware menus and stable links | menu/module/capability config | visible navigation and disabled/denied explanation |
GetCurrentUserCapabilities |
command/UI decision support | role/menu/module/policy | named capabilities, provenance and policy state |
GetTenantConfigurationView |
admin-safe typed configuration | tenant config and published deployment context | values plus source/version; secret references redacted |
3.2 CTC Inbound and Loader queries¶
| Query | Purpose | Authoritative/derived sources | Important constraints |
|---|---|---|---|
GetInboundPlanningBoard |
current Office planning workload | transload, planner, equipment, yard, company/master | date/profile scope, derived readiness, no hidden mutation |
GetAssignmentBoard |
current/next/ready work by Loader | planner + transload + Loader roster + staff state | queue derivation and multi-Loader policy explicit |
GetLoaderCurrentWork |
personal Loader current/next work | authenticated actor + planner/transload | server-scoped personal assignment; current versus completed separated |
GetLoaderTimeline |
staff/job evidence for manager review | staff events + planner context | derived totals and immutable events distinguished |
GetBreakQueue |
scheduled/active Break work | Break compatibility rows + staff events | reads must not secretly own expiry mutation in target design |
3.3 Final Review and inventory queries¶
| Query | Purpose | Sources | Required distinctions |
|---|---|---|---|
GetFinalLoadingReviewQueue |
Pending/Confirmed review candidates | transload review fields, final metrics, planner and inventory evidence | readiness reasons, selected date, exact review state |
GetFinalLoadingReviewDetail |
one source-backed review | transload, equipment/load, lot/ledger/placement | Data, Source, Leftover, Weight and audit sections |
GetInventoryAdjustmentOptions |
eligible Source/Leftover actions | lots, balances, placements and active ledger | eligibility, quantity/UOM and current balance |
GetLotLedger |
immutable movement/reversal history | inventory ledger | signed amount, source, reversal and actor/reason |
3.4 Yard and Driver queries¶
| Query | Purpose | Sources | Important constraints |
|---|---|---|---|
GetYardDispatchQueue |
Office queue planning/monitoring | queue, location, equipment | active/completed/cancelled definitions and physical mismatch cues |
GetYardInstruction |
personal Yard Driver claim/current work | queue + authenticated actor + location | assigned/claim ownership enforced server-side |
GetYardMap |
physical occupancy projection | Yard location plus permitted overlays | freshness and source-of-truth labels |
GetPullOutClosingContext |
closing inputs and current checkpoint | queue, equipment/load, scale ticket, files | existing closing evidence versus missing Yard completion |
GetDriverCurrentWork |
personal Driver log and delivery cards | actor, driver log, delivery, equipment/load | no caller-selected arbitrary user scope |
GetParkingContext |
request/assignment/placement state | delivery, Yard queue/location, notification | independent checkpoints visible |
3.5 Billing/provider queries¶
| Query | Purpose | Sources | Important constraints |
|---|---|---|---|
GetBillingCandidates |
source-backed local invoice candidates | transactions/presets/source processes | freshness, selected source and totals |
GetLocalTransaction |
authoritative AP/AR local state | transaction and lines | provider status separate |
GetProviderReconciliation |
local effect intent versus QBO/Gmail/Telegram state | effect records + provider lookup | unknown/unmatched/manual review |
GetTransactionFiles |
file links and readability | T_FILE + storage | object/link/readability separated |
3.6 MK queries¶
| Query | Purpose | Sources |
|---|---|---|
GetCommercialOrder |
Purchase/Sales agreement and lines | commercial order tables |
GetInboundPurchase |
operational Purchase and receipt/lot readiness | load/items, transload/lot/scale |
GetOutboundSales |
Sales demand, booking and allocation readiness | load/items, booking, equipment, allocation |
GetBookingEditorContext |
parameterized fields/options | booking, order, profile/capability/config |
GetAllocationWorkbench |
lot availability and outbound demand | lots, ledger/balance, load items/allocation |
GetScaleWork |
physical Scale stage and owner context | scale ticket/events + owner process |
GetTradeSummary |
derived deal result | orders, allocation, costs, rates, scale |
4. Command Contract Catalog¶
The tables below are reconstruction targets. Exact DTOs and policies remain owned by capability packets.
4.1 Planning, assignment and workforce¶
| Command | Actor | Preconditions | Local transaction | Readback | Separate effects |
|---|---|---|---|---|---|
CheckInInboundWork |
Office | scheduled/pre-planned eligible row | transload status/check-in | transload detail and planning board | optional operation event |
SaveInboundPlan |
Office | arrived/editable row; valid equipment/location/fields | planner and approved transload plan fields | plan detail/readiness | none or explicit Yard planning intent |
ConfirmInboundAssignment |
Office | plan ready; Loader policy satisfied | assignment/queue fields and status | assignment board + Loader current work | Telegram intent |
AssignLoader |
Office | planner exists; Loader eligible | assigned user(s), queue order | planner/assignment detail | Telegram intent |
ReorderLoaderQueue |
Office | same tenant/Loader and eligible scheduled rows | ordered assignment values | assignment board | none |
ClockInStaff |
staff/manager | no conflicting open Clock state | staff event | current staff state | QuickBooks Time intent |
ClockOutStaff |
staff/manager | approved active-job/open-Break policy | Clock Out event plus approved scheduled-assignment release | staff state + released assignments | QuickBooks Time intent and notifications |
CreateBreakRequest |
manager/Office | Loader/shift eligible | Break request/compatibility row | Break queue | Telegram intent |
StartBreak |
assigned Loader/manager | current approved Break, working, no conflicting state | BREAK_IN + Break state | staff state + Break queue | QuickBooks Time intent |
EndBreak |
worker/manager/system | open Break | BREAK_OUT + Break completion | staff state + next queue | QuickBooks Time + next notification |
StartLoaderJob |
assigned Loader/authorized Office recovery | scheduled assignment, actor, equipment/location, no conflicting active attempt | transload state + planner job attempt + staff evidence | Loader current work and plan | operation/Telegram intent |
CompleteLoaderJob |
assigned Loader/authorized recovery | active attempt and completion evidence | transload terminal state + planner finish + approved inventory/Yard handoff checkpoint | completion detail, review/inventory/Yard status | notifications/effect intents |
UndoLoaderJobAttempt |
authorized recovery | approved active attempt and compensation scope | restore executable state + immutable compensation evidence | planner/transload/timeline | no silent evidence deletion |
4.2 Final Review and inventory¶
| Command | Actor | Preconditions | Local transaction | Readback | Separate effects |
|---|---|---|---|---|---|
ConfirmFinalLoadingReview |
authorized Office reviewer | eligible Pending review, readiness true, current version | review status/actor/time/reason + transition evidence | review detail and queue | optional notification |
BulkConfirmFinalLoadingReviews |
authorized reviewer | each row independently eligible | explicit all-or-nothing or per-row policy | per-row result and queue | optional summary notification |
ReopenFinalLoadingReview |
authorized reviewer | Confirmed and correction reason/policy | review state/history | Pending detail | none |
UseInboundWeight |
authorized reviewer | explicit approved weight policy | final weight/reason as part of one command | review detail | none |
ApplySourceLot |
inventory operator | positive difference, eligible lot/balance/location | lot balance + ledger + relation/placement | lot/ledger/review readiness | operation event |
CreateLeftoverLot |
inventory operator | negative difference and approved source/location | new lot + ledger + placement/relation | new lot/ledger/review readiness | operation event |
VoidInventoryAdjustment |
authorized correction role | reversible adjustment and no invalid downstream use | reversal ledger + restored balances/placement | ledger and balances | audit/notification |
4.3 Yard and Driver¶
| Command | Actor | Preconditions | Local transaction | Readback | Separate effects |
|---|---|---|---|---|---|
CreateYardWork |
Office | entity/current location/destination valid | queue row | queue and Yard map | optional notification |
ScheduleYardWork |
Office | destination resolved and work eligible | queue state/order | Yard queue | notification optional |
ClaimYardWork |
Yard Driver/authorized Office | scheduled, physical source valid, no conflicting claim | compare-and-set claim | personal instruction + queue | operation event |
UnclaimYardWork |
claimant/authorized Office | currently claimed | queue to scheduled; claim semantics explicit | queue/instruction | none |
CompleteYardMove |
claimant/authorized Office | claimed, actual location valid, physical work done | queue + Yard location + mirrors | completed queue + Yard map | operation event / dependent queue evaluation |
RecordPullOutClosing |
Yard Driver/closing role | intended queue/equipment and evidence | scale/closing checkpoint | closing detail | files/device effects as defined |
CompletePullOut |
claimant/authorized recovery | closing checkpoint exists and queue still active | Yard queue/location completion | closing + queue + Yard map | operation event |
StartDelivery |
assigned Driver/Office recovery | active Driver Log, assigned scheduled delivery, Yard blockers resolved | delivery/equipment approved boundary | delivery + Yard state | notification/event |
FinishDelivery |
assigned Driver/Office recovery | dispatched, evidence and destination policy satisfied | delivery/equipment and approved Yard checkpoint | delivery, files, Yard/parking | notification/event |
RequestParking |
assigned Driver | eligible delivery and return-to-yard context | parking request | parking context | Telegram intent |
AssignParking |
Office | requested and target valid | parking assignment | parking context | Telegram intent |
ConfirmParking |
assigned Driver/Office recovery | assigned target and physical placement | Yard queue/location + parking checkpoint | parking, Yard, delivery | notification and separate delivery completion where required |
4.4 Billing and providers¶
| Command | Actor | Preconditions | Local transaction | Readback | Separate effects |
|---|---|---|---|---|---|
ConfirmLocalInvoice |
authorized billing role | source/candidate current and totals valid | transaction/header/lines | local transaction | QBO/file/email intents optional |
CorrectLocalTransaction |
authorized billing role | correction policy and downstream state permit | corrected transaction + audit | transaction detail | provider reconciliation if already sent |
SendInvoiceToQbo |
authorized billing role/worker | local transaction committed and not reconciled | effect intent only or provider-result persistence | local/provider reconciliation | QBO call |
LinkTransactionFile |
authorized role | object uploaded and relation valid | file relation | file list/readability | storage object may precede relation |
SendBolEmail |
authorized TMS role/worker | source/recipient/attachments current | email intent | effect status | Gmail call |
SendPackingListEmail |
authorized booking role/worker | target/parts current | email intent | effect status | Gmail call |
4.5 MK order-first commands¶
CreateCommercialOrderUpdateCommercialOrderCreateInboundPurchaseUpdateInboundPurchaseItemMaterializeReceiptAndLotCreateOutboundSalesUpdateOutboundSalesItemCreateOrLinkBookingUpdateBookingAllocateInventoryCorrectAllocationonly after approved policyStartScaleTicketAcceptScaleReadingCorrectOrVoidScaleReading- owner-specific Purchase/Sales/Yard/Delivery finalization commands
- explicit cost/rate correction commands
Each must be parameterized by profile/capability rather than customer ID.
5. Error Taxonomy¶
The target application should use typed errors mapped by adapters.
| Category | Meaning | Typical HTTP | User action |
|---|---|---|---|
| Validation | input is incomplete/invalid | 400/422 | correct fields |
| Unauthenticated | no valid session/principal | 401 | sign in |
| Forbidden | actor lacks capability/record access | 403 | stop/escalate; do not switch accounts casually |
| Not Found | record absent in tenant/current scope | 404 | refresh/search/correct reference |
| Conflict | stale state, duplicate, concurrent transition | 409 | reread before deciding |
| Dependency Blocked | related process/provider/config prevents action | 409/422/503 by contract | resolve named dependency |
| Rate Limited | provider/system throttle | 429 | wait/retry per policy |
| Provider Unknown | local intent exists but provider outcome unknown | 202/409 or domain result | reconcile; do not repeat business command |
| Unexpected | server defect/infrastructure failure | 500 | record request ID and escalate |
Internal SQL/provider messages must not be returned as public validation errors.
6. Idempotency And Duplicate Contract¶
Business commands¶
Use a stable idempotency/request identity when duplicate execution can create a second business result.
The command result should allow:
newly committed
already committed with same request
conflict with different request/state
unknown and requires reread
Effects¶
Provider/file/device retries must use an effect identity separate from the business command.
Example:
AssignLoader command ID: A
Telegram assignment effect ID: A:telegram:loader:<id>
Retrying the Telegram effect must not re-run AssignLoader.
Batch operations¶
Every batch documents one of:
- all-or-nothing transaction;
- independent per-row commits with result list;
- chunked commits with resume token;
- dry-run plus explicit apply.
The UI must display which rows committed.
7. Timeout And Unknown-Result Pattern¶
sequenceDiagram
participant User
participant UI
participant App
participant DB
participant Provider
User->>UI: Submit once
UI->>App: Command with request ID
App->>DB: Conditional transaction
DB-->>App: Commit
App->>Provider: Effect or persist intent
Note over UI,App: Response is lost / times out
UI->>App: Query by business ID and request/correlation ID
App->>DB: Reread authoritative record/effect status
DB-->>App: Committed / not committed / partial
App-->>UI: Current state and safe next action
Required operator rule:
Do not repeat the original physical, business or provider action
until authoritative state and independent effect checkpoints are reread.
8. Provider Integration Contract¶
Every integration documents:
provider name
credential owner and secret reference
local business owner
local intent record
idempotency strategy
request timeout
retryable/non-retryable errors
provider response and provider object ID
final reconciliation query
manual recovery
retention/redaction
rate limits
sandbox/test strategy
observability
Telegram¶
- notification only unless a process explicitly makes delivery an approval/readiness condition;
- message target must use stable user/chat mapping;
- sent/failed/skipped/unknown are separate;
- resend does not repeat assignment, Break or delivery command;
- current Break readiness coupling requires an explicit policy decision before migration.
Gmail¶
- preserve Gmail message/thread/draft/send identity;
- attachment/source identity and recipient selection are explicit;
- draft creation and send are different effects;
- unknown send requires provider/thread lookup before retry;
- appointment intake and outbound email remain separate capabilities.
QuickBooks Online¶
- local transaction remains separately readable;
- provider customer/item/account mapping is explicit;
- create/update/search/reconcile paths are documented;
- provider-created/local-save-unknown is a first-class recovery state;
- no blind invoice resend.
QuickBooks Time¶
- local staff events remain CTC source of truth unless Product changes that policy;
- provider user/jobcode mapping is configuration;
- sync is separate from Clock/Break command success;
- manual review is required for external active timesheets outside the supported model.
AI extraction¶
- input file/message, extraction type, model, prompt/version and raw/normalized result are traceable;
- deterministic parsing is preferred where reliable;
- AI cannot silently commit business state;
- human review and edits are retained before application command;
- sensitive data and retention are defined.
Files¶
- upload object and business link are separate checkpoints;
- content hash/type/size and storage reference are recorded where possible;
- direct upload/large file flow is distinct from business commit;
- object missing, link deleted and business record deleted are different states.
Scale/device¶
- device reading and accepted business weight are different;
- raw reading provenance and unit are preserved;
- timeouts/eventual commit are reconciled by ticket/session identity;
- correction/void never overwrites history silently.
9. Event And Worker Model¶
Target durable work candidates:
- Break expiry and next-job notification;
- Telegram assignment/Break/Driver messages;
- QuickBooks Time synchronization;
- QBO invoice delivery and reconciliation;
- Gmail sends/drafts and appointment ingestion continuation;
- PDF/Excel/image generation;
- AI extraction;
- file processing and preview;
- report refresh/materialization when approved;
- retry/reconciliation scans;
- migration/import batches.
Worker sequence¶
sequenceDiagram
participant App
participant DB
participant Worker
participant Provider
App->>DB: Commit business record + effect intent
DB-->>App: Committed result
App-->>User: Local success/readback
Worker->>DB: Claim due effect by identity
Worker->>Provider: Execute adapter call
alt provider accepted
Provider-->>Worker: Provider ID/result
Worker->>DB: Store success/reconciliation
else retryable failure
Provider-->>Worker: Error
Worker->>DB: Store attempt + next retry
else manual review
Worker->>DB: Store manual-review state
end
A request-response after() hook may record lightweight telemetry but is not a durable queue substitute.
10. Current Adapter Inventory Entry Format¶
For each active route/page/helper, record:
| Field | Meaning |
|---|---|
| adapter path | exact source file |
| public entry | page slug/API route/job/webhook |
| method/action | exact operation |
| module key | current module gating |
| role/record guard | current authorization source |
| request fields | browser/external contract |
| query/command invoked | current or target semantic owner |
| tables read/written | current data footprint |
| transaction | owner and commit boundary |
| effects | provider/file/device timing |
| response | visible result/error |
| callers | pages/external clients/jobs |
| target disposition | retain/adapt/replace/retire |
| caller-zero evidence | source/runtime proof required |
This inventory belongs in P5/capability packets, not in one giant generated registry detached from actual consumers.
11. Migration Adapter Rules¶
During coexistence:
- current PHP may call a new TypeScript service only through an explicit compatibility contract;
- Next.js may call a legacy PHP API temporarily when PHP remains the writer;
- neither direction may create two independent transaction authorities;
- shared DTOs are versioned and mapped deliberately;
- provider effect ownership remains single;
- rollback restores the previous entry/writer without replaying committed effects;
- stable user/Wiki URLs receive redirect/compatibility treatment;
- every compatibility path has a removal condition and owning Task.
Read adapter¶
Next.js Server Component
-> TypeScript query
-> MySQL repository
Do not HTTP-call the same Next.js application from a Server Component merely to reach its own Route Handler.
Write adapter¶
React form
-> Server Action or Route Handler
-> TypeScript command
-> MySQL repository transaction
-> effect intent
-> exact readback
Use a Route Handler when another consumer needs the HTTP contract. Use a Server Action only as a UI-local adapter.
12. Interface Reconstruction Completion Checklist¶
For each interface:
- [ ] semantic query/command/effect name;
- [ ] owner and consumer;
- [ ] actor/tenant/profile/capability;
- [ ] input/output DTO;
- [ ] validation and record authorization;
- [ ] state predicate;
- [ ] tables and transaction owner;
- [ ] exact readback;
- [ ] idempotency/duplicate/conflict;
- [ ] timeout/unknown result;
- [ ] effect intent/attempt/reconciliation;
- [ ] public error mapping;
- [ ] current adapters and callers;
- [ ] target React/Next.js/TypeScript/worker mapping;
- [ ] migration one-writer and rollback;
- [ ] caller-zero and retirement;
- [ ] Runbook/Wiki reference;
- [ ] verification scenarios.
13. Priority Missing Interface Packets¶
- CTC Billing/QBO/file/email effect contracts;
- typed Loader assignment and job-attempt commands;
- typed Break and workforce commands independent from planner compatibility storage;
- Final Review policy DTO and transition history;
- Yard Pull Out resumable checkpoint contract;
- Driver parking and finish partial-result contract;
- MK parameterized Booking field contract;
- allocation correction/concurrency contract;
- Scale device/session/finalization contract;
- tenant/profile/capability and Next.js session bridge.
---¶
Source:
docs/reconstruction/INTERFACE_INTEGRATION_AND_EFFECT_CATALOG.md— ctc repository · This page is an English translation of the source document. Identifiers, file paths and code symbols are unchanged.