How to carry out this brief
Follow this entire specification as one connected task, using Grill → Plan → Goal → Review. First read the whole brief and inspect only what is authorized.
- Grill: ask focused questions only about material conflicts or missing prerequisites; resolve them before planning.
- Plan: produce a decision-complete plan without editing files and STOP for my explicit approval.
- Goal: only after that approval, implement the agreed scope in verified milestones.
- Review: inspect the result against every requirement without edits and report prioritized findings with evidence. Ask for authorization before addressing findings outside the approved scope. The instruction to deliver a working application never overrides the plan approval gate. The detailed instructions for all four stages are included at the end of this same prompt.
These are portable prompting styles, not universal agent modes. A prompt does not change your agent’s actual operating mode or permissions. Select a native mode separately if your agent provides one.
| Deliverable | Required result |
|---|---|
| Application | Working SOKit service, SOKit UI, migrations and shared contracts |
| Business workflow | DRAFT → SUBMITTED → APPROVED → FINALIZED; SUBMITTED → RETURNED → SUBMITTED; SUBMITTED → REJECTED |
| Trust boundaries | Organization ownership, assigned review, separate issuance and protected evidence |
| Delivery evidence | Fixtures, automated tests, local startup and requirement-to-test report |
Build this application, with these boundaries
Build the Certificate of Origin (COO) application specified below, including working persistence, migrations, reference management, secured document operations, a complete SOKit UI, protected attachments, localized notifications, sample certificate output and automated acceptance tests. Do not stop at a mockup, generic CRUD, skeleton or a plan. First produce the implementation plan; execute it after I approve it. Treat the requirements below as the agreed example scope, not as questions for the AI to invent answers to. Ask only about genuine conflicts, unavailable dependencies or decisions that prevent implementation.
Model the business structure with exporter and other parties, separate request and issuance references, transport and goods details, assigned review, applicant-visible correspondence and restricted internal notes. The exact limits, numbering, permissions and simplified lifecycle below are deliberate rules for this training application, not legal requirements. Exclude payments, cancellation, reissue, official signing, seals and external certification integrations. Never represent the output as a legally valid certificate.
Inspect the repository and its instruction files first. If it is empty apart from repository metadata or documentation, discover the supported application scaffolds and propose a monorepo with the required UI, services, shared contracts, tests and deployment configuration before creating files. If an application exists, preserve its topology and conventions, find the owning components and extend them without creating another application or replacing root configuration. If the project is incompatible, explain why and ask for a migration decision before restructuring.
Use SMART to discover the applicable framework profile and load relevant guidance at the returned revision. Follow supported SOKit and SOKit UI contracts, explicit monorepo dependency directions and the project’s Quarkus conventions for injection, validation, persistence, transactions, configuration and tests. Reuse generated contracts and pinned build tools; do not invent APIs, copy older build files or silently change versions. Report missing guidance, access or dependencies honestly. Use fictional data and keep secrets out of examples.
Repository, components and deliverables
For an empty repository, use the supported scaffold to create one monorepo. Plan named owners for the web UI, COO document service, reference management, shared generated contracts, integration/end-to-end tests and local deployment configuration. Capabilities may share an existing service where the selected scaffold supports that; do not create a microservice per table. Keep UI dependencies on public generated contracts, service dependencies on owned domain/persistence components, and shared libraries free of application-specific reverse dependencies. Root commands orchestrate component builds and checks.
For an existing application, locate and extend these owners in place, preserving its package manager, build system, routes, authentication and module boundaries. Do not create a second application or replace root files. For an incompatible project, describe the incompatibility and obtain a migration decision before restructuring. Deliver an architecture map, schema/migrations, supported generated DTOs/contracts, implemented screens and operations, localized messages, fixtures, tests, environment-variable example without secrets, local startup instructions and a requirement-to-test checklist. Discover SMART's applicable revision/profile and use its current SOKit, SOKit UI and Quarkus contracts; the logical names in this brief are not invented framework APIs.
Identity, roles and authorization matrix
Require authentication everywhere except the sign-in entry. Use trusted identity and organization membership to resolve applicant organization, issuing organization and staff eligibility. Never accept owner IDs, roles, reviewer identity, state, business references or audit actors from editable applicant fields. The applicant account may act for an exporter only through a server-verified mandate; for the seeded example, applicant organization and exporter are the same.
Implement these logical permissions through the application's supported authorization system: Applicant may create, search, read, edit and submit records owned by an organization in which they have active applicant membership. Reviewer may read assigned records belonging to their issuing organization and return, approve or reject a SUBMITTED record. Review supervisor may see that issuer's review queue and assign/reassign eligible reviewers, with a mandatory reason; supervisor status alone does not grant decision authority. Issuing officer may issue APPROVED records of their issuing organization. Reference administrator may manage catalogs but gains no document access from that role alone. Authorized issuer staff may read internal notes on records within their permitted scope; applicants may never read them, even if another role would otherwise expose them on their own application.
Deny self-review and self-issuance: a decision actor must not be the creator or an applicant member of the owning organization. The issuing officer must also differ from the approving actor. Check both operation permission and record scope on the server for search, reads, action discovery, mutations, history, correspondence, sample output and downloads. An unassigned reviewer cannot discover another reviewer's records. Use the existing application's non-disclosing access-denial convention consistently. Test direct URL and forged-request access, not just hidden buttons.
Route each applicant organization to its issuing organization using trusted server configuration; fail creation if no authorized route exists. Staff eligibility includes active membership, operation permission and every separation-of-duty rule in this brief. Apply those checks when resolving configured default reviewers and issuing officers as well as at execution time.
Data model: document, parties and shipment
Use the supported versioned e-document identity and expected-version mechanism. The aggregate contains: immutable documentId; version; state; trusted ownerOrganizationId, createdBy, createdAt and updatedAt; issuingOrganizationId; assignedReviewerId; submittedAt; resubmissionCount initially 0; approvedBy/approvedAt; requestReference/requestDate; issuanceReference/issuedAt; validFrom/validUntil. Store instants in UTC and business dates as date-only values. Use a configurable issuer business time zone, UTC in the demo. Model server-controlled fields in restricted operation-specific DTOs, not a mass-assignment DTO.
Embed exporter and consignee snapshots: identifier (1–64 characters), legalName (1–200), address (1–500), country reference, contactName (optional, up to 200), email (optional, valid and up to 254), phone (optional, up to 32). Both parties are required at submission. Additional parties are an ordered child collection with stable row ID, role BROKER or NOTIFY_PARTY, and the same fields. They are optional, at most 10, with no duplicate role/identifier pair. Keep applicant identity distinct from these commercial party snapshots. Snapshot issuing organization identity from trusted configuration.
Shipment fields required at submit/resubmit: originCountry, destinationCountry, finalDestinationCountry, transportMode, expectedExportDate, loadingLocation, unloadingLocation, finalUnloadingLocation. The three locations must belong respectively to origin, destination and final destination countries. Allow equal destination and final destination. For SEA require vesselName; ROAD require vehicleRegistration; AIR require flightNumber; RAIL require trainReference; each up to 100 characters. Other mode-specific fields remain optional and are omitted from output if empty. Expected export date must be on or after the operation's business date at submission/resubmission. Do not reapply that future-date rule during later review or issuance.
Reference tables and historical meaning
Implement nine catalogs: countries; locations with parent country; transport modes; package types; supplementary units; currencies with minor-unit precision; commodity classifications; origin criteria; attachment types. Each record has stable code (1–32), translated EN/FR/ES/AR labels (1–200), active flag, optional inclusive validFrom/validTo dates and version. Codes are unique within a catalog and immutable after creation; validTo cannot precede validFrom. Referenced rows cannot be physically deleted: deactivate them. New submissions require references active and effective on the submission date.
Provide paginated code/label search, active/effective filters, translated labels with a documented fallback, and create/edit/deactivate screens restricted to reference administrators. Authenticated users may read applicable catalogs. Location pickers filter by their selected country. Persist code and display-label snapshots in document versions so subsequent renaming/deactivation cannot rewrite historical meaning. Revalidate edited/resubmitted requests; do not invalidate an issued certificate retroactively.
Seed clearly fictional DEMO-prefixed countries, locations, units, currencies and classifications for tests, plus mode behavior for SEA/ROAD/AIR/RAIL, attachment types INVOICE and ORIGIN_EVIDENCE, and illustrative criteria DEMO_WHOLLY_OBTAINED and DEMO_VALUE_CONTENT. The latter requires percentageExportPrice; the former forbids it. Do not import fabricated official tariff or origin rules. Real catalog imports are outside the demo until an authorized source and license are supplied.
Goods lines, amounts and submission rules
Store 1–100 ordered goods lines. Each line has a stable ID distinct from sequenceNumber, classification reference, commercialDescription (1–255), marksAndNumbers (1–255; use the explicit value NO MARKS if none), packageType, packageCount (positive integer), supplementaryQuantity and unit, grossWeightKg, netWeightKg, originCriterion, optional percentageExportPrice, invoiceReference (1–64), invoiceDate, invoiceCurrency and invoiceValue. Require all fields except the conditional percentage at submit/resubmit. Line sequence numbers are unique and consecutive; reordering must preserve IDs.
Use decimal arithmetic, not binary floating point. Quantities and weights are positive with at most three fractional digits; net weight cannot exceed gross weight. Invoice value is positive, decimal precision 18 with scale matching the selected currency's 0–3 minor units; reject excess precision instead of silently rounding user input. Percentage is a decimal from 0 through 100 inclusive, at most two fractional digits, required only for DEMO_VALUE_CONTENT and absent for DEMO_WHOLLY_OBTAINED. Preserve a permitted zero percentage as zero. Invoice date must not be after the submit/resubmit business date or the expected export date.
Compute read-only totals by currency by summing line values; a line's invoiceValue means the value allocated to that goods line, not the whole invoice repeated on every line. Lines sharing invoice reference/date must have the same currency. Show total packages and weights separately; never add supplementary quantities across different units or convert currencies implicitly. Enforce limits, field types and numeric consistency even when saving an incomplete draft, but defer completeness and submission-date checks to submit/resubmit. Return localized, line-specific and field-specific errors without discarding valid input.
Exact lifecycle and operation inputs
Use exactly these core persisted states: DRAFT, SUBMITTED, RETURNED, APPROVED, REJECTED, FINALIZED (displayed as Issued). Reviewing is an activity on SUBMITTED, not another state. Generate actions from the supported e-document contracts; do not expose a writable status field. Every mutation requires current expectedVersion and runs its authorization, validation, state change and history in one transaction. For CREATE_DRAFT, use the supported initial-operation contract instead of requiring a previous document version.
CREATE_DRAFT
no record → DRAFT; Applicant; editable party/shipment/goods/attachment data, possibly incomplete.
SAVE_DRAFT
DRAFT → DRAFT; owning Applicant; same editable fields.
SUBMIT
DRAFT → SUBMITTED; owning Applicant; full completeness, catalog and evidence validation; assign request reference/date and submittedAt on first submission. Resolve the issuer's configured default reviewer from trusted active staff; fail clearly without committing if none is eligible. Applicant cannot choose or spoof that reviewer.
RETURN
SUBMITTED → RETURNED; assigned Reviewer; public reason 10–2000 characters and optional internal note up to 4000, with no goods edits.
SAVE_CORRECTION
RETURNED → RETURNED; owning Applicant; editable business data, same relaxed draft rules.
RESUBMIT
RETURNED → SUBMITTED; owning Applicant; full submission validation and public correction summary 10–2000; increment resubmissionCount, preserve request reference/date, and preserve the assigned reviewer if still eligible, otherwise resolve the configured eligible default.
APPROVE
SUBMITTED → APPROVED; assigned Reviewer; validFrom and validUntil, optional public comment and optional internal note; recheck required business fields and evidence, excluding submission-only future-date rules; store approving actor/time.
REJECT
SUBMITTED → REJECTED; assigned Reviewer; required public reason 10–2000 and optional internal note.
REASSIGN
SUBMITTED → SUBMITTED; issuer Review supervisor; eligible reviewer ID and internal reason 10–2000; record old/new reviewer and actor in restricted history. It grants no permission to edit commercial data.
ISSUE
APPROVED → FINALIZED; Issuing officer satisfying separation of duties; no editable commercial fields; validate approved snapshot and validity, assign issuance reference/time and freeze the issued snapshot atomically. No return, edit, delete, cancellation or reissue is allowed from APPROVED, REJECTED or FINALIZED in this core scope. Preserve all earlier versions. Repeated or concurrent operations must not duplicate transitions, numbering or notifications: reject stale/replayed mutations with a recoverable conflict and provide the authorized current state. Only one concurrent issuance may succeed.
| Operation | Transition | Authorized actor | Required input / guard |
|---|---|---|---|
| CREATE_DRAFT | — → DRAFT | Owning applicant | Incomplete business data allowed |
| SAVE_DRAFT | DRAFT → DRAFT | Owning applicant | Incomplete business data allowed |
| SUBMIT | DRAFT → SUBMITTED | Owning applicant | Complete data, active references, evidence |
| RETURN | SUBMITTED → RETURNED | Assigned reviewer | Public reason; optional internal note |
| SAVE_CORRECTION | RETURNED → RETURNED | Owning applicant | Incomplete business data allowed |
| RESUBMIT | RETURNED → SUBMITTED | Owning applicant | Correction summary and full validation |
| APPROVE | SUBMITTED → APPROVED | Assigned reviewer | Validity dates; required data and evidence |
| REJECT | SUBMITTED → REJECTED | Assigned reviewer | Public reason; optional internal note |
| REASSIGN | SUBMITTED → SUBMITTED | Issuer supervisor | Eligible reviewer and internal reason |
| ISSUE | APPROVED → FINALIZED | Issuing officer | Approved snapshot; validity; separation of duties |
Numbering, validity and sample certificate
Allocate server-side request references as COO-REQ-{year}-{six-digit-sequence} at first successful submission, unique per issuing organization/year. Allocate COO-ISS-{year}-{six-digit-sequence} only on successful issuance, with a separate sequence and the same uniqueness scope. Use database-backed atomic allocation and uniqueness constraints, never count existing rows or trust client numbers. Gaps are acceptable. Server dates use the issuer business time zone. Business references are not primary keys and are not access credentials.
For this demo, approval requires validFrom on or after the approval business date and validUntil = validFrom plus 89 days, giving 90 inclusive calendar days. Default validFrom to the approval business date. Issuance requires the current business date to fall within that interval; expired approval cannot be issued, and correction of an expired approval is outside this core example. These are illustrative training rules, not a legal certificate-validity policy.
Deliver an accessible certificate preview and protected downloadable sample PDF from the immutable issued snapshot. Both must visibly say SAMPLE — NOT AN OFFICIAL CERTIFICATE, include request and issuance references/dates, validity, issuer, exporter, consignee, shipment, goods and totals by currency, and omit internal notes and private contact details. Before issuance, show a separately labeled draft preview with no issuance number; rendering it changes no state. Rendering failure after issuance must permit a retry without issuing again or allocating another reference. Reuse the supported rendering integration, report an unavailable dependency explicitly, and do not substitute a fake download button.
Correspondence, internal notes and evidence
Store public correspondence and internal notes in separate child models and response projections. Each entry has immutable ID, document/version association, trusted author/time, plain-text body and operation context. Return/rejection reasons and correction summaries appear in applicant-visible correspondence. Internal notes are visible only to authorized issuer staff within record scope, excluded from applicant DTOs, public history, searches, notifications, logs and sample output. Entries are append-only; no silent edits or deletion. The core UI adds messages through the specified operations; do not invent a separate chat workflow.
Each attachment row contains its own stable ID, authentic bucket file identity, attachment-type reference, verified file name/MIME/size, uploader/time and version association. Use supported bucket upload and attachment mapping; distinguish local UI ID, persistent row ID and bucket ID. Server-validate authentic upload responses and ownership. Allow PDF/JPEG/PNG, up to 10 MiB per file and 10 attachments per request. Reject empty files and mismatched/unsupported content using supported server validation; a browser MIME declaration is insufficient. Integrate any scanner required by the selected storage policy and block pending/rejected files from submission.
Require at least one INVOICE and one ORIGIN_EVIDENCE attachment at submit/resubmit and approval. Only an owning Applicant in DRAFT or RETURNED may add/remove attachments. Downloads require the parent document/version access check and short-lived authorized retrieval; never public object URLs. Preserve files referenced by historical versions. Unattached temporary uploads expire after 24 hours through a reference-aware cleanup job; never delete a file referenced by a current or historical document. Display upload progress/retry and retain form data if upload or save fails.
Committed notifications and audit
Implement localized EN/FR/ES/AR templates with server-resolved recipients and authenticated record links. On submit/resubmit, notify the assigned reviewer. On return or rejection, notify the submitting applicant account. On approval, notify the issuer's configured eligible issuing officer and tell the applicant Approved, awaiting issuance. On issuance, notify the applicant that the sample certificate is available. On reassignment, notify the new reviewer. Fail missing required staff configuration before the corresponding operation commits; never accept arbitrary recipient addresses from operation input.
Persist a durable notification outbox entry in the same database transaction as the document operation. A worker delivers only committed entries to a local sink in development. Use a unique event key of document ID, committed version, event type and recipient; retry transient failures at 1, 5 and 30 minutes, then mark failed for operational inspection and explicit retry. Delivery is at least once, with deduplication where supported, not a promise of exactly once. Notification failure must not reverse or misreport the already committed document operation. Rollback creates no deliverable notification.
Audit every successful operation with document/version, prior/new state, authenticated actor, time and safe decision metadata. Separate restricted assignment/internal-note details from the applicant-visible timeline. Log denied actions and delivery failures without file contents, credentials or private notes. Verify authorization for every history version and output retrieval, not merely the current document.
UI: workspaces, form and reviewer decisions
Use the application's SOKit UI components and visual language. Generate an applicant workspace with a Create request action and paginated table: request reference, exporter, destination, state, last update and issuance reference. Filter by reference text, state and date range. Default to most recently updated. Include helpful empty state, loading state and recoverable error/retry. On phones turn rows into readable cards without losing actions or status.
Generate an issuer workspace with My assigned requests, Assignment queue visible only to supervisors, and Approved awaiting issuance visible to eligible issuing officers. Rows show request, applicant/exporter, submission date, state and assigned reviewer; filters include state, date and reviewer where authorized. Links open the actual authorized document. Do not render every role's workspace to all users and merely disable buttons.
The document header shows state, request reference, issuance reference if issued, version, last update and only server-authorized actions. Use a desktop section rail and a mobile section selector for Parties, Shipment, Goods, Evidence, Correspondence and History; show Internal notes only to authorized staff. Keep contextual totals and validation summary available. Parties have clearly separate exporter/consignee blocks and an optional additional-party repeater. Shipment uses dependent country/location reference pickers and mode-specific fields. Goods uses a summary table plus an accessible line editor with add/edit/remove/reorder, decimal inputs and per-currency totals. Evidence shows file type, size, upload progress and authorized download/remove actions.
Save draft and Submit are separate actions; Returned shows the reviewer's reason, editable corrections and a required summary before Resubmit. Return/Reject dialogs require a public reason and clearly separate optional internal-note input. Approval shows a read-only business summary, validity dates and an explicit confirmation. Issue shows approved data and validity with explicit confirmation; prevent duplicate clicks while pending, but rely on server concurrency protection. Issued and Rejected views are read-only. Warn before abandoning unsaved changes. On stale-version conflict preserve the attempted input, explain the conflict and offer reload/reconciliation without automatic overwrite.
Accessibility, localization and implementation quality
Provide complete EN/FR/ES/AR labels, validation, state names, correspondence UI and notification templates. Keep user-entered business content unchanged. Use the recipient's preferred locale for notifications and selected UI locale for formatting dates/numbers. Arabic is RTL, with isolated LTR identifiers and correctly ordered actions. The sample output uses the selected locale while preserving codes and stored business values.
Verify layouts at 360, 768 and 1440 pixels. Forms use a single column on phones and sensible grouped columns on desktop; controls never overflow, sticky elements never cover input or actions. Ensure keyboard access, visible focus, descriptive labels, screen-reader validation announcements, focus on the error summary and dialog focus return. Do not communicate state by color alone. Show permission, network, upload and validation failures distinctly without losing input.
Use current SMART guidance for SOKit operations/validation groups, generated contracts, record security, references, bucket mapping and notifications. Follow the selected Quarkus profile for CDI, persistence, transaction ownership, configuration, DTO validation and tests; no platform-version drift, unmanaged dependencies, entity exposure as public input or fabricated API names. Use migrations with constraints/indexes, paginated bounded queries and intentional fetch plans; avoid N+1 queries. Keep secrets outside source control, do not log personal data, and use supported authentication/CSRF/origin protections appropriate to the existing application.
Fixtures, acceptance scenarios and definition of done
Create fictional issuer Demo Chamber, applicant/exporter Demo Export Ltd, consignee Demo Import Ltd, and a second unrelated applicant organization. Seed separate applicant, assigned reviewer, other reviewer, supervisor, issuing officer and reference administrator identities through the supported local auth fixture mechanism; no production credentials. Supply a valid two-line shipment, the nine reference catalogs and harmless invoice/origin-evidence fixtures. Use a controlled test clock so date rules remain reproducible.
Automate this complete path: create incomplete draft → save → complete parties/shipment/two goods lines/evidence → submit and obtain one request reference → assigned reviewer returns with a public reason and private internal note → applicant sees only the reason → correct/save/resubmit with the same request reference and resubmissionCount 1 → approve with 90-day validity → distinct issuing officer issues once → retrieve a watermarked sample PDF from the frozen snapshot. Verify state, version, actor, history, allowed actions and outbox entries at every transition. Also cover the terminal rejection path.
Negative tests must cover every role/state combination in the matrix, forged owner/reviewer fields, cross-organization reads/search/history/files, unassigned and self-review, same-person approval/issuance, internal-note leakage, inactive references, wrong-country locations, missing mode fields/evidence, invalid dates/precision/weights, mixed-currency totals, changed/reordered line IDs, oversize or spoofed uploads, failed upload/save and temporary-file cleanup. Test two concurrent submissions/issuances, stale edits, expired validity, unique numbering, immutable issued output, rollback with no notification, delivery retry/deduplication, rendering retry without reissuance, and unauthorized direct endpoint access.
Run the appropriate component builds, type checks, lint, backend/integration tests and UI end-to-end checks, including all four locales and responsive sizes. Deliver a requirement-to-test matrix with actual outcomes, changed component/file list, local startup commands, migration/fixture instructions and operational configuration. State exactly which checks could not run and why. A milestone is complete only when its observable behavior works; do not claim a full application when only scaffolds, mocks or a plan exist.
Grill
Challenge my brief before we implement it. Identify missing requirements, contradictions and risky assumptions. Ask one focused question at a time, explain why the answer matters, and offer meaningful alternatives with a recommendation. Cover actors and ownership, data fields, reference sources, state transitions, validation, failure recovery, notifications, UI behavior and acceptance criteria. Separate confirmed decisions from assumptions. Do not write code or silently decide business policy. Finish with a concise decision log and any unresolved blockers.
Plan
Inspect the repository and produce a decision-complete plan for the agreed scope without changing files. Map the data model, reference tables, component owners, interfaces, state/operation/permission matrix, operation-specific validation, migrations, protected files and committed side effects. Include UI routes, accessibility, EN/FR/ES/AR behavior, failure states and acceptance tests. Break the work into reviewable milestones and name the actual build/check entrypoints. Resolve material ambiguity with me before finalizing the plan; do not begin implementation.
Goal
Implement only the goal and milestones already agreed with me. If no approved scope or plan is present, ask for it first. Work in small, reviewable increments: foundations and references, document workflow and access, UI, attachments and notifications, then end-to-end verification. Run the relevant checks after each meaningful change, investigate failures and report evidence. Preserve unrelated work. Do not expand into deployment, destructive migration, external messaging or unrelated features without authorization. Stop and explain concrete blockers requiring a decision or missing access; do not claim an unrun check passed. Finish with changed files, actual results and remaining work.
Review
Review the implementation against the agreed brief, plan and current SMART guidance. Do not edit files. Prioritize correctness, authorization across records/search/history/files, state transitions, validation, transaction boundaries, notification failure semantics, component dependencies, configuration, tests, accessibility and all four languages. Ground each finding in a file/location, a concrete trigger, its impact and a recommended fix. Distinguish defects from optional improvements and missing evidence. If nothing actionable is found, say so and identify the remaining verification limits; do not invent findings.