Compare commits

...
Author SHA1 Message Date
Hermes Agent 6045ed638c fix(ci): integrate automated release retention cleanup in stage and prod cache scripts 2026-11-04 14:39:31 +00:00
Canina Hermes 7a103303b0 fix(security): completely remove Swagger UI endpoint mounting from runtime
Deploy Canina / deploy (push) Failing after 11s
2026-11-02 05:42:55 +00:00
Canina Hermes 5a483e0cce fix(security): enforce secure-by-default Swagger UI disabling
Deploy Canina / deploy (push) Failing after 12s
2026-11-02 05:39:17 +00:00
Canina Hermes 6935ac9134 refactor(market-intelligence): dynamic API-driven opportunity tabs with no hardcoded data
Deploy Canina / deploy (push) Successful in 1m3s
2026-11-01 10:41:58 +00:00
Canina Hermes f2239be43c feat(market-intelligence): add major pet shops and real Canina sellers to ecosystem atlas
Deploy Canina / deploy (push) Successful in 1m2s
2026-11-01 10:20:19 +00:00
Canina Hermes b14b26a2e4 feat(market-intelligence): 33-seller ecosystem atlas, brand matrix, and executive importer proposal
Deploy Canina / deploy (push) Successful in 1m3s
2026-11-01 09:34:06 +00:00
Canina Hermes a6d0269427 fix(hermes-tasks): department counts stability and mobile responsive cards
Deploy Canina / deploy (push) Successful in 2m33s
2026-10-31 19:48:42 +00:00
Canina Hermes 8c4faf8820 feat(corporate): exact task claim and manual plan inventory execution slice
Deploy Canina / deploy (push) Successful in 2m31s
2026-10-31 18:45:30 +00:00
Canina Hermes 216e05ba25 feat(corporate): persist dated monthly plans and repair verified release gates
Deploy Canina / deploy (push) Successful in 4m38s
2026-10-30 12:28:51 +00:00
Canina Automation 18094f91a6 fix(blog): represent absent article imagery honestly
Deploy Canina / deploy (push) Successful in 3m12s
2026-10-29 08:10:03 +00:00
Canina Automation 5642c1609c feat(corporate): expose persisted execution evidence and QA dossier
Deploy Canina / deploy (push) Successful in 3m56s
2026-10-28 21:56:55 +00:00
Canina Automation 69dd6922f6 fix(stage): accept persisted ADMIN human role in maintenance
Deploy Canina / deploy (push) Successful in 2m41s
Stage author bootstrap (dedicated repair) / bootstrap (push) Successful in 1m5s
2026-10-28 21:08:40 +00:00
Canina Automation a0d588ba12 fix(stage): retain allowlisted bootstrap API failure status
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 48s
2026-10-28 21:02:09 +00:00
Canina Automation 5c93517b9e fix(stage): stream Redis snapshot with native stdout support
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 49s
2026-10-28 20:57:03 +00:00
Canina Automation 2408bafc49 fix(stage): verify existing database alias for bootstrap runtime
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 38s
2026-10-28 20:48:21 +00:00
Canina Automation 46da1c5339 fix(stage): isolate credentialless author bootstrap and recovery rehearsal
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 3m55s
2026-10-28 19:52:55 +00:00
Canina Automation 6ed0e73311 feat(admin): implement authenticated Stage author restoration API
Deploy Canina / deploy (push) Failing after 2m1s
2026-10-28 14:55:19 +00:00
Canina Automation bee9c4d6e1 fix(corporate): detach no-input migration Docker stdin
Deploy Canina / deploy (push) Failing after 27s
2026-10-28 13:55:45 +00:00
Canina Automation 90dcec413d feat(corporate): add dormant source audits and evidence-led daily planning
Deploy Canina / deploy (push) Failing after 22m23s
2026-10-28 13:36:51 +00:00
Canina Automation 94f08b8c8a fix(corporate): align runtime timestamps and require database-ready pilots
Deploy Canina / deploy (push) Failing after 1s
2026-10-28 13:08:29 +00:00
Canina Automation b642833b8b feat(ci): gate Stage corporate migration on durable verified backup
Deploy Canina / deploy (push) Has been cancelled
2026-10-28 12:58:56 +00:00
Canina Automation 435a75a442 fix(security): fence corporate orchestration and human key administration 2026-10-28 12:48:30 +00:00
Canina Automation d80845af0d feat(corporate): add dormant manual source runtime and independent QA adapter 2026-10-28 12:48:29 +00:00
Canina Automation cc365bcda2 feat(hermes): persist guarded corporate orchestration backend 2026-10-28 11:57:15 +00:00
Canina Automation 5550c80a75 feat(admin): integrate paginated Hermes records and authoritative task details 2026-10-28 11:57:15 +00:00
Canina Automation 3b05fe2e85 fix(admin): remove fabricated Hermes fallback and expose unavailable states
Deploy Canina / deploy (push) Successful in 53s
2026-10-28 11:57:13 +00:00
Canina Automation 1f01b9dab9 feat(hermes): add Hermes Autonomous HQ menu, CorporateTasks, MarketIntelligence, MonthlyRoadmap, and replace terminology
Deploy Canina / deploy (push) Successful in 55s
2026-10-28 11:33:20 +00:00
Canina Automation 8197259e54 feat(admin): redesign SEO tracking page with mobile-first card UI and rich status cards
Deploy Canina / deploy (push) Successful in 7m1s
2026-10-28 10:30:04 +00:00
Canina Automation fb1deadbbc feat(seo): atomic directive fencing and transactional blog publication
Deploy Canina / deploy (push) Successful in 4m45s
2026-10-28 08:02:30 +00:00
Canina Automation 0a156fd7b4 test(stage-schema): fault-inject fail-closed apply prerequisites 2026-10-28 08:01:38 +00:00
Canina Automation db3979d212 feat(seo-worker): collect cached read-only Clarity aggregates 2026-10-28 08:00:20 +00:00
Canina Automation 13dc74807a feat(analytics): instrument privacy-minimized catalog navigation 2026-10-28 07:59:35 +00:00
Canina Automation c62d9836e9 ops(stage): version isolated SEO schema rehearsal and CI operation 2026-10-28 07:53:18 +00:00
Canina Automation 312fcc2acc feat(seo): integrate analytics worker and real HTTP PostgreSQL acceptance 2026-10-28 07:21:52 +00:00
Canina Automation 5750e1589e feat(content): add dormant versioned research directive publisher consumer 2026-10-28 07:18:40 +00:00
Canina Automation df5584d214 feat(admin): complete resilient SEO tracking and versioned feedback UI 2026-10-28 07:10:09 +00:00
Canina Automation 6102556eae fix(seo): validate ingress and fence directive and snapshot writes 2026-10-28 06:58:22 +00:00
Canina Automation 39f5b705c5 feat(seo): add versioned findings and nullable snapshot provenance 2026-10-28 06:44:45 +00:00
Canina Automation 13f4fdc58d feat(seo-tracking): implement closed-loop performance tracking, admin panel and CEO directive gate 2026-10-28 06:31:49 +00:00
Canina Automation 00ba4360cf fix(search): normalize search expansion lookup for hamza-ye variants
Deploy Canina / deploy (push) Successful in 2m42s
2026-10-27 11:56:13 +00:00
Canina Automation 8669d183d5 feat(search): add bidirectional domain aliases (taurine/taurin, carnitine) and include ingredientCardSlug
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-27 11:49:15 +00:00
Canina Automation 66b9d75524 feat(search-pagination): implement normalized weighted search and standardized pagination across blogs, products and wiki
Deploy Canina / deploy (push) Successful in 4m25s
2026-10-27 11:39:55 +00:00
Canina Automation d3a0a61d79 feat(storefront): increase blog list limit to 200, resolve wiki taurine alias and expand related products search
Deploy Canina / deploy (push) Successful in 2m42s
2026-10-27 10:18:37 +00:00
Canina Automation 0ad39bb92c fix(blogs): enforce atomic optimistic update concurrency
Deploy Canina / deploy (push) Successful in 52s
2026-10-27 08:20:33 +00:00
Canina Automation 0e952ef701 fix(prod-ci): add --repair-empty to revalidation provisioning on production release
Deploy Canina / deploy (push) Successful in 39s
2026-10-26 20:30:19 +00:00
Canina Automation f1382e943c ci: retry production release after runner permission verification
Deploy Canina / deploy (push) Failing after 11s
2026-10-26 20:25:38 +00:00
Canina Automation 53fccc2d3c fix(ci): route production code-only release through safe locked deployment without migrations
Deploy Canina / deploy (push) Failing after 10s
2026-10-26 20:17:27 +00:00
Canina Automation 9ae839138c [verified] Fix Stage readiness against paginated public blogs contract
Deploy Canina / deploy (push) Successful in 39s
2026-10-26 19:19:26 +00:00
Canina Automation 0fa6abc53d [verified] fix Stage helper lock under daemon userns remapping
Deploy Canina / deploy (push) Failing after 7m24s
2026-10-26 18:50:29 +00:00
Canina Automation 2a32f31097 fix(stage): fence runtime authority and bound release transports
Deploy Canina / deploy (push) Failing after 5s
2026-10-26 18:25:16 +00:00
Canina Automation 52a7aebb51 fix(ci): prepare fail-closed exact-SHA code-only Stage release 2026-10-26 16:42:08 +00:00
Canina Automation af32ec14e1 fix(seo): provide explicit noindex and self-canonical for login and cart pages 2026-10-26 16:32:52 +00:00
Canina Automation e34156b2d3 fix(seo): normalize and safely encode wiki route slug to prevent double-encoding 404s 2026-10-26 16:32:52 +00:00
Canina Automation 721118787a fix(cache): restore backend-to-next revalidation and expose revalidation status safely
Deploy Canina / deploy (push) Successful in 1m10s
2026-10-26 15:12:10 +00:00
parsa aghaei 292ed7f920 fix(deploy): make stage_test_principal migration idempotent and resolve existing migrations before deploy
Deploy Canina / deploy (push) Successful in 1m7s
2026-10-26 14:00:35 +03:30
parsa aghaei 432f6a21c7 fix(deploy): resolve revalidation env missing and resolve legacy orchestration migrations
Deploy Canina / deploy (push) Failing after 1m2s
2026-10-26 13:45:41 +03:30
parsa aghaei 2087001ecd fix(ci): restore original working deploy.yml and direct deploy.sh from eb17c8e284
Deploy Canina / deploy (push) Failing after 2m59s
2026-10-26 12:57:29 +03:30
parsa aghaei ec93af0064 fix(admin): restore clean persian dashboard and monitoring page, remove extra workflows
Deploy Canina / deploy (push) Failing after 3s
2026-10-26 11:58:20 +03:30
parsa aghaei effe30ee58 feat(admin): remove governance, orchestration, approvals, tasks, and audit logs modules
Deploy Canina / deploy (push) Successful in 4m14s
2026-10-26 10:15:06 +03:30
devops 99f0c0d626 test(ops): fence rollout fixture evidence and systemctl writes
Deploy Canina / deploy (push) Failing after 1s
2026-10-26 05:10:41 +00:00
devops 1e27387016 fix(ops): retire exact CI-generated historical release deltas safely
Deploy Canina / deploy (push) Successful in 6m12s
2026-10-26 05:02:35 +00:00
devops c733a806bd test(ops): assert restored CI render state after acceptance
Deploy Canina / deploy (push) Failing after 2s
2026-10-26 04:58:26 +00:00
devops 23cbd693a8 test(ops): isolate host retention installer from rollout fixture
Deploy Canina / deploy (push) Failing after 2s
2026-10-26 04:58:12 +00:00
devops 366bc9fc88 fix(ops): conservative post-rollout retention and deterministic disk watch
Deploy Canina / deploy (push) Has been cancelled
2026-10-26 04:57:33 +00:00
devops b4420e54b7 fix(release): admit exact reviewed publisher SEO repair paths
Deploy Canina / deploy (push) Failing after 9h30m37s
2026-10-25 18:34:09 +00:00
devops 44d74d35e6 fix(blog): publish truthful image and team SEO metadata
Deploy Canina / deploy (push) Successful in 4m50s
2026-10-25 18:03:49 +00:00
devops 5897abcbad fix(ci): wait for final TCP server before schema restore
Approved narrow auth schema reconciliation / reconcile (push) Successful in 15s
Deploy Canina / deploy (push) Failing after 21s
2026-10-25 13:27:39 +00:00
devops b3b9e617b5 fix(stage): recreate cached frontend for release provenance 2026-10-25 13:26:49 +00:00
devops 6f9529d31f fix(release): admit exact schema CI push regression test
Deploy Canina / deploy (push) Successful in 2m17s
Approved narrow auth schema reconciliation / reconcile (push) Failing after 10s
2026-10-25 13:04:53 +00:00
devops c25b10f7f3 fix(ci): trigger approved auth schema operation on exact Gitea push refs 2026-10-25 13:04:34 +00:00
devops c69a779ecc fix(release): scope missing-column guard and allow exact schema repair 2026-10-25 12:59:40 +00:00
devops 688a0e4de5 fix(auth): prepare narrow approved CI schema reconciliation 2026-10-25 12:43:20 +00:00
devops cf9b80bbb3 fix(release): gate generated Prisma client against live production catalog 2026-10-25 12:43:20 +00:00
devops 2a341d3969 fix(deploy): supply internal npm registry build arg for production compose snapshot
Deploy Canina / deploy (push) Successful in 2m37s
2026-10-25 08:44:41 +00:00
devops 9275233d09 fix(release): admit audited freshness frontend fixes in production release allowlist
Deploy Canina / deploy (push) Failing after 1m50s
2026-10-25 08:34:29 +00:00
Canina Engineering 13dceaa460 fix(blog): expose author role and bound FAQ heading extraction
Deploy Canina / deploy (push) Successful in 10m28s
2026-10-25 08:19:44 +00:00
Canina Engineering 0ab2980ff4 fix(editorial): crash-safe upgrade with durable phase, previous metadata and recovery 2026-10-25 08:19:44 +00:00
devops fd14c05f3a fix(build): enforce secure TLS registry and binary verification 2026-10-25 08:19:30 +00:00
Canina Engineering cc0358bb12 fix(editorial): upgrade only verified installed runtime payload
Deploy Canina / deploy (push) Failing after 2m51s
2026-10-25 07:39:22 +00:00
Canina Engineering f94ef580fb fix(infra): integrate private revalidation provisioning and narrow release gates
Deploy Canina / deploy (push) Failing after 1m6s
2026-10-25 07:18:30 +00:00
devops 1bb6274b35 fix(frontend): restore full admin gates and preserve analytics protocol 2026-10-25 06:59:37 +00:00
Canina Engineering 448c250944 feat(deploy): gate immutable production CI promotion on audited Stage acceptance 2026-10-25 06:52:32 +00:00
Canina Engineering 5f5c3eb3b9 fix(infra): refresh Docker upstream DNS and provision revalidation runtime 2026-10-25 06:52:05 +00:00
Canina Engineering 3805057923 fix(blog): sort articles by raw publication timestamps 2026-10-25 06:42:52 +00:00
Canina Engineering f4678c48ca test(backend): isolate worker secrets and support HTTP listener 2026-10-25 06:30:18 +00:00
Canina Engineering c40e931168 fix(cache): target Next server for fallback revalidation 2026-10-25 05:51:26 +00:00
Hermes Agent e96a13b255 fix(editorial): synchronize corrected PMO skill bundle digest
Deploy Canina / deploy (push) Failing after 1m28s
2026-10-24 17:40:26 +00:00
Recovery Review 4413c2ef6c Test completed recovery over JWT HTTP Postgres and narrowly admit Stage reviewer
Deploy Canina / deploy (push) Failing after 1m25s
2026-10-24 17:35:56 +00:00
devops 65063e224a fix(editorial): constrain synthesis contract and admit fenced completed-run recovery 2026-10-24 17:35:42 +00:00
Hermes Agent c8063b5f2a fix(ci): admit exact installed runner evidence in ownership preflight
Deploy Canina / deploy (push) Successful in 3m44s
2026-10-24 16:32:27 +00:00
devops bfeb464bfb fix(editorial): honor functional bring-up model and completion policy
Deploy Canina / deploy (push) Failing after 1m30s
2026-10-24 16:26:50 +00:00
devops 860324e3a9 fix(editorial): retain bounded timeout session evidence and budget headroom
Deploy Canina / deploy (push) Successful in 3m44s
2026-10-24 15:38:04 +00:00
devops f705511164 fix(ci): install durable Stage cleanup worker during guarded rollout
Deploy Canina / deploy (push) Successful in 4m56s
2026-10-24 13:04:35 +00:00
devops 70a5449d35 fix(auth): persist generation-fenced Stage principal cleanup retries 2026-10-24 13:04:35 +00:00
devops 80a2e188cf fix(auth): fence temporary Stage credentials by account generation 2026-10-24 13:04:35 +00:00
devops e036c5d436 feat(stage): add opt-in bounded CI editorial test principal 2026-10-24 13:04:35 +00:00
devops ed77f87ab5 fix(editorial): preflight installed CLI and categorize profile failures
Deploy Canina / deploy (push) Successful in 3m17s
2026-10-24 11:31:48 +00:00
devops 4712433903 feat(admin): add fenced expired editorial run recovery control
Deploy Canina / deploy (push) Successful in 4m46s
2026-10-24 10:58:18 +00:00
devops f4add07780 fix(editorial): migrate exact CI ownership and fence failed research runs
Deploy Canina / deploy (push) Successful in 5m1s
2026-10-24 10:28:30 +00:00
devops 01b6f1d3d7 fix(editorial): fence runner identity before claim and expose safe stages 2026-10-24 10:28:30 +00:00
devops 60a4e14b4b fix(orchestration): expose queued Gate1 expiry and audited renewal
Deploy Canina / deploy (push) Successful in 4m51s
2026-10-24 09:53:07 +00:00
devops 6e465663bd test(editorial): resolve runner imports under CI discovery
Deploy Canina / deploy (push) Successful in 3m11s
2026-10-24 09:07:05 +00:00
devops b1142bd0c0 feat(editorial): implement bounded canonical-profile research runner
Deploy Canina / deploy (push) Failing after 1m22s
2026-10-24 09:01:46 +00:00
devops 50d0df822c fix(orchestration): atomically queue approvals with optional not-before schedule
Deploy Canina / deploy (push) Successful in 4m56s
2026-10-24 06:16:20 +00:00
devops ab2f330eb8 fix(admin): open fresh card decisions in confirmation dialog
Deploy Canina / deploy (push) Successful in 4m34s
2026-10-24 05:24:39 +00:00
devops ca3d4f6a16 fix(users): preserve superadmin roles and enforce actor privilege boundary 2026-10-24 05:14:22 +00:00
devops 3321bac22d fix(admin): render users list contract and allowlist user projection
Deploy Canina / deploy (push) Successful in 4m37s
2026-10-24 04:46:26 +00:00
devops 3e78b89cc1 fix(orchestration): provision explicit Stage owner Gate1 review access
Deploy Canina / deploy (push) Successful in 4m40s
Preserve independent proposer checks, canonical Admin UUID allowlist and deny ordinary admins. Revalidate pinned owner in read-only CI preflight; expose server-advertised card decisions and distinguish reservation from unknown real cost. Verified backend 42 HTTP/service/config tests and build; admin 18 relevant tests, app tsc and Vite build; 3 CI config tests and bash syntax.
2026-10-24 04:25:35 +00:00
devops bfb1841370 Add bounded approved editorial brief ingestion pending independent QA
Deploy Canina / deploy (push) Successful in 4m32s
2026-10-24 04:08:17 +00:00
devops 6ba2c51403 Fix orchestration actor role normalization at HTTP boundary
Deploy Canina / deploy (push) Successful in 4m50s
2026-10-24 04:01:38 +00:00
devops ba0aa5ee4e Isolate PMO credential from existing differently owned credentials directory
Deploy Canina / deploy (push) Successful in 4m30s
2026-10-24 03:45:51 +00:00
devops 7485c89e9b feat(editorial): wire serialized Stage runtime install and PMO proposal client
Deploy Canina / deploy (push) Failing after 1m23s
2026-10-24 03:41:43 +00:00
devops 8869ce2583 feat(editorial): add blocked profile policy distribution and isolated installer 2026-10-24 03:32:46 +00:00
devops 64419f6755 feat(orchestration): bind PMO editorial proposals to owner Gate1 2026-10-24 03:27:00 +00:00
devops 8cedc2cd67 feat(orchestration): expose owner Gate1 queue and audited hold decisions
Deploy Canina / deploy (push) Successful in 3m9s
2026-10-24 02:28:58 +00:00
devops 65a6fe1f0c Repair Persian RTL orchestration panel and honest unavailable states
Deploy Canina / deploy (push) Successful in 2m1s
Preserve bounded command safety and snapshot provenance; render structured Persian records without translating human evidence. Validated app/node TypeScript, Vite build and 394 tests across 64 files in private Node 22 runner.
2026-10-23 20:48:52 +00:00
devops afbee9cf70 Fix nginx access to admin fonts and correct Shabnam asset path
Deploy Canina / deploy (push) Successful in 2m23s
2026-10-23 20:16:25 +00:00
devops 5984242ce4 Add authenticated fixed Tech one-shot adapter with bounded transport and admission
Deploy Canina / deploy (push) Successful in 3m10s
2026-10-23 19:36:56 +00:00
devops c523acc9e8 Add separately admitted Tech source ingestion with retained unknown cost 2026-10-23 19:36:56 +00:00
devops c78bdbcdb5 Accept quoted opaque session cookie emitted by installed Hermes
Deploy Canina / deploy (push) Successful in 3m9s
2026-10-23 19:15:41 +00:00
devops 7a081e28df Avoid inherited virtual address cap breaking Docker Go client
Deploy Canina / deploy (push) Successful in 3m13s
2026-10-23 19:09:54 +00:00
devops 93d43fb261 Match reviewed Stage API prefix and readable public runtime entrypoint
Deploy Canina / deploy (push) Failing after 1m18s
2026-10-23 19:07:18 +00:00
devops 8c435ab09e Restore Stage availability with explicit runtime provisioning rollback
Deploy Canina / deploy (push) Successful in 1m32s
2026-10-23 18:31:23 +00:00
devops 4388a5c2e6 Recover prior accepted backend within CI provisioning after pre-start failure
Deploy Canina / deploy (push) Failing after 1m44s
2026-10-23 18:28:44 +00:00
devops 62a7a87378 Quote comma-containing tmpfs options as one Compose mount
Deploy Canina / deploy (push) Failing after 1m17s
2026-10-23 18:25:50 +00:00
devops 19583c5ad8 Bound Docker client runtime within provisioning resource ceiling
Deploy Canina / deploy (push) Failing after 1m38s
2026-10-23 18:23:28 +00:00
devops 1858eba3e6 Prevent provisioning import cache from dirtying approved CI checkout
Deploy Canina / deploy (push) Failing after 1m17s
2026-10-23 18:20:58 +00:00
devops cb20c2acb5 Enable reviewed Stage runtime provisioning across authenticated CI boundary
Deploy Canina / deploy (push) Failing after 1m18s
2026-10-23 18:17:43 +00:00
devops 105ab07fbd Wire opt-in Stage runtime provisioning before isolated render; verify snapshot and Compose integration 2026-10-23 18:15:47 +00:00
devops bf84e5da43 Bound pilot inference with ongoing heartbeat and process-group cancellation 2026-10-23 16:58:12 +00:00
devops 02badd0e25 Add fail-closed real Hermes Tech pilot and independent artifact QA proof 2026-10-23 16:49:09 +00:00
devops aa23c7ef91 Add opt-in CI Stage credential provisioning and restricted SQLite inventory export 2026-10-23 16:49:09 +00:00
devops 4b147b0091 Route CI Stage deployment through authenticated pinned SSH host boundary
Deploy Canina / deploy (push) Successful in 4m35s
2026-10-23 15:06:24 +00:00
devops 6950ff0d79 Isolate commit-pinned Stage releases from dirty operational checkout 2026-10-23 14:50:32 +00:00
devops cc9ec25388 Wire explicitly enabled worker startup and exact legacy rehearsal comparison 2026-10-23 14:41:48 +00:00
devops be2ff0719a feat(worker): add fail-closed reviewed startup config registration 2026-10-23 14:38:54 +00:00
devops 9d93707848 fix(worker): scope artifact access and harden immutable transport storage 2026-10-23 14:07:01 +00:00
devops aa99216c49 feat(worker): add authenticated bounded PREPARE HTTP executor tracer 2026-10-23 13:49:38 +00:00
devops 58d3794050 fix(admin): distinguish snapshot inventory from live runtime telemetry 2026-10-23 13:34:53 +00:00
devops 16f9610027 Wire runtime read routes with explicit file-granted startup opt-in 2026-10-23 13:26:29 +00:00
devops 2023dd4e36 Make snapshot inventory provenance explicit and deny false live readiness 2026-10-23 13:22:21 +00:00
devops 0bed6e0313 fix(admin): restore immutable PREPARE scope contract
Match d43aa02 metadata validation and exact DTO; distinguish missing safe-projection workflow scope from human review evidence. Preserve action normalization and explicit kill-switch capability. TDD regression RED verified; disposable admin 61 files / 381 tests, app+node TypeScript and build pass.
2026-10-23 13:13:41 +00:00
devops f29ba4ab8b fix(admin): reconcile bounded PREPARE backend contracts 2026-10-23 13:04:06 +00:00
devops 56b6696ca3 Preserve bounded PREPARE scope and normalize proposal conflicts 2026-10-23 13:04:06 +00:00
devops 0d0c67704c Complete safe admin workflow and authenticated runtime read UI 2026-10-23 12:53:06 +00:00
devops 09e8a890e0 Add bounded Stage PREPARE workflow with transactional leased outbox 2026-10-23 12:53:06 +00:00
devops 4b17a6fcc3 Add admin-scoped Hermes runtime reads and isolated pinned HTTP inventory 2026-10-23 12:53:06 +00:00
devops 5507fbcb29 Add server-only Hermes login broker with deny-first module registration 2026-10-23 11:05:27 +00:00
devops 176cc08a6b Restore guarded legacy approvals controller removed by background run 2026-10-23 09:33:42 +00:00
devops 5953c3cf75 Remove outdated approvals controller 2026-10-23 09:13:22 +00:00
devops 0952a482fb Checkpoint recovered orchestration core with tested fail-closed boundaries 2026-10-23 08:01:08 +00:00
devops c7f1d25e98 Integrate schema-first Stage rollout with immutable CI commit pinning 2026-10-23 07:52:49 +00:00
devops 841eab0556 Harden integration read-only boundaries and admin contracts 2026-10-23 06:38:39 +00:00
devops ac065fa911 feat(orchestration): integrate read-only v4 surfaces with mutation lockdown 2026-10-22 19:04:00 +00:00
devops 70d8128bfb feat(router-usage): add protected read-only consumption adapter with honest quota unknowns 2026-10-22 18:54:24 +00:00
devops 8c8ae66c7d feat(runtime): add fail-closed Hermes management adapter and contract gates 2026-10-22 18:54:24 +00:00
devops c8a3f35b0a feat(admin): add backend-authoritative orchestration command center and usage view 2026-10-22 18:54:24 +00:00
devops e5c83e87fe feat(orchestration): add v4 additive backend core and policy tests 2026-10-22 18:15:32 +00:00
devops eb17c8e284 feat(orchestration): enforce corporate guardrails, domain invariant and daily publishing rate limits
Deploy Canina / deploy (push) Successful in 28s
2026-10-20 20:43:39 +00:00
devops 459f8b59fe Merge develop into main: complete autonomous corporate orchestration, manager actions separation, and truthful QA gates
Deploy Canina / deploy (push) Successful in 50s
2026-10-20 20:01:23 +00:00
devops e6c705cef7 feat(orchestration): implement live HTTP artifact verification with soft-404 detection
Deploy Canina / deploy (push) Successful in 24s
2026-10-20 19:55:28 +00:00
devops 19c4bb451d merge(worker): integrate orchestration worker contract
Deploy Canina / deploy (push) Successful in 2m56s
2026-10-20 19:43:59 +00:00
devops f71b79a17f merge(market): integrate feat/safe-market-proposals-20261020 2026-10-20 19:43:31 +00:00
devops e3eb7ca205 merge(admin_ui): integrate feat/admin-manager-actions-separation-20261020 2026-10-20 19:43:30 +00:00
devops 2e54163d9e merge(backend): integrate feat/backend-approval-separation-20261020 2026-10-20 19:43:30 +00:00
devops 344f79039f feat(orchestration): implement atomic claims, root task selection and truthful completion gates 2026-10-20 19:42:53 +00:00
devops 02fe634944 feat(admin): implement approval separation and verifiable completion policy
- Separate B2B_SUPPLIER_STRATEGY strategic manager actions from digital tasks
- Ensure strategic proposals do not create/requeue digital tasks or set executedAt
- Ensure SEO and digital approvals transition actionable tasks to TODO
- Strengthen task completion policy: require independently verifiable HTTP(S) deliverables, reject canina://, git://stage, and post-tsk missing article placeholders
- Reject completion when QA verification evidence reports 404 or missing article errors
- Add unit test coverage for ApprovalsController, DepartmentTasksController and completion policy
2026-10-20 19:41:39 +00:00
devops 7b1f64d727 feat(admin): separate manager actions from operational authorization and eliminate synthetic 3D room 2026-10-20 19:30:47 +00:00
devops d53e38a48f test: gate market proposal evidence and dedup before approval 2026-10-20 19:13:48 +00:00
devops 740e738fca Merge develop into main: modernize ApprovalsPage with clean light theme and smart payload mapper
Deploy Canina / deploy (push) Successful in 38s
2026-10-20 16:01:17 +00:00
devops ee90284129 feat(admin): modernize ApprovalsPage UI with clean light theme, structured payload visualizer and CEO directives
Deploy Canina / deploy (push) Successful in 38s
2026-10-20 16:00:59 +00:00
devops de42b3126b Merge feature/task-status-history-and-ceo-priority into main
Deploy Canina / deploy (push) Successful in 39s
2026-10-20 13:37:01 +00:00
devops 71dccbc590 feat(admin): add status transition metrics and CEO_EXPEDITE priority to task manager
Deploy Canina / deploy (push) Successful in 37s
2026-10-20 13:36:59 +00:00
devops 4c6127786f Merge develop into main: complete department and status filters in task management
Deploy Canina / deploy (push) Successful in 39s
2026-10-20 12:25:11 +00:00
devops bf082c59fe feat(admin): complete all department and status filters in task management
Deploy Canina / deploy (push) Successful in 37s
2026-10-20 12:00:59 +00:00
devops ee35c10454 merge: fix GA4 gtag arguments and route tracking
Deploy Canina / deploy (push) Successful in 2m32s
2026-10-20 10:54:19 +00:00
devops 1651fd00a2 fix(analytics): pass native arguments to dataLayer and track route changes
Deploy Canina / deploy (push) Successful in 2m20s
2026-10-20 10:49:56 +00:00
devops d9e4447903 merge: suppress Prisma CLI update banner during migrations
Deploy Canina / deploy (push) Successful in 40s
2026-10-20 09:54:23 +00:00
devops f59dd6ebec fix(prisma): suppress CLI update banner during migrations and builds
Deploy Canina / deploy (push) Successful in 2m34s
2026-10-20 09:46:32 +00:00
devops 10413547c1 merge: publish blog attribution and freshness fixes
Deploy Canina / deploy (push) Successful in 2m37s
2026-10-20 09:08:50 +00:00
devops 2f178db2c6 fix(blog): keep attribution rows on one line
Deploy Canina / deploy (push) Successful in 2m20s
2026-10-20 09:01:32 +00:00
devops 28485d51f7 fix(blog): improve attribution layout and freshness
Deploy Canina / deploy (push) Successful in 4m4s
2026-10-20 08:41:40 +00:00
devops 24362b89d7 fix(blog): refine editorial team label
Deploy Canina / deploy (push) Successful in 2m40s
2026-10-20 07:59:08 +00:00
devops 159e4a4cbf fix(blog): separate Canina author and editorial team
Deploy Canina / deploy (push) Successful in 2m47s
2026-10-20 07:52:07 +00:00
devops 13a7919c91 merge: reconcile main before blog freshness release
Deploy Canina / deploy (push) Successful in 2m34s
2026-10-20 07:26:54 +00:00
devops d670690816 fix(blog): unify structured author identity
Deploy Canina / deploy (push) Successful in 5m16s
2026-10-20 07:15:20 +00:00
devops 62c58c7c89 fix(blog): harden creation and unify author fallback 2026-10-20 06:59:43 +00:00
devops 0b4d9a8463 fix(blog): harden freshness and authorship 2026-10-20 06:31:22 +00:00
devops 51ca8c7e34 feat(blog): add material freshness and authorship 2026-10-20 05:36:03 +00:00
devops 64047054b8 merge: integrate live HQ telemetry and child task execution pipeline
Deploy Canina / deploy (push) Successful in 38s
2026-10-19 17:49:00 +00:00
devops 3f5258a76c feat(admin-hq): bind 3D orchestration room to live telemetry and dynamic task state
Deploy Canina / deploy (push) Successful in 36s
2026-10-19 17:48:44 +00:00
devops 3b93308b71 merge: resilient orchestration JSON parsing
Deploy Canina / deploy (push) Successful in 39s
2026-10-19 14:13:03 +00:00
devops bf53f2e17c fix(orchestration): tolerate raw control characters in model JSON
Deploy Canina / deploy (push) Successful in 36s
2026-10-19 14:13:00 +00:00
devops c2eca11a3b merge: verified completion gates and cross-department orchestration
Deploy Canina / deploy (push) Successful in 51s
2026-10-19 14:07:01 +00:00
devops 4c3f8de1fb feat(orchestration): enforce verified completion and cross-department fan-out
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-19 13:59:22 +00:00
devops b3e1869724 merge: add CompanyOrchestrationHQ into main
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 13:03:56 +00:00
devops 624f58c723 feat(pages): add CompanyOrchestrationHQ interactive 3D component
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 13:03:54 +00:00
devops aedc0f6979 merge: register /governance/hq route into main
Deploy Canina / deploy (push) Failing after 7s
2026-10-19 13:03:31 +00:00
devops 1e53ceeda6 feat(governance): register /governance/hq route
Deploy Canina / deploy (push) Failing after 8s
2026-10-19 13:03:29 +00:00
devops f08ed0c22c merge: integrate Tasks state fix and Sidebar 3D link into main
Deploy Canina / deploy (push) Successful in 39s
2026-10-19 12:51:18 +00:00
devops ee0f877d97 fix(tasks): define sortOrder state and add 3D HQ to Sidebar navigation
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 12:50:12 +00:00
devops b3d4e08914 merge: integrate develop fixes (Dashboard null-safety, Tasks Tehran datetime, and sorting) into main
Deploy Canina / deploy (push) Successful in 2m47s
2026-10-19 12:43:06 +00:00
devops ec9dd83e77 fix: syntax escape in TasksManagementPage
Deploy Canina / deploy (push) Successful in 3m21s
2026-10-19 12:33:00 +00:00
devops 4930e2a870 feat(tasks): interactive date-sorting toggle and Tehran datetime column
Deploy Canina / deploy (push) Failing after 8s
2026-10-19 12:32:25 +00:00
devops 5e21cc76fc fix(admin): resolve Dashboard crash with null safety and add Tehran time/sorting to Tasks
Deploy Canina / deploy (push) Failing after 2m16s
2026-10-19 12:29:33 +00:00
devops 529110a693 feat(support-chat): delegate blog consultation CTA clicks to open support chat modal
Deploy Canina / deploy (push) Successful in 2m38s
2026-10-19 06:32:11 +00:00
devops 0b5f2a88cc fix(blog): highlight in-article links and trigger support chat from smart advisor button
Deploy Canina / deploy (push) Successful in 2m44s
2026-10-19 06:24:22 +00:00
devops ff6f04fe46 fix(cache): revalidate storefront after admin mutations
Deploy Canina / deploy (push) Successful in 2m35s
2026-10-18 19:31:46 +00:00
devops 2e9a0e30c1 chore: sync feature branch with latest origin/develop
Deploy Canina / deploy (push) Successful in 2m40s
2026-10-18 18:53:04 +00:00
devops ad0acaccc2 refactor(admin): extract ProductFaqTab component from monolithic Products.tsx [FE-020] 2026-10-18 18:34:52 +00:00
devops 30019a02d8 fix(deps): upgrade next to 16.4.2 eliminating critical vulnerability [FE-023] 2026-10-18 18:30:31 +00:00
devops 87999be3d2 fix(frontend): comprehensive SEO, A11y, media upload validation, and logging enhancements [FE-013 to FE-022] 2026-10-18 17:55:37 +00:00
devops 4ce9f6000c fix(ux): enforce safe responsive containment on mobile CartDrawer [FE-012] 2026-10-18 16:42:57 +00:00
devops 0529962391 fix(admin): resolve array response unwrapping in SupportChatAnalyticsPage [FE-011] 2026-10-18 16:37:45 +00:00
devops 14c45e4f6c fix(api): preserve error semantics in getProductBySlug distinguishing 404 from 5xx [FE-010] 2026-10-18 16:35:14 +00:00
devops 1c38b95fb0 fix(auth): align admin refresh token contract with backend cookie and bearer endpoints [FE-009] 2026-10-18 16:32:28 +00:00
devops dab66a2dce fix(checkout): guard against empty cart order submission and disable checkout CTA [FE-008] 2026-10-18 16:16:15 +00:00
devops 86eb0cfcae fix(monitoring): eliminate Math.random mock values from admin monitoring stats [FE-007] 2026-10-18 16:12:32 +00:00
devops d3aa10c769 fix(security): sanitize dynamic HTML rendering in Hero and ProductPage [FE-006] 2026-10-18 16:09:36 +00:00
devops 15524609fe fix(security): enforce withCredentials true on storefront api for httpOnly cookies [FE-005] 2026-10-18 16:04:34 +00:00
devops aacb91ac70 fix(security): sanitize and block payment tokens and secrets in public ui-texts endpoint [FE-004] 2026-10-18 15:47:12 +00:00
devops f91502026b feat(admin): configure vitest test runner and fix dashboard audit-logs array guards [FE-003] 2026-10-18 15:43:19 +00:00
devops 7f2f638f38 test(backend): fix unit tests for media magic validation, slow query logger, and support chat specs
Deploy Canina / deploy (push) Successful in 41s
2026-10-18 15:40:03 +00:00
devops 7879ead486 fix(frontend): harmonize selectors and assertions across failing application unit tests [FE-002] 2026-10-18 15:35:43 +00:00
devops dda1caf3e0 feat(backend & dba): implement inventory concurrency guard, redis distributed locks, magic byte file validation, slow query logger, and db check constraints 2026-10-18 15:29:37 +00:00
devops bb483d3e68 fix(frontend): resolve react-hooks declaration order and lint errors in SupportChat [FE-001] 2026-10-18 15:23:12 +00:00
devops 73bc79b4bb fix(backend): encapsulate TasksService in TasksModule and export OrdersService
Deploy Canina / deploy (push) Successful in 30s
2026-10-18 14:43:17 +00:00
devops 9520426a66 perf(backend & dba): resolve unindexed foreign keys, eliminate N+1 in product catalog, add background tasks for inventory release & payment reconciliation, and harden SQL queries
Deploy Canina / deploy (push) Failing after 36s
2026-10-18 14:35:41 +00:00
devops b077423ab2 fix: move BackToTop to right side, wire global prescription modal trigger in header & mobile drawer
Deploy Canina / deploy (push) Successful in 2m15s
2026-10-18 14:09:01 +00:00
devops 94867fbd5a fix(frontend): ensure use client is first line in ArchivePage
Deploy Canina / deploy (push) Successful in 2m16s
2026-10-18 13:54:31 +00:00
devops 6a37f2f4c7 fix: support chat elevated only on PDP, rx button opens modal instantly, and hide pet badge when not logged in
Deploy Canina / deploy (push) Failing after 21s
2026-10-18 13:50:54 +00:00
devops b54338f91f fix(backend): fix duplicate success in deleteSymptom
Deploy Canina / deploy (push) Successful in 2m33s
2026-10-18 13:28:39 +00:00
devops c7b95b4d2b feat: dock PDP buy bar above mobile nav, redesign B2B modal to mobile-card layout, and implement full symptoms CRUD in backend & admin panel
Deploy Canina / deploy (push) Failing after 1m23s
2026-10-18 13:26:01 +00:00
devops 8e4388c325 fix(backend): fix duplicate success property in renameSymptom response
Deploy Canina / deploy (push) Successful in 2m30s
2026-10-18 12:58:12 +00:00
devops 305995cbe2 fix(backend): correct syntax for prisma transaction in renameSymptom
Deploy Canina / deploy (push) Failing after 1m15s
2026-10-18 12:55:11 +00:00
devops 468170349d feat(ux-fix): resolve wiki fallback 404, responsive B2B modal, clean badges, aligned bullets, mobile bottom nav on PDP and admin Rx/symptoms management
Deploy Canina / deploy (push) Failing after 1m14s
2026-10-18 12:51:04 +00:00
devops 52446592e7 fix(header): clean up prescription button navigation onClick handler
Deploy Canina / deploy (push) Successful in 2m16s
2026-10-18 11:35:43 +00:00
devops 7bca0ef335 feat(prescriptions): launch online veterinary prescription assessment portal with regression tests (B2B-03)
Deploy Canina / deploy (push) Failing after 1m6s
2026-10-18 11:31:49 +00:00
devops 80717680a1 feat(b2b): connect B2B landing inquiry form to public inquiry endpoint with regression test (B2B-01)
Deploy Canina / deploy (push) Successful in 2m14s
2026-10-18 11:19:51 +00:00
devops bb81f2c944 feat(blog): implement interactive in-article product cards (CAT-P2-10)
Deploy Canina / deploy (push) Successful in 2m15s
2026-10-18 06:37:05 +00:00
devops 69094a8646 fix(admin): resolve ReferenceError SmartChatAnalyticsPage in admin routes
Deploy Canina / deploy (push) Successful in 38s
2026-10-18 05:33:18 +00:00
devops bed0b480d7 Merge develop into main for sub-sitemaps, FAQ schema and local font release (SEO-P1-07, SEO-P1-10, SEO-P2-16)
Deploy Canina / deploy (push) Successful in 26s
2026-10-17 20:38:55 +00:00
devops f8f9329c50 feat(seo): implement FAQPage schema, sub-sitemaps and local Lalezar WOFF2 font (SEO-P1-07, SEO-P1-10, SEO-P2-16)
Deploy Canina / deploy (push) Successful in 2m10s
- SEO-P1-07: extract FAQs and accordion items from blog content and inject JSON-LD FAQPage schema
- SEO-P1-10: add dynamic sub-sitemaps /sitemap-blog.xml and /sitemap-wiki.xml and register in robots.ts
- SEO-P2-16: host Lalezar font locally as optimized WOFF2 with preload enabled in lib/fonts.ts
- Add full regression test suites with 100% pass rate
2026-10-17 20:38:09 +00:00
devops 189e1f1202 Merge develop into main for technical SEO fixes release (SEO-P0-01, SEO-P0-02, SEO-P1-06, SEO-P2-15)
Deploy Canina / deploy (push) Successful in 2m14s
2026-10-17 20:11:48 +00:00
devops 5cf2863987 fix(seo): resolve technical SEO issues (SEO-P0-01, SEO-P0-02, SEO-P1-06, SEO-P2-15)
Deploy Canina / deploy (push) Successful in 2m11s
- SEO-P0-01: prioritize options.canonicalPath in getPageMetadata over shop_canonical text
- SEO-P0-02: invoke notFound() in /shop/[slug] and /wiki/[slug] when entity is missing
- SEO-P1-06: package root JSON-LD Organization and WebSite into @graph structure
- SEO-P2-15: add hreflang fa-IR and x-default alternates in root layout metadata
- Add regression test suite lib/__tests__/seo-technical.test.ts
2026-10-17 20:02:56 +00:00
devops 83cf70ac74 Merge develop into main for complete UX overhaul release (UX-01 to UX-37)
Deploy Canina / deploy (push) Successful in 2m25s
2026-10-17 19:23:20 +00:00
devops 87bf867513 feat(ux-37): add /api/version deployment metadata endpoint and CI verification gate
Deploy Canina / deploy (push) Successful in 2m9s
2026-10-17 19:06:01 +00:00
devops 961bb383db test(ux-36): establish multi-device responsive matrix specification and test suite 2026-10-17 19:04:02 +00:00
devops 5d5cc14f9e test(ux-35): enforce 100% home section retention and zero mobile content exclusion regression gate 2026-10-17 19:02:19 +00:00
devops bfe228adee test(ux-34): add automated WCAG 2.1 AA/AAA contrast and readability gate 2026-10-17 18:58:03 +00:00
devops b5b4e64453 fix(ux-33): prevent support button overlap on contact form and elevate with safe-area spacing 2026-10-17 18:56:13 +00:00
devops f23efbf90d fix(ux-32): verify responsive menu sheet trigger and add mobile safe padding on search route 2026-10-17 18:53:20 +00:00
devops 81d1fa816b fix(ux-31): eliminate 13px horizontal viewport overflow and align MobileBottomNav with safe-area 2026-10-17 18:47:20 +00:00
devops f5c970f82e feat(ux-30): ensure touch targets exceed 44px across CartDrawer, Wiki, Contact, Footer and MobileBottomNav with regression tests 2026-10-17 18:43:34 +00:00
devops 6d0dea07f8 test(ux-29): add responsive and semantic tests for login, cart, profile, videos and smart-advisor routes 2026-10-17 18:37:26 +00:00
devops c4d95762f8 test(ux-28): add integration test verifying singleton authmodal and cartdrawer in shell layout 2026-10-17 18:33:29 +00:00
devops 23724df4e4 feat(ux-27): normalize persian text, add persistent error/retry state and accessible aria empty-state to search 2026-10-17 18:27:21 +00:00
devops 21f7768cce feat(ux-26): implement real shop pagination with deep-link page support and regression test 2026-10-17 18:15:42 +00:00
devops 92065cc7f2 fix(ux-25): add persistent error state with retry and recovery to shop archive 2026-10-17 18:05:35 +00:00
devops 956ef3b4d3 fix(ux-24): enforce semantic single H1 in catalog spread and add heading hierarchy regression tests 2026-10-17 17:28:27 +00:00
devops 0d8125bd37 fix(shop): unify responsive H1 and strip nested H1 tag in catalog title
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-17 16:10:38 +00:00
devops ea4d33b6bb fix(mobile): ensure touch targets exceed 44x44px across bottom navigation
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-17 15:44:19 +00:00
devops b4fdd7abb8 fix(contact): add standard autocomplete, inputmode and attributes for contact inputs
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-17 15:27:07 +00:00
devops f9d70bc196 fix(shop): prevent duplicate product card rendering across breakpoints in list viewMode
Deploy Canina / deploy (push) Successful in 2m5s
2026-10-17 14:42:44 +00:00
devops 5b20bab381 feat(wiki): add accessible accordion disclosures for ingredients
Deploy Canina / deploy (push) Successful in 2m6s
2026-10-17 14:01:23 +00:00
devops 2c3e4bb752 fix(search): connect tabs to results panel
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-17 12:52:00 +00:00
devops 570f0acc66 feat(search): add segmented universal results
Deploy Canina / deploy (push) Successful in 2m7s
2026-10-17 12:33:00 +00:00
devops 297aaadbe6 fix(blog): preserve sanitized content through hydration
Deploy Canina / deploy (push) Successful in 2m12s
2026-10-17 11:45:34 +00:00
devops 5573bb3568 fix(wiki): contain long ingredient codes on mobile
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-17 11:24:36 +00:00
devops 80d9dc2f45 fix(wiki): compact mobile cards and add pagination
Deploy Canina / deploy (push) Successful in 2m9s
2026-10-17 11:18:52 +00:00
devops 092933860a feat(ux): complete 5-task suite (category filter, real total count, mobile wiki, blog mobile UX, chatbot typewriter)
Deploy Canina / deploy (push) Successful in 2m12s
2026-10-17 10:59:21 +00:00
devops 3d45b618ab feat(search): redesign search page for mobile-first layout with multi-content tabs (products, blogs, wiki, videos)
Deploy Canina / deploy (push) Successful in 2m9s
2026-10-17 10:42:55 +00:00
devops 2ab2318732 fix(ux): render mobile solution and symptom modals via React Portal to prevent CSS mask clipping
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-17 10:29:51 +00:00
devops f3806cd6de fix(ux): remove search autoFocus in mobile shop sheet and add dedicated search entry in mobile menu
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-17 10:20:49 +00:00
devops 8326e10ce8 feat(catalog): add progressive product pagination and load more action
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-17 10:04:10 +00:00
devops d77ddd4bb2 feat(ux): optimize mobile spacing, padding and density across landing sections without removing content
Deploy Canina / deploy (push) Successful in 2m6s
2026-10-17 09:52:06 +00:00
devops 9149e2b5ab fix(seo): ensure proper H1 heading on shop, wiki, checkout, track, success and dashboard pages
Deploy Canina / deploy (push) Successful in 2m6s
2026-10-17 09:42:22 +00:00
devops 5534d050af fix(ux): replace overlay button with clean gradient mask for mobile catalog filters
Deploy Canina / deploy (push) Successful in 2m7s
2026-10-17 09:31:34 +00:00
devops 994086e580 feat(ux): add visible interactive scroll cue for mobile catalog filters
Deploy Canina / deploy (push) Successful in 2m11s
2026-10-17 09:12:34 +00:00
devops dbd7d8b37d fix(ux): expand mobile catalog filter fade height and width for visible affordance
Deploy Canina / deploy (push) Successful in 3m7s
2026-10-17 09:02:44 +00:00
devops f440c60891 feat(ux): add mobile catalog filter edge affordance
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-17 07:57:05 +00:00
devops 8672d4bcac feat(ux): add mobile catalog filter edge affordance
Deploy Canina / deploy (push) Successful in 2m15s
2026-10-17 07:53:46 +00:00
devops 87ad359e60 fix(frontend): separate mobile back-to-top control
Deploy Canina / deploy (push) Successful in 2m7s
2026-10-17 07:44:07 +00:00
devops 5afa2a37be fix(ux): remove duplicate utility route shells
Deploy Canina / deploy (push) Successful in 2m9s
2026-10-17 06:53:10 +00:00
devops d73b2e51c6 fix(blogs): tolerate missing stage author relations
Deploy Canina / deploy (push) Successful in 1m59s
2026-10-17 06:29:15 +00:00
devops 26f5f68708 fix(ux): harden dialogs and remove unsupported contact fallbacks
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-17 05:52:02 +00:00
devops 86cfa4b3c8 fix(pdp): keep initial server product visible
Deploy Canina / deploy (push) Successful in 2m7s
2026-10-16 21:03:13 +00:00
devops e2b6d2acae fix(pdp): render product from server data
Deploy Canina / deploy (push) Successful in 2m9s
2026-10-16 20:57:54 +00:00
devops 8ef98cb415 test(shop): cover mobile catalog search refresh
Deploy Canina / deploy (push) Successful in 2m13s
2026-10-16 20:51:18 +00:00
devops 6dbee69601 fix(a11y): label catalog sort control
Deploy Canina / deploy (push) Successful in 2m15s
2026-10-16 20:47:00 +00:00
devops 1aad481930 fix(a11y): label catalog search controls
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-16 20:41:53 +00:00
devops 4393de5d8f fix(a11y): label global search controls
Deploy Canina / deploy (push) Successful in 2m13s
2026-10-16 20:35:53 +00:00
devops 5380bb66bb test(ux): add frontend quality gates
Deploy Canina / deploy (push) Successful in 2m46s
2026-10-16 20:31:32 +00:00
devops 9a9ab149ed feat(ux): restore login and cart routes
Deploy Canina / deploy (push) Successful in 2m11s
2026-10-16 20:22:41 +00:00
devops bec76393bb fix(shop): render products from server data
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-16 19:48:37 +00:00
devops 427b0d8591 Merge support chat pet context and analytics
Deploy Canina / deploy (push) Successful in 49s
2026-10-16 11:56:13 +00:00
devops 1de8fd9a60 feat(support-chat): add pet context and admin analytics
Deploy Canina / deploy (push) Successful in 2m10s
2026-10-16 11:52:17 +00:00
devops 5c90d1629d Merge develop into main
Deploy Canina / deploy (push) Successful in 2m22s
2026-10-15 21:45:06 +00:00
devops c1a5223798 fix(support-chat): ground identity and improve widget UX
Deploy Canina / deploy (push) Successful in 3m43s
2026-10-15 21:39:29 +00:00
devops 139aaff86c Merge develop into main
Deploy Canina / deploy (push) Successful in 2m22s
2026-10-15 20:17:11 +00:00
devops d9ff4aef58 fix(contact): use database settings everywhere
Deploy Canina / deploy (push) Successful in 3m36s
2026-10-15 20:13:57 +00:00
devops a68e9b2c1e Merge develop into main
Deploy Canina / deploy (push) Successful in 28s
2026-10-15 19:02:33 +00:00
devops 66cbf4c68d fix(support-chat): recognize Finglish contact requests
Deploy Canina / deploy (push) Successful in 26s
2026-10-15 19:02:24 +00:00
devops 30ca17712c Merge develop into main
Deploy Canina / deploy (push) Successful in 28s
2026-10-15 18:56:37 +00:00
devops 781b437c11 fix(support-chat): ground contact answers in live source
Deploy Canina / deploy (push) Successful in 25s
2026-10-15 18:56:29 +00:00
devops cf8f920aa6 Merge develop into main
Deploy Canina / deploy (push) Successful in 39s
2026-10-15 18:51:18 +00:00
devops c16e34df02 fix(support-chat): send classifier-compatible payload
Deploy Canina / deploy (push) Successful in 1m54s
2026-10-15 18:51:10 +00:00
devops e67a4bd51c Merge develop into main
Deploy Canina / deploy (push) Successful in 39s
2026-10-15 18:39:45 +00:00
devops 18e59efdcc fix(support-chat): register config routes before history
Deploy Canina / deploy (push) Successful in 1m55s
2026-10-15 18:39:38 +00:00
devops c596c3a8b2 Merge develop into main
Deploy Canina / deploy (push) Successful in 38s
2026-10-15 18:35:44 +00:00
devops 1f68210d08 fix(support-chat): import UUID route validator
Deploy Canina / deploy (push) Successful in 1m50s
2026-10-15 18:35:37 +00:00
devops fb4669e5a5 Merge develop into main
Deploy Canina / deploy (push) Failing after 1m6s
2026-10-15 18:33:28 +00:00
devops 7b376f1126 fix(support-chat): baseline legacy migration in CI
Deploy Canina / deploy (push) Failing after 1m10s
2026-10-15 18:33:20 +00:00
devops e3426449e8 Merge develop into main
Deploy Canina / deploy (push) Failing after 25s
2026-10-15 18:28:35 +00:00
devops 8795617d7f fix(deploy): apply committed support chat migrations
Deploy Canina / deploy (push) Successful in 27s
2026-10-15 18:28:28 +00:00
devops 0dbf9cabb5 Merge develop into main
Deploy Canina / deploy (push) Successful in 2m18s
2026-10-15 15:50:32 +00:00
devops b6ac30d0e3 fix(prisma): quote support chat schema mappings
Deploy Canina / deploy (push) Successful in 4m2s
2026-10-15 15:50:25 +00:00
devops d79612b7e8 Merge develop into main
Deploy Canina / deploy (push) Failing after 29s
2026-10-15 15:39:57 +00:00
devops 33c605132b feat(support-chat): resolve trusted page context
Deploy Canina / deploy (push) Failing after 24s
2026-10-15 15:39:55 +00:00
devops 686de48a95 Merge develop into main
Deploy Canina / deploy (push) Has been cancelled
2026-10-15 15:39:13 +00:00
devops 043488fe55 fix(support-chat): allow safe Canina research and contact links
Deploy Canina / deploy (push) Failing after 31s
2026-10-15 15:39:06 +00:00
devops f292195edf fix(support-chat): restore saved conversation history
Deploy Canina / deploy (push) Failing after 30s
2026-10-15 07:41:21 +00:00
devops b61ba761bc fix(support-chat): default conversation updated timestamp
Deploy Canina / deploy (push) Failing after 23s
2026-10-15 07:34:44 +00:00
devops 4d64ad96b2 fix(support-chat): complete conversation analytics persistence
Deploy Canina / deploy (push) Has been cancelled
2026-10-15 07:34:07 +00:00
devops def903734f feat(support-chat): persist conversations and analytics
Deploy Canina / deploy (push) Failing after 28s
2026-10-15 07:28:02 +00:00
devops 59ab154d0f fix(support-chat): capture bot key before recreate
Deploy Canina / deploy (push) Successful in 32s
2026-10-15 07:02:27 +00:00
devops 31c55525c3 fix(support-chat): sync backend key from running bot
Deploy Canina / deploy (push) Successful in 21s
2026-10-15 07:02:00 +00:00
devops 332d400a37 fix(ci): recreate bot through runner docker daemon
Deploy Canina / deploy (push) Successful in 21s
2026-10-15 06:55:16 +00:00
devops b5dcdec18c fix(ci): correct support key env newline
Deploy Canina / deploy (push) Failing after 4s
2026-10-15 06:40:35 +00:00
devops c6cf2e31aa fix(ci): preserve newline in support key env
Deploy Canina / deploy (push) Failing after 5s
2026-10-15 06:40:06 +00:00
devops b7268d0c47 fix(support-chat): do not overwrite synced key with empty CI secret
Deploy Canina / deploy (push) Failing after 5s
2026-10-15 06:39:55 +00:00
devops a7b7164fc0 fix(support-chat): sync backend key with bot at deploy
Deploy Canina / deploy (push) Failing after 16s
2026-10-15 06:32:21 +00:00
devops 73f5d6d278 fix(deploy): prevent runtime prisma schema mutation
Deploy Canina / deploy (push) Failing after 5s
2026-10-15 06:18:47 +00:00
devops c04f1675f6 fix(ci): create bot override directory at runtime
Deploy Canina / deploy (push) Failing after 15s
2026-10-15 06:10:55 +00:00
devops 50cbd5b8ae fix(ci): create bot override directory
Deploy Canina / deploy (push) Has been cancelled
2026-10-15 06:10:49 +00:00
devops 19a029291b fix(ci): build support bot without unavailable buildx
Deploy Canina / deploy (push) Failing after 5s
2026-10-15 06:07:28 +00:00
devops bd7345078a fix(ci): preserve compose build continuation
Deploy Canina / deploy (push) Failing after 2s
2026-10-15 06:04:45 +00:00
devops 4969ec3fcd chore(ci): normalize deploy script whitespace
Deploy Canina / deploy (push) Failing after 1m21s
2026-10-15 06:00:48 +00:00
devops ec420e6053 fix(ci): expand bot image variables at deploy time
Deploy Canina / deploy (push) Has been cancelled
2026-10-15 06:00:41 +00:00
devops 4749ec91e4 fix(ci): preserve deploy variables in bot override
Deploy Canina / deploy (push) Failing after 2s
2026-10-15 06:00:00 +00:00
devops 679a551243 ci: deploy support chat bot from committed source
Deploy Canina / deploy (push) Failing after 2s
2026-10-15 05:59:48 +00:00
devops 240a176151 fix(support-chat): preserve provider catalog in isolated runtime
Deploy Canina / deploy (push) Successful in 30s
2026-10-14 21:55:58 +00:00
devops d2c227c733 fix(revalidation): preserve production runtime secret
Deploy Canina / deploy (push) Successful in 17s
2026-10-14 21:33:34 +00:00
devops a532e2c73f merge: synchronize main into develop before release
Deploy Canina / deploy (push) Has been cancelled
2026-10-14 21:33:02 +00:00
devops 3ff77d585d fix(deploy): make rollout code-only
Deploy Canina / deploy (push) Failing after 13s
2026-10-14 21:28:27 +00:00
devops 2a58e0c731 fix(revalidation): load runtime secret from env file
Deploy Canina / deploy (push) Successful in 37s
2026-10-14 21:20:38 +00:00
devops 200ddda352 fix(ci): preserve support chat runtime configuration
Deploy Canina / deploy (push) Successful in 33s
2026-10-14 20:57:08 +00:00
devops 1cbd210be1 fix(ci): preserve support chat runtime configuration
Deploy Canina / deploy (push) Successful in 49s
2026-10-14 20:57:07 +00:00
devops 419e478489 merge: remove redundant e2e and torob workflows
Deploy Canina / deploy (push) Successful in 2m4s
2026-10-14 20:08:43 +00:00
devops 8f8f0c36d5 ci: keep deploy workflow only
Deploy Canina / deploy (push) Successful in 38s
2026-10-14 20:08:41 +00:00
devops 2271291c87 merge: promote available products ordering
Deploy Canina / deploy (push) Waiting to run
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 6s
Torob regression / torob-regression (push) Failing after 42s
2026-10-14 20:06:43 +00:00
devops ed20f6d089 merge: prioritize available products
Deploy Canina / deploy (push) Has been cancelled
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
Torob regression / torob-regression (push) Failing after 38s
2026-10-14 20:06:40 +00:00
devops 12861288f2 feat(shop): show available products first 2026-10-14 20:04:50 +00:00
devops 73bfe0d893 merge: promote develop to main
Deploy Canina / deploy (push) Successful in 2m18s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
Torob regression / torob-regression (push) Failing after 34s
2026-10-14 19:58:50 +00:00
devops a289c40503 merge: admin smart-chat settings
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 6s
Torob regression / torob-regression (push) Failing after 40s
Deploy Canina / deploy (push) Successful in 4m32s
2026-10-14 19:44:40 +00:00
devops b6735b5a9c feat(support-chat): add admin smart chat settings 2026-10-14 19:44:24 +00:00
devops f6736cd43f fix(stage): deploy Torob backend without schema writes [skip ci] 2026-10-14 19:38:57 +00:00
devops fa4f1124e6 fix(stage): deploy Torob backend without schema writes [skip ci] 2026-10-14 19:36:18 +00:00
devops 30cebb92fa test(torob): verify PostgreSQL feed regression and guard invalid pagination 2026-10-14 19:35:21 +00:00
624 changed files with 40512 additions and 4198 deletions

No files matched your search

+4
View File
@@ -12,3 +12,7 @@ uploads
**/uploads **/uploads
*.pdf *.pdf
graphify-out graphify-out
**/.revalidation.env*
**/.support*.env*
**/*runtime.env
**/release.override.json
+6 -2
View File
@@ -13,6 +13,8 @@ jobs:
- name: Run deploy.sh from within the scripts folder - name: Run deploy.sh from within the scripts folder
env: env:
BRANCH: ${{ github.ref_name }} BRANCH: ${{ github.ref_name }}
DEPLOY_SHA: ${{ github.sha }}
GITHUB_ACTIONS: 'true'
run: | run: |
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی # 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
@@ -24,8 +26,10 @@ jobs:
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری # 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
mkdir -p scripts mkdir -p scripts
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/branch/${BRANCH}/scripts/deploy.sh wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/deploy.sh
wget --no-proxy -qO scripts/release-cache-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-stage.sh
wget --no-proxy -qO scripts/release-cache-prod.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-prod.sh
chmod +x scripts/deploy.sh chmod +x scripts/deploy.sh
cd scripts cd scripts
./deploy.sh ${BRANCH} ./deploy.sh "${BRANCH}"
-45
View File
@@ -1,45 +0,0 @@
name: E2E Playwright Tests
on:
push:
branches:
- main
- develop
pull_request:
branches:
- main
- develop
jobs:
test-e2e:
name: Run Full E2E & Security Suites
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install Monorepo Dependencies
run: npm ci
- name: Install Playwright Browsers
run: npx playwright install --with-deps chromium
- name: Run E2E Test Suite
run: npx playwright test --project=chromium-desktop --project=admin-chromium
env:
CI: true
NODE_ENV: test
- name: Upload Test Report
if: always()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: playwright-report/
retention-days: 14
@@ -0,0 +1,42 @@
name: Stage author bootstrap (dedicated repair)
on:
push:
branches:
- ops/author-bootstrap-stage-rehearse
- ops/author-bootstrap-stage-apply
jobs:
bootstrap:
runs-on: canina
steps:
- name: Exact SHA build then isolated rehearsal and authorized repair
env:
GITHUB_SHA: ${{ github.sha }}
GITHUB_REF: ${{ github.ref }}
GITHUB_ACTIONS: 'true'
STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA }}
# Path only, NOT a token value. Parent supplies an existing private file
# visible to the runner; absent file blocks repair AFTER image build.
AUTHOR_BOOTSTRAP_TOKEN_FILE: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_TOKEN_FILE }}
run: |
set -eu
set +x
umask 077
case "$GITHUB_REF" in
refs/heads/ops/author-bootstrap-stage-rehearse|refs/heads/ops/author-bootstrap-stage-apply) ;;
*) exit 2 ;;
esac
test "$STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA" = "$GITHUB_SHA"
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
root=$(mktemp -d)
chmod 700 "$root"
git init "$root/source"
git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA"
git -C "$root/source" checkout --detach FETCH_HEAD
test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA"
export AUTHOR_BOOTSTRAP_EVIDENCE="$root/evidence"
printf 'Private Stage evidence directory (retained on failure): %s\n' "$root/evidence"
python3 "$root/source/scripts/stage-author-bootstrap/ci.py"
# Retain private dumps locally; never upload archive or credential files.
printf 'Private Stage evidence directory: %s\n' "$root/evidence"
+35
View File
@@ -0,0 +1,35 @@
name: Stage SEO schema operation
on:
push:
branches:
- ops/seo-schema-stage-rehearse
- ops/seo-schema-stage-apply
jobs:
schema:
runs-on: canina
steps:
- name: Exact immutable Stage operation
env:
GITHUB_SHA: ${{ github.sha }}
GITHUB_REF: ${{ github.ref }}
GITHUB_ACTIONS: 'true'
STAGE_SCHEMA_REVIEWED_SHA: ${{ secrets.STAGE_SCHEMA_REVIEWED_SHA }}
run: |
set -eu
case "$GITHUB_REF" in
refs/heads/ops/seo-schema-stage-rehearse) mode=rehearse ;;
refs/heads/ops/seo-schema-stage-apply) mode=apply ;;
*) exit 2 ;;
esac
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
root=$(mktemp -d)
chmod 700 "$root"
git init "$root/source"
git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA"
git -C "$root/source" checkout --detach FETCH_HEAD
test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA"
python3 "$root/source/scripts/stage-schema/operation.py" "$mode" --sha "$GITHUB_SHA" --evidence "$root/evidence"
# Private backups remain in this restricted runner directory; never upload dumps.
printf 'Private Stage evidence directory: %s\n' "$root/evidence"
+4
View File
@@ -16,3 +16,7 @@ playwright-report/
playwright/.auth/ playwright/.auth/
blob-report/ blob-report/
# Python CI helpers must not dirty immutable release checkouts.
__pycache__/
*.pyc
+14
View File
@@ -0,0 +1,14 @@
# Machine-local Spec Kit state — not meant to be shared.
# Managed by the Specify CLI; safe to edit (your changes are preserved on refresh).
# Local pointer to the current feature directory. Rewritten every time you
# switch features, so it is per-checkout state rather than something to share.
feature.json
# Per-machine extension config overrides.
extensions/*/local-config.yml
# Executable adapter packages and their per-checkout provenance registry.
# Execution consent is stored separately in the user's local trust registry.
integrations/packages/
integrations/packages.json
+251
View File
@@ -0,0 +1,251 @@
---
description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before analysis)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_analyze` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Goal.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Goal
Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. This command MUST run only after `/speckit.tasks` has successfully produced a complete `tasks.md`.
## Operating Constraints
**STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually).
**Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is **non-negotiable** within this analysis scope. Constitution conflicts are automatically CRITICAL and require adjustment of the spec, plan, or tasks—not dilution, reinterpretation, or silent ignoring of the principle. If a principle itself needs to change, that must occur in a separate, explicit constitution update outside `/speckit.analyze`.
## Execution Steps
### 1. Initialize Analysis Context
Run `.specify/scripts/bash/check-prerequisites.sh --json --require-spec --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths:
- SPEC = FEATURE_DIR/spec.md
- PLAN = FEATURE_DIR/plan.md
- TASKS = FEATURE_DIR/tasks.md
Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command).
For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
### 2. Load Artifacts (Progressive Disclosure)
Load only the minimal necessary context from each artifact:
**From spec.md:**
- Overview/Context
- Functional Requirements
- Success Criteria (measurable outcomes — e.g., performance, security, availability, user success, business impact)
- User Stories
- Edge Cases (if present)
**From plan.md:**
- Architecture/stack choices
- Data Model references
- Phases
- Technical constraints
**From tasks.md:**
- Task IDs
- Descriptions
- Phase grouping
- Parallel markers [P]
- Referenced file paths
**From constitution:**
- Load `.specify/memory/constitution.md` for principle validation
### 3. Build Semantic Models
Create internal representations (do not include raw artifacts in output):
- **Requirements inventory**: For each Functional Requirement (FR-###) and Success Criterion (SC-###), record a stable key. Use the explicit FR-/SC- identifier as the primary key when present, and optionally also derive an imperative-phrase slug for readability (e.g., "User can upload file" → `user-can-upload-file`). Include only Success Criteria items that require buildable work (e.g., load-testing infrastructure, security audit tooling), and exclude post-launch outcome metrics and business KPIs (e.g., "Reduce support tickets by 50%").
- **User story/action inventory**: Discrete user actions with acceptance criteria
- **Task coverage mapping**: Map each task to one or more requirements or stories (inference by keyword / explicit reference patterns like IDs or key phrases)
- **Constitution rule set**: Extract principle names and MUST/SHOULD normative statements
### 4. Detection Passes (Token-Efficient Analysis)
Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary.
#### A. Duplication Detection
- Identify near-duplicate requirements
- Mark lower-quality phrasing for consolidation
#### B. Ambiguity Detection
- Flag vague adjectives (fast, scalable, secure, intuitive, robust) lacking measurable criteria
- Flag unresolved placeholders (TODO, TKTK, ???, `<placeholder>`, etc.)
#### C. Underspecification
- Requirements with verbs but missing object or measurable outcome
- User stories missing acceptance criteria alignment
- Tasks referencing files or components not defined in spec/plan
#### D. Constitution Alignment
- Any requirement or plan element conflicting with a MUST principle
- Missing mandated sections or quality gates from constitution
#### E. Coverage Gaps
- Requirements with zero associated tasks
- Tasks with no mapped requirement/story
- Success Criteria requiring buildable work (performance, security, availability) not reflected in tasks
#### F. Inconsistency
- Terminology drift (same concept named differently across files)
- Data entities referenced in plan but absent in spec (or vice versa)
- Task ordering contradictions (e.g., integration tasks before foundational setup tasks without dependency note)
- Conflicting requirements (e.g., one requires Next.js while other specifies Vue)
### 5. Severity Assignment
Use this heuristic to prioritize findings:
- **CRITICAL**: Violates constitution MUST, missing core spec artifact, or requirement with zero coverage that blocks baseline functionality
- **HIGH**: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion
- **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case
- **LOW**: Style/wording improvements, minor redundancy not affecting execution order
### 6. Produce Compact Analysis Report
Output a Markdown report (no file writes) with the following structure:
## Specification Analysis Report
| ID | Category | Severity | Location(s) | Summary | Recommendation |
|----|----------|----------|-------------|---------|----------------|
| A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version |
(Add one row per finding; generate stable IDs prefixed by category initial.)
**Coverage Summary Table:**
| Requirement Key | Has Task? | Task IDs | Notes |
|-----------------|-----------|----------|-------|
**Constitution Alignment Issues:** (if any)
**Unmapped Tasks:** (if any)
**Metrics:**
- Total Requirements
- Total Tasks
- Coverage % (requirements with >=1 task)
- Ambiguity Count
- Duplication Count
- Critical Issues Count
### 7. Provide Next Actions
At end of report, output a concise Next Actions block:
- If CRITICAL issues exist: Recommend resolving before `/speckit.implement`
- If only LOW/MEDIUM: User may proceed, but provide improvement suggestions
- Provide explicit command suggestions: e.g., "Run /speckit.specify with refinement", "Run /speckit.plan to adjust architecture", "Manually edit tasks.md to add coverage for 'performance-metrics'"
### 8. Offer Remediation
Ask the user: "Would you like me to suggest concrete remediation edits for the top N issues?" (Do NOT apply them automatically.)
### 9. Check for extension hooks
After reporting, check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_analyze` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Operating Principles
### Context Efficiency
- **Minimal high-signal tokens**: Focus on actionable findings, not exhaustive documentation
- **Progressive disclosure**: Load artifacts incrementally; don't dump all content into analysis
- **Token-efficient output**: Limit findings table to 50 rows; summarize overflow
- **Deterministic results**: Rerunning without changes should produce consistent IDs and counts
### Analysis Guidelines
- **NEVER modify files** (this is read-only analysis)
- **NEVER hallucinate missing sections** (if absent, report them accurately)
- **Prioritize constitution violations** (these are always CRITICAL)
- **Use examples over exhaustive rules** (cite specific instances, not generic patterns)
- **Report zero issues gracefully** (emit success report with coverage statistics)
## Context
$ARGUMENTS
+375
View File
@@ -0,0 +1,375 @@
---
description: Generate a custom checklist for the current feature based on user requirements.
---
## Checklist Purpose: "Unit Tests for English"
**CRITICAL CONCEPT**: Checklists are **UNIT TESTS FOR REQUIREMENTS WRITING** - they validate the quality, clarity, and completeness of requirements in a given domain.
**NOT for verification/testing**:
- ❌ NOT "Verify the button clicks correctly"
- ❌ NOT "Test error handling works"
- ❌ NOT "Confirm the API returns 200"
- ❌ NOT checking if code/implementation matches the spec
**FOR requirements quality validation**:
- ✅ "Are visual hierarchy requirements defined for all card types?" (completeness)
- ✅ "Is 'prominent display' quantified with specific sizing/positioning?" (clarity)
- ✅ "Are hover state requirements consistent across all interactive elements?" (consistency)
- ✅ "Are accessibility requirements defined for keyboard navigation?" (coverage)
- ✅ "Does the spec define what happens when logo image fails to load?" (edge cases)
**Metaphor**: If your spec is code written in English, the checklist is its unit test suite. You're testing whether the requirements are well-written, complete, unambiguous, and ready for implementation - NOT whether the implementation works.
**Ownership and checkbox lifecycle**:
- Custom checklists generated by this command are reviewer-owned requirements-quality review artifacts.
- `[x]` means the reviewer determined the requirements-quality criterion is satisfied.
- `[x]` does NOT mean implementation work is complete.
- This command generates or appends checklist items; it MUST NOT mark generated items `[x]`.
- An agent may assist with evaluating items only when explicitly asked by the reviewer.
- `checklists/requirements.md` is a separate built-in spec-quality checklist maintained by `/speckit.specify` and `/speckit.clarify`; do not treat that exception as applying to custom checklists generated here.
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before checklist generation)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_checklist` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Execution Steps.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Execution Steps
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json --template checklist-template` from repo root and parse JSON for FEATURE_DIR, AVAILABLE_DOCS list, and TEMPLATE_CONTENT.
- All file paths must be absolute.
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints.
3. **Clarify intent (dynamic)**: Derive up to THREE initial contextual clarifying questions (no pre-baked catalog). They MUST:
- Be generated from the user's phrasing + extracted signals from spec/plan/tasks
- Only ask about information that materially changes checklist content
- Be skipped individually if already unambiguous in `$ARGUMENTS`
- Prefer precision over breadth
Generation algorithm:
1. Extract signals: feature domain keywords (e.g., auth, latency, UX, API), risk indicators ("critical", "must", "compliance"), stakeholder hints ("QA", "review", "security team"), and explicit deliverables ("a11y", "rollback", "contracts").
2. Cluster signals into candidate focus areas (max 4) ranked by relevance.
3. Identify probable audience & timing (author, reviewer, QA, release) if not explicit.
4. Detect missing dimensions: scope breadth, depth/rigor, risk emphasis, exclusion boundaries, measurable acceptance criteria.
5. Formulate questions chosen from these archetypes:
- Scope refinement (e.g., "Should this include integration touchpoints with X and Y or stay limited to local module correctness?")
- Risk prioritization (e.g., "Which of these potential risk areas should receive mandatory gating checks?")
- Depth calibration (e.g., "Is this a lightweight pre-commit sanity list or a formal release gate?")
- Audience framing (e.g., "Will this be used by the author only or peers during PR review?")
- Boundary exclusion (e.g., "Should we explicitly exclude performance tuning items this round?")
- Scenario class gap (e.g., "No recovery flows detected—are rollback / partial failure paths in scope?")
Question formatting rules:
- If presenting options, generate a compact table with columns: Option | Candidate | Why It Matters
- Limit to A–E options maximum; omit table if a free-form answer is clearer
- Never ask the user to restate what they already said
- Avoid speculative categories (no hallucination). If uncertain, ask explicitly: "Confirm whether X belongs in scope."
Defaults when interaction impossible:
- Depth: Standard
- Audience: Reviewer (PR) if code-related; Author otherwise
- Focus: Top 2 relevance clusters
Output the questions (label Q1/Q2/Q3). After answers: if ≥2 scenario classes (Alternate / Exception / Recovery / Non-Functional domain) remain unclear, you MAY ask up to TWO more targeted follow‑ups (Q4/Q5) with a one-line justification each (e.g., "Unresolved recovery path risk"). Do not exceed five total questions. Skip escalation if user explicitly declines more.
4. **Understand user request**: Combine `$ARGUMENTS` + clarifying answers:
- Derive checklist theme (e.g., security, review, deploy, ux)
- Consolidate explicit must-have items mentioned by user
- Map focus selections to category scaffolding
- Infer any missing context from spec/plan/tasks (do NOT hallucinate)
5. **Load feature context**: Read from FEATURE_DIR:
- spec.md: Feature requirements and scope
- plan.md (if exists): Technical details, dependencies
- tasks.md (if exists): Implementation tasks
**Context Loading Strategy**:
- Load only necessary portions relevant to active focus areas (avoid full-file dumping)
- Prefer summarizing long sections into concise scenario/requirement bullets
- Use progressive disclosure: add follow-on retrieval only if gaps detected
- If source docs are large, generate interim summary items instead of embedding raw text
6. **Generate checklist** - Use TEMPLATE_CONTENT as the structural template and create "Unit Tests for Requirements":
- Create `FEATURE_DIR/checklists/` directory if it doesn't exist
- Generate unique checklist filename:
- Use short, descriptive name based on domain (e.g., `ux.md`, `api.md`, `security.md`)
- Format: `[domain].md`
- File handling behavior:
- If file does NOT exist: Create new file and number items starting from CHK001
- If file exists: Append new items to existing file, continuing from the last CHK ID (e.g., if last item is CHK015, start new items at CHK016)
- Never delete or replace existing checklist content - always preserve and append
- Leave every newly generated item unchecked (`[ ]`); checkbox state belongs to the reviewer
**CORE PRINCIPLE - Test the Requirements, Not the Implementation**:
Every checklist item MUST evaluate the REQUIREMENTS THEMSELVES for:
- **Completeness**: Are all necessary requirements present?
- **Clarity**: Are requirements unambiguous and specific?
- **Consistency**: Do requirements align with each other?
- **Measurability**: Can requirements be objectively verified?
- **Coverage**: Are all scenarios/edge cases addressed?
**Category Structure** - Group items by requirement quality dimensions:
- **Requirement Completeness** (Are all necessary requirements documented?)
- **Requirement Clarity** (Are requirements specific and unambiguous?)
- **Requirement Consistency** (Do requirements align without conflicts?)
- **Acceptance Criteria Quality** (Are success criteria measurable?)
- **Scenario Coverage** (Are all flows/cases addressed?)
- **Edge Case Coverage** (Are boundary conditions defined?)
- **Non-Functional Requirements** (Performance, Security, Accessibility, etc. - are they specified?)
- **Dependencies & Assumptions** (Are they documented and validated?)
- **Ambiguities & Conflicts** (What needs clarification?)
**HOW TO WRITE CHECKLIST ITEMS - "Unit Tests for English"**:
❌ **WRONG** (Testing implementation):
- "Verify landing page displays 3 episode cards"
- "Test hover states work on desktop"
- "Confirm logo click navigates home"
✅ **CORRECT** (Testing requirements quality):
- "Are the exact number and layout of featured episodes specified?" [Completeness]
- "Is 'prominent display' quantified with specific sizing/positioning?" [Clarity]
- "Are hover state requirements consistent across all interactive elements?" [Consistency]
- "Are keyboard navigation requirements defined for all interactive UI?" [Coverage]
- "Is the fallback behavior specified when logo image fails to load?" [Edge Cases]
- "Are loading states defined for asynchronous episode data?" [Completeness]
- "Does the spec define visual hierarchy for competing UI elements?" [Clarity]
**ITEM STRUCTURE**:
Each item should follow this pattern:
- Question format asking about requirement quality
- Focus on what's WRITTEN (or not written) in the spec/plan
- Include quality dimension in brackets [Completeness/Clarity/Consistency/etc.]
- Reference spec section `[Spec §X.Y]` when checking existing requirements
- Use `[Gap]` marker when checking for missing requirements
**EXAMPLES BY QUALITY DIMENSION**:
Completeness:
- "Are error handling requirements defined for all API failure modes? [Gap]"
- "Are accessibility requirements specified for all interactive elements? [Completeness]"
- "Are mobile breakpoint requirements defined for responsive layouts? [Gap]"
Clarity:
- "Is 'fast loading' quantified with specific timing thresholds? [Clarity, Spec §NFR-2]"
- "Are 'related episodes' selection criteria explicitly defined? [Clarity, Spec §FR-5]"
- "Is 'prominent' defined with measurable visual properties? [Ambiguity, Spec §FR-4]"
Consistency:
- "Do navigation requirements align across all pages? [Consistency, Spec §FR-10]"
- "Are card component requirements consistent between landing and detail pages? [Consistency]"
Coverage:
- "Are requirements defined for zero-state scenarios (no episodes)? [Coverage, Edge Case]"
- "Are concurrent user interaction scenarios addressed? [Coverage, Gap]"
- "Are requirements specified for partial data loading failures? [Coverage, Exception Flow]"
Measurability:
- "Are visual hierarchy requirements measurable/testable? [Acceptance Criteria, Spec §FR-1]"
- "Can 'balanced visual weight' be objectively verified? [Measurability, Spec §FR-2]"
**Scenario Classification & Coverage** (Requirements Quality Focus):
- Check if requirements exist for: Primary, Alternate, Exception/Error, Recovery, Non-Functional scenarios
- For each scenario class, ask: "Are [scenario type] requirements complete, clear, and consistent?"
- If scenario class missing: "Are [scenario type] requirements intentionally excluded or missing? [Gap]"
- Include resilience/rollback when state mutation occurs: "Are rollback requirements defined for migration failures? [Gap]"
**Traceability Requirements**:
- MINIMUM: ≥80% of items MUST include at least one traceability reference
- Each item should reference: spec section `[Spec §X.Y]`, or use markers: `[Gap]`, `[Ambiguity]`, `[Conflict]`, `[Assumption]`
- If no ID system exists: "Is a requirement & acceptance criteria ID scheme established? [Traceability]"
**Surface & Resolve Issues** (Requirements Quality Problems):
Ask questions about the requirements themselves:
- Ambiguities: "Is the term 'fast' quantified with specific metrics? [Ambiguity, Spec §NFR-1]"
- Conflicts: "Do navigation requirements conflict between §FR-10 and §FR-10a? [Conflict]"
- Assumptions: "Is the assumption of 'always available podcast API' validated? [Assumption]"
- Dependencies: "Are external podcast API requirements documented? [Dependency, Gap]"
- Missing definitions: "Is 'visual hierarchy' defined with measurable criteria? [Gap]"
**Content Consolidation**:
- Soft cap: If raw candidate items > 40, prioritize by risk/impact
- Merge near-duplicates checking the same requirement aspect
- If >5 low-impact edge cases, create one item: "Are edge cases X, Y, Z addressed in requirements? [Coverage]"
**🚫 ABSOLUTELY PROHIBITED** - These make it an implementation test, not a requirements test:
- ❌ Any item starting with "Verify", "Test", "Confirm", "Check" + implementation behavior
- ❌ References to code execution, user actions, system behavior
- ❌ "Displays correctly", "works properly", "functions as expected"
- ❌ "Click", "navigate", "render", "load", "execute"
- ❌ Test cases, test plans, QA procedures
- ❌ Implementation details (frameworks, APIs, algorithms)
**✅ REQUIRED PATTERNS** - These test requirements quality:
- ✅ "Are [requirement type] defined/specified/documented for [scenario]?"
- ✅ "Is [vague term] quantified/clarified with specific criteria?"
- ✅ "Are requirements consistent between [section A] and [section B]?"
- ✅ "Can [requirement] be objectively measured/verified?"
- ✅ "Are [edge cases/scenarios] addressed in requirements?"
- ✅ "Does the spec define [missing aspect]?"
7. **Structure Reference**: Generate the checklist following the canonical template in `.specify/templates/checklist-template.md` for title, meta section, category headings, ownership note, notes section, and ID formatting. If template is unavailable, use: H1 title, purpose/created meta lines, an ownership note explaining that `[x]` means reviewer approval of requirements quality, `##` category sections containing `- [ ] CHK### <requirement item>` lines with globally incrementing IDs starting at CHK001, and notes that `/speckit.implement` reads checklist state but does not modify markers.
8. **Report**: Output full path to checklist file, item count, and summarize whether the run created a new file or appended to an existing one. Summarize:
- Focus areas selected
- Depth level
- Actor/timing
- Any explicit user-specified must-have items incorporated
**Important**: Each `/speckit.checklist` command invocation uses a short, descriptive checklist filename and either creates a new file or appends to an existing one. This allows:
- Multiple checklists of different types (e.g., `ux.md`, `test.md`, `security.md`)
- Simple, memorable filenames that indicate checklist purpose
- Easy identification and navigation in the `checklists/` folder
To avoid clutter, use descriptive types and clean up obsolete checklists when done.
## Example Checklist Types & Sample Items
**UX Requirements Quality:** `ux.md`
Sample items (testing the requirements, NOT the implementation):
- "Are visual hierarchy requirements defined with measurable criteria? [Clarity, Spec §FR-1]"
- "Is the number and positioning of UI elements explicitly specified? [Completeness, Spec §FR-1]"
- "Are interaction state requirements (hover, focus, active) consistently defined? [Consistency]"
- "Are accessibility requirements specified for all interactive elements? [Coverage, Gap]"
- "Is fallback behavior defined when images fail to load? [Edge Case, Gap]"
- "Can 'prominent display' be objectively measured? [Measurability, Spec §FR-4]"
**API Requirements Quality:** `api.md`
Sample items:
- "Are error response formats specified for all failure scenarios? [Completeness]"
- "Are rate limiting requirements quantified with specific thresholds? [Clarity]"
- "Are authentication requirements consistent across all endpoints? [Consistency]"
- "Are retry/timeout requirements defined for external dependencies? [Coverage, Gap]"
- "Is versioning strategy documented in requirements? [Gap]"
**Performance Requirements Quality:** `performance.md`
Sample items:
- "Are performance requirements quantified with specific metrics? [Clarity]"
- "Are performance targets defined for all critical user journeys? [Coverage]"
- "Are performance requirements under different load conditions specified? [Completeness]"
- "Can performance requirements be objectively measured? [Measurability]"
- "Are degradation requirements defined for high-load scenarios? [Edge Case, Gap]"
**Security Requirements Quality:** `security.md`
Sample items:
- "Are authentication requirements specified for all protected resources? [Coverage]"
- "Are data protection requirements defined for sensitive information? [Completeness]"
- "Is the threat model documented and requirements aligned to it? [Traceability]"
- "Are security requirements consistent with compliance obligations? [Consistency]"
- "Are security failure/breach response requirements defined? [Gap, Exception Flow]"
## Anti-Examples: What NOT To Do
**❌ WRONG - These test implementation, not requirements:**
```markdown
- [ ] CHK001 - Verify landing page displays 3 episode cards [Spec §FR-001]
- [ ] CHK002 - Test hover states work correctly on desktop [Spec §FR-003]
- [ ] CHK003 - Confirm logo click navigates to home page [Spec §FR-010]
- [ ] CHK004 - Check that related episodes section shows 3-5 items [Spec §FR-005]
```
**✅ CORRECT - These test requirements quality:**
```markdown
- [ ] CHK001 - Are the number and layout of featured episodes explicitly specified? [Completeness, Spec §FR-001]
- [ ] CHK002 - Are hover state requirements consistently defined for all interactive elements? [Consistency, Spec §FR-003]
- [ ] CHK003 - Are navigation requirements clear for all clickable brand elements? [Clarity, Spec §FR-010]
- [ ] CHK004 - Is the selection criteria for related episodes documented? [Gap, Spec §FR-005]
- [ ] CHK005 - Are loading state requirements defined for asynchronous episode data? [Gap]
- [ ] CHK006 - Can "visual hierarchy" requirements be objectively measured? [Measurability, Spec §FR-001]
```
**Key Differences:**
- Wrong: Tests if the system works correctly
- Correct: Tests if the requirements are written correctly
- Wrong: Verification of behavior
- Correct: Validation of requirement quality
- Wrong: "Does it do X?"
- Correct: "Is X clearly specified?"
## Post-Execution Checks
**Check for extension hooks (after checklist generation)**:
Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_checklist` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
+287
View File
@@ -0,0 +1,287 @@
---
description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec.
handoffs:
- label: Build Technical Plan
agent: speckit.plan
prompt: Create a plan for the spec. I am building with...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before clarification)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_clarify` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
Goal: Detect and reduce ambiguity or missing decision points in the active feature specification and record the clarifications directly in the spec file.
Note: This clarification workflow is expected to run (and be completed) BEFORE invoking `/speckit.plan`. If the user explicitly states they are skipping clarification (e.g., exploratory spike), you may proceed, but must warn that downstream rework risk increases.
Execution steps:
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --paths-only` from repo root **once** (combined `--json --paths-only` mode / `-Json -PathsOnly`). Parse minimal JSON payload fields:
- `FEATURE_DIR`
- `FEATURE_SPEC`
- (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.)
- If JSON parsing fails, abort and instruct user to re-run `/speckit.specify` or verify feature branch environment.
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints.
3. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked).
Functional Scope & Behavior:
- Core user goals & success criteria
- Explicit out-of-scope declarations
- User roles / personas differentiation
Domain & Data Model:
- Entities, attributes, relationships
- Identity & uniqueness rules
- Lifecycle/state transitions
- Data volume / scale assumptions
Interaction & UX Flow:
- Critical user journeys / sequences
- Error/empty/loading states
- Accessibility or localization notes
Non-Functional Quality Attributes:
- Performance (latency, throughput targets)
- Scalability (horizontal/vertical, limits)
- Reliability & availability (uptime, recovery expectations)
- Observability (logging, metrics, tracing signals)
- Security & privacy (authN/Z, data protection, threat assumptions)
- Compliance / regulatory constraints (if any)
Integration & External Dependencies:
- External services/APIs and failure modes
- Data import/export formats
- Protocol/versioning assumptions
Edge Cases & Failure Handling:
- Negative scenarios
- Rate limiting / throttling
- Conflict resolution (e.g., concurrent edits)
Constraints & Tradeoffs:
- Technical constraints (language, storage, hosting)
- Explicit tradeoffs or rejected alternatives
Terminology & Consistency:
- Canonical glossary terms
- Avoided synonyms / deprecated terms
Completion Signals:
- Acceptance criteria testability
- Measurable Definition of Done style indicators
Misc / Placeholders:
- TODO markers / unresolved decisions
- Ambiguous adjectives ("robust", "intuitive") lacking quantification
For each category with Partial or Missing status, add a candidate question opportunity unless:
- Clarification would not materially change implementation or validation strategy
- The item is specifically about implementation method, tech-stack comparison, or task breakdown (note internally)
4. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints:
- Maximum of 5 total questions across the whole session.
- Each question must be answerable with EITHER:
- A short multiple‑choice selection (2–5 distinct, mutually exclusive options), OR
- A one-word / short‑phrase answer (explicitly constrain: "Answer in <=5 words").
- Only include questions whose answers materially impact architecture, data modeling, task decomposition, test design, UX behavior, operational readiness, or compliance validation.
- Ensure category coverage balance: attempt to cover the highest impact unresolved categories first; avoid asking two low-impact questions when a single high-impact area (e.g., security posture) is unresolved.
- Exclude questions already answered, trivial stylistic preferences, or plan-level execution details (unless blocking correctness).
- Favor clarifications that reduce downstream rework risk or prevent misaligned acceptance tests.
- If more than 5 categories remain unresolved, select the top 5 by (Impact * Uncertainty) heuristic.
5. Sequential questioning loop (interactive):
- Present EXACTLY ONE question at a time.
- **Question writing quality (applies to every question, MC or short-answer):**
- Lead with `**Question:**` followed by a full interrogative that ends with `?`. The question text before the `?` must make sense on its own.
- NEVER use a topic label, section heading, or requirement id as the question itself. For example, `Acceptance device/runtime matrix (FR-023)` is INVALID — it is a label, not a question.
- After the `?`, the only permitted suffix is an optional parenthesized requirement/question id. Exact format: `**Question:** <interrogative>?` or `**Question:** <interrogative>? (FR-023)`. Never put the id before the `?`, and never use the id (alone or with a topic label) as the whole prompt.
- Immediately after the question line, add one plain-language "Why it matters" sentence (the stake for acceptance or shipping) before the recommendation/options.
- Use everyday wording; introduce jargon only if defined in the same sentence. Self-check: a reader who does not know Spec Kit must be able to answer from the Question line alone. Terse is fine; cryptic labels are not.
- For multiple‑choice questions:
- **Analyze all options** and determine the **most suitable option** based on:
- Best practices for the project type
- Common patterns in similar implementations
- Risk reduction (security, performance, maintainability)
- Alignment with any explicit project goals or constraints visible in the spec
- Present your **recommended option prominently** at the top with clear reasoning (1-2 sentences explaining why this is the best choice).
- Format as: `**Recommended:** Option [X] - <reasoning>`
- Then render all options as a Markdown table:
| Option | Description |
|--------|-------------|
| A | <Option A description> |
| B | <Option B description> |
| C | <Option C description> (add D/E as needed up to 5) |
| Short | Provide a different short answer (<=5 words) (Include only if free-form alternative is appropriate) |
- After the table, add: `You can reply with the option letter (e.g., "A"), accept the recommendation by saying "yes" or "recommended", or provide your own short answer.`
- For short‑answer style (no meaningful discrete options):
- Provide your **suggested answer** based on best practices and context.
- Format as: `**Suggested:** <your proposed answer> - <brief reasoning>`
- Then output: `Format: Short answer (<=5 words). You can accept the suggestion by saying "yes" or "suggested", or provide your own answer.`
- After the user answers:
- If the user replies with "yes", "recommended", or "suggested", use your previously stated recommendation/suggestion as the answer.
- Otherwise, validate the answer maps to one option or fits the <=5 word constraint.
- If ambiguous, ask for a quick disambiguation (count still belongs to same question; do not advance).
- Once satisfactory, record it in working memory (do not yet write to disk) and move to the next queued question.
- Stop asking further questions when:
- All critical ambiguities resolved early (remaining queued items become unnecessary), OR
- User signals completion ("done", "good", "no more"), OR
- You reach 5 asked questions.
- Never reveal future queued questions in advance.
- If no valid questions exist at start, immediately report no critical ambiguities.
6. Integration after EACH accepted answer (incremental update approach):
- Maintain in-memory representation of the spec (loaded once at start) plus the raw file contents.
- For the first integrated answer in this session:
- Ensure a `## Clarifications` section exists (create it just after the highest-level contextual/overview section per the spec template if missing).
- Under it, create (if not present) a `### Session YYYY-MM-DD` subheading for today.
- Append a bullet line immediately after acceptance: `- Q: <question> → A: <final answer>`.
- Then immediately apply the clarification to the most appropriate section(s):
- Functional ambiguity → Update or add a bullet in Functional Requirements.
- User interaction / actor distinction → Update User Stories or Actors subsection (if present) with clarified role, constraint, or scenario.
- Data shape / entities → Update Data Model (add fields, types, relationships) preserving ordering; note added constraints succinctly.
- Non-functional constraint → Add/modify measurable criteria in Success Criteria > Measurable Outcomes (convert vague adjective to metric or explicit target).
- Edge case / negative flow → Add a new bullet under Edge Cases / Error Handling (or create such subsection if template provides placeholder for it).
- Terminology conflict → Normalize term across spec; retain original only if necessary by adding `(formerly referred to as "X")` once.
- If the clarification invalidates an earlier ambiguous statement, replace that statement instead of duplicating; leave no obsolete contradictory text.
- Save the spec file AFTER each integration to minimize risk of context loss (atomic overwrite).
- Preserve formatting: do not reorder unrelated sections; keep heading hierarchy intact.
- Keep each inserted clarification minimal and testable (avoid narrative drift).
7. Validation (performed after EACH write plus final pass):
- Clarifications session contains exactly one bullet per accepted answer (no duplicates).
- Total asked (accepted) questions ≤ 5.
- Updated sections contain no lingering vague placeholders the new answer was meant to resolve.
- No contradictory earlier statement remains (scan for now-invalid alternative choices removed).
- Markdown structure valid; only allowed new headings: `## Clarifications`, `### Session YYYY-MM-DD`.
- Terminology consistency: same canonical term used across all updated sections.
8. Write the updated spec back to `FEATURE_SPEC`.
9. **Re-validate Spec Quality Checklist** (if it exists):
- Check if `FEATURE_DIR/checklists/requirements.md` exists.
- If it does NOT exist, skip this step silently.
- If it exists:
1. Read the checklist file.
2. Identify all GitHub task-list checkbox lines — lines matching `- [ ]`, `- [x]`, or `- [X]` (case-insensitive, tolerant of leading whitespace for nested items) outside of code fences. Ignore all other content (headings, notes, non-checkbox bullets, metadata).
3. For each checkbox line, record its current marker state (checked or unchecked) and item text into a before-snapshot list.
4. Re-evaluate each checkbox item against the **updated** spec (the version just saved in step 7).
5. For each checkbox item, update only if the checked/unchecked state actually changes:
- If the item now passes and was unchecked: change `[ ]` to `[x]`.
- If the item now fails and was checked: change `[x]`/`[X]` to `[ ]`.
- If the state is unchanged: leave the marker as-is (preserve existing case to avoid cosmetic diffs).
6. Save the updated checklist file. **Only toggle the `[ ]`/`[x]` marker portion of checkbox lines whose state changed.** All other file content — headings, metadata, notes, line ordering, whitespace — must remain unchanged to avoid noisy diffs.
7. Compare the before-snapshot with the current state to compute three lists for the Completion Report:
- **Newly passing**: items that changed from unchecked to checked.
- **Regressions**: items that changed from checked to unchecked.
- **Still unchecked**: items that remain unchecked.
8. Record the before/after pass counts as checked/total checkbox items (e.g., "12/16 → 15/16 items passing").
Behavior rules:
- If no meaningful ambiguities found (or all potential questions would be low-impact), respond: "No critical ambiguities detected worth formal clarification." and suggest proceeding.
- If spec file missing, instruct user to run `/speckit.specify` first (do not create a new spec here).
- Never exceed 5 total asked questions (clarification retries for a single question do not count as new questions).
- Avoid speculative tech stack questions unless the absence blocks functional clarity.
- Respect user early termination signals ("stop", "done", "proceed").
- If no questions asked due to full coverage, output a compact coverage summary (all categories Clear) then suggest advancing.
- If quota reached with unresolved high-impact categories remaining, explicitly flag them under Deferred with rationale.
Context for prioritization: $ARGUMENTS
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_clarify`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_clarify` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Report completion (after questioning loop ends or early termination):
- Number of questions asked & answered.
- Path to updated spec.
- Sections touched (list names).
- Spec quality checklist status (if `FEATURE_DIR/checklists/requirements.md` was re-validated): show before/after pass counts (e.g., "Spec Quality Checklist: 12/16 → 15/16 items passing") and list any items that changed state — both newly checked (unchecked → checked) and any regressions (checked → unchecked). If any items remain unchecked, list them as areas needing attention.
- Coverage summary table listing each taxonomy category with Status: Resolved (was Partial/Missing and addressed), Deferred (exceeds question quota, or remaining item is specifically implementation method, tech-stack comparison, or task breakdown), Clear (already sufficient), Outstanding (still Partial/Missing but low impact).
- If any Outstanding or Deferred remain, recommend whether to proceed to `/speckit.plan` or run `/speckit.clarify` again later post-plan.
- Suggested next command.
## Done When
- [ ] Spec ambiguities identified and clarifications integrated into spec file
- [ ] Spec quality checklist re-validated against updated spec (if `FEATURE_DIR/checklists/requirements.md` exists)
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with questions answered, sections touched, checklist status, and coverage summary
+175
View File
@@ -0,0 +1,175 @@
---
description: Create or update the project constitution from interactive or provided principle inputs.
handoffs:
- label: Build Specification
agent: speckit.specify
prompt: Implement the feature specification based on the updated constitution. I want to build...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Scope Guard
This command's own work is limited to updating the project constitution itself. Dependent templates
and commands read the constitution at runtime and are not modified here.
- Classify every part of the user input as either constitution content or a separate,
non-governance intent.
- If the input includes feature implementation, code generation, refactoring, building, or
deployment requests, you **MUST NOT** execute them. Extract them as deferred intents instead.
- You **MUST NOT** create, modify, or delete application source files, feature routes,
components, tests, deployment files, or other artifacts unrelated to the constitution
workflow.
- If it is unclear whether an instruction is constitution content, ask for clarification before
making changes.
- After completing the constitution update, include a `Next Actions` section for each deferred
intent. List the original intent and suggest the appropriate follow-up Spec Kit command, such
as `/speckit.specify`, without invoking it.
- If there are no non-governance intents, omit the `Next Actions` section.
## Pre-Execution Checks
**Check for extension hooks (before constitution update)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_constitution` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
You are updating the project constitution at `.specify/memory/constitution.md`. The active
constitution scaffold is resolved at command time from `constitution-template` through the Spec Kit
preset/template resolution stack.
Follow this execution flow:
1. Run `.specify/scripts/bash/resolve-template.sh constitution-template --json` from the repository root and parse `TEMPLATE_CONTENT` as the active template.
- The shared resolver applies project overrides, composing preset layers, and extension layers
before the core template fallback. It MUST succeed before continuing.
- If it fails, stop and report the resolution error; do not continue with only one contributing
template layer.
- If `.specify/memory/constitution.md` exists, load it as the source of current project-specific
values and amendments. Preserve information that is still applicable when applying the newly
resolved scaffold.
- If it does not exist, use the resolved template as the initial document.
- Do not write back to any versioned template layer.
- Identify every placeholder token of the form `[ALL_CAPS_IDENTIFIER]`.
**IMPORTANT**: The user might require less or more principles than the ones used in the template. If a number is specified, respect that - follow the general template. You will update the doc accordingly.
2. Collect/derive values for placeholders:
- If user input (conversation) supplies a value, use it.
- Otherwise infer from existing repo context (README, docs, prior constitution versions if embedded).
- For governance dates: `RATIFICATION_DATE` is the original adoption date (if unknown ask or mark TODO), `LAST_AMENDED_DATE` is today if changes are made, otherwise keep previous.
- `CONSTITUTION_VERSION` must increment according to semantic versioning rules:
- MAJOR: Backward incompatible governance/principle removals or redefinitions.
- MINOR: New principle/section added or materially expanded guidance.
- PATCH: Clarifications, wording, typo fixes, non-semantic refinements.
- If version bump type ambiguous, propose reasoning before finalizing.
3. Draft the updated constitution content using the resolved template as the required structure:
- Replace every placeholder with concrete text (no bracketed tokens left except intentionally retained template slots that the project has chosen not to define yet—explicitly justify any left).
- Preserve heading hierarchy and comments can be removed once replaced unless they still add clarifying guidance.
- Ensure each Principle section: succinct name line, paragraph (or bullet list) capturing non‑negotiable rules, explicit rationale if not obvious.
- Ensure Governance section lists amendment procedure, versioning policy, and compliance review expectations.
4. Produce a Sync Impact Report as an HTML comment at the top of the constitution file after update.
This report is temporary scratch material for human review of the amendment, not governance
content; it is expected to be removed before the amended constitution file is committed.
- Version change: old → new
- List of modified principles (old title → new title if renamed)
- Added sections
- Removed sections
- Follow-up TODOs if any placeholders intentionally deferred.
5. Validation before final output:
- No remaining unexplained bracket tokens.
- Version line matches report.
- Dates ISO format YYYY-MM-DD.
- Principles are declarative, testable, and free of vague language ("should" → replace with MUST/SHOULD rationale where appropriate).
6. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite).
7. Output a final summary to the user with:
- New version and bump rationale.
- Any TODO placeholders or deferred items requiring manual follow-up.
- Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`).
- A `Next Actions` section for any deferred non-governance intents.
Formatting & Style Requirements:
- Use Markdown headings exactly as in the template (do not demote/promote levels).
- Wrap long rationale lines to keep readability (<100 chars ideally) but do not hard enforce with awkward breaks.
- Keep a single blank line between sections.
- Avoid trailing whitespace.
If the user supplies partial updates (e.g., only one principle revision), still perform validation and version decision steps.
If critical info missing (e.g., ratification date truly unknown), insert `TODO(<FIELD_NAME>): explanation` and include in the Sync Impact Report under deferred items.
Write only `.specify/memory/constitution.md`; do not create or modify template source files.
## Post-Execution Checks
**Check for extension hooks (after constitution update)**:
Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_constitution` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
+275
View File
@@ -0,0 +1,275 @@
---
description: Assess the current codebase against the feature's spec, plan, and tasks, then append any remaining unbuilt work as new tasks to tasks.md so implement can complete it.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before convergence)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_converge` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```text
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```text
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Goal.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Goal
Close the gap between what a feature's specification, plan, and tasks call for and what the
codebase currently implements. Read `spec.md`, `plan.md`, and `tasks.md` as the **sole
source of intent** (with the constitution as governing constraints), assess the current
state of the code, determine which requirements, acceptance criteria, plan decisions, and
existing tasks are unmet, incomplete, or only partially satisfied, and **append each piece
of remaining work as a new, traceable task** at the bottom of `tasks.md` so that
`/speckit.implement` can complete it. This command MUST run only after
`/speckit.implement` has run on the current `tasks.md`, and after `/speckit.tasks` has produced a complete `tasks.md`.
This is **not** a diff tool and does **not** track changes. It assesses the present state
of the code relative to the feature's artifacts — no git, no branch comparison, no history.
## Operating Constraints
**APPEND-ONLY, NEVER REWRITE**: The command's **only** write is appending a new
`## Phase N: Convergence` section to `tasks.md`. It MUST NOT:
- modify `spec.md` or `plan.md` in any way;
- rewrite, renumber, reorder, or delete any existing task (including tasks from a prior
Convergence phase);
- modify, create, or delete any application code — completing the appended tasks is the
job of `/speckit.implement`.
When the codebase already satisfies everything, the command MUST leave `tasks.md`
**byte-for-byte unchanged** (no empty Convergence header) and report a clean result.
**Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is
**non-negotiable**. Code that violates a MUST principle is the highest-severity finding and
produces a corresponding remediation task. If the constitution is an unfilled template,
skip constitution checks gracefully rather than failing.
## Execution Steps
### 1. Initialize Convergence Context
Run `.specify/scripts/bash/check-prerequisites.sh --json --require-spec --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths:
- SPEC = FEATURE_DIR/spec.md
- PLAN = FEATURE_DIR/plan.md
- TASKS = FEATURE_DIR/tasks.md
- CONSTITUTION = `.specify/memory/constitution.md` (if present)
If `spec.md`, `plan.md`, or `tasks.md` is missing, STOP with a clear, actionable message naming the
prerequisite command to run (`/speckit.specify` for a missing spec, `/speckit.plan` for a missing plan,
`/speckit.tasks` for missing tasks). Do not produce partial output.
For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
### 2. Load Artifacts (Progressive Disclosure)
Load only the minimal necessary context from each artifact:
**From spec.md:**
- Functional Requirements (FR-###)
- Success Criteria (SC-###) — include only items requiring buildable work; exclude
post-launch outcome metrics and business KPIs
- User Stories and their Acceptance Scenarios
- Edge Cases (if present)
**From plan.md:**
- Architecture/stack choices and technical decisions
- Data Model references
- Phases and named touch-points (files/components the plan says will be created or edited)
- Technical constraints
**From tasks.md:**
- Task IDs (to compute the next ID and next phase number)
- Descriptions, phase grouping, and referenced file paths
**From constitution (if not an unfilled template):**
- Principle names and MUST/SHOULD normative statements
### 3. Build the Intent Inventory
Create an internal model (do not echo raw artifacts):
- **Requirements inventory**: one stable key per FR-### / SC-### / user-story acceptance
scenario (e.g. `US1/AC2`), plus the plan decisions and constitution principles that
impose buildable obligations.
- **Code-scope map**: from the file paths named in `plan.md` and `tasks.md`, plus a keyword
search for the concepts each requirement describes, derive the set of source files and
components in scope for assessment. Bound the assessment to these — do **not** infer
scope beyond what the artifacts define.
### 4. Assess the Codebase and Classify Findings
Include every existing task in the intent inventory, regardless of checkbox state or
Convergence phase: completion claims are not evidence. Verify current behavior against
the spec, plan, tasks, and constitution; for corrective task chains, assess the resulting
behavior, not superseded implementation details. Check both unmet obligations and
implementation that contradicts, exceeds, or falls outside the stated intent.
For each item in the intent inventory, inspect the current code in scope and produce a
`Finding` only where there is a gap. Classify every finding by **gap type**:
- **`missing`**: the required work is absent from the code entirely.
- **`partial`**: the work exists but does not yet fully satisfy the requirement /
acceptance criterion / plan decision.
- **`contradicts`**: the code does something that conflicts with stated intent or a
constitution MUST principle.
- **`unrequested`**: the code contains work not called for by the spec, plan, or tasks
(surfaced for awareness — converge does **not** delete code, it only appends a task to
review/justify or remove it).
Each `Finding` records: a stable id, the `source-ref` it traces to, the `gap-type`, a
severity, and a short human-readable description with the evidence (the file/area observed).
**Edge cases:**
- **Little or no code yet**: treat the entire specified scope as `missing` remaining work
rather than failing.
- **Nothing remains**: produce zero findings and follow the converged branch in Step 7.
### 5. Assign Severity
- **CRITICAL**: violates a constitution MUST principle, or a `missing`/`contradicts` gap
that blocks baseline functionality of a P1 user story.
- **HIGH**: a `missing` or `partial` gap on a core functional requirement or acceptance
criterion.
- **MEDIUM**: a `partial` gap on a secondary requirement, or an `unrequested` addition with
unclear justification.
- **LOW**: minor partial gaps, polish, or low-risk `unrequested` additions.
### 6. Present the In-Session Findings Summary
Before appending anything, output a compact, severity-graded summary (no file writes yet):
## Convergence Findings
| ID | Gap Type | Severity | Source | Evidence | Remaining Work |
|----|----------|----------|--------|----------|----------------|
| F1 | missing | HIGH | FR-008 | Example: no append-only guard detected in path/to/module.py when writing tasks.md | Add append-only enforcement |
**Summary metrics:**
- Requirements / acceptance criteria checked
- Plan decisions checked
- Constitution principles checked (or "skipped — template")
- Findings by gap type (missing / partial / contradicts / unrequested)
- Findings by severity
### 7. Append Convergence Tasks (or report converged)
**If there are one or more actionable findings** (`tasks_appended` outcome):
Append to the **end** of `tasks.md`, per the append contract:
1. Scan all existing task IDs; let `M` be the maximum. Determine the next phase number `N`
(highest existing phase + 1).
2. Write a single new section header `## Phase N: Convergence`.
3. Emit one checklist item per actionable finding, ordered CRITICAL/HIGH first, assigning
zero-padded IDs `T{M+1:03d}, T{M+2:03d}, …`:
```markdown
- [ ] T042 <imperative description> per <source-ref> (<gap-type>)
```
`<source-ref>` traces the task to its origin: e.g. `FR-003`, `SC-002`,
`US1/AC2`, `plan: storage decision`, `Constitution II`.
`<gap-type>` is one of `missing`, `partial`, `contradicts`, `unrequested`.
Constitution-violation tasks MUST be emitted first and described as
`CRITICAL`.
4. Never reuse or renumber existing IDs. If a prior Convergence phase exists, add a new,
separately-numbered one below it — do not touch the old one.
**If there are no actionable findings** (`converged` outcome):
- Do **not** modify `tasks.md` at all — no empty phase header.
- Report: **"✅ Converged — the implementation satisfies the spec, plan, and tasks."**
- Include the summary counts of what was checked.
### 8. Provide Next Actions (Handoff)
- On `tasks_appended`: state how many tasks were appended under which phase, and recommend
running `/speckit.implement` to complete them; note that a follow-up converge
run will find fewer or no remaining items.
- On `converged`: recommend proceeding to review / opening a PR. No further implement pass
is needed for this feature's specified scope.
### 9. Check for extension hooks
After producing the result, check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_converge` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- Report the convergence outcome (`converged` or `tasks_appended`) in-session before listing
any hooks, so users can decide whether to run optional follow-up commands.
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```text
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```text
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
+218
View File
@@ -0,0 +1,218 @@
---
description: Execute the implementation plan by processing and executing all tasks defined in tasks.md
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before implementation)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_implement` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Check checklists status** (if FEATURE_DIR/checklists/ exists):
- Treat checklist markers as a read-only gate: scan checkbox state, report status, and ask before proceeding when needed; do NOT modify checklist files or markers
- `checklists/requirements.md` is the built-in spec-quality checklist maintained by `/speckit.specify` and `/speckit.clarify`; custom checklists generated by `/speckit.checklist` are reviewer-owned requirements-quality review artifacts
- For custom checklists, `[x]` means the reviewer determined the requirements-quality criterion is satisfied; it does NOT mean implementation work is complete
- Scan all checklist files in the checklists/ directory
- For each checklist, count:
- Total items: All lines matching `- [ ]` or `- [X]` or `- [x]`
- Checked items: Lines matching `- [X]` or `- [x]`
- Unchecked items: Lines matching `- [ ]`
- Create a status table:
```text
| Checklist | Total | Checked | Unchecked | Status |
|-----------|-------|---------|-----------|--------|
| ux.md | 12 | 12 | 0 | ✓ PASS |
| test.md | 8 | 5 | 3 | ✗ FAIL |
| security.md | 6 | 6 | 0 | ✓ PASS |
```
- Calculate overall status:
- **PASS**: All checklists have 0 unchecked items
- **FAIL**: One or more checklists have unchecked items
- **If any checklist has unchecked items**:
- Display the table with unchecked item counts
- **STOP** and ask: "Some checklists have unchecked items. Do you want to proceed with implementation anyway? (yes/no)"
- Wait for user response before continuing
- If user says "no" or "wait" or "stop", halt execution
- If user says "yes" or "proceed" or "continue", proceed to step 3
- **If all checklists are checked**:
- Display the table showing all checklists passed
- Automatically proceed to step 3
3. Load and analyze the implementation context:
- **REQUIRED**: Read tasks.md for the complete task list and execution plan
- **REQUIRED**: Read plan.md for tech stack, architecture, and file structure
- **IF EXISTS**: Read data-model.md for entities and relationships
- **IF EXISTS**: Read contracts/ for API specifications and test requirements
- **IF EXISTS**: Read research.md for technical decisions and constraints
- **IF EXISTS**: Read .specify/memory/constitution.md for governance constraints
- **IF EXISTS**: Read quickstart.md for integration scenarios
4. **Project Setup Verification**:
- **REQUIRED**: Create/verify ignore files based on actual project setup:
**Detection & Creation Logic**:
- Check if the following command succeeds to determine if the repository is a git repo (create/verify .gitignore if so):
```sh
git rev-parse --git-dir 2>/dev/null
```
- Check if Dockerfile* exists or Docker in plan.md → create/verify .dockerignore
- Check if .eslintrc* exists → create/verify .eslintignore
- Check if eslint.config.* exists → ensure the config's `ignores` entries cover required patterns
- Check if .prettierrc* exists → create/verify .prettierignore
- Check if .npmrc or package.json exists → create/verify .npmignore (if publishing)
- Check if terraform files (*.tf) exist → create/verify .terraformignore
- Check if .helmignore needed (helm charts present) → create/verify .helmignore
**If ignore file already exists**: Verify it contains essential patterns, append missing critical patterns only
**If ignore file missing**: Create with full pattern set for detected technology
**Common Patterns by Technology** (from plan.md tech stack):
- **Node.js/JavaScript/TypeScript**: `node_modules/`, `dist/`, `build/`, `*.log`, `.env*`
- **Python**: `__pycache__/`, `*.pyc`, `.venv/`, `venv/`, `dist/`, `*.egg-info/`
- **Java**: `target/`, `*.class`, `*.jar`, `.gradle/`, `build/`
- **C#/.NET**: `bin/`, `obj/`, `*.user`, `*.suo`, `packages/`
- **Go**: `*.exe`, `*.test`, `vendor/`, `*.out`
- **Ruby**: `.bundle/`, `log/`, `tmp/`, `*.gem`, `vendor/bundle/`
- **PHP**: `vendor/`, `*.log`, `*.cache`, `*.env`
- **Rust**: `target/`, `debug/`, `release/`, `*.rs.bk`, `*.rlib`, `*.prof*`, `.idea/`, `*.log`, `.env*`
- **Kotlin**: `build/`, `out/`, `.gradle/`, `.idea/`, `*.class`, `*.jar`, `*.iml`, `*.log`, `.env*`
- **C++**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.so`, `*.a`, `*.exe`, `*.dll`, `.idea/`, `*.log`, `.env*`
- **C**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.a`, `*.so`, `*.exe`, `*.dll`, `autom4te.cache/`, `config.status`, `config.log`, `.idea/`, `*.log`, `.env*`
- **Swift**: `.build/`, `DerivedData/`, `*.swiftpm/`, `Packages/`
- **R**: `.Rproj.user/`, `.Rhistory`, `.RData`, `.Ruserdata`, `*.Rproj`, `packrat/`, `renv/`
- **Universal**: `.DS_Store`, `Thumbs.db`, `*.tmp`, `*.swp`, `.vscode/`, `.idea/`
**Tool-Specific Patterns**:
- **Docker**: `node_modules/`, `.git/`, `Dockerfile*`, `.dockerignore`, `*.log*`, `.env*`, `coverage/`
- **ESLint**: `node_modules/`, `dist/`, `build/`, `coverage/`, `*.min.js`
- **Prettier**: `node_modules/`, `dist/`, `build/`, `coverage/`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
- **Terraform**: `.terraform/`, `*.tfstate*`, `*.tfvars`, `.terraform.lock.hcl`
- **Kubernetes/k8s**: `*.secret.yaml`, `secrets/`, `.kube/`, `kubeconfig*`, `*.key`, `*.crt`
5. Parse tasks.md structure and extract:
- **Task phases**: Setup, Tests, Core, Integration, Polish
- **Task dependencies**: Sequential vs parallel execution rules
- **Task details**: ID, description, file paths, parallel markers [P]
- **Execution flow**: Order and dependency requirements
6. Execute implementation following the task plan:
- **Phase-by-phase execution**: Complete each phase before moving to the next
- **Respect dependencies**: Run sequential tasks in order, parallel tasks [P] can run together
- **Follow TDD approach**: Execute test tasks before their corresponding implementation tasks
- **File-based coordination**: Tasks affecting the same files must run sequentially
- **Validation checkpoints**: Verify each phase completion before proceeding
7. Implementation execution rules:
- **Setup first**: Initialize project structure, dependencies, configuration
- **Tests before code**: If you need to write tests for contracts, entities, and integration scenarios
- **Core development**: Implement models, services, CLI commands, endpoints
- **Integration work**: Database connections, middleware, logging, external services
- **Polish and validation**: Unit tests, performance optimization, documentation
8. Progress tracking and error handling:
- Report progress after each completed task
- Halt execution if any non-parallel task fails
- For parallel tasks [P], continue with successful tasks, report failed ones
- Provide clear error messages with context for debugging
- Suggest next steps if implementation cannot proceed
- **IMPORTANT** For completed tasks, make sure to mark the task off as [X] in the tasks file.
9. Completion validation:
- Verify all required tasks are completed
- Check that implemented features match the original specification
- Validate that tests pass and coverage meets requirements
- Confirm the implementation follows the technical plan
Note: This command assumes a complete task breakdown exists in tasks.md. If tasks are incomplete or missing, suggest running `/speckit.tasks` first to regenerate the task list.
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_implement`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_implement` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Report final status with summary of completed work.
## Done When
- [ ] All tasks in tasks.md completed and marked `[X]`
- [ ] Implementation validated against specification, plan, and test coverage
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with summary of completed work
+166
View File
@@ -0,0 +1,166 @@
---
description: Execute the implementation planning workflow using the plan template to generate design artifacts.
handoffs:
- label: Create Tasks
agent: speckit.tasks
prompt: Break the plan into tasks
send: true
- label: Create Checklist
agent: speckit.checklist
prompt: Create a checklist for the following domain...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before planning)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_plan` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
1. **Setup**: Run `.specify/scripts/bash/setup-plan.sh --json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, FEATURE_DIR, BRANCH. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Load context**: Read FEATURE_SPEC and `.specify/memory/constitution.md`. Load IMPL_PLAN template (already copied).
3. **Execute plan workflow**: Follow the structure in IMPL_PLAN template to:
- Fill Technical Context (mark unknowns as "NEEDS CLARIFICATION")
- Fill Constitution Check section from constitution
- Evaluate gates (ERROR if violations unjustified)
- Phase 0: Generate research.md (resolve all NEEDS CLARIFICATION)
- Phase 1: Generate data-model.md, contracts/, quickstart.md
- Re-evaluate Constitution Check post-design
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_plan`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_plan` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Command ends after Phase 1 design. Report branch, IMPL_PLAN path, and generated artifacts.
## Phases
### Phase 0: Outline & Research
1. **Extract unknowns from Technical Context** above:
- For each NEEDS CLARIFICATION → research task
- For each dependency → best practices task
- For each integration → patterns task
2. **Generate and dispatch research agents**:
```text
For each unknown in Technical Context:
Task: "Research {unknown} for {feature context}"
For each technology choice:
Task: "Find best practices for {tech} in {domain}"
```
3. **Consolidate findings** in `research.md` using format:
- Decision: [what was chosen]
- Rationale: [why chosen]
- Alternatives considered: [what else evaluated]
**Output**: research.md with all NEEDS CLARIFICATION resolved
### Phase 1: Design & Contracts
**Prerequisites:** `research.md` complete
1. **Extract entities from feature spec** → `data-model.md`:
- Entity name, fields, relationships
- Validation rules from requirements
- State transitions if applicable
2. **Define interface contracts** (if project has external interfaces) → `/contracts/`:
- Identify what interfaces the project exposes to users or other systems
- Document the contract format appropriate for the project type
- Examples: public APIs for libraries, command schemas for CLI tools, endpoints for web services, grammars for parsers, UI contracts for applications
- Skip if project is purely internal (build scripts, one-off tools, etc.)
3. **Create quickstart validation guide** → `quickstart.md`:
- Document runnable validation scenarios that prove the feature works end-to-end
- Include prerequisites, setup commands, test/run commands, and expected outcomes
- Use links or references to contracts and data model details instead of duplicating them
- Do not include full implementation code, model/service/controller bodies, migrations, or complete test suites
- Keep this artifact as a validation/run guide; implementation details belong in `tasks.md` and the implementation phase
**Output**: data-model.md, /contracts/*, quickstart.md
## Key rules
- Use absolute paths for filesystem operations; use project-relative paths for references in documentation
- ERROR on gate failures or unresolved clarifications
## Done When
- [ ] Plan workflow executed and design artifacts generated
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with branch, plan path, and generated artifacts
+345
View File
@@ -0,0 +1,345 @@
---
description: Create or update the feature specification from a natural language feature description.
handoffs:
- label: Build Technical Plan
agent: speckit.plan
prompt: Create a plan for the spec. I am building with...
- label: Clarify Spec Requirements
agent: speckit.clarify
prompt: Clarify specification requirements
send: true
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before specification)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_specify` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
The text the user typed after `/speckit.specify` in the triggering message **is** the feature description. Assume you always have it available in this conversation even if `$ARGUMENTS` appears literally below. Do not ask the user to repeat it unless they provided an empty command.
Given that feature description, do this:
1. **Generate a concise short name** (2-4 words) for the feature:
- Analyze the feature description and extract the most meaningful keywords
- Create a 2-4 word short name that captures the essence of the feature
- Use action-noun format when possible (e.g., "add-user-auth", "fix-payment-bug")
- Preserve technical terms and acronyms (OAuth2, API, JWT, etc.)
- Keep it concise but descriptive enough to understand the feature at a glance
- Examples:
- "I want to add user authentication" → "user-auth"
- "Implement OAuth2 integration for the API" → "oauth2-api-integration"
- "Create a dashboard for analytics" → "analytics-dashboard"
- "Fix payment processing timeout bug" → "fix-payment-timeout"
2. **Branch creation** (optional, via hook):
If a `before_specify` hook ran successfully in the Pre-Execution Checks above, it will have created/switched to a git branch and output JSON containing `BRANCH_NAME` and `FEATURE_NUM`. Note these values for reference, but the branch name does **not** dictate the spec directory name.
If the user explicitly provided `GIT_BRANCH_NAME`, pass it through to the hook so the branch script uses the exact value as the branch name (bypassing all prefix/suffix generation).
3. **Create the spec feature directory**:
Specs live under the default `specs/` directory unless the user explicitly provides `SPECIFY_FEATURE_DIRECTORY`.
**Resolution order for `SPECIFY_FEATURE_DIRECTORY`**:
1. If the user explicitly provided `SPECIFY_FEATURE_DIRECTORY` (e.g., via environment variable, argument, or configuration), use it as-is
2. Otherwise, auto-generate it under `specs/`:
- Check `.specify/init-options.json` for `feature_numbering` (preferred) or `branch_numbering` (deprecated, migration only — will be removed in a future release)
- If `"timestamp"`: prefix is `YYYYMMDD-HHMMSS` (current timestamp)
- If `"sequential"` or absent: prefix is `NNN` (next available 3-digit number after scanning existing directories in `specs/`)
- Construct the directory name: `<prefix>-<short-name>` (e.g., `003-user-auth` or `20260319-143022-user-auth`)
- Set `SPECIFY_FEATURE_DIRECTORY` to `specs/<directory-name>`
- If `branch_numbering` was used (and `feature_numbering` was absent), emit a one-line warning: "⚠️ `branch_numbering` in init-options.json is deprecated. Rename to `feature_numbering`."
**Create the directory and spec file**:
- `mkdir -p SPECIFY_FEATURE_DIRECTORY`
- Resolve the active `spec-template` through the Spec Kit preset/template resolution stack (equivalent to `specify preset resolve spec-template`)
- Copy the resolved `spec-template` file to `SPECIFY_FEATURE_DIRECTORY/spec.md` as the starting point
- Set `SPEC_FILE` to `SPECIFY_FEATURE_DIRECTORY/spec.md`
- Persist the resolved path to `.specify/feature.json`:
```json
{
"feature_directory": "<resolved feature dir>"
}
```
Write the actual resolved directory path value (for example, `specs/003-user-auth`), not the literal string `SPECIFY_FEATURE_DIRECTORY`.
This allows downstream commands (`/speckit.plan`, `/speckit.tasks`, etc.) to locate the feature directory without relying on git branch name conventions.
**IMPORTANT**:
- You must only create one feature per `/speckit.specify` invocation
- The spec directory name and the git branch name are independent — they may be the same but that is the user's choice
- The spec directory and file are always created by this command, never by the hook
4. Load the resolved active `spec-template` file to understand required sections.
5. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints.
6. Follow this execution flow:
1. Parse user description from arguments
If empty: ERROR "No feature description provided"
2. Extract key concepts from description
Identify: actors, actions, data, constraints
3. For unclear aspects:
- Make informed guesses based on context and industry standards
- Only mark with [NEEDS CLARIFICATION: specific question] if:
- The choice significantly impacts feature scope or user experience
- Multiple reasonable interpretations exist with different implications
- No reasonable default exists
- **LIMIT: Maximum 3 [NEEDS CLARIFICATION] markers total**
- Prioritize clarifications by impact: scope > security/privacy > user experience > technical details
4. Fill User Scenarios & Testing section
If no clear user flow: ERROR "Cannot determine user scenarios"
5. Generate Functional Requirements
Each requirement must be testable
Use reasonable defaults for unspecified details (document assumptions in Assumptions section)
6. Define Success Criteria
Create measurable, technology-agnostic outcomes
Include both quantitative metrics (time, performance, volume) and qualitative measures (user satisfaction, task completion)
Each criterion must be verifiable without implementation details
7. Identify Key Entities (if data involved)
8. Return: SUCCESS (spec ready for planning)
7. Write the specification to SPEC_FILE using the template structure, replacing placeholders with concrete details derived from the feature description (arguments) while preserving section order and headings.
8. **Specification Quality Validation**: After writing the initial spec, validate it against quality criteria:
a. **Create Spec Quality Checklist**: Generate a checklist file at `SPECIFY_FEATURE_DIRECTORY/checklists/requirements.md` using the checklist template structure with these validation items:
```markdown
# Specification Quality Checklist: [FEATURE NAME]
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: [DATE]
**Feature**: [Link to spec.md]
## Content Quality
- [ ] No implementation details (languages, frameworks, APIs)
- [ ] Focused on user value and business needs
- [ ] Written for non-technical stakeholders
- [ ] All mandatory sections completed
## Requirement Completeness
- [ ] No [NEEDS CLARIFICATION] markers remain
- [ ] Requirements are testable and unambiguous
- [ ] Success criteria are measurable
- [ ] Success criteria are technology-agnostic (no implementation details)
- [ ] All acceptance scenarios are defined
- [ ] Edge cases are identified
- [ ] Scope is clearly bounded
- [ ] Dependencies and assumptions identified
## Feature Readiness
- [ ] All functional requirements have clear acceptance criteria
- [ ] User scenarios cover primary flows
- [ ] Feature meets measurable outcomes defined in Success Criteria
- [ ] No implementation details leak into specification
## Notes
- Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan`
```
b. **Run Validation Check**: Review the spec against each checklist item:
- For each item, determine if it passes or fails
- Document specific issues found (quote relevant spec sections)
c. **Handle Validation Results**:
- **If all items pass**: Mark checklist complete and proceed to the Mandatory Post-Execution Hooks section
- **If items fail (excluding [NEEDS CLARIFICATION])**:
1. List the failing items and specific issues
2. Update the spec to address each issue
3. Re-run validation until all items pass (max 3 iterations)
4. If still failing after 3 iterations, document remaining issues in checklist notes and warn user
- **If [NEEDS CLARIFICATION] markers remain**:
1. Extract all [NEEDS CLARIFICATION: ...] markers from the spec
2. **LIMIT CHECK**: If more than 3 markers exist, keep only the 3 most critical (by scope/security/UX impact) and make informed guesses for the rest
3. For each clarification needed (max 3), present options to user in this format:
```markdown
## Question [N]: [Topic]
**Context**: [Quote relevant spec section]
**What we need to know**: [Specific question from NEEDS CLARIFICATION marker]
**Suggested Answers**:
| Option | Answer | Implications |
|--------|--------|--------------|
| A | [First suggested answer] | [What this means for the feature] |
| B | [Second suggested answer] | [What this means for the feature] |
| C | [Third suggested answer] | [What this means for the feature] |
| Custom | Provide your own answer | [Explain how to provide custom input] |
**Your choice**: _[Wait for user response]_
```
4. **CRITICAL - Table Formatting**: Ensure markdown tables are properly formatted:
- Use consistent spacing with pipes aligned
- Each cell should have spaces around content: `| Content |` not `|Content|`
- Header separator must have at least 3 dashes: `|--------|`
- Test that the table renders correctly in markdown preview
5. Number questions sequentially (Q1, Q2, Q3 - max 3 total)
6. Present all questions together before waiting for responses
7. Wait for user to respond with their choices for all questions (e.g., "Q1: A, Q2: Custom - [details], Q3: B")
8. Update the spec by replacing each [NEEDS CLARIFICATION] marker with the user's selected or provided answer
9. Re-run validation after all clarifications are resolved
d. **Update Checklist**: After each validation iteration, update the checklist file with current pass/fail status
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_specify`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_specify` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Report completion to the user with:
- `SPECIFY_FEATURE_DIRECTORY` — the feature directory path
- `SPEC_FILE` — the spec file path
- Checklist results summary
- Readiness for the next phase (`/speckit.clarify` or `/speckit.plan`)
**NOTE:** Branch creation is handled by the `before_specify` hook (git extension). Spec directory and file creation are always handled by this core command.
## Quick Guidelines
- Focus on **WHAT** users need and **WHY**.
- Avoid HOW to implement (no tech stack, APIs, code structure).
- Written for business stakeholders, not developers.
- DO NOT create any checklists that are embedded in the spec. That will be a separate command.
### Section Requirements
- **Mandatory sections**: Must be completed for every feature
- **Optional sections**: Include only when relevant to the feature
- When a section doesn't apply, remove it entirely (don't leave as "N/A")
### For AI Generation
When creating this spec from a user prompt:
1. **Make informed guesses**: Use context, industry standards, and common patterns to fill gaps
2. **Document assumptions**: Record reasonable defaults in the Assumptions section
3. **Limit clarifications**: Maximum 3 [NEEDS CLARIFICATION] markers - use only for critical decisions that:
- Significantly impact feature scope or user experience
- Have multiple reasonable interpretations with different implications
- Lack any reasonable default
4. **Prioritize clarifications**: scope > security/privacy > user experience > technical details
5. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item
6. **Common areas needing clarification** (only if no reasonable default exists):
- Feature scope and boundaries (include/exclude specific use cases)
- User types and permissions (if multiple conflicting interpretations possible)
- Security/compliance requirements (when legally/financially significant)
**Examples of reasonable defaults** (don't ask about these):
- Data retention: Industry-standard practices for the domain
- Performance targets: Standard web/mobile app expectations unless specified
- Error handling: User-friendly messages with appropriate fallbacks
- Authentication method: Standard session-based or OAuth2 for web apps
- Integration patterns: Use project-appropriate patterns (REST/GraphQL for web services, function calls for libraries, CLI args for tools, etc.)
### Success Criteria Guidelines
Success criteria must be:
1. **Measurable**: Include specific metrics (time, percentage, count, rate)
2. **Technology-agnostic**: No mention of frameworks, languages, databases, or tools
3. **User-focused**: Describe outcomes from user/business perspective, not system internals
4. **Verifiable**: Can be tested/validated without knowing implementation details
**Good examples**:
- "Users can complete checkout in under 3 minutes"
- "System supports 10,000 concurrent users"
- "95% of searches return results in under 1 second"
- "Task completion rate improves by 40%"
**Bad examples** (implementation-focused):
- "API response time is under 200ms" (too technical, use "Users see results instantly")
- "Database can handle 1000 TPS" (implementation detail, use user-facing metric)
- "React components render efficiently" (framework-specific)
- "Redis cache hit rate above 80%" (technology-specific)
## Done When
- [ ] Specification written to `SPEC_FILE` and validated against quality checklist
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with feature directory, spec file path, and checklist results
+216
View File
@@ -0,0 +1,216 @@
---
description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts.
handoffs:
- label: Analyze For Consistency
agent: speckit.analyze
prompt: Run a project analysis for consistency
send: true
- label: Implement Project
agent: speckit.implement
prompt: Start the implementation in phases
send: true
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before tasks generation)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_tasks` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
1. **Setup**: Run `.specify/scripts/bash/setup-tasks.sh --json` from repo root and parse FEATURE_DIR, TASKS_TEMPLATE_CONTENT, TASKS_TEMPLATE, and AVAILABLE_DOCS list. `FEATURE_DIR` and `TASKS_TEMPLATE` must be absolute paths when provided. `AVAILABLE_DOCS` is a list of document names/relative paths available under `FEATURE_DIR` (for example `research.md` or `contracts/`). For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Load design documents**: Read from FEATURE_DIR:
- **Required**: plan.md (tech stack, libraries, structure), spec.md (user stories with priorities)
- **Optional**: data-model.md (entities), contracts/ (interface contracts), research.md (decisions), quickstart.md (test scenarios)
- **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints
- Note: Not all projects have all documents. Generate tasks based on what's available.
3. **Execute task generation workflow**:
- Load plan.md and extract tech stack, libraries, project structure
- Load spec.md and extract user stories with their priorities (P1, P2, P3, etc.)
- If data-model.md exists: Extract entities and map to user stories
- If contracts/ exists: Map interface contracts to user stories
- If research.md exists: Extract decisions for setup tasks
- Generate tasks organized by user story (see Task Generation Rules below)
- Generate dependency graph showing user story completion order
- Create parallel execution examples per user story
- Validate task completeness (each user story has all needed tasks, independently testable)
4. **Generate tasks.md**: Use TASKS_TEMPLATE_CONTENT (from the JSON output above) as the structure. For compatibility with older setup scripts that omit TASKS_TEMPLATE_CONTENT, read TASKS_TEMPLATE instead. Fill with:
- Correct feature name from plan.md
- Phase 1: Setup tasks (project initialization)
- Phase 2: Foundational tasks (blocking prerequisites for all user stories)
- Phase 3+: One phase per user story (in priority order from spec.md)
- Each phase includes: story goal, independent test criteria, tests (if requested), implementation tasks
- Final Phase: Polish & cross-cutting concerns
- All tasks must follow the strict checklist format (see Task Generation Rules below)
- Clear file paths for each task
- Dependencies section showing story completion order
- Parallel execution examples per story
- Implementation strategy section (MVP first, incremental delivery)
## Mandatory Post-Execution Hooks
**You MUST complete this section before reporting completion to the user.**
Check if `.specify/extensions.yml` exists in the project root.
- If it does not exist, or no hooks are registered under `hooks.after_tasks`, skip to the Completion Report.
- If it exists, read it and look for entries under the `hooks.after_tasks` key.
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue to the Completion Report.
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Mandatory hook** (`optional: false`) — **You MUST emit `EXECUTE_COMMAND:` for each mandatory hook**:
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
## Completion Report
Output path to generated tasks.md and summary:
- Total task count
- Task count per user story
- Parallel opportunities identified
- Independent test criteria for each story
- Suggested MVP scope (typically just User Story 1)
- Format validation: Confirm ALL tasks follow the checklist format (checkbox, ID, labels, file paths)
Context for task generation: $ARGUMENTS
The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without additional context.
## Task Generation Rules
**CRITICAL**: Tasks MUST be organized by user story to enable independent implementation and testing.
**Tests are OPTIONAL**: Only generate test tasks if explicitly requested in the feature specification or if user requests TDD approach.
### Checklist Format (REQUIRED)
Every task MUST strictly follow this format:
```text
- [ ] [TaskID] [P?] [Story?] Description with file path
```
**Format Components**:
1. **Checkbox**: ALWAYS start with `- [ ]` (markdown checkbox)
2. **Task ID**: Sequential number (T001, T002, T003...) in execution order
3. **[P] marker**: Include ONLY if task is parallelizable (different files, no dependencies on incomplete tasks)
4. **[Story] label**: REQUIRED for user story phase tasks only
- Format: [US1], [US2], [US3], etc. (maps to user stories from spec.md)
- Setup phase: NO story label
- Foundational phase: NO story label
- User Story phases: MUST have story label
- Polish phase: NO story label
5. **Description**: Clear action with exact file path
**Examples**:
- ✅ CORRECT: `- [ ] T001 Create project structure per implementation plan`
- ✅ CORRECT: `- [ ] T005 [P] Implement authentication middleware in src/middleware/auth.py`
- ✅ CORRECT: `- [ ] T012 [P] [US1] Create User model in src/models/user.py`
- ✅ CORRECT: `- [ ] T014 [US1] Implement UserService in src/services/user_service.py`
- ❌ WRONG: `- [ ] Create User model` (missing ID and Story label)
- ❌ WRONG: `T001 [US1] Create model` (missing checkbox)
- ❌ WRONG: `- [ ] [US1] Create User model` (missing Task ID)
- ❌ WRONG: `- [ ] T001 [US1] Create model` (missing file path)
### Task Organization
1. **From User Stories (spec.md)** - PRIMARY ORGANIZATION:
- Each user story (P1, P2, P3...) gets its own phase
- Map all related components to their story:
- Models needed for that story
- Services needed for that story
- Interfaces/UI needed for that story
- If tests requested: Tests specific to that story
- Mark story dependencies (most stories should be independent)
2. **From Contracts**:
- Map each interface contract → to the user story it serves
- If tests requested: Each interface contract → contract test task [P] before implementation in that story's phase
3. **From Data Model**:
- Map each entity to the user story(ies) that need it
- If entity serves multiple stories: Put in earliest story or Setup phase
- Relationships → service layer tasks in appropriate story phase
- For each field with constraints in data-model.md (max length, nullable/required, enum values, validation rules), quote the constraint verbatim in the task description so it is not left to implementation-time discretion
4. **From Setup/Infrastructure**:
- Shared infrastructure → Setup phase (Phase 1)
- Foundational/blocking tasks → Foundational phase (Phase 2)
- Story-specific setup → within that story's phase
### Phase Structure
- **Phase 1**: Setup (project initialization)
- **Phase 2**: Foundational (blocking prerequisites - MUST complete before user stories)
- **Phase 3+**: User Stories in priority order (P1, P2, P3...)
- Within each story: Tests (if requested) → Models → Services → Endpoints → Integration
- Each phase should be a complete, independently testable increment
- **Final Phase**: Polish & Cross-Cutting Concerns
## Done When
- [ ] tasks.md generated with all phases, task IDs, and file paths
- [ ] Extension hooks dispatched or skipped according to the rules in Mandatory Post-Execution Hooks above
- [ ] Completion reported to user with task count, story breakdown, and MVP scope
+110
View File
@@ -0,0 +1,110 @@
---
description: "Deprecated: Convert existing tasks into actionable, dependency-ordered GitHub issues for the feature based on available design artifacts."
tools: ['github/github-mcp-server/list_issues', 'github/github-mcp-server/issue_write']
---
## Deprecation Notice
You **MUST display the following concise warning first**, as the first step of this command and before the User Input and Pre-Execution Checks sections below:
> ⚠️ `/speckit.taskstoissues` is deprecated and will be removed in a future minor release. Use the bundled `github` extension instead: run `specify extension add github`, then invoke `/speckit.github.taskstoissues`.
Continue with the existing workflow unchanged. Do not install or enable the extension automatically, do not stop, and do not run the replacement command.
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Pre-Execution Checks
**Check for extension hooks (before tasks-to-issues conversion)**:
- Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.before_taskstoissues` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Pre-Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Pre-Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
Wait for the result of the hook command before proceeding to the Outline.
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
## Outline
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
1. **IF EXISTS**: Load `.specify/memory/constitution.md` for project principles and governance constraints.
1. From the executed script, extract the path to **tasks**.
1. Get the Git remote by running:
```bash
git config --get remote.origin.url
```
> [!CAUTION]
> ONLY PROCEED TO NEXT STEPS IF THE REMOTE IS A GITHUB URL
1. **Fetch existing issues for deduplication**: Before creating anything, build the set of task IDs you are about to process from `tasks.md` (each is a `T` followed by **at least** three digits, e.g. `T001` — `/speckit.converge` assigns new IDs with `T{M+1:03d}`, which is a floor rather than a cap, so once a file has more than 999 tasks the IDs are four digits or longer). Then use the GitHub MCP server's `list_issues` tool to look for issues that already cover those IDs. Do not pass a `state` value, since omitting it makes the tool return both open and closed issues. Request `perPage: 100` to keep the number of calls down, and since the tool uses cursor-based pagination, request pages with the `after` parameter (using the `endCursor` from the previous response). For each issue title, match it against the task ID pattern `\bT\d{3,}\b` (the `{3,}` accepts four-digit and longer IDs — with `\d{3}` a title containing `T1000` would not match at all, because the trailing `\b` cannot fall between two digits, so that task would be silently neither deduplicated nor created; word boundaries still stop a token like `ST001` from matching, and force the whole digit run to be consumed so `T100` can never match inside `T1000`; this also recognises titles written as `T001 ...`, `T001: ...` or `[T001] ...`) and, when it matches one of your task IDs, mark that ID as already having an issue. Stop paginating as soon as every task ID has been matched, or when there are no more pages, so you do not keep fetching the whole repository's issue history once all task IDs are accounted for. This bounds the number of calls on repos with large issue histories and still prevents duplicates when the command is re-run after `tasks.md` is regenerated or the skill is re-invoked.
1. For each task in the list, use the GitHub MCP server to create a new issue in the repository that is representative of the Git remote. Task lines in `tasks.md` start with a markdown checkbox, so first strip the leading `- [ ]` (and any `[P]` / `[US#]` markers) to recover the task ID and its description. Create the issue with a single canonical title of the form `T001: <description>`, with the ID written once followed by the task description (for example, the line `- [ ] T001 Create project structure` becomes the title `T001: Create project structure`).
- **Skip** any task whose ID is already present in the set of existing issues from the previous step, and report it (for example, `T001 already has an issue, skipping`).
- Only create issues for tasks that do not yet have a matching issue.
> [!CAUTION]
> UNDER NO CIRCUMSTANCES EVER CREATE ISSUES IN REPOSITORIES THAT DO NOT MATCH THE REMOTE URL
## Post-Execution Checks
**Check for extension hooks (after tasks-to-issues conversion)**:
Check if `.specify/extensions.yml` exists in the project root.
- If it exists, read it and look for entries under the `hooks.after_taskstoissues` key
- If the YAML cannot be parsed or is invalid, do not skip silently: tell the user that `.specify/extensions.yml` could not be read (include the parser error) and that no hooks were checked, including any mandatory (`optional: false`) hooks registered there, then continue normally
- Filter out hooks where `enabled` is explicitly `false`. Treat hooks without an `enabled` field as enabled by default.
- For each remaining hook, do **not** attempt to interpret or evaluate hook `condition` expressions:
- If the hook has no `condition` field, or it is null/empty, treat the hook as executable
- If the hook defines a non-empty `condition`, skip the hook and leave condition evaluation to the HookExecutor implementation
- For each executable hook, output the following based on its `optional` flag:
- **Optional hook** (`optional: true`):
```
## Extension Hooks
**Optional Hook**: {extension}
Command: `/{command}`
Description: {description}
Prompt: {prompt}
To execute: `/{command}`
```
- **Mandatory hook** (`optional: false`):
```
## Extension Hooks
**Automatic Hook**: {extension}
Executing: `/{command}`
EXECUTE_COMMAND: {command}
```
After emitting the block above you MUST actually invoke the hook and wait for it to finish before continuing. Run it the same way you would run the command yourself in this agent/session (the invocation may differ from the literal `{command}` id shown above, e.g. a skills-mode agent runs it as `/skill:speckit-...` or `$speckit-...`). Emitting the block alone does not run the hook.
- If no hooks are registered or `.specify/extensions.yml` does not exist, skip silently
+10
View File
@@ -0,0 +1,10 @@
# Convergence / review handoff
Atomic guarded algorithm accepted by independent follow-up reviewer (deleg_46675de9); first review correctly rejected unit-only evidence. Source service/test hashes stayed unchanged across reviews. No commit/push/deploy performed because frontend full gates unresolved.
Actual results: backend 92 suites / 798 tests passed (2 suites / 3 tests skipped); targeted blogs 5 suites / 105 tests passed. Backend, admin, storefront builds passed. Admin current and clean HEAD archive with same dependencies both 1 failed /50 passed files,309 passed tests (missing ApprovalsPage import). Storefront current bounded180s and clean archive bounded120s timeout124, no completion summary; exact root cause unresolved. Baseline extracted inside owned worktree, no other worktree altered.
Isolated PostgreSQL18.4 + actual Prisma5.22 passed four microsecond boundary roundtrips, true concurrent reads-before-transactions one-winner race, loser tag absence and real nested unique failure complete-row/relations rollback plus cache counts. Daemon stopped. db push targeted only fresh local concurrency_test (not shared DB, no migration file). Actual production read-only metadata: revision0e952ef70184040a27a6b53d7b59073502d25743; Prisma5.22; timestamp with time zone precision6; compiled controller Object body; global whitelist; no deployed expectedUpdatedAt support. Deployed PG16 exact-major integration parity and nonnull author rollback fixture remain unproven. Legacy token omission remains last-write-wins.
Spec consistency: all core guarded acceptance criteria represented; HTTP/Nest request-level execution is not added, actual deployed compiled metatype inspected. Existing whitelist any-body contract intentionally retained, service allowlist consumes token separately. Constitution scaffold finalized late, not claimed preapproved.
Parent should resolve/waive existing frontend gates under policy before any Stage push, retain exact artifact review, rerun on deployed PG16 if required, then coordinate Stage deployment and pilot. No archive/blog mutation occurred here.
+1
View File
@@ -0,0 +1 @@
Graphify query: BlogsService update expectedUpdatedAt Prisma relations concurrency, BFS depth2, 133 nodes (57 displayed). Source graph is inherited and stale (BlogsService.updateBlog graph L144 versus current L276). Verified affected edges: admin controller -> service -> Prisma, revalidation; service tag/category/author nested mutation; public frontend freshness. Query stamped graphify-out/cache/last_query_stamp only; exclude incidental stamp from delivered diff. API change is additive optional field, no UI or schema changes.
+9
View File
@@ -0,0 +1,9 @@
{
"ai": "generic",
"allow_symlinks": false,
"feature_numbering": "sequential",
"here": true,
"integration": "generic",
"script": "sh",
"speckit_version": "1.2.3"
}
+19
View File
@@ -0,0 +1,19 @@
{
"version": "1.2.3",
"integration_state_schema": 1,
"installed_integrations": [
"generic"
],
"integration_settings": {
"generic": {
"script": "sh",
"raw_options": "--commands-dir .specify/commands/",
"parsed_options": {
"commands_dir": ".specify/commands/"
},
"invoke_separator": "."
}
},
"integration": "generic",
"default_integration": "generic"
}
@@ -0,0 +1,17 @@
{
"integration": "generic",
"version": "1.2.3",
"installed_at": "2026-10-27T07:16:59.909007+00:00",
"files": {
".specify/commands/speckit.analyze.md": "91fe16257ededdea9cc21d3cb27d539fcdd12d93ddcea52332cd4b68176b6a8d",
".specify/commands/speckit.clarify.md": "dd11eb5b9759f7d3cd18c9d7f23a0ae2fe7973fc6ca2486dbfaf53a5569224b1",
".specify/commands/speckit.constitution.md": "9a7e9296f0878cdf4ed011b0de74cfb3656938680b64e43e808553fdfd054efc",
".specify/commands/speckit.implement.md": "e036ce63702db93e656e1c91ee6c02a8dc3d4a4f8624f8ba4adc69027fe68983",
".specify/commands/speckit.converge.md": "3cb55244c9dc5b9bf52ee3127ba177c52cabd5e5e5197e1312497b3eaeb8b9a4",
".specify/commands/speckit.plan.md": "3be8b011db9c6bb1cc77037f7d90756a6dbcbda1995cda2192818385732b27ff",
".specify/commands/speckit.checklist.md": "fa58b19e2604ce56ff5f5427061f6ee94fd44d7194e740b874824d9bf21ee15b",
".specify/commands/speckit.specify.md": "21634a45dfcf642fddb1645f4ad2980f98c89778442e47663df8a6c3a1eaf8bc",
".specify/commands/speckit.tasks.md": "6754ae39649c8e73a5ed376ad5cfcf04422e321a10e07c5ccd92fd1b9bccf776",
".specify/commands/speckit.taskstoissues.md": "6a23057adb077af03f6d7c99a8cc3fdfd699ad72975b7d5e1457659732955095"
}
}
@@ -0,0 +1,19 @@
{
"integration": "speckit",
"version": "1.2.3",
"installed_at": "2026-10-27T07:16:59.975057+00:00",
"files": {
".specify/scripts/bash/check-prerequisites.sh": "ac3d9bfd836c4e873bfb8fb5d898ba4c1d2f80d3488c2298148408a3830ac8d1",
".specify/scripts/bash/setup-plan.sh": "d378ec66ba20d2da01c71dad8935062c1c27f0bba890be9a6d3dda52ea056a4e",
".specify/scripts/bash/common.sh": "53cb1c23e349db4586c272436ce35c6e2f36a9c0b5351a85e0b216d9887a26b7",
".specify/scripts/bash/setup-tasks.sh": "cf6e99575a24b64ac01ffa3a50a40971ba95e3c1ec269b9a6dc3e35bbbb09191",
".specify/scripts/bash/resolve-template.sh": "829e227096abc8bf0889889ec9f792f503ca5d395b7836a8a7eb739ee75214e7",
".specify/scripts/bash/create-new-feature.sh": "972f03ed8ca5ee17b7baad6d56d821d46269d77abc337496beafb0fe85a725f2",
".specify/templates/plan-template.md": "5ef0e4c97b36e9f91372dc6eb8e5a7e515af8958cf1a9286e43a1ebd9bd48540",
".specify/templates/constitution-template.md": "ce7549540fa45543cca797a150201d868e64495fdff39dc38246fb17bd4024b3",
".specify/templates/tasks-template.md": "c731575d8099b3f871861186fbd1a592b51b2ba57fb99e1a0dab439ff6d5608f",
".specify/templates/checklist-template.md": "3f4124a13ffbc0c2d8e979d9a08248f29ce53cc6c324a8303a6ae0d231b78836",
".specify/templates/spec-template.md": "3945437fc35cd30a5b2bf7beea680337c3516826d3efa5a6b92c4a7eca1ba28e",
".specify/.gitignore": "0a61c5378b0bb2e0f85babff99c8b166f2170a2c12378cd17d929aa19296ec88"
}
}
@@ -0,0 +1,4 @@
{
"sha256": "ce7549540fa45543cca797a150201d868e64495fdff39dc38246fb17bd4024b3",
"source": "core"
}
+5
View File
@@ -0,0 +1,5 @@
# Canina concurrency prerequisite constitution
Preserve existing worktree edits. Graphify impact and written spec/plan/tasks precede source edits. TDD requires recorded RED then GREEN. Real DB concurrency and rollback evidence complements unit doubles; synthetic test fixtures only in isolated disposable databases, never production content. No production deployments, migrations or blog/media mutations in this task. Optional concurrency tokens preserve legacy UI behavior explicitly. Cache failure cannot fail already committed persistence. Independent exact-artifact review precedes any Stage push; failed full-suite gates are not green.
Version 1.0.0; scoped to this prerequisite. Scaffold initially existed as template; finalized after implementation rather than falsely backdating approval.
+5
View File
@@ -0,0 +1,5 @@
# Plan and clarified contract
Base develop 0e952ef70184040a27a6b53d7b59073502d25743 fetched via verified nested SSH proxy (origin is local bundle).
Graphify query before editing identified BlogsController -> BlogsService -> PrismaService and RevalidationService; graph source locations service update L144 and controller L29 are old, so inspect current source. Actual source has PUT admin/blogs/:id @Body any, not public UpdateBlogDto. Global whitelist is skipped for Object/any metatype, so service explicit scalar allowlist is authoritative; expectedUpdatedAt is consumed separately, never persisted. UI omission remains accepted.
Blog.updatedAt is @db.Timestamptz() (PostgreSQL default precision 6), @updatedAt. JS/JSON tokens have millisecond precision. CAS predicate uses [token,token+1ms), not exact equality to truncated DB value. Atomic claim via blog.updateMany inside interactive transaction, advancing updatedAt strictly beyond token millisecond; if count !=1 throw 409. Then nested blog.update (author/category/tags) in same transaction, retaining claimed timestamp. Relation failures roll back claim. No relation writes outside transaction. Revalidation occurs after transaction resolves only. Invalid tokens restricted to timezone-qualified ISO string with <=3 fractional digits and valid calendar round-trip; no coercive Date/null/number acceptance.
Deployed runtime version/column precision still need read-only release evidence; source evidence is not deployed proof. No writes to shared services during validation.
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env bash
# Consolidated prerequisite checking script
#
# This script provides unified prerequisite checking for Spec-Driven Development workflow.
# It replaces the functionality previously spread across multiple scripts.
#
# Usage: ./check-prerequisites.sh [OPTIONS]
#
# OPTIONS:
# --json Output in JSON format
# --require-spec Require spec.md to exist (for analysis phase)
# --require-tasks Require tasks.md to exist (for implementation phase)
# --include-tasks Include tasks.md in AVAILABLE_DOCS list
# --paths-only Only output path variables (no validation)
# --template NAME Include composed template content in JSON output
# --help, -h Show help message
#
# OUTPUTS:
# JSON mode: {"FEATURE_DIR":"...", "AVAILABLE_DOCS":["..."]}
# Text mode: FEATURE_DIR:... \n AVAILABLE_DOCS: \n ✓/✗ file.md
# Paths only: REPO_ROOT: ... \n BRANCH: ... \n FEATURE_DIR: ... etc.
set -e
# Parse command line arguments
JSON_MODE=false
REQUIRE_SPEC=false
REQUIRE_TASKS=false
INCLUDE_TASKS=false
PATHS_ONLY=false
TEMPLATE_NAME=""
while [[ $# -gt 0 ]]; do
case "$1" in
--json)
JSON_MODE=true
;;
--require-spec)
REQUIRE_SPEC=true
;;
--require-tasks)
REQUIRE_TASKS=true
;;
--include-tasks)
INCLUDE_TASKS=true
;;
--paths-only)
PATHS_ONLY=true
;;
--template)
shift
if [[ $# -eq 0 ]]; then
echo "ERROR: --template requires a template name" >&2
exit 1
fi
TEMPLATE_NAME="$1"
;;
--help|-h)
cat << 'EOF'
Usage: check-prerequisites.sh [OPTIONS]
Consolidated prerequisite checking for Spec-Driven Development workflow.
OPTIONS:
--json Output in JSON format
--require-spec Require spec.md to exist (for analysis phase)
--require-tasks Require tasks.md to exist (for implementation phase)
--include-tasks Include tasks.md in AVAILABLE_DOCS list
--paths-only Only output path variables (no prerequisite validation)
--template NAME Include composed template content in JSON output
--help, -h Show this help message
EXAMPLES:
# Check task prerequisites (plan.md required)
./check-prerequisites.sh --json
# Check implementation prerequisites (plan.md + tasks.md required)
./check-prerequisites.sh --json --require-tasks --include-tasks
# Get feature paths only (no validation)
./check-prerequisites.sh --paths-only
EOF
exit 0
;;
*)
echo "ERROR: Unknown option '$1'. Use --help for usage information." >&2
exit 1
;;
esac
shift
done
# Source common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get feature paths.
# In --paths-only mode this is pure resolution, so pass --no-persist to opt out
# of the feature.json write side effect (issue #3025).
if $PATHS_ONLY; then
_paths_output=$(get_feature_paths --no-persist) || { echo "ERROR: Failed to resolve feature paths" >&2; exit 1; }
else
_paths_output=$(get_feature_paths) || { echo "ERROR: Failed to resolve feature paths" >&2; exit 1; }
fi
eval "$_paths_output"
unset _paths_output
# If paths-only mode, output paths and exit (no validation)
if $PATHS_ONLY; then
if $JSON_MODE; then
# Minimal JSON paths payload (no validation performed)
if has_jq; then
jq -cn \
--arg repo_root "$REPO_ROOT" \
--arg branch "$CURRENT_BRANCH" \
--arg feature_dir "$FEATURE_DIR" \
--arg feature_spec "$FEATURE_SPEC" \
--arg impl_plan "$IMPL_PLAN" \
--arg tasks "$TASKS" \
'{REPO_ROOT:$repo_root,BRANCH:$branch,FEATURE_DIR:$feature_dir,FEATURE_SPEC:$feature_spec,IMPL_PLAN:$impl_plan,TASKS:$tasks}'
else
printf '{"REPO_ROOT":"%s","BRANCH":"%s","FEATURE_DIR":"%s","FEATURE_SPEC":"%s","IMPL_PLAN":"%s","TASKS":"%s"}\n' \
"$(json_escape "$REPO_ROOT")" "$(json_escape "$CURRENT_BRANCH")" "$(json_escape "$FEATURE_DIR")" "$(json_escape "$FEATURE_SPEC")" "$(json_escape "$IMPL_PLAN")" "$(json_escape "$TASKS")"
fi
else
echo "REPO_ROOT: $REPO_ROOT"
echo "BRANCH: $CURRENT_BRANCH"
echo "FEATURE_DIR: $FEATURE_DIR"
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "TASKS: $TASKS"
fi
exit 0
fi
# Validate required directories and files
if [[ ! -d "$FEATURE_DIR" ]]; then
echo "ERROR: Feature directory not found: $FEATURE_DIR" >&2
echo "Run /speckit.specify first to create the feature structure." >&2
exit 1
fi
if [[ ! -f "$IMPL_PLAN" ]]; then
echo "ERROR: plan.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.plan first to create the implementation plan." >&2
exit 1
fi
if [[ ! -s "$IMPL_PLAN" ]]; then
echo "ERROR: plan.md is empty in $FEATURE_DIR" >&2
echo "Populate it, or remove the empty file and rerun /speckit.plan with a valid plan template." >&2
exit 1
fi
# Check for spec.md if required
if $REQUIRE_SPEC && [[ ! -f "$FEATURE_SPEC" ]]; then
echo "ERROR: spec.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.specify first to create the feature specification." >&2
exit 1
fi
# Check for tasks.md if required
if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then
echo "ERROR: tasks.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.tasks first to create the task list." >&2
exit 1
fi
# Build list of available documents
docs=()
# Always check these optional docs
[[ -f "$RESEARCH" ]] && docs+=("research.md")
[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md")
# Check contracts directory (only if it exists and has files)
if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then
docs+=("contracts/")
fi
[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md")
# Include tasks.md if requested and it exists
if $INCLUDE_TASKS && [[ -f "$TASKS" ]]; then
docs+=("tasks.md")
fi
TEMPLATE_CONTENT=""
if [[ -n "$TEMPLATE_NAME" ]]; then
if TEMPLATE_CONTENT=$(resolve_template_content "$TEMPLATE_NAME" "$REPO_ROOT"; status=$?; printf x; exit "$status"); then
TEMPLATE_CONTENT="${TEMPLATE_CONTENT%x}"
else
echo "ERROR: Could not resolve required $TEMPLATE_NAME from the template override stack for $REPO_ROOT" >&2
exit 1
fi
fi
# Output results
if $JSON_MODE; then
# Build JSON array of documents
if has_jq; then
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(printf '%s\n' "${docs[@]}" | jq -R . | jq -s .)
fi
if [[ -n "$TEMPLATE_NAME" ]]; then
jq -cn \
--arg feature_dir "$FEATURE_DIR" \
--argjson docs "$json_docs" \
--arg template_content "$TEMPLATE_CONTENT" \
'{FEATURE_DIR:$feature_dir,AVAILABLE_DOCS:$docs,TEMPLATE_CONTENT:$template_content}'
else
jq -cn \
--arg feature_dir "$FEATURE_DIR" \
--argjson docs "$json_docs" \
'{FEATURE_DIR:$feature_dir,AVAILABLE_DOCS:$docs}'
fi
else
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(for d in "${docs[@]}"; do printf '"%s",' "$(json_escape "$d")"; done)
json_docs="[${json_docs%,}]"
fi
if [[ -n "$TEMPLATE_NAME" ]]; then
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s,"TEMPLATE_CONTENT":"%s"}\n' \
"$(json_escape "$FEATURE_DIR")" "$json_docs" "$(json_escape "$TEMPLATE_CONTENT")"
else
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s}\n' "$(json_escape "$FEATURE_DIR")" "$json_docs"
fi
fi
else
# Text output
echo "FEATURE_DIR:$FEATURE_DIR"
echo "AVAILABLE_DOCS:"
# Show status of each potential document
check_file "$RESEARCH" "research.md"
check_file "$DATA_MODEL" "data-model.md"
check_dir "$CONTRACTS_DIR" "contracts/"
check_file "$QUICKSTART" "quickstart.md"
if $INCLUDE_TASKS; then
check_file "$TASKS" "tasks.md"
fi
fi
+942
View File
@@ -0,0 +1,942 @@
#!/usr/bin/env bash
# Common functions and variables for all scripts
# Find repository root by searching upward for .specify directory
# This is the primary marker for spec-kit projects
find_specify_root() {
local dir="${1:-$(pwd)}"
# Normalize to absolute path to prevent infinite loop with relative paths
# Use -- to handle paths starting with - (e.g., -P, -L)
dir="$(cd -- "$dir" 2>/dev/null && pwd)" || return 1
local prev_dir=""
while true; do
if [ -d "$dir/.specify" ]; then
echo "$dir"
return 0
fi
# Stop if we've reached filesystem root or dirname stops changing
if [ "$dir" = "/" ] || [ "$dir" = "$prev_dir" ]; then
break
fi
prev_dir="$dir"
dir="$(dirname "$dir")"
done
return 1
}
# Resolve an explicit SPECIFY_INIT_DIR project override (the directory that
# *contains* .specify/), for non-interactive / CI use — e.g. running a Spec Kit
# command against a member project from a monorepo root without cd.
#
# Precondition: SPECIFY_INIT_DIR is non-empty. Echoes the validated absolute
# project root, or prints an error and returns 1. Strict by design: the path
# must exist and contain .specify/, with no silent fallback to cwd or the
# script-location default (which would silently write to the wrong project).
#
# This is the single resolver: bundled extensions inherit it by sourcing core
# (e.g. the git extension's create-new-feature-branch) rather than duplicating it.
resolve_specify_init_dir() {
local init_root
# Normalize: relative paths resolve against $(pwd); a trailing slash collapses.
# CDPATH="" so a relative value cannot be resolved against the caller's CDPATH
# (which would also echo to stdout and corrupt the captured path).
if ! init_root="$(CDPATH="" cd -- "$SPECIFY_INIT_DIR" 2>/dev/null && pwd)"; then
echo "ERROR: SPECIFY_INIT_DIR does not point to an existing directory: $SPECIFY_INIT_DIR" >&2
return 1
fi
if [[ ! -d "$init_root/.specify" ]]; then
echo "ERROR: SPECIFY_INIT_DIR is not a Spec Kit project (no .specify/ directory): $init_root" >&2
return 1
fi
printf '%s\n' "$init_root"
}
# Get repository root, prioritizing .specify directory
# This prevents using a parent repository when spec-kit is initialized in a subdirectory
get_repo_root() {
# Explicit project override wins (see resolve_specify_init_dir).
if [[ -n "${SPECIFY_INIT_DIR:-}" ]]; then
resolve_specify_init_dir
return
fi
# First, look for .specify directory (spec-kit's own marker)
local specify_root
if specify_root=$(find_specify_root); then
echo "$specify_root"
return
fi
# Final fallback to script location
local script_dir="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
(cd "$script_dir/../../.." && pwd)
}
# Get current feature name from explicit state only.
# Returns the feature identifier or empty string if none is set.
# Feature state is set by SPECIFY_FEATURE (from create-new-feature or
# the git extension) or implicitly via .specify/feature.json.
get_current_branch() {
if [[ -n "${SPECIFY_FEATURE:-}" ]]; then
echo "$SPECIFY_FEATURE"
return
fi
# No explicit feature set — caller must handle this via feature.json
# in get_feature_paths(). Return empty to signal "unknown".
echo ""
}
# Safely read .specify/feature.json's "feature_directory" value.
# Prints the raw value (possibly relative) to stdout, or empty string if the file
# is missing, unparseable, or does not contain the key. Always returns 0 so callers
# under `set -e` cannot be aborted by parser failure.
# Parser order mirrors the historical get_feature_paths behavior: jq -> python3 -> grep/sed.
read_feature_json_feature_directory() {
local repo_root="$1"
local fj="$repo_root/.specify/feature.json"
[[ -f "$fj" ]] || { printf '%s' ''; return 0; }
# Try parsers in order (jq -> python3 -> grep/sed), falling through on
# failure. Selection is by *parse success*, not mere availability: on
# Windows `python3` commonly resolves to the Microsoft Store App Execution
# Alias stub, which passes `command -v` but fails at runtime (exit 49), so
# an availability-gated `elif` would pick python3, swallow its failure, and
# never reach the grep/sed fallback -- leaving feature.json unreadable even
# though it is valid (issue #3304).
local _fd=''
if command -v jq >/dev/null 2>&1; then
if ! _fd=$(jq -r '.feature_directory // empty' "$fj" 2>/dev/null); then
_fd=''
fi
fi
if [[ -z "$_fd" ]] && command -v python3 >/dev/null 2>&1; then
# Use Python so pretty-printed/multi-line JSON still parses correctly.
if ! _fd=$(python3 -c "import json,sys; d=json.load(open(sys.argv[1], encoding='utf-8')); v=d.get('feature_directory'); print(v if v else '')" "$fj" 2>/dev/null); then
_fd=''
fi
fi
if [[ -z "$_fd" ]]; then
# Last-resort single-line grep/sed fallback. The `|| true` guards against
# grep returning 1 (no match) aborting under `set -e` / `pipefail`.
_fd=$( { grep -E '"feature_directory"[[:space:]]*:' "$fj" 2>/dev/null || true; } \
| head -n 1 \
| sed -E 's/^[^:]*:[[:space:]]*"([^"]*)".*$/\1/' )
fi
printf '%s' "$_fd"
return 0
}
# Persist a feature_directory value to .specify/feature.json.
# Writes only when the file is missing or the value differs from what's stored.
# Accepts the raw (possibly relative) path — callers should pass the original
# user-supplied value, not the normalized absolute path.
_persist_feature_json() {
local repo_root="$1"
local feature_dir_value="$2"
local fj="$repo_root/.specify/feature.json"
# Strip repo_root prefix if the value is absolute and under repo_root
if [[ "$feature_dir_value" == "$repo_root/"* ]]; then
feature_dir_value="${feature_dir_value#"$repo_root/"}"
fi
# Read current value (if any) and skip write when unchanged
local current_val
current_val=$(read_feature_json_feature_directory "$repo_root")
if [[ "$current_val" == "$feature_dir_value" ]]; then
return 0
fi
# Ensure .specify/ directory exists
mkdir -p "$repo_root/.specify"
# Write feature.json — prefer jq for safe JSON, fall back to printf
if command -v jq >/dev/null 2>&1; then
jq -cn --arg fd "$feature_dir_value" '{feature_directory:$fd}' > "$fj"
else
printf '{"feature_directory":"%s"}\n' "$(json_escape "$feature_dir_value")" > "$fj"
fi
}
get_feature_paths() {
# Read-only callers (e.g. check-prerequisites.sh --paths-only) pass
# --no-persist so pure path resolution never writes .specify/feature.json,
# which would dirty the working tree or overwrite a pinned value (issue #3025).
local no_persist=false
if [[ "${1:-}" == "--no-persist" ]]; then
no_persist=true
shift
fi
# SPECIFY_FEATURE_NO_PERSIST is the environment-level equivalent of --no-persist,
# letting an orchestrator (multi-agent runner, CI matrix) guarantee that no
# script invocation in the process tree writes .specify/feature.json, even
# scripts that don't pass --no-persist themselves (#4128).
if [[ "${SPECIFY_FEATURE_NO_PERSIST:-}" == "1" || "${SPECIFY_FEATURE_NO_PERSIST:-}" == "true" ]]; then
no_persist=true
fi
# Split decl/assignment so a SPECIFY_INIT_DIR validation failure in
# get_repo_root propagates as a hard error instead of being masked by `local`.
local repo_root
repo_root=$(get_repo_root) || return 1
local current_branch
current_branch=$(get_current_branch)
# Resolve feature directory. Priority:
# 1. SPECIFY_FEATURE_DIRECTORY env var (explicit override)
# 2. .specify/feature.json "feature_directory" key (persisted by specify command)
# 3. Error — no feature context available
local feature_dir
if [[ -n "${SPECIFY_FEATURE_DIRECTORY:-}" ]]; then
feature_dir="$SPECIFY_FEATURE_DIRECTORY"
# Normalize relative paths to absolute under repo root
[[ "$feature_dir" != /* ]] && feature_dir="$repo_root/$feature_dir"
# Persist to feature.json so future sessions without the env var still
# work — unless the caller opted out for read-only resolution (#3025).
if [[ "$no_persist" != true ]]; then
_persist_feature_json "$repo_root" "$SPECIFY_FEATURE_DIRECTORY"
fi
elif [[ -f "$repo_root/.specify/feature.json" ]]; then
local _fd
_fd=$(read_feature_json_feature_directory "$repo_root")
if [[ -n "$_fd" ]]; then
feature_dir="$_fd"
# Normalize relative paths to absolute under repo root
[[ "$feature_dir" != /* ]] && feature_dir="$repo_root/$feature_dir"
else
echo "ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or ensure .specify/feature.json contains feature_directory." >&2
return 1
fi
else
echo "ERROR: Feature directory not found. Set SPECIFY_FEATURE_DIRECTORY or run the specify command to create .specify/feature.json." >&2
return 1
fi
# When no branch context exists (no SPECIFY_FEATURE, feature resolved via
# SPECIFY_FEATURE_DIRECTORY or feature.json), fall back to the feature
# directory basename so CURRENT_BRANCH is a usable identifier rather than
# an empty, misleading value (issue #3026).
if [[ -z "$current_branch" ]]; then
local feature_dir_trimmed="${feature_dir%/}"
current_branch="${feature_dir_trimmed##*/}"
fi
# Use printf '%q' to safely quote values, preventing shell injection
# via crafted branch names or paths containing special characters
printf 'REPO_ROOT=%q\n' "$repo_root"
printf 'CURRENT_BRANCH=%q\n' "$current_branch"
printf 'FEATURE_DIR=%q\n' "$feature_dir"
printf 'FEATURE_SPEC=%q\n' "$feature_dir/spec.md"
printf 'IMPL_PLAN=%q\n' "$feature_dir/plan.md"
printf 'TASKS=%q\n' "$feature_dir/tasks.md"
printf 'RESEARCH=%q\n' "$feature_dir/research.md"
printf 'DATA_MODEL=%q\n' "$feature_dir/data-model.md"
printf 'QUICKSTART=%q\n' "$feature_dir/quickstart.md"
printf 'CONTRACTS_DIR=%q\n' "$feature_dir/contracts"
}
# Check if jq is available for safe JSON construction
has_jq() {
command -v jq >/dev/null 2>&1
}
get_invoke_separator() {
local repo_root="${1:-$(get_repo_root)}"
if [[ "${_SPECIFY_INVOKE_SEPARATOR_CACHE_REPO_ROOT:-}" == "$repo_root" && -n "${_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE:-}" ]]; then
printf '%s\n' "$_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE"
return 0
fi
local integration_json="$repo_root/.specify/integration.json"
local separator="."
local parsed=0
if [[ -f "$integration_json" ]]; then
# Try parsers in order (jq -> python3 -> awk), falling through on
# failure. Selection is by *parse success*, not mere availability: on
# Windows `python3` commonly resolves to the Microsoft Store App
# Execution Alias stub, which passes `command -v` but fails at runtime
# (exit 49). An availability-gated branch would pick python3, swallow
# its failure, and — because this function historically had no text
# fallback — silently return "." even for `-`-separator integrations
# (e.g. forge, cline), yielding wrong command hints (issue #3304).
if command -v jq >/dev/null 2>&1; then
local jq_separator
if jq_separator=$(jq -r '(.default_integration // .integration // "") as $k | if $k == "" then "." else (.integration_settings[$k].invoke_separator // ".") end' "$integration_json" 2>/dev/null); then
case "$jq_separator" in
"."|"-") separator="$jq_separator"; parsed=1 ;;
esac
fi
fi
if [[ "$parsed" -eq 0 ]] && command -v python3 >/dev/null 2>&1; then
local py_separator
if py_separator=$(python3 - "$integration_json" <<'PY' 2>/dev/null
import json
import sys
try:
with open(sys.argv[1], encoding="utf-8") as fh:
state = json.load(fh)
key = state.get("default_integration") or state.get("integration") or ""
settings = state.get("integration_settings")
separator = "."
if isinstance(key, str) and isinstance(settings, dict):
entry = settings.get(key)
if isinstance(entry, dict) and entry.get("invoke_separator") in {".", "-"}:
separator = entry["invoke_separator"]
print(separator)
except Exception:
sys.exit(1)
PY
); then
case "$py_separator" in
"."|"-") separator="$py_separator"; parsed=1 ;;
esac
fi
fi
if [[ "$parsed" -eq 0 ]]; then
# Last-resort text fallback for environments with neither jq nor a
# working python3 (e.g. stock Windows + Git Bash). Reads the active
# integration key (default_integration, else integration) and its
# invoke_separator from within the integration_settings object.
# Handles both pretty-printed (the written form) and compact JSON.
# Accumulate all lines into one buffer in END rather than using
# gawk-only whole-file slurp (RS="^$"), so this stays portable to
# the BSD awk on macOS.
local awk_separator
awk_separator=$(awk '
function keyval(d, name, v) {
if (match(d, "\"" name "\"[ \t\r\n]*:[ \t\r\n]*\"[^\"]*\"")) {
v=substr(d,RSTART,RLENGTH); sub(/^.*:[ \t\r\n]*"/,"",v); sub(/"$/,"",v); return v
}
return ""
}
{ doc = doc $0 "\n" }
END {
key=keyval(doc,"default_integration"); if (key=="") key=keyval(doc,"integration")
sep="."
if (key!="") {
settings=doc
if (match(doc, /"integration_settings"[ \t\r\n]*:[ \t\r\n]*[{]/)) {
settings=substr(doc, RSTART+RLENGTH-1)
}
if (match(settings, "\"" key "\"[ \t\r\n]*:[ \t\r\n]*[{]")) {
start=RSTART+RLENGTH-1
depth=0
obj=""
for (i=start; i<=length(settings); i++) {
c=substr(settings,i,1)
obj=obj c
if (c=="{") depth++
else if (c=="}") { depth--; if (depth==0) break }
}
if (match(obj, /"invoke_separator"[ \t\r\n]*:[ \t\r\n]*"[-.]"/)) {
tok=substr(obj,RSTART,RLENGTH); s=substr(tok,length(tok)-1,1)
if (s=="." || s=="-") sep=s
}
}
}
print sep
}
' "$integration_json" 2>/dev/null)
case "$awk_separator" in
"."|"-") separator="$awk_separator" ;;
esac
fi
fi
_SPECIFY_INVOKE_SEPARATOR_CACHE_REPO_ROOT="$repo_root"
_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE="$separator"
printf '%s\n' "$separator"
}
format_speckit_command() {
local command_name="$1"
local repo_root="${2:-$(get_repo_root)}"
local separator
if [[ "${_SPECIFY_INVOKE_SEPARATOR_CACHE_REPO_ROOT:-}" == "$repo_root" && -n "${_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE:-}" ]]; then
separator="$_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE"
else
separator=$(get_invoke_separator "$repo_root")
_SPECIFY_INVOKE_SEPARATOR_CACHE_REPO_ROOT="$repo_root"
_SPECIFY_INVOKE_SEPARATOR_CACHE_VALUE="$separator"
fi
command_name="${command_name#/}"
command_name="${command_name#speckit.}"
command_name="${command_name#speckit-}"
command_name="${command_name//./$separator}"
printf '/speckit%s%s\n' "$separator" "$command_name"
}
# Escape a string for safe embedding in a JSON value (fallback when jq is unavailable).
# Handles backslash, double-quote, and JSON-required control character escapes (RFC 8259).
json_escape() {
local s="$1"
s="${s//\\/\\\\}"
s="${s//\"/\\\"}"
s="${s//$'\n'/\\n}"
s="${s//$'\t'/\\t}"
s="${s//$'\r'/\\r}"
s="${s//$'\b'/\\b}"
s="${s//$'\f'/\\f}"
# Escape any remaining U+0001-U+001F control characters as \uXXXX.
# (U+0000/NUL cannot appear in bash strings and is excluded.)
# LC_ALL=C ensures ${#s} counts bytes and ${s:$i:1} yields single bytes,
# so multi-byte UTF-8 sequences (first byte >= 0xC0) pass through intact.
local LC_ALL=C
local i char code
for (( i=0; i<${#s}; i++ )); do
char="${s:$i:1}"
printf -v code '%d' "'$char" 2>/dev/null || code=256
if (( code >= 1 && code <= 31 )); then
printf '\\u%04x' "$code"
else
printf '%s' "$char"
fi
done
}
check_file() { [[ -f "$1" ]] && echo " ✓ $2" || echo " ✗ $2"; }
check_dir() { [[ -d "$1" && -n $(ls -A "$1" 2>/dev/null) ]] && echo " ✓ $2" || echo " ✗ $2"; }
_python3_command() {
# SPECKIT_PYTHON_EXECUTABLE is the canonical override; SPECKIT_PYTHON is
# kept as a deprecated fallback (still used by update-agent-context.sh).
local override="${SPECKIT_PYTHON_EXECUTABLE:-${SPECKIT_PYTHON:-}}"
if [[ -n "$override" ]] && command -v "$override" >/dev/null 2>&1 &&
"$override" -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1 &&
"$override" -c 'import yaml' >/dev/null 2>&1; then
printf '%s\n' "$override"
elif command -v python3 >/dev/null 2>&1 &&
python3 -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1; then
printf '%s\n' "python3"
elif command -v python >/dev/null 2>&1 &&
python -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1; then
printf '%s\n' "python"
elif command -v py >/dev/null 2>&1 &&
py -3 -c 'import sys' >/dev/null 2>&1; then
printf '%s\n' "py" "-3"
else
return 1
fi
}
_sorted_extension_ids() {
local ext_dir="$1"
local -a python_cmd=()
local _python_cmd_line
while IFS= read -r _python_cmd_line; do
python_cmd+=("$_python_cmd_line")
done < <(_python3_command)
if [ "${#python_cmd[@]}" -gt 0 ]; then
local py_stderr sorted_ids
py_stderr=$(mktemp)
if sorted_ids=$(SPECKIT_EXTENSIONS="$ext_dir" "${python_cmd[@]}" -c "
import json, os, re, sys
from pathlib import Path
root = Path(os.environ['SPECKIT_EXTENSIONS'])
registered = {}
registry = root / '.registry'
if os.path.lexists(registry):
if not registry.is_file():
print('registry_invalid: not a regular file', file=sys.stderr)
sys.exit(1)
try:
data = json.loads(registry.read_text(encoding='utf-8'))
except Exception as exc:
print('registry_invalid: ' + str(exc), file=sys.stderr)
sys.exit(1)
if not isinstance(data, dict):
print('registry_invalid: root must be a mapping', file=sys.stderr)
sys.exit(1)
raw_extensions = data.get('extensions', {})
if not isinstance(raw_extensions, dict):
print('registry_invalid: extensions must be a mapping', file=sys.stderr)
sys.exit(1)
registered = raw_extensions
def priority(value):
if isinstance(value, bool):
return 10
try:
parsed = int(value)
return parsed if parsed >= 1 else 10
except (TypeError, ValueError, OverflowError):
return 10
ranked = []
for ext_id, meta in registered.items():
if isinstance(ext_id, str) and re.fullmatch(r'[a-z0-9-]+', ext_id) and isinstance(meta, dict) and bool(meta.get('enabled', True)):
ranked.append((priority(meta.get('priority')), ext_id))
for path in root.iterdir():
if path.is_dir() and re.fullmatch(r'[a-z0-9-]+', path.name) and path.name not in registered:
ranked.append((10, path.name))
for _, ext_id in sorted(ranked):
print(ext_id)
" 2>"$py_stderr"); then
rm -f "$py_stderr"
printf '%s\n' "$sorted_ids"
return 0
else
echo "Error: invalid extension registry $ext_dir/.registry" >&2
rm -f "$py_stderr"
return 1
fi
fi
if [ -e "$ext_dir/.registry" ] || [ -L "$ext_dir/.registry" ]; then
if [ ! -f "$ext_dir/.registry" ] || [ ! -r "$ext_dir/.registry" ]; then
echo "Error: invalid extension registry $ext_dir/.registry" >&2
return 1
fi
echo "Error: Python 3 is required to honor the extension registry" >&2
return 2
fi
local ext extension_id
for ext in "$ext_dir"/*/; do
[ -d "$ext" ] || continue
extension_id=$(basename "$ext")
case "$extension_id" in *[!a-z0-9-]*) continue ;; esac
printf '%s\n' "$extension_id"
done
}
# Resolve a template name to a file path using the priority stack:
# 1. .specify/templates/overrides/
# 2. .specify/presets/<preset-id>/templates/ (sorted by priority from .registry)
# 3. .specify/extensions/<ext-id>/templates/
# 4. .specify/templates/ (core)
resolve_template() {
local template_name="$1"
local repo_root="$2"
local base="$repo_root/.specify/templates"
case "$template_name" in ""|*[!a-z0-9-]*) return 1 ;; esac
# Priority 1: Project overrides
local override="$base/overrides/${template_name}.md"
[ -f "$override" ] && echo "$override" && return 0
# Priority 2: Installed presets (sorted by priority from .registry)
local presets_dir="$repo_root/.specify/presets"
if [ -d "$presets_dir" ]; then
local registry_file="$presets_dir/.registry"
local -a python_cmd=()
local _python_cmd_line
while IFS= read -r _python_cmd_line; do
python_cmd+=("$_python_cmd_line")
done < <(_python3_command)
if [ -f "$registry_file" ] && [ "${#python_cmd[@]}" -gt 0 ]; then
# Read preset IDs sorted by priority (lower number = higher precedence).
# The python3 call is wrapped in an if-condition so that set -e does not
# abort the function when python3 exits non-zero (e.g. invalid JSON).
local sorted_presets=""
if sorted_presets=$(SPECKIT_REGISTRY="$registry_file" "${python_cmd[@]}" -c "
import json, re, sys, os
try:
with open(os.environ['SPECKIT_REGISTRY'], encoding='utf-8') as f:
data = json.load(f)
presets = data.get('presets', {})
def priority(meta):
if not isinstance(meta, dict) or isinstance(meta.get('priority'), bool):
return 10
try:
value = int(meta.get('priority', 10))
return value if value >= 1 else 10
except (TypeError, ValueError, OverflowError):
return 10
for pid, meta in sorted(presets.items(), key=lambda x: (priority(x[1]), x[0])):
if isinstance(meta, dict) and bool(meta.get('enabled', True)) and re.fullmatch(r'[a-z0-9-]+', pid):
print(pid)
except Exception:
sys.exit(1)
" 2>/dev/null); then
if [ -n "$sorted_presets" ]; then
# python3 succeeded and returned preset IDs — search in priority order
while IFS= read -r preset_id; do
local candidate="$presets_dir/$preset_id/templates/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
candidate="$presets_dir/$preset_id/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
done <<< "$sorted_presets"
fi
# python3 succeeded but registry has no presets — nothing to search
else
# python3 failed (missing, or registry parse error) — fall back to unordered directory scan
for preset in "$presets_dir"/*/; do
[ -d "$preset" ] || continue
local candidate="$preset/templates/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
candidate="$preset/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
done
fi
else
# Fallback: alphabetical directory order (no python3 available)
for preset in "$presets_dir"/*/; do
[ -d "$preset" ] || continue
local candidate="$preset/templates/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
candidate="$preset/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
done
fi
fi
# Priority 3: Extension-provided templates
local ext_dir="$repo_root/.specify/extensions"
if [ -d "$ext_dir" ]; then
local sorted_extensions=""
if ! sorted_extensions=$(_sorted_extension_ids "$ext_dir"); then
return 2
fi
while IFS= read -r extension_id; do
[ -n "$extension_id" ] || continue
local ext="$ext_dir/$extension_id"
local candidate="$ext/templates/${template_name}.md"
[ -f "$candidate" ] || candidate="$ext/${template_name}.md"
[ -f "$candidate" ] && echo "$candidate" && return 0
done <<< "$sorted_extensions"
fi
# Priority 4: Core templates
local core="$base/${template_name}.md"
[ -f "$core" ] && echo "$core" && return 0
# Template not found in any location.
# Return 1 so callers can distinguish "not found" from "found".
# Callers running under set -e should use: TEMPLATE=$(resolve_template ...) || true
return 1
}
# Resolve a template name to composed content using composition strategies.
# Reads strategy metadata from preset manifests and composes content
# from multiple layers using prepend, append, or wrap strategies.
#
# Usage: CONTENT=$(resolve_template_content "template-name" "$REPO_ROOT")
# Returns composed content string on stdout; exit code 1 if not found.
resolve_template_content() {
local template_name="$1"
local repo_root="$2"
local base="$repo_root/.specify/templates"
case "$template_name" in ""|*[!a-z0-9-]*) return 1 ;; esac
# Collect all layers (highest priority first)
local -a layer_paths=()
local -a layer_strategies=()
# Priority 1: Project overrides (always "replace")
local override="$base/overrides/${template_name}.md"
if [ -f "$override" ]; then
if ! cat "$override"; then
echo "Error: failed to read template layer $override" >&2
return 2
fi
return 0
fi
local effective_base_found=false
# Priority 2: Installed presets (sorted by priority from .registry)
local presets_dir="$repo_root/.specify/presets"
if [ -d "$presets_dir" ]; then
local registry_file="$presets_dir/.registry"
local sorted_presets=""
local registry_parsed=false
local -a python_cmd=()
local _python_cmd_line
while IFS= read -r _python_cmd_line; do
python_cmd+=("$_python_cmd_line")
done < <(_python3_command)
if [ -f "$registry_file" ] && [ "${#python_cmd[@]}" -gt 0 ]; then
if sorted_presets=$(SPECKIT_REGISTRY="$registry_file" "${python_cmd[@]}" -c "
import json, re, sys, os
try:
with open(os.environ['SPECKIT_REGISTRY'], encoding='utf-8') as f:
data = json.load(f)
presets = data.get('presets', {})
def priority(meta):
if not isinstance(meta, dict) or isinstance(meta.get('priority'), bool):
return 10
try:
value = int(meta.get('priority', 10))
return value if value >= 1 else 10
except (TypeError, ValueError, OverflowError):
return 10
for pid, meta in sorted(presets.items(), key=lambda x: (priority(x[1]), x[0])):
if isinstance(meta, dict) and bool(meta.get('enabled', True)) and re.fullmatch(r'[a-z0-9-]+', pid):
print(pid)
except Exception:
sys.exit(1)
" 2>/dev/null); then
registry_parsed=true
fi
fi
if [ "$registry_parsed" = false ]; then
for preset in "$presets_dir"/*/; do
[ -d "$preset" ] || continue
local fallback_id
fallback_id=$(basename "$preset")
case "$fallback_id" in *[!a-z0-9-]*) continue ;; esac
sorted_presets+="${sorted_presets:+$'\n'}$fallback_id"
done
fi
if [ -n "$sorted_presets" ]; then
while IFS= read -r preset_id; do
local strategy="replace"
local manifest_file=""
local manifest="$presets_dir/$preset_id/preset.yml"
local manifest_declared=false
if [ -f "$manifest" ]; then
if [ "${#python_cmd[@]}" -eq 0 ]; then
echo "Error: Python 3 and PyYAML are required to resolve preset template composition" >&2
return 2
fi
local result
local py_stderr
local parse_status
py_stderr=$(mktemp)
if result=$(SPECKIT_MANIFEST="$manifest" SPECKIT_TMPL="$template_name" "${python_cmd[@]}" -c "
import sys, os
try:
import yaml
except ImportError:
print('yaml_missing', file=sys.stderr)
sys.exit(2)
try:
with open(os.environ['SPECKIT_MANIFEST'], encoding='utf-8') as f:
data = yaml.safe_load(f)
if not isinstance(data, dict):
raise ValueError('manifest root must be a mapping')
if 'provides' not in data:
raise ValueError('manifest missing provides section')
provides = data['provides']
if not isinstance(provides, dict):
raise ValueError('manifest provides must be a mapping')
if 'templates' not in provides:
raise ValueError('manifest provides missing templates')
templates = provides['templates']
if not isinstance(templates, list):
raise ValueError('manifest templates must be a list')
if not templates:
raise ValueError('manifest must provide at least one template')
valid_types = ('template', 'command', 'script')
valid_strategies = ('replace', 'prepend', 'append', 'wrap')
for t in templates:
if not isinstance(t, dict):
raise ValueError('manifest template entries must be mappings')
if 'type' not in t or 'name' not in t or 'file' not in t:
raise ValueError('manifest template entry missing type, name, or file')
for field in ('type', 'name', 'file'):
if not isinstance(t[field], str):
raise ValueError('manifest template ' + field + ' must be a string')
if t['type'] not in valid_types:
raise ValueError('invalid manifest template type')
strategy = t.get('strategy', 'replace')
if not isinstance(strategy, str):
raise ValueError('manifest template strategy must be a string')
strategy = strategy.lower()
if strategy not in valid_strategies:
raise ValueError('invalid manifest template strategy')
if t['type'] == 'script' and strategy not in ('replace', 'wrap'):
raise ValueError('invalid manifest script strategy')
for t in templates:
if t.get('name') == os.environ['SPECKIT_TMPL'] and t.get('type', 'template') == 'template':
file_value = t.get('file', '')
strategy = t.get('strategy', 'replace')
print('found\t' + strategy + '\t' + file_value)
sys.exit(0)
print('absent\treplace\t')
except Exception as exc:
print(f'manifest_invalid: {exc}', file=sys.stderr)
sys.exit(3)
" 2>"$py_stderr"); then
parse_status=0
else
parse_status=$?
fi
if [ "$parse_status" -ne 0 ]; then
if [ "$parse_status" -eq 2 ]; then
echo "Error: PyYAML is required to resolve preset template composition" >&2
else
echo "Error: invalid preset manifest $manifest" >&2
fi
rm -f "$py_stderr"
return 2
fi
if [ -n "$result" ]; then
local declaration
IFS=$'\t' read -r declaration strategy manifest_file <<< "$result"
[ "$declaration" = "found" ] && manifest_declared=true
strategy=$(printf '%s' "$strategy" | tr '[:upper:]' '[:lower:]')
fi
rm -f "$py_stderr"
fi
local candidate=""
if [ -n "$manifest_file" ]; then
case "$manifest_file" in
/*|*../*) manifest_file="" ;;
esac
fi
if [ -n "$manifest_file" ]; then
local mf="$presets_dir/$preset_id/$manifest_file"
[ -f "$mf" ] && candidate="$mf"
fi
if [ -z "$candidate" ] && [ "$manifest_declared" = false ]; then
local cf="$presets_dir/$preset_id/templates/${template_name}.md"
[ -f "$cf" ] && candidate="$cf"
if [ -z "$candidate" ]; then
cf="$presets_dir/$preset_id/${template_name}.md"
[ -f "$cf" ] && candidate="$cf"
fi
fi
if [ -n "$candidate" ]; then
layer_paths+=("$candidate")
layer_strategies+=("$strategy")
if [ "$strategy" = "replace" ]; then
effective_base_found=true
break
fi
fi
done <<< "$sorted_presets"
fi
fi
# Priority 3: Extension-provided templates (always "replace")
local ext_dir="$repo_root/.specify/extensions"
if [ "$effective_base_found" = false ] && [ -d "$ext_dir" ]; then
local sorted_extensions=""
if ! sorted_extensions=$(_sorted_extension_ids "$ext_dir"); then
return 2
fi
while IFS= read -r extension_id; do
[ -n "$extension_id" ] || continue
local ext="$ext_dir/$extension_id"
local candidate="$ext/templates/${template_name}.md"
[ -f "$candidate" ] || candidate="$ext/${template_name}.md"
if [ -f "$candidate" ]; then
layer_paths+=("$candidate")
layer_strategies+=("replace")
effective_base_found=true
break
fi
done <<< "$sorted_extensions"
fi
# Priority 4: Core templates (always "replace")
local core="$base/${template_name}.md"
if [ "$effective_base_found" = false ] && [ -f "$core" ]; then
layer_paths+=("$core")
layer_strategies+=("replace")
fi
local count=${#layer_paths[@]}
[ "$count" -eq 0 ] && return 1
# Check if any layer uses a non-replace strategy
local has_composition=false
for s in "${layer_strategies[@]}"; do
[ "$s" != "replace" ] && has_composition=true && break
done
# If the top (highest-priority) layer is replace, it wins entirely —
# lower layers are irrelevant regardless of their strategies.
if [ "${layer_strategies[0]}" = "replace" ]; then
if ! cat "${layer_paths[0]}"; then
echo "Error: failed to read template layer ${layer_paths[0]}" >&2
return 2
fi
return 0
fi
if [ "$has_composition" = false ]; then
if ! cat "${layer_paths[0]}"; then
echo "Error: failed to read template layer ${layer_paths[0]}" >&2
return 2
fi
return 0
fi
# Find the effective base: scan from highest priority (index 0) downward
# to find the nearest replace layer. Only compose layers above that base.
local base_idx=-1
local i
for (( i=0; i<count; i++ )); do
if [ "${layer_strategies[$i]}" = "replace" ]; then
base_idx=$i
break
fi
done
if [ $base_idx -lt 0 ]; then
echo "Error: template '$template_name' has composing layers but no replace base" >&2
return 2
fi
# Read the base content; compose layers above the base (higher priority)
local content
if ! content=$(cat "${layer_paths[$base_idx]}"; status=$?; printf x; exit "$status"); then
echo "Error: failed to read template layer ${layer_paths[$base_idx]}" >&2
return 2
fi
content="${content%x}"
for (( i=base_idx-1; i>=0; i-- )); do
local path="${layer_paths[$i]}"
local strat="${layer_strategies[$i]}"
local layer_content
# Preserve trailing newlines
if ! layer_content=$(cat "$path"; status=$?; printf x; exit "$status"); then
echo "Error: failed to read template layer $path" >&2
return 2
fi
layer_content="${layer_content%x}"
case "$strat" in
replace) content="$layer_content" ;;
prepend)
content=$(printf '%s\n\n%s' "$layer_content" "$content"; printf x)
content="${content%x}"
;;
append)
content=$(printf '%s\n\n%s' "$content" "$layer_content"; printf x)
content="${content%x}"
;;
wrap)
case "$layer_content" in
*'{CORE_TEMPLATE}'*) ;;
*) echo "Error: wrap strategy missing {CORE_TEMPLATE} placeholder" >&2; return 2 ;;
esac
# Consume the wrapper left to right instead of rewriting it in
# place. Rewriting re-scanned the string just modified, so base
# content holding a literal {CORE_TEMPLATE} reintroduced the
# token every pass and the loop never terminated. Advancing over
# ``rest`` bounds the work by the tokens in the original wrapper
# and leaves inserted content untouched, matching the single-pass
# semantics of .Replace()/.replace() in the PowerShell and Python
# ports.
local wrapped="" rest="$layer_content"
while [[ "$rest" == *'{CORE_TEMPLATE}'* ]]; do
wrapped="${wrapped}${rest%%\{CORE_TEMPLATE\}*}${content}"
rest="${rest#*\{CORE_TEMPLATE\}}"
done
content="${wrapped}${rest}"
;;
*) echo "Error: unknown strategy '$strat'" >&2; return 2 ;;
esac
done
printf '%s' "$content"
return 0
}
+504
View File
@@ -0,0 +1,504 @@
#!/usr/bin/env bash
set -e
JSON_MODE=false
DRY_RUN=false
ALLOW_EXISTING=false
SHORT_NAME=""
BRANCH_NUMBER=""
USE_TIMESTAMP=false
NUMBER_EXPLICIT=false
ARGS=()
i=1
while [ $i -le $# ]; do
arg="${!i}"
case "$arg" in
--json)
JSON_MODE=true
;;
--dry-run)
DRY_RUN=true
;;
--allow-existing-branch)
ALLOW_EXISTING=true
;;
--short-name)
if [ $((i + 1)) -gt $# ]; then
echo 'Error: --short-name requires a value' >&2
exit 1
fi
i=$((i + 1))
next_arg="${!i}"
# Check if the next argument is another option (starts with --)
if [[ "$next_arg" == --* ]]; then
echo 'Error: --short-name requires a value' >&2
exit 1
fi
SHORT_NAME="$next_arg"
;;
--number)
if [ $((i + 1)) -gt $# ]; then
echo 'Error: --number requires a value' >&2
exit 1
fi
i=$((i + 1))
next_arg="${!i}"
if [[ "$next_arg" == --* ]]; then
echo 'Error: --number requires a value' >&2
exit 1
fi
BRANCH_NUMBER="$next_arg"
if [ -n "$BRANCH_NUMBER" ]; then
NUMBER_EXPLICIT=true
fi
;;
--timestamp)
USE_TIMESTAMP=true
;;
--help|-h)
echo "Usage: $0 [--json] [--dry-run] [--allow-existing-branch] [--short-name <name>] [--number N] [--timestamp] <feature_description>"
echo ""
echo "Options:"
echo " --json Output in JSON format"
echo " --dry-run Compute feature name and paths without creating directories or files"
echo " --allow-existing-branch Reuse an existing feature directory if it already exists"
echo " --short-name <name> Provide a custom short name (2-4 words) for the feature"
echo " --number N Prefer a feature number (auto-corrected if its specs prefix exists)"
echo " --timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " $0 'Add user authentication system' --short-name 'user-auth'"
echo " $0 'Implement OAuth2 integration for API' --number 5"
echo " $0 --timestamp --short-name 'user-auth' 'Add user authentication'"
exit 0
;;
*)
ARGS+=("$arg")
;;
esac
i=$((i + 1))
done
FEATURE_DESCRIPTION="${ARGS[*]}"
if [ -z "$FEATURE_DESCRIPTION" ]; then
echo "Usage: $0 [--json] [--dry-run] [--allow-existing-branch] [--short-name <name>] [--number N] [--timestamp] <feature_description>" >&2
exit 1
fi
# Trim whitespace and validate description is not empty (e.g., user passed only whitespace)
FEATURE_DESCRIPTION=$(echo "$FEATURE_DESCRIPTION" | sed -E 's/^[[:space:]]+|[[:space:]]+$//g')
if [ -z "$FEATURE_DESCRIPTION" ]; then
echo "Error: Feature description cannot be empty or contain only whitespace" >&2
exit 1
fi
MAX_FEATURE_NUMBER=9223372036854775807
MAX_BRANCH_LENGTH=244
is_feature_number_in_range() {
local value="$1"
local normalized="${value#"${value%%[!0]*}"}"
[ -n "$normalized" ] || normalized=0
[ ${#normalized} -lt ${#MAX_FEATURE_NUMBER} ] && return 0
[ ${#normalized} -gt ${#MAX_FEATURE_NUMBER} ] && return 1
# Equal-length digit strings must be compared without arithmetic overflow.
# shellcheck disable=SC2071
[[ "$normalized" < "$MAX_FEATURE_NUMBER" || "$normalized" == "$MAX_FEATURE_NUMBER" ]]
}
# Function to get highest number from specs directory
get_highest_from_specs() {
local specs_dir="$1"
local highest=0
if [ -d "$specs_dir" ]; then
for dir in "$specs_dir"/*; do
[ -d "$dir" ] || continue
dirname=$(basename "$dir")
# Match sequential prefixes (>=3 digits), but skip timestamp dirs.
if echo "$dirname" | grep -Eq '^[0-9]{3,}-' && ! echo "$dirname" | grep -Eq '^[0-9]{8}-[0-9]{6}-'; then
number=$(echo "$dirname" | grep -Eo '^[0-9]+')
if is_feature_number_in_range "$number"; then
number=$((10#$number))
if [ "$number" -gt "$highest" ]; then
highest=$number
fi
fi
fi
done
fi
echo "$highest"
}
# Return success when a spec directory owns the given numeric prefix.
spec_prefix_exists() {
local specs_dir="$1"
local feature_num="$2"
for spec_path in "$specs_dir/${feature_num}-"*; do
[ -d "$spec_path" ] && return 0
done
return 1
}
# Function to clean and format a branch name
#
# Three details keep this consistent with the Python and PowerShell twins:
# * Unicode classification uses Python: POSIX [:alnum:] differs by platform.
# * `--*` instead of the GNU-only `\+`, which POSIX/BSD sed reads as a literal
# '+', leaving repeated separators uncollapsed on macOS.
# * printf instead of echo, so a name of "-n"/"-e"/"-E" is text, not options.
contains_non_ascii() {
LC_ALL=C grep -q '[^[:print:][:cntrl:]]'
}
UNICODE_LOCALE=""
locale_candidates=(C.UTF-8 C.utf8 en_US.UTF-8 en_US.utf8 "${LC_CTYPE:-${LANG:-}}")
if [ -n "${LC_ALL:-}" ]; then
locale_candidates=("$LC_ALL")
fi
for candidate in "${locale_candidates[@]}"; do
if [ -n "$candidate" ] && [ "$(printf 'é。' | LC_ALL="$candidate" sed 's/[^[:alnum:]]/-/g' 2>/dev/null)" = 'é-' ]; then
UNICODE_LOCALE="$candidate"
break
fi
done
if [ -z "$UNICODE_LOCALE" ]; then
UNICODE_LOCALE=C
if printf '%s' "${SHORT_NAME:-$FEATURE_DESCRIPTION}" | contains_non_ascii; then
if [ -n "${LC_ALL:-}" ]; then
echo "Error: A UTF-8 locale is required to create a Unicode feature name; LC_ALL=$LC_ALL is not usable" >&2
else
echo "Error: A UTF-8 locale is required to create a Unicode feature name" >&2
fi
exit 1
fi
fi
unicode_words() {
local name="${1//$'\n'/ }"
local separator="$2"
if printf '%s' "$name" | contains_non_ascii; then
local -a python_cmd=()
local override="${SPECKIT_PYTHON_EXECUTABLE:-${SPECKIT_PYTHON:-}}"
if [ -n "$override" ] && command -v "$override" >/dev/null 2>&1 &&
"$override" -c 'import sys; raise SystemExit(sys.version_info.major != 3)' >/dev/null 2>&1; then
python_cmd=("$override")
else
local python_line
while IFS= read -r python_line; do
python_cmd+=("$python_line")
done < <(_python3_command)
fi
if [ "${#python_cmd[@]}" -eq 0 ]; then
echo "Error: Python 3 is required to create a Unicode feature name" >&2
return 1
fi
printf '%s' "$name" | "${python_cmd[@]}" -c '
import sys
value = sys.stdin.buffer.read().decode("utf-8")
lower = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
result = "".join(
char if char.isalpha() or char.isdecimal() else sys.argv[1]
for char in value.translate(lower)
)
sys.stdout.buffer.write(result.encode("utf-8"))
' "$separator"
else
printf '%s' "$name" | LC_ALL=C tr '[:upper:]' '[:lower:]' | LC_ALL=C sed "s/[^a-z0-9]/$separator/g"
fi
}
clean_branch_name() {
local name="$1"
local cleaned
cleaned=$(unicode_words "$name" '-') || return 1
printf '%s\n' "$cleaned" | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//'
}
branch_byte_count() {
printf '%s' "$1" | wc -c | tr -d '[:space:]'
}
# Fit a feature prefix and suffix within GitHub's branch-name limit.
fit_branch_name() {
local feature_num="$1"
local branch_suffix="$2"
local branch_name="${feature_num}-${branch_suffix}"
if [ "$(branch_byte_count "$branch_name")" -gt "$MAX_BRANCH_LENGTH" ]; then
local prefix_length=$(( ${#feature_num} + 1 ))
local max_suffix_length=$((MAX_BRANCH_LENGTH - prefix_length))
local truncated_suffix
local -x LC_ALL="$UNICODE_LOCALE"
local low=0 high=${#branch_suffix} mid
if (( high > max_suffix_length )); then
high=$max_suffix_length
fi
while (( low < high )); do
mid=$(((low + high + 1) / 2))
if [ "$(branch_byte_count "${branch_suffix:0:$mid}")" -le "$max_suffix_length" ]; then
low=$mid
else
high=$((mid - 1))
fi
done
truncated_suffix="${branch_suffix:0:$low}"
truncated_suffix="${truncated_suffix%-}"
branch_name="${feature_num}-${truncated_suffix}"
fi
printf '%s' "$branch_name"
}
# Quote a value for POSIX shell reuse, byte-identical to Python's shlex.quote
# so the persistence hints match the Python variant exactly (printf %q output
# differs between bash versions and from shlex.quote for spaces/metachars).
shell_quote() {
local value="$1" LC_ALL=C
if [[ "$value" =~ ^[A-Za-z0-9_@%+=:,./-]+$ ]]; then
printf '%s' "$value"
else
local q="'\"'\"'"
printf "'%s'" "${value//\'/$q}"
fi
}
# Resolve repository root using common.sh functions which prioritize .specify
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
REPO_ROOT=$(get_repo_root) || exit 1
cd "$REPO_ROOT"
SPECS_DIR="$REPO_ROOT/specs"
if [ "$DRY_RUN" != true ]; then
mkdir -p "$SPECS_DIR"
fi
# Function to generate branch name with stop word filtering and length filtering
generate_branch_name() {
local description="$1"
# Common stop words to filter out
local stop_words="^(i|a|an|the|to|for|of|in|on|at|by|with|from|is|are|was|were|be|been|being|have|has|had|do|does|did|will|would|should|could|can|may|might|must|shall|this|that|these|those|my|your|our|their|want|need|add|get|set)$"
# Use a UTF-8 locale for character-safe length checks and split words.
local -x LC_ALL="$UNICODE_LOCALE"
local clean_name
clean_name=$(unicode_words "$description" ' ') || return 1
# Filter words: remove stop words and words shorter than 3 chars (unless they're uppercase acronyms in original)
local meaningful_words=()
for word in $clean_name; do
# Skip empty words
[ -z "$word" ] && continue
# Retain non-ASCII words even when shorter than three characters.
if ! printf '%s\n' "$word" | LC_ALL=C grep -qE "$stop_words"; then
if [ ${#word} -ge 3 ] || printf '%s' "$word" | contains_non_ascii; then
meaningful_words+=("$word")
# Keep short words that appear as an uppercase acronym in the original.
# Uppercase via tr and match with grep -w (both portable) rather than
# bash's 4+ "^^" case expansion (breaks on macOS bash 3.2) and \b (non-POSIX).
elif printf '%s' "$description" | LC_ALL=C grep -qw -- "$(printf '%s' "$word" | LC_ALL=C tr '[:lower:]' '[:upper:]')"; then
meaningful_words+=("$word")
fi
fi
done
# If we have meaningful words, use first 3-4 of them
if [ ${#meaningful_words[@]} -gt 0 ]; then
local max_words=3
if [ ${#meaningful_words[@]} -eq 4 ]; then max_words=4; fi
local result=""
local count=0
for word in "${meaningful_words[@]}"; do
if [ $count -ge $max_words ]; then break; fi
if [ -n "$result" ]; then result="$result-"; fi
result="$result$word"
count=$((count + 1))
done
echo "$result"
else
# Fallback to original logic if no meaningful words found
local cleaned=$(clean_branch_name "$description")
echo "$cleaned" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//'
fi
}
# Generate branch name
if [ -n "$SHORT_NAME" ]; then
# Use provided short name, just clean it up
BRANCH_SUFFIX=$(clean_branch_name "$SHORT_NAME")
else
# Generate from description with smart filtering
BRANCH_SUFFIX=$(generate_branch_name "$FEATURE_DESCRIPTION")
fi
if [ -z "$BRANCH_SUFFIX" ]; then
echo "[specify] Warning: Feature name is empty after removing unsupported characters. Use --short-name with letters or digits (for example, user-auth)." >&2
fi
# Warn if --number and --timestamp are both specified
if [ "$USE_TIMESTAMP" = true ] && [ -n "$BRANCH_NUMBER" ]; then
>&2 echo "[specify] Warning: --number is ignored when --timestamp is used"
BRANCH_NUMBER=""
fi
# Determine branch prefix
if [ "$USE_TIMESTAMP" = true ]; then
FEATURE_NUM=$(date +%Y%m%d-%H%M%S)
BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
else
if [ -n "$BRANCH_NUMBER" ] && [[ ! "$BRANCH_NUMBER" =~ ^[0-9]+$ ]]; then
echo "Error: --number must be an unsigned integer, got '$BRANCH_NUMBER'" >&2
exit 1
fi
# Bash arithmetic is signed 64-bit; reject digit strings that would wrap.
if [ -n "$BRANCH_NUMBER" ] && ! is_feature_number_in_range "$BRANCH_NUMBER"; then
echo "Error: --number must be between 0 and $MAX_FEATURE_NUMBER, got '$BRANCH_NUMBER'" >&2
exit 1
fi
# Determine branch number from existing feature directories
if [ -z "$BRANCH_NUMBER" ]; then
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
if [ "$HIGHEST" -eq "$MAX_FEATURE_NUMBER" ]; then
echo "Error: feature number must be between 0 and $MAX_FEATURE_NUMBER, got '9223372036854775808'" >&2
exit 1
fi
BRANCH_NUMBER=$((HIGHEST + 1))
fi
# Force base-10 interpretation to prevent octal conversion (e.g., 010 → 8 in octal, but should be 10 in decimal)
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
# Treat an explicit number as a preference when its prefix is already used
# by a feature directory. Auto-detected numbers are already conflict-free.
if [ "$NUMBER_EXPLICIT" = true ]; then
SPEC_CONFLICT=false
REQUESTED_BRANCH_NAME=$(fit_branch_name "$FEATURE_NUM" "$BRANCH_SUFFIX")
REQUESTED_DIR="$SPECS_DIR/$REQUESTED_BRANCH_NAME"
if [ "$ALLOW_EXISTING" != true ] || [ ! -d "$REQUESTED_DIR" ]; then
spec_prefix_exists "$SPECS_DIR" "$FEATURE_NUM" && SPEC_CONFLICT=true
fi
if [ "$SPEC_CONFLICT" = true ]; then
REQUESTED_NUM="$FEATURE_NUM"
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
BRANCH_NUMBER=$HIGHEST
while true; do
if [ "$BRANCH_NUMBER" -eq "$MAX_FEATURE_NUMBER" ]; then
echo "Error: feature number must be between 0 and $MAX_FEATURE_NUMBER, got '9223372036854775808'" >&2
exit 1
fi
BRANCH_NUMBER=$((BRANCH_NUMBER + 1))
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
spec_prefix_exists "$SPECS_DIR" "$FEATURE_NUM" || break
done
>&2 echo "[specify] Warning: --number $REQUESTED_NUM conflicts with an existing spec directory; using $FEATURE_NUM instead"
fi
fi
fi
# GitHub enforces a 244-byte limit on branch names
# Validate and truncate if necessary
ORIGINAL_BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
BRANCH_NAME=$(fit_branch_name "$FEATURE_NUM" "$BRANCH_SUFFIX")
if [ "$BRANCH_NAME" != "$ORIGINAL_BRANCH_NAME" ]; then
>&2 echo "[specify] Warning: Branch name exceeded GitHub's 244-byte limit"
>&2 echo "[specify] Original: $ORIGINAL_BRANCH_NAME ($(branch_byte_count "$ORIGINAL_BRANCH_NAME") bytes)"
>&2 echo "[specify] Truncated to: $BRANCH_NAME ($(branch_byte_count "$BRANCH_NAME") bytes)"
fi
FEATURE_DIR="$SPECS_DIR/$BRANCH_NAME"
SPEC_FILE="$FEATURE_DIR/spec.md"
if [ "$DRY_RUN" != true ]; then
if [ -d "$FEATURE_DIR" ] && [ "$ALLOW_EXISTING" != true ]; then
if [ "$USE_TIMESTAMP" = true ]; then
>&2 echo "Error: Feature directory '$FEATURE_DIR' already exists. Rerun to get a new timestamp or use a different --short-name."
else
>&2 echo "Error: Feature directory '$FEATURE_DIR' already exists. Please use a different feature name or specify a different number with --number."
fi
exit 1
fi
NEEDS_SPEC=false
SPEC_TEMPLATE_FOUND=false
SPEC_TEMPLATE_CONTENT=""
if [ ! -f "$SPEC_FILE" ]; then
NEEDS_SPEC=true
if SPEC_TEMPLATE_CONTENT=$(resolve_template_content "spec-template" "$REPO_ROOT"; status=$?; printf x; exit "$status"); then
SPEC_TEMPLATE_CONTENT="${SPEC_TEMPLATE_CONTENT%x}"
SPEC_TEMPLATE_FOUND=true
else
resolve_status=$?
if [ "$resolve_status" -ne 1 ]; then
exit "$resolve_status"
fi
fi
fi
mkdir -p "$FEATURE_DIR"
if [ "$NEEDS_SPEC" = true ]; then
if [ "$SPEC_TEMPLATE_FOUND" = true ]; then
printf '%s' "$SPEC_TEMPLATE_CONTENT" > "$SPEC_FILE"
else
echo "Warning: Spec template not found; created empty spec file" >&2
touch "$SPEC_FILE"
fi
fi
# Persist to .specify/feature.json so downstream commands can find the
# feature, unless the orchestrator opted out via SPECIFY_FEATURE_NO_PERSIST (#4129).
if [[ "${SPECIFY_FEATURE_NO_PERSIST:-}" != "1" && "${SPECIFY_FEATURE_NO_PERSIST:-}" != "true" ]]; then
_persist_feature_json "$REPO_ROOT" "$FEATURE_DIR"
fi
# Inform the user how to set feature state in their own shell
printf '# To persist: export SPECIFY_FEATURE=%s\n' "$(shell_quote "$BRANCH_NAME")" >&2
printf '# export SPECIFY_FEATURE_DIRECTORY=%s\n' "$(shell_quote "$FEATURE_DIR")" >&2
fi
if $JSON_MODE; then
if command -v jq >/dev/null 2>&1; then
if [ "$DRY_RUN" = true ]; then
jq -cn \
--arg branch_name "$BRANCH_NAME" \
--arg spec_file "$SPEC_FILE" \
--arg feature_num "$FEATURE_NUM" \
'{BRANCH_NAME:$branch_name,SPEC_FILE:$spec_file,FEATURE_NUM:$feature_num,DRY_RUN:true}'
else
jq -cn \
--arg branch_name "$BRANCH_NAME" \
--arg spec_file "$SPEC_FILE" \
--arg feature_num "$FEATURE_NUM" \
'{BRANCH_NAME:$branch_name,SPEC_FILE:$spec_file,FEATURE_NUM:$feature_num}'
fi
else
if [ "$DRY_RUN" = true ]; then
printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s","DRY_RUN":true}\n' "$(json_escape "$BRANCH_NAME")" "$(json_escape "$SPEC_FILE")" "$(json_escape "$FEATURE_NUM")"
else
printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s"}\n' "$(json_escape "$BRANCH_NAME")" "$(json_escape "$SPEC_FILE")" "$(json_escape "$FEATURE_NUM")"
fi
fi
else
echo "BRANCH_NAME: $BRANCH_NAME"
echo "SPEC_FILE: $SPEC_FILE"
echo "FEATURE_NUM: $FEATURE_NUM"
if [ "$DRY_RUN" != true ]; then
printf '# To persist in your shell: export SPECIFY_FEATURE=%s\n' "$(shell_quote "$BRANCH_NAME")"
printf '# export SPECIFY_FEATURE_DIRECTORY=%s\n' "$(shell_quote "$FEATURE_DIR")"
fi
fi
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -e
SCRIPT_DIR="$(CDPATH="" cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
JSON_MODE=false
TEMPLATE_NAME=""
for arg in "$@"; do
case "$arg" in
--json) JSON_MODE=true ;;
--help|-h)
echo "Usage: $0 <template-name> [--json]"
exit 0
;;
-*)
echo "ERROR: Unknown option '$arg'" >&2
exit 1
;;
*)
if [[ -n "$TEMPLATE_NAME" ]]; then
echo "ERROR: Unexpected argument '$arg'" >&2
exit 1
fi
TEMPLATE_NAME="$arg"
;;
esac
done
if [[ -z "$TEMPLATE_NAME" ]]; then
echo "ERROR: Template name is required" >&2
exit 1
fi
REPO_ROOT=$(get_repo_root)
if TEMPLATE_CONTENT=$(resolve_template_content "$TEMPLATE_NAME" "$REPO_ROOT"; status=$?; printf x; exit "$status"); then
TEMPLATE_CONTENT="${TEMPLATE_CONTENT%x}"
else
echo "ERROR: Could not resolve required $TEMPLATE_NAME from the template override stack for $REPO_ROOT" >&2
exit 1
fi
if $JSON_MODE; then
if has_jq; then
jq -cn \
--arg template_name "$TEMPLATE_NAME" \
--arg template_content "$TEMPLATE_CONTENT" \
'{TEMPLATE_NAME:$template_name,TEMPLATE_CONTENT:$template_content}'
else
printf '{"TEMPLATE_NAME":"%s","TEMPLATE_CONTENT":"%s"}\n' \
"$(json_escape "$TEMPLATE_NAME")" "$(json_escape "$TEMPLATE_CONTENT")"
fi
else
printf '%s' "$TEMPLATE_CONTENT"
fi
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env bash
set -e
# Parse command line arguments
JSON_MODE=false
for arg in "$@"; do
case "$arg" in
--json)
JSON_MODE=true
;;
--help|-h)
echo "Usage: $0 [--json]"
echo " --json Output results in JSON format"
echo " --help Show this help message"
exit 0
;;
*)
echo "ERROR: Unknown option '$arg'" >&2
exit 1
;;
esac
done
# Get script directory and load common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get all paths and variables from common functions
_paths_output=$(get_feature_paths) || { echo "ERROR: Failed to resolve feature paths" >&2; exit 1; }
eval "$_paths_output"
unset _paths_output
# Ensure the feature directory exists
mkdir -p "$FEATURE_DIR"
# Copy plan template if plan doesn't already exist
if [[ -f "$IMPL_PLAN" ]]; then
if $JSON_MODE; then
echo "Plan already exists at $IMPL_PLAN, skipping template copy" >&2
else
echo "Plan already exists at $IMPL_PLAN, skipping template copy"
fi
else
template_file=$(mktemp)
trap 'rm -f "$template_file"' EXIT
if resolve_template_content "plan-template" "$REPO_ROOT" > "$template_file"; then
if [[ ! -s "$template_file" ]]; then
echo "ERROR: Plan template is empty; no new plan.md was created." >&2
echo "Restore a valid plan template and rerun plan setup." >&2
exit 1
fi
cat "$template_file" > "$IMPL_PLAN"
if $JSON_MODE; then
echo "Copied plan template to $IMPL_PLAN" >&2
else
echo "Copied plan template to $IMPL_PLAN"
fi
else
resolve_status=$?
if [ "$resolve_status" -ne 1 ]; then
exit "$resolve_status"
fi
echo "ERROR: Plan template not found; no new plan.md was created." >&2
echo "Restore a valid plan template and rerun plan setup." >&2
exit 1
fi
fi
# Output results
if $JSON_MODE; then
if has_jq; then
jq -cn \
--arg feature_spec "$FEATURE_SPEC" \
--arg impl_plan "$IMPL_PLAN" \
--arg feature_dir "$FEATURE_DIR" \
--arg branch "$CURRENT_BRANCH" \
'{FEATURE_SPEC:$feature_spec,IMPL_PLAN:$impl_plan,FEATURE_DIR:$feature_dir,BRANCH:$branch}'
else
printf '{"FEATURE_SPEC":"%s","IMPL_PLAN":"%s","FEATURE_DIR":"%s","BRANCH":"%s"}\n' \
"$(json_escape "$FEATURE_SPEC")" "$(json_escape "$IMPL_PLAN")" "$(json_escape "$FEATURE_DIR")" "$(json_escape "$CURRENT_BRANCH")"
fi
else
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "FEATURE_DIR: $FEATURE_DIR"
echo "BRANCH: $CURRENT_BRANCH"
fi
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env bash
set -e
# Parse command line arguments
JSON_MODE=false
for arg in "$@"; do
case "$arg" in
--json) JSON_MODE=true ;;
--help|-h)
echo "Usage: $0 [--json]"
echo " --json Output results in JSON format"
echo " --help Show this help message"
exit 0
;;
*) echo "ERROR: Unknown option '$arg'" >&2; exit 1 ;;
esac
done
# Source common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get feature paths
_paths_output=$(get_feature_paths) || { echo "ERROR: Failed to resolve feature paths" >&2; exit 1; }
eval "$_paths_output"
unset _paths_output
# Validate required files
if [[ ! -f "$IMPL_PLAN" ]]; then
echo "ERROR: plan.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.plan first to create the implementation plan." >&2
exit 1
fi
if [[ ! -f "$FEATURE_SPEC" ]]; then
echo "ERROR: spec.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.specify first to create the feature structure." >&2
exit 1
fi
# Build available docs list
docs=()
[[ -f "$RESEARCH" ]] && docs+=("research.md")
[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md")
if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then
docs+=("contracts/")
fi
[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md")
# Resolve tasks template through override stack
TASKS_TEMPLATE=$(resolve_template "tasks-template" "$REPO_ROOT") || true
if TASKS_TEMPLATE_CONTENT=$(resolve_template_content "tasks-template" "$REPO_ROOT"; status=$?; printf x; exit "$status"); then
TASKS_TEMPLATE_CONTENT="${TASKS_TEMPLATE_CONTENT%x}"
else
echo "ERROR: Could not resolve required tasks-template from the template override stack for $REPO_ROOT" >&2
echo "Template 'tasks-template' was not found in any supported location (overrides, presets, extensions, or shared core). Add an override at .specify/templates/overrides/tasks-template.md, or run 'specify init' / reinstall shared infra to restore the core .specify/templates/tasks-template.md template." >&2
exit 1
fi
# Output results
if $JSON_MODE; then
if has_jq; then
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(printf '%s\n' "${docs[@]}" | jq -R . | jq -s .)
fi
jq -cn \
--arg feature_dir "$FEATURE_DIR" \
--argjson docs "$json_docs" \
--arg tasks_template "${TASKS_TEMPLATE:-}" \
--arg tasks_template_content "$TASKS_TEMPLATE_CONTENT" \
'{FEATURE_DIR:$feature_dir,AVAILABLE_DOCS:$docs,TASKS_TEMPLATE:$tasks_template,TASKS_TEMPLATE_CONTENT:$tasks_template_content}'
else
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(for d in "${docs[@]}"; do printf '"%s",' "$(json_escape "$d")"; done)
json_docs="[${json_docs%,}]"
fi
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s,"TASKS_TEMPLATE":"%s","TASKS_TEMPLATE_CONTENT":"%s"}\n' \
"$(json_escape "$FEATURE_DIR")" "$json_docs" "$(json_escape "${TASKS_TEMPLATE:-}")" "$(json_escape "$TASKS_TEMPLATE_CONTENT")"
fi
else
echo "FEATURE_DIR: $FEATURE_DIR"
echo "TASKS_TEMPLATE: ${TASKS_TEMPLATE:-not found}"
echo "AVAILABLE_DOCS:"
check_file "$RESEARCH" "research.md"
check_file "$DATA_MODEL" "data-model.md"
check_dir "$CONTRACTS_DIR" "contracts/"
check_file "$QUICKSTART" "quickstart.md"
fi
+3
View File
@@ -0,0 +1,3 @@
# Atomic blog update prerequisite
Guarded publishers submit the updatedAt string returned by GET to PUT /admin/blogs/:id as expectedUpdatedAt. A stale or invalid supplied token must return 409 before any scalar, relation, tag creation, or cache side effect. Exactly one competing guarded writer sharing a token can commit. Missing records retain 404. Existing UI callers omitting the token retain legacy last-write-wins behavior deliberately; they are not concurrency-protected. No production content writes or migrations are permitted.
Acceptance: current token succeeds; stale/invalid/null/number/object/array tokens fail; offset-equivalent timestamps work; microsecond DB timestamps round-trip through millisecond JSON; same-millisecond successors invalidate old tokens; relation failure rolls back scalar claim; postcommit revalidation remains fail-safe.
+7
View File
@@ -0,0 +1,7 @@
# Tasks
- [x] Preserve inherited service patch/test and fetch gitea/develop; inspect Graphify impact and schema/controller/whitelist.
- [x] Specify contract/compatibility/precision before implementation.
- [ ] RED: expand invalid/current/stale/same-ms/race/rollback and HTTP whitelist tests.
- [ ] GREEN: transactional predicate and nested relations; preserve legacy omission.
- [ ] Targeted and complete backend/admin/store suites plus all builds; isolate baseline failures without modifying another worktree.
- [ ] Independent review of exact hashed diff; do not push before accepted. Parent handles pilot, deployment and archive loop.
+45
View File
@@ -0,0 +1,45 @@
# [CHECKLIST TYPE] Checklist: [FEATURE NAME]
**Purpose**: [Brief description of what this checklist covers]
**Created**: [DATE]
**Feature**: [Link to spec.md or relevant documentation]
**Note**: This custom checklist is generated by the `/speckit.checklist` command based on feature context and requirements.
**Review Ownership**: This checklist is a reviewer-owned requirements-quality review artifact. Mark an item `[x]` only when the reviewer determines the requirements-quality criterion is satisfied.
**Marker Semantics**: `[x]` means the criterion has been reviewed and satisfied for requirements quality. It does not mean implementation work is complete.
<!--
============================================================================
IMPORTANT: The checklist items below are SAMPLE ITEMS for illustration only.
The /speckit.checklist command MUST replace these with actual items based on:
- User's specific checklist request
- Feature requirements from spec.md
- Technical context from plan.md
- Implementation details from tasks.md
DO NOT keep these sample items in the generated checklist file.
============================================================================
-->
## [Category 1]
- [ ] CHK001 First checklist item with clear action
- [ ] CHK002 Second checklist item
- [ ] CHK003 Third checklist item
## [Category 2]
- [ ] CHK004 Another category item
- [ ] CHK005 Item with specific criteria
- [ ] CHK006 Final item in this category
## Notes
- Mark items `[x]` only after review confirms the requirement-quality criterion is satisfied
- Leave items unchecked when they still require clarification, correction, or reviewer evaluation
- `/speckit.implement` reads checklist checkbox state as a gate and must not modify markers
- `checklists/requirements.md` has a separate built-in lifecycle maintained by `/speckit.specify` and `/speckit.clarify`
- Add comments or findings inline
- Link to relevant resources or documentation
- Items are numbered sequentially for easy reference
@@ -0,0 +1,50 @@
# [PROJECT_NAME] Constitution
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
[SECTION_2_CONTENT]
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
## [SECTION_3_NAME]
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
[SECTION_3_CONTENT]
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
+113
View File
@@ -0,0 +1,113 @@
# Implementation Plan: [FEATURE]
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
**Note**: This template is filled in by the `/speckit.plan` command; its definition describes the execution workflow.
## Summary
[Extract from feature spec: primary requirement + technical approach from research]
## Technical Context
<!--
ACTION REQUIRED: Replace the content in this section with the technical details
for the project. The structure here is presented in advisory capacity to guide
the iteration process.
-->
**Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION]
**Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION]
**Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
**Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION]
**Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION]
**Project Type**: [e.g., library/cli/web-service/mobile-app/compiler/desktop-app or NEEDS CLARIFICATION]
**Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION]
**Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION]
**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION]
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
[Gates determined based on constitution file]
## Project Structure
### Documentation (this feature)
```text
specs/[###-feature]/
├── plan.md # This file (/speckit.plan command output)
├── research.md # Phase 0 output (/speckit.plan command)
├── data-model.md # Phase 1 output (/speckit.plan command)
├── quickstart.md # Phase 1 output (/speckit.plan command)
├── contracts/ # Phase 1 output (/speckit.plan command)
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
```
### Source Code (repository root)
<!--
ACTION REQUIRED: Replace the placeholder tree below with the concrete layout
for this feature. Delete unused options and expand the chosen structure with
real paths (e.g., apps/admin, packages/something). The delivered plan must
not include Option labels.
-->
```text
# [REMOVE IF UNUSED] Option 1: Single project (DEFAULT)
src/
├── models/
├── services/
├── cli/
└── lib/
tests/
├── contract/
├── integration/
└── unit/
# [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected)
backend/
├── src/
│ ├── models/
│ ├── services/
│ └── api/
└── tests/
frontend/
├── src/
│ ├── components/
│ ├── pages/
│ └── services/
└── tests/
# [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected)
api/
└── [same as backend above]
ios/ or android/
└── [platform-specific structure: feature modules, UI flows, platform tests]
```
**Structure Decision**: [Document the selected structure and reference the real
directories captured above]
## Complexity Tracking
> **Fill ONLY if Constitution Check has violations that must be justified**
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |
+131
View File
@@ -0,0 +1,131 @@
# Feature Specification: [FEATURE NAME]
**Feature Branch**: `[###-feature-name]`
**Created**: [DATE]
**Status**: Draft
**Input**: User description: "$ARGUMENTS"
## User Scenarios & Testing *(mandatory)*
<!--
IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance.
Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them,
you should still have a viable MVP (Minimum Viable Product) that delivers value.
Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical.
Think of each story as a standalone slice of functionality that can be:
- Developed independently
- Tested independently
- Deployed independently
- Demonstrated to users independently
-->
### User Story 1 - [Brief Title] (Priority: P1)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
2. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
### User Story 2 - [Brief Title] (Priority: P2)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
### User Story 3 - [Brief Title] (Priority: P3)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
[Add more user stories as needed, each with an assigned priority]
### Edge Cases
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right edge cases.
-->
- What happens when [boundary condition]?
- How does system handle [error scenario]?
## Requirements *(mandatory)*
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right functional requirements.
-->
### Functional Requirements
- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"]
- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"]
- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"]
- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"]
- **FR-005**: System MUST [behavior, e.g., "log all security events"]
*Example of marking unclear requirements:*
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
### Key Entities *(include if feature involves data)*
- **[Entity 1]**: [What it represents, key attributes without implementation]
- **[Entity 2]**: [What it represents, relationships to other entities]
## Success Criteria *(mandatory)*
<!--
ACTION REQUIRED: Define measurable success criteria.
These must be technology-agnostic and measurable.
-->
### Measurable Outcomes
- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"]
- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"]
- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"]
- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"]
## Assumptions
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right assumptions based on reasonable defaults
chosen when the feature description did not specify certain details.
-->
- [Assumption about target users, e.g., "Users have stable internet connectivity"]
- [Assumption about scope boundaries, e.g., "Mobile support is out of scope for v1"]
- [Assumption about data/environment, e.g., "Existing authentication system will be reused"]
- [Dependency on existing system/service, e.g., "Requires access to the existing user profile API"]
+252
View File
@@ -0,0 +1,252 @@
---
description: "Task list template for feature implementation"
---
# Tasks: [FEATURE NAME]
**Input**: Design documents from `/specs/[###-feature-name]/`
**Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/
**Tests**: The examples below include test tasks. Tests are OPTIONAL - only include them if explicitly requested in the feature specification.
**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel (different files, no dependencies)
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
- Include exact file paths in descriptions
## Path Conventions
- **Single project**: `src/`, `tests/` at repository root
- **Web app**: `backend/src/`, `frontend/src/`
- **Mobile**: `api/src/`, `ios/src/` or `android/src/`
- Paths shown below assume single project - adjust based on plan.md structure
<!--
============================================================================
IMPORTANT: The tasks below are SAMPLE TASKS for illustration purposes only.
The /speckit.tasks command MUST replace these with actual tasks based on:
- User stories from spec.md (with their priorities P1, P2, P3...)
- Feature requirements from plan.md
- Entities from data-model.md
- Endpoints from contracts/
Tasks MUST be organized by user story so each story can be:
- Implemented independently
- Tested independently
- Delivered as an MVP increment
DO NOT keep these sample tasks in the generated tasks.md file.
============================================================================
-->
## Phase 1: Setup (Shared Infrastructure)
**Purpose**: Project initialization and basic structure
- [ ] T001 Create project structure per implementation plan
- [ ] T002 Initialize [language] project with [framework] dependencies
- [ ] T003 [P] Configure linting and formatting tools
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented
**⚠️ CRITICAL**: No user story work can begin until this phase is complete
Examples of foundational tasks (adjust based on your project):
- [ ] T004 Setup database schema and migrations framework
- [ ] T005 [P] Implement authentication/authorization framework
- [ ] T006 [P] Setup API routing and middleware structure
- [ ] T007 Create base models/entities that all stories depend on
- [ ] T008 Configure error handling and logging infrastructure
- [ ] T009 Setup environment configuration management
**Checkpoint**: Foundation ready - user story implementation can now begin in parallel
---
## Phase 3: User Story 1 - [Title] (Priority: P1) 🎯 MVP
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 1 (OPTIONAL - only if tests requested) ⚠️
> **NOTE: Write these tests FIRST, ensure they FAIL before implementation**
- [ ] T010 [P] [US1] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T011 [P] [US1] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 1
- [ ] T012 [P] [US1] Create [Entity1] model in src/models/[entity1].py
- [ ] T013 [P] [US1] Create [Entity2] model in src/models/[entity2].py
- [ ] T014 [US1] Implement [Service] in src/services/[service].py (depends on T012, T013)
- [ ] T015 [US1] Implement [endpoint/feature] in src/[location]/[file].py
- [ ] T016 [US1] Add validation and error handling
- [ ] T017 [US1] Add logging for user story 1 operations
**Checkpoint**: At this point, User Story 1 should be fully functional and testable independently
---
## Phase 4: User Story 2 - [Title] (Priority: P2)
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 2 (OPTIONAL - only if tests requested) ⚠️
- [ ] T018 [P] [US2] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T019 [P] [US2] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 2
- [ ] T020 [P] [US2] Create [Entity] model in src/models/[entity].py
- [ ] T021 [US2] Implement [Service] in src/services/[service].py
- [ ] T022 [US2] Implement [endpoint/feature] in src/[location]/[file].py
- [ ] T023 [US2] Integrate with User Story 1 components (if needed)
**Checkpoint**: At this point, User Stories 1 AND 2 should both work independently
---
## Phase 5: User Story 3 - [Title] (Priority: P3)
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 3 (OPTIONAL - only if tests requested) ⚠️
- [ ] T024 [P] [US3] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T025 [P] [US3] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 3
- [ ] T026 [P] [US3] Create [Entity] model in src/models/[entity].py
- [ ] T027 [US3] Implement [Service] in src/services/[service].py
- [ ] T028 [US3] Implement [endpoint/feature] in src/[location]/[file].py
**Checkpoint**: All user stories should now be independently functional
---
[Add more user story phases as needed, following the same pattern]
---
## Phase N: Polish & Cross-Cutting Concerns
**Purpose**: Improvements that affect multiple user stories
- [ ] TXXX [P] Documentation updates in docs/
- [ ] TXXX Code cleanup and refactoring
- [ ] TXXX Performance optimization across all stories
- [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/
- [ ] TXXX Security hardening
- [ ] TXXX Run quickstart.md validation
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: No dependencies - can start immediately
- **Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories
- **User Stories (Phase 3+)**: All depend on Foundational phase completion
- User stories can then proceed in parallel (if staffed)
- Or sequentially in priority order (P1 → P2 → P3)
- **Polish (Final Phase)**: Depends on all desired user stories being complete
### User Story Dependencies
- **User Story 1 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories
- **User Story 2 (P2)**: Can start after Foundational (Phase 2) - May integrate with US1 but should be independently testable
- **User Story 3 (P3)**: Can start after Foundational (Phase 2) - May integrate with US1/US2 but should be independently testable
### Within Each User Story
- Tests (if included) MUST be written and FAIL before implementation
- Models before services
- Services before endpoints
- Core implementation before integration
- Story complete before moving to next priority
### Parallel Opportunities
- All Setup tasks marked [P] can run in parallel
- All Foundational tasks marked [P] can run in parallel (within Phase 2)
- Once Foundational phase completes, all user stories can start in parallel (if team capacity allows)
- All tests for a user story marked [P] can run in parallel
- Models within a story marked [P] can run in parallel
- Different user stories can be worked on in parallel by different team members
---
## Parallel Example: User Story 1
```bash
# Launch all tests for User Story 1 together (if tests requested):
Task: "Contract test for [endpoint] in tests/contract/test_[name].py"
Task: "Integration test for [user journey] in tests/integration/test_[name].py"
# Launch all models for User Story 1 together:
Task: "Create [Entity1] model in src/models/[entity1].py"
Task: "Create [Entity2] model in src/models/[entity2].py"
```
---
## Implementation Strategy
### MVP First (User Story 1 Only)
1. Complete Phase 1: Setup
2. Complete Phase 2: Foundational (CRITICAL - blocks all stories)
3. Complete Phase 3: User Story 1
4. **STOP and VALIDATE**: Test User Story 1 independently
5. Deploy/demo if ready
### Incremental Delivery
1. Complete Setup + Foundational → Foundation ready
2. Add User Story 1 → Test independently → Deploy/Demo (MVP!)
3. Add User Story 2 → Test independently → Deploy/Demo
4. Add User Story 3 → Test independently → Deploy/Demo
5. Each story adds value without breaking previous stories
### Parallel Team Strategy
With multiple developers:
1. Team completes Setup + Foundational together
2. Once Foundational is done:
- Developer A: User Story 1
- Developer B: User Story 2
- Developer C: User Story 3
3. Stories complete and integrate independently
---
## Notes
- [P] tasks = different files, no dependencies
- [Story] label maps task to specific user story for traceability
- Each user story should be independently completable and testable
- Verify tests fail before implementing
- Commit after each task or logical group
- Stop at any checkpoint to validate story independently
- Avoid: vague tasks, same file conflicts, cross-story dependencies that break independence
+74
View File
@@ -0,0 +1,74 @@
schema_version: "1.0"
workflow:
id: "speckit"
name: "Full SDD Cycle"
version: "1.0.1"
author: "GitHub"
description: "Runs specify → plan → tasks → implement with review gates"
requires:
# 0.8.5 is the first release with engine-side resolution of the
# ``integration: "auto"`` default. Older versions would treat "auto"
# as a literal integration key and fail at dispatch.
speckit_version: ">=0.8.5"
integrations:
# The four commands below (specify, plan, tasks, implement) are core
# spec-kit commands provided by every integration. The list here is an
# advisory, non-exhaustive compatibility hint following the documented
# ``any: [...]`` schema -- it is NOT a closed set. The workflow runs
# against any integration the project was initialized with, including
# ones not listed below, as long as that integration provides the four
# core commands referenced in ``steps``.
any:
- "alquimia"
- "claude"
- "copilot"
- "gemini"
- "opencode"
inputs:
spec:
type: string
required: true
prompt: "Describe what you want to build"
integration:
type: string
default: "auto"
prompt: "Integration to use (e.g. claude, copilot, gemini; 'auto' uses the project's initialized integration)"
steps:
- id: specify
command: speckit.specify
integration: "{{ inputs.integration }}"
input:
args: "{{ inputs.spec }}"
- id: review-spec
type: gate
message: "Review the generated spec before planning."
options: [approve, reject]
on_reject: abort
- id: plan
command: speckit.plan
integration: "{{ inputs.integration }}"
input:
args: "{{ inputs.spec }}"
- id: review-plan
type: gate
message: "Review the plan before generating tasks."
options: [approve, reject]
on_reject: abort
- id: tasks
command: speckit.tasks
integration: "{{ inputs.integration }}"
input:
args: "{{ inputs.spec }}"
- id: implement
command: speckit.implement
integration: "{{ inputs.integration }}"
input:
args: "{{ inputs.spec }}"
+13
View File
@@ -0,0 +1,13 @@
{
"schema_version": "1.0",
"workflows": {
"speckit": {
"name": "Full SDD Cycle",
"version": "1.0.1",
"description": "Runs specify \u2192 plan \u2192 tasks \u2192 implement with review gates",
"source": "bundled",
"installed_at": "2026-10-27T07:17:00.004616+00:00",
"updated_at": "2026-10-27T07:17:00.004650+00:00"
}
}
}
+9 -9
View File
@@ -1,4 +1,4 @@
FROM node:20-alpine AS app-builder FROM node:22-alpine AS app-builder
USER root USER root
WORKDIR /app WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1 ENV NEXT_TELEMETRY_DISABLED=1
@@ -7,18 +7,17 @@ ENV NEXT_PUBLIC_API_URL=https://api.canina.ir/api
# Optional: Use Nexus as npm registry # Optional: Use Nexus as npm registry
ARG NPM_REGISTRY= ARG NPM_REGISTRY=
RUN if [ -n "$NPM_REGISTRY" ]; then \ RUN if [ -n "$NPM_REGISTRY" ]; then \
npm config set registry "$NPM_REGISTRY" && \ npm config set registry "$NPM_REGISTRY"; \
npm config set strict-ssl false; \
fi fi
COPY frontend/application/package*.json ./ COPY frontend/application/package*.json ./
RUN npm ci --include=dev --prefer-offline --no-audit RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/next
COPY frontend/application ./ COPY frontend/application ./
ARG NEXT_PUBLIC_API_URL ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
RUN npm run build RUN npm run build
FROM node:20-alpine AS admin-builder FROM node:22-alpine AS admin-builder
USER root USER root
WORKDIR /app WORKDIR /app
ENV VITE_API_URL=https://api.canina.ir/api ENV VITE_API_URL=https://api.canina.ir/api
@@ -26,18 +25,17 @@ ENV VITE_API_URL=https://api.canina.ir/api
# Optional: Use Nexus as npm registry (inherits build-arg) # Optional: Use Nexus as npm registry (inherits build-arg)
ARG NPM_REGISTRY= ARG NPM_REGISTRY=
RUN if [ -n "$NPM_REGISTRY" ]; then \ RUN if [ -n "$NPM_REGISTRY" ]; then \
npm config set registry "$NPM_REGISTRY" && \ npm config set registry "$NPM_REGISTRY"; \
npm config set strict-ssl false; \
fi fi
COPY frontend/admin-panel/package*.json ./ COPY frontend/admin-panel/package*.json ./
RUN npm ci --include=dev --prefer-offline --no-audit RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/vite
COPY frontend/admin-panel ./ COPY frontend/admin-panel ./
ARG VITE_API_URL ARG VITE_API_URL
ENV VITE_API_URL=$VITE_API_URL ENV VITE_API_URL=$VITE_API_URL
RUN npm run build RUN npm run build
FROM node:20-alpine FROM node:22-alpine
USER root USER root
RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true
RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d
@@ -49,6 +47,8 @@ RUN chown -R nginx:nginx /var/log/nginx /var/cache/nginx /run/nginx 2>/dev/null
WORKDIR /app WORKDIR /app
COPY --from=app-builder /app . COPY --from=app-builder /app .
COPY --from=admin-builder /app/dist ./admin_static COPY --from=admin-builder /app/dist ./admin_static
# Build-context umask must not make public assets unreadable by nginx workers.
RUN chmod -R a+rX /app/admin_static
COPY nginx.conf /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/http.d/default.conf COPY nginx.conf /etc/nginx/http.d/default.conf
+6 -3
View File
@@ -2,6 +2,7 @@ FROM node:20-alpine AS builder
USER root USER root
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
WORKDIR /app WORKDIR /app
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
ENV DISABLE_OPENCOLLECTIVE=1 ENV DISABLE_OPENCOLLECTIVE=1
@@ -11,7 +12,6 @@ ENV npm_config_cache=/tmp/npm-cache
ARG NPM_REGISTRY= ARG NPM_REGISTRY=
RUN if [ -n "$NPM_REGISTRY" ]; then \ RUN if [ -n "$NPM_REGISTRY" ]; then \
npm config set registry "$NPM_REGISTRY" && \ npm config set registry "$NPM_REGISTRY" && \
npm config set strict-ssl false && \
echo "Using npm registry: $NPM_REGISTRY"; \ echo "Using npm registry: $NPM_REGISTRY"; \
fi fi
@@ -31,8 +31,11 @@ RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
FROM node:20-alpine FROM node:20-alpine
USER root USER root
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
RUN mkdir -p /app/uploads && chown node:node /app/uploads RUN mkdir -p /app/uploads /app/private-stage-test && chmod 700 /app/private-stage-test && chown node:node /app/uploads /app/private-stage-test
WORKDIR /app WORKDIR /app
ARG STAGE_TEST_ARTIFACT_SHA=disabled
RUN printf "%s" "$STAGE_TEST_ARTIFACT_SHA" > /app/STAGE_TEST_ARTIFACT_SHA
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
COPY --chown=node:node --from=builder /app/package*.json ./ COPY --chown=node:node --from=builder /app/package*.json ./
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
@@ -45,4 +48,4 @@ COPY --chown=node:node --from=builder /app/src ./src
COPY --chown=node:node --from=builder /app/test ./test COPY --chown=node:node --from=builder /app/test ./test
EXPOSE 3000 EXPOSE 3000
USER node USER node
CMD ["sh", "-c", "npx prisma db push --skip-generate && if [ -f dist/src/main.js ]; then node dist/src/main.js; else node dist/main.js; fi"] CMD ["node", "dist/main.js"]
+1 -1
View File
@@ -13,7 +13,7 @@
"start:debug": "nest start --debug --watch", "start:debug": "nest start --debug --watch",
"start:prod": "node dist/main", "start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest", "test": "python3 scripts/test-postgres.py",
"test:watch": "jest --watch", "test:watch": "jest --watch",
"test:cov": "jest --coverage", "test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
+28
View File
@@ -0,0 +1,28 @@
# Prisma migration history and Orchestration v4 rollout boundary
The checked-in history is **not a complete baseline of the current Prisma schema**. Do not assume that replaying it into an empty database can recreate the application, or that existing production tables imply corresponding migration records. Never use `prisma db push`, reset, or edit applied SQL to reconcile this.
## Actual tracked history
| Migration | What its SQL actually does |
| --- | --- |
| `20260526145407_init` | Creates users, addresses, wallets, products, product ingredients/symptoms, pets and medical conditions, reminders/completions, health logs, coupons, orders and order items, with their indexes/foreign keys. |
| `20260526160916_add_ui_texts_and_scientific_terms` | Creates `ui_texts` and `scientific_terms`. |
| `20261013210253_add_admin_modules` | Creates only `competitor_price_logs`, `b2b_leads`, `price_suggestions`, and `sms_campaigns`, with indexes and product foreign keys. It does **not** create legacy approvals, department tasks or audit logs. |
| `20261015000000_add_support_conversations` | Creates support conversations/messages and their foreign keys. |
| `20261020000000_add_blog_freshness_authorship` | Adds three columns to an assumed-existing `blogs` table. No earlier tracked migration creates `blogs`; fresh replay is therefore incomplete before v4. |
| `20261022000000_add_orchestration_v4_core` | Additively creates nine `orchestration_*` tables, indexes and internal foreign keys; it neither creates nor copies legacy governance tables. |
There is no checked-in CREATE TABLE migration for `approval_requests`, `department_tasks`, or `audit_logs`. Their models/controllers are not evidence that either live environment has these tables, nor proof of how any historical database acquired them. The broader missing legacy schema must be reconciled separately. This document does not certify live table existence or migration status.
## Required rollout safeguards (not authorization to deploy)
1. Back up each environment and verify restore capability. Capture its actual schema and `_prisma_migrations` history read-only; compare those independently against all tracked SQL, including prerequisites such as `blogs`.
2. Rehearse the exact planned chain on a disposable database restored from a reviewed baseline. A failed empty replay is a legacy-history gap, not evidence that the additive v4 SQL alone is faulty. Resolve the missing baseline through a separately reviewed migration/baseline plan, never by skipping errors.
3. `prisma migrate resolve --applied <name>` only records history; it creates no objects. Use it only for a specifically verified, fully matching existing migration and reviewed environment-specific plan. Never mark the whole chain applied or mark missing tables as applied.
4. After baseline reconciliation and rehearsal pass, apply reviewed pending migrations through CI/CD only using `prisma migrate deploy`. Verify all nine v4 tables, constraints, migration records and application health before considering the read surface ready.
5. Keep v4 mutations, chat and runtime capabilities denied. Retiring legacy mutation routes does not authorize a replacement execution path.
No deployment, live DDL, baseline resolution or migration SQL change is part of this hardening milestone. Schema rollout remains a separate gate, not full-system completion.
Rollback is application-first: stop use of the new module while retaining append-only records. Do not drop tables in automated rollback; removal requires separately reviewed archival migration.
@@ -0,0 +1,8 @@
CREATE TABLE support_conversations (id UUID NOT NULL, user_id UUID, anonymous_browser_id VARCHAR(64), entry_path VARCHAR(512), product_slugs JSONB, topics JSONB, unanswered BOOLEAN NOT NULL DEFAULT false, needs_followup BOOLEAN NOT NULL DEFAULT false, escalation_signal BOOLEAN NOT NULL DEFAULT false, summary TEXT, summary_status VARCHAR(20) NOT NULL DEFAULT 'pending', created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMPTZ NOT NULL, CONSTRAINT support_conversations_pkey PRIMARY KEY (id));
CREATE TABLE support_conversation_messages (id UUID NOT NULL, conversation_id UUID NOT NULL, role VARCHAR(20) NOT NULL, content TEXT NOT NULL, sequence INTEGER NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT support_conversation_messages_pkey PRIMARY KEY (id));
CREATE UNIQUE INDEX support_conversation_messages_conversation_id_sequence_key ON support_conversation_messages(conversation_id, sequence);
CREATE INDEX support_conversations_user_id_updated_at_idx ON support_conversations(user_id, updated_at);
CREATE INDEX support_conversations_anonymous_browser_id_updated_at_idx ON support_conversations(anonymous_browser_id, updated_at);
CREATE INDEX support_conversation_messages_conversation_id_created_at_idx ON support_conversation_messages(conversation_id, created_at);
ALTER TABLE support_conversations ADD CONSTRAINT support_conversations_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE support_conversation_messages ADD CONSTRAINT support_conversation_messages_conversation_id_fkey FOREIGN KEY (conversation_id) REFERENCES support_conversations(id) ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
@@ -0,0 +1,211 @@
-- CreateTable
CREATE TABLE "orchestration_tasks" (
"id" UUID NOT NULL,
"key" VARCHAR(120) NOT NULL,
"title" VARCHAR(255) NOT NULL,
"department" VARCHAR(50) NOT NULL,
"state" VARCHAR(40) NOT NULL DEFAULT 'DRAFT',
"operation_mode" VARCHAR(30) NOT NULL,
"model_tier" VARCHAR(2),
"budget_limit_cents" INTEGER NOT NULL,
"version" INTEGER NOT NULL DEFAULT 1,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL,
CONSTRAINT "orchestration_tasks_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_runs" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"attempt" INTEGER NOT NULL DEFAULT 1,
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
"commit_sha" VARCHAR(64) NOT NULL,
"environment" VARCHAR(50) NOT NULL,
"retry_class" VARCHAR(30),
"idempotency_key" VARCHAR(150) NOT NULL,
"started_at" TIMESTAMPTZ,
"finished_at" TIMESTAMPTZ,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_runs_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_artifacts" (
"id" UUID NOT NULL,
"run_id" UUID NOT NULL,
"kind" VARCHAR(50) NOT NULL,
"uri" TEXT NOT NULL,
"sha256" CHAR(64) NOT NULL,
"size_bytes" BIGINT,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_artifacts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_attestations" (
"id" UUID NOT NULL,
"run_id" UUID NOT NULL,
"kind" VARCHAR(50) NOT NULL,
"subject_hash" CHAR(64) NOT NULL,
"predicate" JSONB NOT NULL,
"signer" VARCHAR(150) NOT NULL,
"signature" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_attestations_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_dependencies" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"depends_on_task_id" UUID NOT NULL,
"kind" VARCHAR(30) NOT NULL DEFAULT 'BLOCKS',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_dependencies_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_approval_decisions" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"gate" INTEGER NOT NULL,
"decision" VARCHAR(20) NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"notes" TEXT,
"expires_at" TIMESTAMPTZ NOT NULL,
"idempotency_key" VARCHAR(150) NOT NULL,
"run_id" UUID,
"artifact_hash" CHAR(64),
"commit_sha" VARCHAR(64),
"environment" VARCHAR(50),
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_approval_decisions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_events" (
"id" UUID NOT NULL,
"task_id" UUID,
"event_type" VARCHAR(60) NOT NULL,
"from_state" VARCHAR(40),
"to_state" VARCHAR(40),
"sequence" INTEGER NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"idempotency_key" VARCHAR(150),
"payload" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_events_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_budget_ledger" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"amount_cents" INTEGER NOT NULL,
"kind" VARCHAR(40) NOT NULL,
"idempotency_key" VARCHAR(150) NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_budget_ledger_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_kill_switches" (
"scope" VARCHAR(80) NOT NULL,
"level" VARCHAR(30) NOT NULL,
"active" BOOLEAN NOT NULL DEFAULT true,
"reason" TEXT NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"version" INTEGER NOT NULL DEFAULT 1,
"updated_at" TIMESTAMPTZ NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_kill_switches_pkey" PRIMARY KEY ("scope")
);
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_tasks_key_key" ON "orchestration_tasks"("key");
-- CreateIndex
CREATE INDEX "orchestration_tasks_state_created_at_idx" ON "orchestration_tasks"("state", "created_at");
-- CreateIndex
CREATE INDEX "orchestration_tasks_department_state_idx" ON "orchestration_tasks"("department", "state");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_runs_idempotency_key_key" ON "orchestration_runs"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_runs_task_id_status_idx" ON "orchestration_runs"("task_id", "status");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_runs_task_id_attempt_key" ON "orchestration_runs"("task_id", "attempt");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_artifacts_run_id_sha256_key" ON "orchestration_artifacts"("run_id", "sha256");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_attestations_run_id_kind_subject_hash_signer_key" ON "orchestration_attestations"("run_id", "kind", "subject_hash", "signer");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_dependencies_task_id_depends_on_task_id_key" ON "orchestration_dependencies"("task_id", "depends_on_task_id");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_approval_decisions_idempotency_key_key" ON "orchestration_approval_decisions"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_approval_decisions_task_id_gate_created_at_idx" ON "orchestration_approval_decisions"("task_id", "gate", "created_at");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_events_idempotency_key_key" ON "orchestration_events"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_events_event_type_created_at_idx" ON "orchestration_events"("event_type", "created_at");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_events_task_id_sequence_key" ON "orchestration_events"("task_id", "sequence");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_budget_ledger_idempotency_key_key" ON "orchestration_budget_ledger"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_budget_ledger_task_id_created_at_idx" ON "orchestration_budget_ledger"("task_id", "created_at");
-- AddForeignKey
ALTER TABLE "orchestration_runs" ADD CONSTRAINT "orchestration_runs_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_artifacts" ADD CONSTRAINT "orchestration_artifacts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_attestations" ADD CONSTRAINT "orchestration_attestations_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_depends_on_task_id_fkey" FOREIGN KEY ("depends_on_task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_events" ADD CONSTRAINT "orchestration_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_budget_ledger" ADD CONSTRAINT "orchestration_budget_ledger_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,10 @@
-- Immutable evidence and accounting; corrections are new entries.
CREATE FUNCTION orchestration_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Orchestration append-only record cannot be changed'; END;
$$;
CREATE TRIGGER orchestration_budget_immutable BEFORE UPDATE OR DELETE ON orchestration_budget_ledger FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
CREATE TRIGGER orchestration_events_immutable BEFORE UPDATE OR DELETE ON orchestration_events FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
CREATE TRIGGER orchestration_approvals_immutable BEFORE UPDATE OR DELETE ON orchestration_approval_decisions FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
CREATE TRIGGER orchestration_artifacts_immutable BEFORE UPDATE OR DELETE ON orchestration_artifacts FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
CREATE TRIGGER orchestration_attestations_immutable BEFORE UPDATE OR DELETE ON orchestration_attestations FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
ALTER TABLE orchestration_tasks ADD CONSTRAINT orchestration_budget_nonnegative CHECK (budget_limit_cents >= 0);
@@ -0,0 +1,10 @@
CREATE TABLE prepare_workflow_outbox (
id uuid PRIMARY KEY, task_id uuid NOT NULL UNIQUE REFERENCES orchestration_tasks(id) ON DELETE RESTRICT,
status varchar(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','DONE')),
attempts integer NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
lease_owner varchar(100), lease_token uuid, lease_until timestamptz, heartbeat_at timestamptz,
run_id uuid REFERENCES orchestration_runs(id) ON DELETE RESTRICT,
reservation_id uuid REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX prepare_workflow_outbox_status_lease_until_idx ON prepare_workflow_outbox(status,lease_until);
@@ -0,0 +1,3 @@
-- Scheduling is distinct from immutable approval validity. Existing queues run immediately.
ALTER TABLE "prepare_workflow_outbox" ADD COLUMN "not_before" TIMESTAMPTZ;
CREATE INDEX "prepare_workflow_outbox_due_idx" ON "prepare_workflow_outbox" ("status", "not_before", "created_at");
@@ -0,0 +1 @@
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "auth_expires_at" TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS "stage_test_session" VARCHAR(64), ADD COLUMN IF NOT EXISTS "stage_test_generation" UUID;
@@ -0,0 +1,14 @@
-- Drop legacy governance and orchestration tables
DROP TABLE IF EXISTS "prepare_workflow_outbox" CASCADE;
DROP TABLE IF EXISTS "orchestration_kill_switches" CASCADE;
DROP TABLE IF EXISTS "orchestration_budget_ledger" CASCADE;
DROP TABLE IF EXISTS "orchestration_events" CASCADE;
DROP TABLE IF EXISTS "orchestration_approval_decisions" CASCADE;
DROP TABLE IF EXISTS "orchestration_dependencies" CASCADE;
DROP TABLE IF EXISTS "orchestration_attestations" CASCADE;
DROP TABLE IF EXISTS "orchestration_artifacts" CASCADE;
DROP TABLE IF EXISTS "orchestration_runs" CASCADE;
DROP TABLE IF EXISTS "orchestration_tasks" CASCADE;
DROP TABLE IF EXISTS "department_tasks" CASCADE;
DROP TABLE IF EXISTS "audit_logs" CASCADE;
DROP TABLE IF EXISTS "approval_requests" CASCADE;
@@ -0,0 +1,89 @@
-- SEO models existed in schema.prisma without a tracked CREATE migration.
-- Create only missing SEO objects, then additively upgrade existing SEO tables.
-- This does not reconcile the repository's broader incomplete baseline: blogs
-- must already exist (see prisma/MIGRATION_BASELINE.md). No live SQL is run here.
DO $$ BEGIN
CREATE TYPE "ResearchFindingStatus" AS ENUM ('RESEARCHED', 'ACTIONED', 'EVALUATING', 'SCALED', 'PRUNED');
EXCEPTION
WHEN duplicate_object THEN NULL;
END $$;
CREATE TABLE IF NOT EXISTS "content_research_findings" (
"id" UUID NOT NULL,
"title" VARCHAR(255) NOT NULL,
"hypothesis" TEXT NOT NULL,
"target_keywords" TEXT[],
"primary_keyword" VARCHAR(128) NOT NULL,
"expected_outcome" TEXT NOT NULL,
"status" "ResearchFindingStatus" NOT NULL DEFAULT 'RESEARCHED',
"blog_id" UUID,
"ceo_feedback" TEXT,
"feedback_submitted_at" TIMESTAMPTZ,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL,
CONSTRAINT "content_research_findings_pkey" PRIMARY KEY ("id"),
CONSTRAINT "content_research_findings_blog_id_fkey" FOREIGN KEY ("blog_id") REFERENCES "blogs"("id") ON DELETE SET NULL ON UPDATE CASCADE
);
ALTER TABLE "content_research_findings"
ADD COLUMN IF NOT EXISTS "version" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS "feedback_version" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS "search_text" TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS "goal_metric" TEXT,
ADD COLUMN IF NOT EXISTS "goal_target" DOUBLE PRECISION,
ADD COLUMN IF NOT EXISTS "action_id" TEXT;
-- action_id is a plain external reference, deliberately without a foreign key.
CREATE UNIQUE INDEX IF NOT EXISTS "content_research_findings_blog_id_key" ON "content_research_findings"("blog_id");
CREATE INDEX IF NOT EXISTS "content_research_findings_status_idx" ON "content_research_findings"("status");
CREATE INDEX IF NOT EXISTS "content_research_findings_primary_keyword_idx" ON "content_research_findings"("primary_keyword");
CREATE TABLE IF NOT EXISTS "content_performance_snapshots" (
"id" UUID NOT NULL,
"finding_id" UUID NOT NULL,
"snapshot_date" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"gsc_impressions" INTEGER,
"gsc_clicks" INTEGER,
"gsc_position" DOUBLE PRECISION,
"ga4_active_users" INTEGER,
"ga4_avg_engagement_sec" DOUBLE PRECISION,
"ga4_bounce_rate" DOUBLE PRECISION,
"ga4_scroll_depth_rate" DOUBLE PRECISION,
"attributed_orders_count" INTEGER,
"attributed_sales_value" DECIMAL(15,2),
"action_recommendation" VARCHAR(64),
"analysis_notes" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "content_performance_snapshots_pkey" PRIMARY KEY ("id"),
CONSTRAINT "content_performance_snapshots_finding_id_fkey" FOREIGN KEY ("finding_id") REFERENCES "content_research_findings"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
ALTER TABLE "content_performance_snapshots"
ADD COLUMN IF NOT EXISTS "period_start" TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS "period_end" TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS "source_metadata" JSONB,
ADD COLUMN IF NOT EXISTS "ingestion_key" TEXT,
ALTER COLUMN "gsc_impressions" DROP NOT NULL,
ALTER COLUMN "gsc_impressions" DROP DEFAULT,
ALTER COLUMN "gsc_clicks" DROP NOT NULL,
ALTER COLUMN "gsc_clicks" DROP DEFAULT,
ALTER COLUMN "gsc_position" DROP NOT NULL,
ALTER COLUMN "gsc_position" DROP DEFAULT,
ALTER COLUMN "ga4_active_users" DROP NOT NULL,
ALTER COLUMN "ga4_active_users" DROP DEFAULT,
ALTER COLUMN "ga4_avg_engagement_sec" DROP NOT NULL,
ALTER COLUMN "ga4_avg_engagement_sec" DROP DEFAULT,
ALTER COLUMN "ga4_bounce_rate" DROP NOT NULL,
ALTER COLUMN "ga4_bounce_rate" DROP DEFAULT,
ALTER COLUMN "ga4_scroll_depth_rate" DROP NOT NULL,
ALTER COLUMN "ga4_scroll_depth_rate" DROP DEFAULT,
ALTER COLUMN "attributed_orders_count" DROP NOT NULL,
ALTER COLUMN "attributed_orders_count" DROP DEFAULT,
ALTER COLUMN "attributed_sales_value" DROP NOT NULL,
ALTER COLUMN "attributed_sales_value" DROP DEFAULT;
-- Do not rewrite historical metrics: old zeros remain zeros, not proven measures.
-- Newly added metadata/period/key columns remain SQL NULL for legacy snapshots;
-- no provenance, observation period, or idempotency key can be inferred safely.
CREATE INDEX IF NOT EXISTS "content_performance_snapshots_finding_id_snapshot_date_idx" ON "content_performance_snapshots"("finding_id", "snapshot_date");
-- PostgreSQL permits multiple NULL keys, preserving all historical snapshots.
CREATE UNIQUE INDEX IF NOT EXISTS "content_performance_snapshots_finding_id_ingestion_key_key" ON "content_performance_snapshots"("finding_id", "ingestion_key");
@@ -0,0 +1,244 @@
-- CreateEnum
CREATE TYPE "CorporateTaskStatus" AS ENUM ('TODO', 'IN_PROGRESS', 'TEST', 'DONE', 'BLOCKED', 'REJECTED', 'CANCELLED');
-- CreateEnum
CREATE TYPE "CorporatePriority" AS ENUM ('CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW');
-- CreateTable
CREATE TABLE "corporate_tasks" (
"id" UUID NOT NULL,
"taskCode" TEXT NOT NULL,
"title" TEXT NOT NULL,
"normalizedTitle" TEXT NOT NULL,
"normalizedCode" TEXT NOT NULL,
"description" TEXT NOT NULL,
"department" TEXT NOT NULL,
"priority" "CorporatePriority" NOT NULL DEFAULT 'CEO_EXPEDITE',
"status" "CorporateTaskStatus" NOT NULL DEFAULT 'TODO',
"actionType" TEXT NOT NULL DEFAULT 'CEO_DIRECTIVE',
"dueCycle" TEXT,
"parentId" UUID,
"goalId" UUID,
"assignedAgent" TEXT,
"claimToken" UUID,
"leasedUntil" TIMESTAMPTZ,
"executionCount" INTEGER NOT NULL DEFAULT 0,
"qaCount" INTEGER NOT NULL DEFAULT 0,
"rejectionCount" INTEGER NOT NULL DEFAULT 0,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ NOT NULL,
CONSTRAINT "corporate_tasks_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_events" (
"id" UUID NOT NULL,
"taskId" UUID NOT NULL,
"speaker" TEXT NOT NULL,
"speakerName" TEXT NOT NULL,
"step" TEXT NOT NULL,
"content" TEXT NOT NULL,
"payload" JSONB,
"timestamp" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_events_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_evidence" (
"id" UUID NOT NULL,
"taskId" UUID NOT NULL,
"claimToken" UUID NOT NULL,
"executor" TEXT NOT NULL,
"artifactUri" TEXT NOT NULL,
"sha256" TEXT NOT NULL,
"summary" TEXT NOT NULL,
"tool" TEXT NOT NULL,
"result" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_evidence_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_reviews" (
"id" UUID NOT NULL,
"taskId" UUID NOT NULL,
"evidenceId" UUID NOT NULL,
"reviewer" TEXT NOT NULL,
"passed" BOOLEAN NOT NULL,
"findings" TEXT NOT NULL,
"verification" JSONB NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_reviews_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_research" (
"id" UUID NOT NULL,
"title" TEXT NOT NULL,
"category" TEXT NOT NULL,
"source" TEXT NOT NULL,
"opportunity" TEXT NOT NULL,
"impact" TEXT NOT NULL,
"recommendedAction" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'DISCOVERED',
"cadence" TEXT NOT NULL,
"provenance" JSONB NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_research_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_sources" (
"id" UUID NOT NULL,
"researchId" UUID NOT NULL,
"url" TEXT NOT NULL,
"title" TEXT NOT NULL,
"excerpt" TEXT NOT NULL,
"retrievedAt" TIMESTAMPTZ NOT NULL,
"sha256" TEXT NOT NULL,
CONSTRAINT "corporate_sources_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_roadmaps" (
"id" UUID NOT NULL,
"researchId" UUID NOT NULL,
"cycleName" TEXT NOT NULL,
"month" TEXT NOT NULL,
"seasonalTheme" TEXT NOT NULL,
"strategicGoals" TEXT[],
"plannedArticlesCount" INTEGER NOT NULL,
"plannedRefreshesCount" INTEGER NOT NULL,
"plannedCatalogEnrichments" INTEGER NOT NULL,
"isActive" BOOLEAN NOT NULL DEFAULT false,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_roadmaps_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_goals" (
"id" UUID NOT NULL,
"roadmapId" UUID NOT NULL,
"title" TEXT NOT NULL,
"department" TEXT NOT NULL,
"acceptanceCriteria" TEXT NOT NULL,
"metric" TEXT NOT NULL,
"target" DOUBLE PRECISION,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_goals_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_effects" (
"id" UUID NOT NULL,
"taskId" UUID NOT NULL,
"metric" TEXT NOT NULL,
"availability" TEXT NOT NULL,
"baseline" DOUBLE PRECISION,
"observed" DOUBLE PRECISION,
"source" TEXT NOT NULL,
"observedAt" TIMESTAMPTZ NOT NULL,
"recordedBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_effects_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_reports" (
"id" UUID NOT NULL,
"day" TEXT NOT NULL,
"summary" TEXT NOT NULL,
"snapshot" JSONB NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_reports_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_operations" (
"key" TEXT NOT NULL,
"payloadHash" TEXT NOT NULL,
"response" JSONB NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_operations_pkey" PRIMARY KEY ("key")
);
-- CreateIndex
CREATE UNIQUE INDEX "corporate_tasks_taskCode_key" ON "corporate_tasks"("taskCode");
-- CreateIndex
CREATE INDEX "corporate_tasks_status_priority_updatedAt_idx" ON "corporate_tasks"("status", "priority", "updatedAt");
-- CreateIndex
CREATE INDEX "corporate_tasks_parentId_idx" ON "corporate_tasks"("parentId");
-- CreateIndex
CREATE INDEX "corporate_tasks_goalId_idx" ON "corporate_tasks"("goalId");
-- CreateIndex
CREATE INDEX "corporate_events_taskId_timestamp_idx" ON "corporate_events"("taskId", "timestamp");
-- CreateIndex
CREATE INDEX "corporate_evidence_taskId_idx" ON "corporate_evidence"("taskId");
-- CreateIndex
CREATE INDEX "corporate_reviews_taskId_idx" ON "corporate_reviews"("taskId");
-- CreateIndex
CREATE INDEX "corporate_sources_researchId_idx" ON "corporate_sources"("researchId");
-- CreateIndex
CREATE INDEX "corporate_roadmaps_month_idx" ON "corporate_roadmaps"("month");
-- CreateIndex
CREATE INDEX "corporate_goals_roadmapId_idx" ON "corporate_goals"("roadmapId");
-- CreateIndex
CREATE INDEX "corporate_effects_taskId_idx" ON "corporate_effects"("taskId");
-- CreateIndex
CREATE UNIQUE INDEX "corporate_reports_day_key" ON "corporate_reports"("day");
-- AddForeignKey
ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "corporate_tasks"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_goalId_fkey" FOREIGN KEY ("goalId") REFERENCES "corporate_goals"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_events" ADD CONSTRAINT "corporate_events_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_evidence" ADD CONSTRAINT "corporate_evidence_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_evidenceId_fkey" FOREIGN KEY ("evidenceId") REFERENCES "corporate_evidence"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_sources" ADD CONSTRAINT "corporate_sources_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_roadmaps" ADD CONSTRAINT "corporate_roadmaps_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_goals" ADD CONSTRAINT "corporate_goals_roadmapId_fkey" FOREIGN KEY ("roadmapId") REFERENCES "corporate_roadmaps"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_effects" ADD CONSTRAINT "corporate_effects_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,22 @@
-- Reviewed attribution-only storage; no business data or historical ledger writes.
DO $$ BEGIN
IF current_database() NOT IN ('caninodb_stage', 'rehearsal') THEN
RAISE EXCEPTION 'public author bootstrap is Stage-only';
END IF;
END $$;
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS is_public_author BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE public.users ALTER COLUMN is_public_author SET NOT NULL;
ALTER TABLE public.users ALTER COLUMN is_public_author SET DEFAULT false;
ALTER TABLE public.users ALTER COLUMN mobile DROP NOT NULL;
-- Repeated application is transactional and revalidates every existing row.
ALTER TABLE public.users DROP CONSTRAINT IF EXISTS users_public_author_identity_check;
ALTER TABLE public.users ADD CONSTRAINT users_public_author_identity_check CHECK (
(is_public_author = false AND mobile IS NOT NULL)
OR
(is_public_author = true
AND mobile IS NULL AND email IS NULL AND password IS NULL
AND role = 'User_PetOwner'
AND auth_expires_at IS NULL
AND stage_test_generation IS NULL AND stage_test_session IS NULL
AND wallet_balance = 0 AND charity_donation_total = 0)
);
+314 -67
View File
@@ -1,3 +1,202 @@
enum CorporateTaskStatus {
TODO
IN_PROGRESS
TEST
DONE
BLOCKED
REJECTED
CANCELLED
}
enum CorporatePriority {
CEO_EXPEDITE
CRITICAL
HIGH
MEDIUM
LOW
}
model CorporateTask {
id String @id @default(uuid()) @db.Uuid
taskCode String @unique
title String
normalizedTitle String
normalizedCode String
description String
department String
priority CorporatePriority @default(CEO_EXPEDITE)
status CorporateTaskStatus @default(TODO)
actionType String @default("CEO_DIRECTIVE")
dueCycle String?
parentId String? @db.Uuid
parent CorporateTask? @relation("TaskChildren", fields: [parentId], references: [id])
children CorporateTask[] @relation("TaskChildren")
goalId String? @db.Uuid
goal CorporateGoal? @relation(fields: [goalId], references: [id])
assignedAgent String?
claimToken String? @db.Uuid
leasedUntil DateTime? @db.Timestamptz()
executionCount Int @default(0)
qaCount Int @default(0)
rejectionCount Int @default(0)
createdBy String
createdAt DateTime @default(now()) @db.Timestamptz()
updatedAt DateTime @updatedAt @db.Timestamptz()
logs CorporateEvent[]
evidence CorporateEvidence[]
reviews CorporateReview[]
effects CorporateEffect[]
@@index([status, priority, updatedAt])
@@index([parentId])
@@index([goalId])
@@map("corporate_tasks")
}
model CorporateEvent {
id String @id @default(uuid()) @db.Uuid
taskId String @db.Uuid
task CorporateTask @relation(fields: [taskId], references: [id])
speaker String
speakerName String
step String
content String
payload Json?
timestamp DateTime @default(now()) @db.Timestamptz()
@@index([taskId, timestamp])
@@map("corporate_events")
}
model CorporateEvidence {
id String @id @default(uuid()) @db.Uuid
taskId String @db.Uuid
task CorporateTask @relation(fields: [taskId], references: [id])
claimToken String @db.Uuid
executor String
artifactUri String
sha256 String
summary String
tool String
result String
createdAt DateTime @default(now()) @db.Timestamptz()
reviews CorporateReview[]
@@index([taskId])
@@map("corporate_evidence")
}
model CorporateReview {
id String @id @default(uuid()) @db.Uuid
taskId String @db.Uuid
task CorporateTask @relation(fields: [taskId], references: [id])
evidenceId String @db.Uuid
evidence CorporateEvidence @relation(fields: [evidenceId], references: [id])
reviewer String
passed Boolean
findings String
verification Json
createdAt DateTime @default(now()) @db.Timestamptz()
@@index([taskId])
@@map("corporate_reviews")
}
model CorporateResearch {
id String @id @default(uuid()) @db.Uuid
title String
category String
source String
opportunity String
impact String
recommendedAction String
status String @default("DISCOVERED")
cadence String
provenance Json
createdBy String
createdAt DateTime @default(now()) @db.Timestamptz()
sources CorporateSource[]
roadmaps CorporateRoadmap[]
@@map("corporate_research")
}
model CorporateSource {
id String @id @default(uuid()) @db.Uuid
researchId String @db.Uuid
research CorporateResearch @relation(fields: [researchId], references: [id])
url String
title String
excerpt String
retrievedAt DateTime @db.Timestamptz()
sha256 String
@@index([researchId])
@@map("corporate_sources")
}
model CorporateRoadmap {
id String @id @default(uuid()) @db.Uuid
researchId String @db.Uuid
research CorporateResearch @relation(fields: [researchId], references: [id])
cycleName String
month String
seasonalTheme String
strategicGoals String[]
plannedArticlesCount Int
plannedRefreshesCount Int
plannedCatalogEnrichments Int
isActive Boolean @default(false)
createdBy String
createdAt DateTime @default(now()) @db.Timestamptz()
goals CorporateGoal[]
@@index([month])
@@map("corporate_roadmaps")
}
model CorporateGoal {
id String @id @default(uuid()) @db.Uuid
roadmapId String @db.Uuid
roadmap CorporateRoadmap @relation(fields: [roadmapId], references: [id])
title String
department String
acceptanceCriteria String
metric String
target Float?
createdAt DateTime @default(now()) @db.Timestamptz()
tasks CorporateTask[]
@@index([roadmapId])
@@map("corporate_goals")
}
model CorporateEffect {
id String @id @default(uuid()) @db.Uuid
taskId String @db.Uuid
task CorporateTask @relation(fields: [taskId], references: [id])
metric String
availability String
baseline Float?
observed Float?
source String
observedAt DateTime @db.Timestamptz()
recordedBy String
createdAt DateTime @default(now()) @db.Timestamptz()
@@index([taskId])
@@map("corporate_effects")
}
model CorporateReport {
id String @id @default(uuid()) @db.Uuid
day String @unique
summary String
snapshot Json
createdBy String
createdAt DateTime @default(now()) @db.Timestamptz()
@@map("corporate_reports")
}
model CorporateOperation {
key String @id
payloadHash String
response Json
createdAt DateTime @default(now()) @db.Timestamptz()
@@map("corporate_operations")
}
generator client { generator client {
provider = "prisma-client-js" provider = "prisma-client-js"
binaryTargets = ["native", "linux-musl-openssl-3.0.x"] binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
@@ -13,9 +212,13 @@ model User {
firstName String @map("first_name") @db.VarChar(100) firstName String @map("first_name") @db.VarChar(100)
lastName String @map("last_name") @db.VarChar(100) lastName String @map("last_name") @db.VarChar(100)
email String? @unique @db.VarChar(150) email String? @unique @db.VarChar(150)
mobile String @unique @db.VarChar(15) mobile String? @unique @db.VarChar(15)
isPublicAuthor Boolean @default(false) @map("is_public_author")
password String? @db.VarChar(255) password String? @db.VarChar(255)
role String @default("User_PetOwner") @db.VarChar(30) role String @default("User_PetOwner") @db.VarChar(30)
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
stageTestGeneration String? @map("stage_test_generation") @db.Uuid
stageTestSession String? @map("stage_test_session") @db.VarChar(64)
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2) walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2) charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
@@ -32,12 +235,49 @@ model User {
tickets Ticket[] tickets Ticket[]
reviews ProductReview[] reviews ProductReview[]
blogComments BlogComment[] blogComments BlogComment[]
supportConversations SupportConversation[]
@@index([role]) @@index([role])
@@index([createdAt]) @@index([createdAt])
@@map("users") @@map("users")
} }
model SupportConversation {
id String @id @default(uuid()) @db.Uuid
userId String? @map("user_id") @db.Uuid
anonymousBrowserId String? @map("anonymous_browser_id") @db.VarChar(64)
entryPath String? @map("entry_path") @db.VarChar(512)
productSlugs Json? @map("product_slugs")
topics Json?
unanswered Boolean @default(false)
needsFollowup Boolean @default(false) @map("needs_followup")
escalationSignal Boolean @default(false) @map("escalation_signal")
summary String? @db.Text
summaryStatus String @default("pending") @map("summary_status") @db.VarChar(20)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
expiresAt DateTime @map("expires_at") @db.Timestamptz()
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
messages SupportConversationMessage[]
@@index([userId, updatedAt])
@@index([anonymousBrowserId, updatedAt])
@@map("support_conversations")
}
model SupportConversationMessage {
id String @id @default(uuid()) @db.Uuid
conversationId String @map("conversation_id") @db.Uuid
role String @db.VarChar(20)
content String @db.Text
sequence Int
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
conversation SupportConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
@@unique([conversationId, sequence])
@@index([conversationId, createdAt])
@@map("support_conversation_messages")
}
model UserAddress { model UserAddress {
id String @id @default(uuid()) @db.Uuid id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid userId String @map("user_id") @db.Uuid
@@ -141,7 +381,9 @@ model Blog {
slug String @unique @db.VarChar(200) slug String @unique @db.VarChar(200)
content String @db.Text content String @db.Text
excerpt String? @db.Text excerpt String? @db.Text
authorId String @map("author_id") @db.Uuid authorId String? @map("author_id") @db.Uuid
authorTeam String? @map("author_team") @db.VarChar(200)
authorRole String? @map("author_role") @db.VarChar(200)
categoryId String? @map("category_id") @db.Uuid categoryId String? @map("category_id") @db.Uuid
imageUrl String? @map("image_url") @db.Text imageUrl String? @map("image_url") @db.Text
imageAlt String? @map("image_alt") @db.VarChar(255) imageAlt String? @map("image_alt") @db.VarChar(255)
@@ -161,6 +403,7 @@ model Blog {
isPublished Boolean @default(true) @map("is_published") isPublished Boolean @default(true) @map("is_published")
publishedAt DateTime? @map("published_at") @db.Timestamptz() publishedAt DateTime? @map("published_at") @db.Timestamptz()
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz() scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
readingTime Int @default(3) @map("reading_time") readingTime Int @default(3) @map("reading_time")
featured Boolean @default(false) featured Boolean @default(false)
allowComments Boolean @default(true) @map("allow_comments") allowComments Boolean @default(true) @map("allow_comments")
@@ -172,10 +415,11 @@ model Blog {
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
author User @relation(fields: [authorId], references: [id]) author User? @relation(fields: [authorId], references: [id])
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull) category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
tags BlogTag[] tags BlogTag[]
comments BlogComment[] comments BlogComment[]
researchFinding ContentResearchFinding?
@@index([categoryId]) @@index([categoryId])
@@index([status]) @@index([status])
@@ -978,76 +1222,79 @@ model SmsCampaign {
} }
// ------------------------------------------------------------------------------ // ------------------------------------------------------------------------------
// 5. ApprovalRequest (CEO Governance & Decision Gate) // 5. SEO & Performance Tracking Models
// ------------------------------------------------------------------------------ // ------------------------------------------------------------------------------
model ApprovalRequest { enum ResearchFindingStatus {
id String @id @default(uuid()) @db.Uuid RESEARCHED
department String @db.VarChar(50) ACTIONED
category String @db.VarChar(50) EVALUATING
title String @db.VarChar(255) SCALED
payload Json @db.JsonB PRUNED
testContext Json? @map("test_context") @db.JsonB }
status String @default("PENDING") @db.VarChar(30)
ceoNotes String? @map("ceo_notes") @db.Text model ContentResearchFinding {
executedAt DateTime? @map("executed_at") @db.Timestamptz() id String @id @default(uuid()) @db.Uuid
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() title String @db.VarChar(255)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() hypothesis String @db.Text
targetKeywords String[] @map("target_keywords")
primaryKeyword String @map("primary_keyword") @db.VarChar(128)
expectedOutcome String @map("expected_outcome") @db.Text
status ResearchFindingStatus @default(RESEARCHED)
version Int @default(0)
feedbackVersion Int @default(0) @map("feedback_version")
searchText String @default("") @map("search_text") @db.Text
goalMetric String? @map("goal_metric")
goalTarget Float? @map("goal_target")
// External action reference only; no orchestration relation or foreign key.
actionId String? @map("action_id")
blogId String? @unique @map("blog_id") @db.Uuid
blog Blog? @relation(fields: [blogId], references: [id], onDelete: SetNull)
ceoFeedback String? @map("ceo_feedback") @db.Text
feedbackSubmittedAt DateTime? @map("feedback_submitted_at") @db.Timestamptz()
snapshots ContentPerformanceSnapshot[]
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
@@index([department])
@@index([category])
@@index([status]) @@index([status])
@@index([createdAt]) @@index([primaryKeyword])
@@map("approval_requests") @@map("content_research_findings")
} }
model ContentPerformanceSnapshot {
id String @id @default(uuid()) @db.Uuid
findingId String @map("finding_id") @db.Uuid
finding ContentResearchFinding @relation(fields: [findingId], references: [id], onDelete: Cascade)
// ------------------------------------------------------------------------------ snapshotDate DateTime @default(now()) @map("snapshot_date") @db.Timestamptz()
// 6. AuditLog (System & Database Changes History)
// ------------------------------------------------------------------------------
model AuditLog {
id String @id @default(uuid()) @db.Uuid
entity String @db.VarChar(50) // e.g. product, blog, order, approval, settings
entityId String? @map("entity_id") @db.VarChar(100)
action String @db.VarChar(50) // CREATE, UPDATE, DELETE, EXECUTE, APPROVE, REJECT
department String? @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
actor String @default("SYSTEM") @db.VarChar(100)
summary String @db.VarChar(255)
oldValues Json? @map("old_values") @db.JsonB
newValues Json? @map("new_values") @db.JsonB
metadata Json? @db.JsonB
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
@@index([entity]) periodStart DateTime? @map("period_start") @db.Timestamptz()
@@index([action]) periodEnd DateTime? @map("period_end") @db.Timestamptz()
@@index([department]) sourceMetadata Json? @map("source_metadata")
@@index([createdAt]) ingestionKey String? @map("ingestion_key")
@@map("audit_logs")
gscImpressions Int? @map("gsc_impressions")
gscClicks Int? @map("gsc_clicks")
gscPosition Float? @map("gsc_position")
ga4ActiveUsers Int? @map("ga4_active_users")
ga4AvgEngagementSec Float? @map("ga4_avg_engagement_sec")
ga4BounceRate Float? @map("ga4_bounce_rate")
ga4ScrollDepthRate Float? @map("ga4_scroll_depth_rate")
attributedOrdersCount Int? @map("attributed_orders_count")
attributedSalesValue Decimal? @map("attributed_sales_value") @db.Decimal(15, 2)
actionRecommendation String? @map("action_recommendation") @db.VarChar(64)
analysisNotes String? @map("analysis_notes") @db.Text
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
@@index([findingId, snapshotDate])
@@unique([findingId, ingestionKey])
@@map("content_performance_snapshots")
} }
// ------------------------------------------------------------------------------
// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager)
// ------------------------------------------------------------------------------
model DepartmentTask {
id String @id @default(uuid()) @db.Uuid
code String @unique @db.VarChar(50)
department String @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
title String @db.VarChar(255)
description String? @db.Text
status String @default("BACKLOG") @db.VarChar(30) // BACKLOG, IN_PROGRESS, IN_REVIEW, APPROVED, DEPLOYING, DONE
priority String @default("MEDIUM") @db.VarChar(20) // LOW, MEDIUM, HIGH, CRITICAL
assignee String? @db.VarChar(100)
acceptanceCriteria Json? @map("acceptance_criteria") @db.JsonB
executionLogs Json? @map("execution_logs") @db.JsonB
deliverableUrl String? @map("deliverable_url") @db.VarChar(255)
approvalId String? @map("approval_id") @db.Uuid
startedAt DateTime? @map("started_at") @db.Timestamptz()
completedAt DateTime? @map("completed_at") @db.Timestamptz()
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
@@index([department])
@@index([status])
@@index([priority])
@@index([createdAt])
@@map("department_tasks")
}
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Run backend tests against freshly initialized, disposable PostgreSQL only.
Requires Python 3, installed backend dependencies, and PostgreSQL 16+ binaries
(initdb, pg_ctl, postgres) on PATH or in PG_BIN. Never reuses a running database.
Stage-principal /app + Redis integration tests remain separately opt-in.
"""
import os
from pathlib import Path
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
BACKEND = Path(__file__).resolve().parents[1]
def run(args, env=None):
subprocess.run([str(a) for a in args], cwd=BACKEND, env=env, check=True)
def binary(name):
candidate = str(Path(os.environ['PG_BIN']) / name) if os.environ.get('PG_BIN') else shutil.which(name)
if not candidate or not os.access(candidate, os.X_OK):
raise RuntimeError(f'{name} unavailable: install PostgreSQL binaries or set PG_BIN; integration tests cannot be skipped')
return candidate
def interrupted(signum, _frame):
raise SystemExit(128 + signum)
def main():
initdb, pg_ctl = binary('initdb'), binary('pg_ctl')
binary('postgres')
if os.geteuid() == 0:
raise RuntimeError('Run disposable PostgreSQL tests as a non-root user')
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, interrupted)
env = os.environ.copy()
# Do not propagate operational database URLs to Prisma schema setup or tests.
for key in list(env):
if key.endswith('DATABASE_URL'):
del env[key]
env.pop('STAGE_PRINCIPAL_DISPOSABLE_TEST', None)
env['DATABASE_URL'] = 'postgresql://disabled@127.0.0.1:1/disabled'
definitions = [
('SEO_TEST_DATABASE_URL', 'seo_test', 55439, 'postgres', ''),
# Keep the existing publication fixture's literal URL allowlist intact.
('PUBLICATION_TEST_DATABASE_URL', 'publication_test', 55447, 'publication_test', None),
('CORPORATE_TEST_DATABASE_URL', 'corporate_test', 55449, 'corporate_test', ''),
]
# Refuse occupied dedicated ports before creating any cluster. PostgreSQL's
# own bind still protects against races; no existing server is ever stopped.
for _, _, port, _, _ in definitions:
with socket.socket() as probe:
probe.bind(('127.0.0.1', port))
started = []
with tempfile.TemporaryDirectory(prefix='backend-pg-', dir=os.environ.get('TMPDIR', '/opt/data/cache/scratch')) as root:
try:
for key, user, port, database, password in definitions:
data = Path(root) / str(port)
unix_socket = Path(root) / f's{port}'
unix_socket.mkdir(mode=0o700)
run([initdb, '-D', data, '-U', user, '--auth=trust', '--no-locale', '--encoding=UTF8'])
# Track our initialized directory before startup, so even an
# interrupted pg_ctl start is cleaned up, never another server.
started.append(data)
run([pg_ctl, '-D', data, '-l', Path(root) / f'{port}.log', '-w', '-t', '30',
'-o', f'-h 127.0.0.1 -p {port} -k {unix_socket}', 'start'])
if password is None:
# The fixture owns its dedicated test-only credential prefix;
# read that literal rather than duplicate or log it here.
import re
fixture = (BACKEND / 'src/seo-tracking/publication.postgres.spec.ts').read_text()
match = re.search(r"url\.startsWith\('([^']+)'\)", fixture)
if not match:
raise RuntimeError('Publication disposable URL allowlist not found')
from urllib.parse import urlsplit
prefix = match.group(1)
parsed = urlsplit(prefix)
if parsed.hostname != '127.0.0.1' or parsed.port != port or parsed.username != user or parsed.path != '/':
raise RuntimeError('Publication allowlist is not the dedicated disposable endpoint')
url = prefix + database
else:
url = f'postgresql://{user}{password}@127.0.0.1:{port}/{database}'
if database != 'postgres':
setup = {**env, 'DATABASE_URL': url.rsplit('/', 1)[0] + '/postgres'}
run(['node', '-e', 'const {PrismaClient}=require("@prisma/client"); const p=new PrismaClient(); '
f'p.$executeRawUnsafe(\'CREATE DATABASE "{database}"\')'
'.finally(()=>p.$disconnect()).catch(e=>{console.error(e);process.exitCode=1})'], setup)
run([BACKEND / 'node_modules/.bin/prisma', 'db', 'push', '--skip-generate'], {**env, 'DATABASE_URL': url})
env[key] = url
print('Disposable PostgreSQL ready: SEO, publication and corporate integration enabled; '
'Stage-principal Redis+/app suites remain explicitly out of scope.', flush=True)
run([BACKEND / 'node_modules/.bin/jest', '--runInBand', *sys.argv[1:]], env)
finally:
failures = []
for data in reversed(started):
result = subprocess.run([pg_ctl, '-D', str(data), '-m', 'immediate', '-w', '-t', '30', 'stop'], cwd=BACKEND)
if result.returncode and (data / 'postmaster.pid').exists():
failures.append(str(data))
if failures:
raise RuntimeError(f'Failed to stop disposable clusters: {failures}')
if __name__ == '__main__':
try:
main()
except (RuntimeError, OSError, subprocess.CalledProcessError) as error:
print(f'Backend PostgreSQL test gate failed: {error}', file=sys.stderr)
sys.exit(1)
@@ -0,0 +1,7 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand api-keys.integration.spec
Test Suites: 1 passed, 1 total
Tests: 5 passed, 5 total
Snapshots: 0 total
Time: 4.044 s
Ran all test suites matching api-keys.integration.spec.
@@ -0,0 +1,104 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand api-keys.integration.spec
FAIL src/admin/api-keys.integration.spec.ts
● human-only key administration / real key authentication and PostgreSQL › denies get to authenticated admin API key without mutating keys
expected 403 "Forbidden", got 200 "OK"
34 | const before = await db.apiKey.count();
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
| ^
37 | expect(await db.apiKey.count()).toBe(before);
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
39 | });
at admin/api-keys.integration.spec.ts:36:174
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
● human-only key administration / real key authentication and PostgreSQL › denies post to authenticated admin API key without mutating keys
expected 403 "Forbidden", got 201 "Created"
34 | const before = await db.apiKey.count();
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
| ^
37 | expect(await db.apiKey.count()).toBe(before);
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
39 | });
at admin/api-keys.integration.spec.ts:36:174
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
● human-only key administration / real key authentication and PostgreSQL › denies patch to authenticated admin API key without mutating keys
expected 403 "Forbidden", got 200 "OK"
34 | const before = await db.apiKey.count();
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
| ^
37 | expect(await db.apiKey.count()).toBe(before);
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
39 | });
at admin/api-keys.integration.spec.ts:36:174
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
● human-only key administration / real key authentication and PostgreSQL › denies delete to authenticated admin API key without mutating keys
expected 403 "Forbidden", got 200 "OK"
34 | const before = await db.apiKey.count();
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
| ^
37 | expect(await db.apiKey.count()).toBe(before);
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
39 | });
at admin/api-keys.integration.spec.ts:36:174
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
Test Suites: 1 failed, 1 total
Tests: 4 failed, 1 passed, 5 total
Snapshots: 0 total
Time: 3.608 s
Ran all test suites matching api-keys.integration.spec.
@@ -0,0 +1,207 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand
[Nest] 3987292 - 10/28/2026, 12:44:07 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed
[Nest] 3987292 - 10/28/2026, 12:44:07 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed
[Nest] 3987292 - 10/28/2026, 12:44:22 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: aborted
[Nest] 3987292 - 10/28/2026, 12:44:07 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: Zibal EBank HTTP 503
[Nest] 3987292 - 10/28/2026, 12:44:08 PM  ERROR [SslService] Failed to parse SSL certificate
[Nest] 3987292 - 10/28/2026, 12:44:08 PM  ERROR [SslService] Error: error:0480006C:PEM routines::no start line
 at new X509Certificate (node:internal/crypto/x509:121:21)
at SslService.getStatus (/opt/data/cache/scratch/corporate-hardening-base/backend/src/admin/ssl.service.ts:104:20)
at Object.<anonymous> (/opt/data/cache/scratch/corporate-hardening-base/backend/src/admin/ssl.service.spec.ts:179:30)
at Promise.finally.completed (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1561:28)
at new Promise (<anonymous>)
at callAsyncCircusFn (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1501:10)
at _callCircusTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1011:40)
at _runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:951:3)
at /opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:853:7
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:866:11)
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:861:11)
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:861:11)
at run (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:765:3)
at runAndTransformResultsToJestFormat (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1993:21)
at jestAdapter (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/runner.js:111:19)
at runTestInternal (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-runner/build/index.js:276:16)
at runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-runner/build/index.js:344:7) {
library: 'PEM routines',
reason: 'no start line',
code: 'ERR_OSSL_PEM_NO_START_LINE'
}
[Nest] 3987292 - 10/28/2026, 12:44:12 PM  ERROR [PaymentService] Security Alert: Amount mismatch on trackId=tr-1! Zibal reported 1000000 Rials, but expected 5000000 Rials in DB.
FAIL src/seo-tracking/publication.postgres.spec.ts
● Test suite failed to run
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
It should have this form: { url: "CONNECTION_STRING" }
Read more at https://pris.ly/d/client-constructor
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
| ^
23 | let user: any;
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
25 | const service = new SeoTrackingService(db as any, cache as any);
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
at seo-tracking/publication.postgres.spec.ts:22:14
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
[Nest] 3987292 - 10/28/2026, 12:44:18 PM  WARN [BlogsService] Cache revalidation failed for updated blog [post]: cache down
FAIL src/wiki/wiki.service.spec.ts
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
@@ -1,21 +1,39 @@
Object {
"orderBy": Object {
"term": "desc",
},
- "skip": 0,
- "take": 10,
+ "skip": undefined,
+ "take": 100,
"where": Object {
"OR": Array [
Object {
"term": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
Object {
+ "key": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
"definition": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "term": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "key": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
],,
Number of calls: 1
56 | });
57 |
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
| ^
59 | where: {
60 | OR: [
61 | { term: { contains: "مفصل", mode: "insensitive" } },
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
Summary of all failing tests
FAIL seo-tracking/publication.postgres.spec.ts
● Test suite failed to run
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
It should have this form: { url: "CONNECTION_STRING" }
Read more at https://pris.ly/d/client-constructor
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
| ^
23 | let user: any;
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
25 | const service = new SeoTrackingService(db as any, cache as any);
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
at seo-tracking/publication.postgres.spec.ts:22:14
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
FAIL wiki/wiki.service.spec.ts
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
@@ -1,21 +1,39 @@
Object {
"orderBy": Object {
"term": "desc",
},
- "skip": 0,
- "take": 10,
+ "skip": undefined,
+ "take": 100,
"where": Object {
"OR": Array [
Object {
"term": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
Object {
+ "key": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
"definition": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "term": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "key": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
],,
Number of calls: 1
56 | });
57 |
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
| ^
59 | where: {
60 | OR: [
61 | { term: { contains: "مفصل", mode: "insensitive" } },
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
Test Suites: 2 failed, 5 skipped, 95 passed, 97 of 102 total
Tests: 1 failed, 13 skipped, 818 passed, 832 total
Snapshots: 0 total
Time: 55.893 s
Ran all test suites.
@@ -0,0 +1,44 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t bounds detail|oversized
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › bounds detail relations and report snapshots with explicit truncation and immutable replay
expect(received).toHaveLength(expected)
Expected length: 100
Received length: 106
Received array: [[Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], …]
153 | await db.corporateEvent.createMany({ data: Array.from({ length: 105 }, () => ({ taskId: task.id, speaker: 'SYSTEM', speakerName: 'fixture', step: 'FIXTURE', content: 'x'.repeat(10000), payload: { nested: ['x'.repeat(10000)] } })) });
154 | const detail = await request(app.getHttpServer()).get('/admin/hermes/tasks/' + task.id).set('x-api-key', 'executor').expect(200);
> 155 | expect(detail.body.logs).toHaveLength(100);
| ^
156 | expect(detail.body.relationsMeta.logs).toEqual({ total: 106, returned: 100, limit: 100, truncated: true });
157 | const op = key(), body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
158 | const report = (await post('reports', body, 'executor', op).expect(201)).body;
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:155:30)
● corporate API / disposable PostgreSQL › rolls back oversized mutation responses instead of persisting huge idempotency values
expect(received).rejects.toThrow()
Received promise resolved instead of rejected
Resolved to value: {"value": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
168 | const service = app.get(CorporateService) as any;
169 | const before = await db.corporateTask.count();
> 170 | await expect(service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
| ^
171 | await tx.corporateTask.create({ data: { title: 'rollback', description: 'fixture', taskCode: key(), normalizedTitle: 'rollback', normalizedCode: key(), department: 'CONTENT_SEO', createdBy: 'fixture' } });
172 | return { value: 'x'.repeat(1100000) };
173 | })).rejects.toThrow('Operation response exceeds limit');
at expect (../../../corporate-backend/backend/node_modules/expect/build/index.js:2116:15)
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:170:11)
Test Suites: 1 failed, 1 total
Tests: 2 failed, 10 skipped, 12 total
Snapshots: 0 total
Time: 4.583 s
Ran all test suites matching corporate.integration.spec with tests matching "bounds detail|oversized".
@@ -0,0 +1,2 @@
npm notice run backend@0.0.1 build
npm notice run tsc -b
@@ -0,0 +1,8 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec corporate-policy.spec api-keys.integration.spec
Test Suites: 3 passed, 3 total
Tests: 20 passed, 20 total
Snapshots: 0 total
Time: 9.263 s
Ran all test suites matching corporate.integration.spec|corporate-policy.spec|api-keys.integration.spec.
@@ -0,0 +1,207 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand
[Nest] 3985069 - 10/28/2026, 12:42:14 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed
[Nest] 3985069 - 10/28/2026, 12:42:14 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed
[Nest] 3985069 - 10/28/2026, 12:42:29 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: aborted
[Nest] 3985069 - 10/28/2026, 12:42:14 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: Zibal EBank HTTP 503
[Nest] 3985069 - 10/28/2026, 12:42:15 PM  ERROR [SslService] Failed to parse SSL certificate
[Nest] 3985069 - 10/28/2026, 12:42:15 PM  ERROR [SslService] Error: error:0480006C:PEM routines::no start line
 at new X509Certificate (node:internal/crypto/x509:121:21)
at SslService.getStatus (/opt/data/cache/scratch/corporate-hardening/backend/src/admin/ssl.service.ts:104:20)
at Object.<anonymous> (/opt/data/cache/scratch/corporate-hardening/backend/src/admin/ssl.service.spec.ts:179:30)
at Promise.finally.completed (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1561:28)
at new Promise (<anonymous>)
at callAsyncCircusFn (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1501:10)
at _callCircusTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1011:40)
at _runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:951:3)
at /opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:853:7
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:866:11)
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:861:11)
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:861:11)
at run (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:765:3)
at runAndTransformResultsToJestFormat (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1993:21)
at jestAdapter (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/runner.js:111:19)
at runTestInternal (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-runner/build/index.js:276:16)
at runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-runner/build/index.js:344:7) {
library: 'PEM routines',
reason: 'no start line',
code: 'ERR_OSSL_PEM_NO_START_LINE'
}
[Nest] 3985069 - 10/28/2026, 12:42:19 PM  ERROR [PaymentService] Security Alert: Amount mismatch on trackId=tr-1! Zibal reported 1000000 Rials, but expected 5000000 Rials in DB.
FAIL src/seo-tracking/publication.postgres.spec.ts
● Test suite failed to run
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
It should have this form: { url: "CONNECTION_STRING" }
Read more at https://pris.ly/d/client-constructor
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
| ^
23 | let user: any;
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
25 | const service = new SeoTrackingService(db as any, cache as any);
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
at seo-tracking/publication.postgres.spec.ts:22:14
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
[Nest] 3985069 - 10/28/2026, 12:42:26 PM  WARN [BlogsService] Cache revalidation failed for updated blog [post]: cache down
FAIL src/wiki/wiki.service.spec.ts
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
@@ -1,21 +1,39 @@
Object {
"orderBy": Object {
"term": "desc",
},
- "skip": 0,
- "take": 10,
+ "skip": undefined,
+ "take": 100,
"where": Object {
"OR": Array [
Object {
"term": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
Object {
+ "key": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
"definition": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "term": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "key": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
],,
Number of calls: 1
56 | });
57 |
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
| ^
59 | where: {
60 | OR: [
61 | { term: { contains: "مفصل", mode: "insensitive" } },
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
Summary of all failing tests
FAIL seo-tracking/publication.postgres.spec.ts
● Test suite failed to run
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
It should have this form: { url: "CONNECTION_STRING" }
Read more at https://pris.ly/d/client-constructor
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
| ^
23 | let user: any;
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
25 | const service = new SeoTrackingService(db as any, cache as any);
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
at seo-tracking/publication.postgres.spec.ts:22:14
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
FAIL wiki/wiki.service.spec.ts
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
@@ -1,21 +1,39 @@
Object {
"orderBy": Object {
"term": "desc",
},
- "skip": 0,
- "take": 10,
+ "skip": undefined,
+ "take": 100,
"where": Object {
"OR": Array [
Object {
"term": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
Object {
+ "key": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
"definition": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "term": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "key": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
],,
Number of calls: 1
56 | });
57 |
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
| ^
59 | where: {
60 | OR: [
61 | { term: { contains: "مفصل", mode: "insensitive" } },
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
Test Suites: 2 failed, 6 skipped, 95 passed, 97 of 103 total
Tests: 1 failed, 25 skipped, 818 passed, 844 total
Snapshots: 0 total
Time: 56.587 s
Ran all test suites.
@@ -0,0 +1,7 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec
Test Suites: 1 passed, 1 total
Tests: 7 passed, 7 total
Snapshots: 0 total
Time: 6.041 s
Ran all test suites matching corporate.integration.spec.
@@ -0,0 +1,25 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t rejects children
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › rejects children after a parent claim commits while child creation waits on its row lock
expect(received).toBe(expected) // Object.is equality
Expected: 409
Received: 201
103 | expect(waiting).toBe(true);
104 | } finally { release(); await claiming; }
> 105 | expect((await pending).status).toBe(409);
| ^
106 | expect(await db.corporateTask.count({ where: { parentId: parent.id } })).toBe(0);
107 | });
108 | it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:105:36)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 6 skipped, 7 total
Snapshots: 0 total
Time: 4.263 s
Ran all test suites matching corporate.integration.spec with tests matching "rejects children".
@@ -0,0 +1,7 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t public reads
Test Suites: 1 passed, 1 total
Tests: 9 skipped, 1 passed, 10 total
Snapshots: 0 total
Time: 4.131 s
Ran all test suites matching corporate.integration.spec with tests matching "public reads".
@@ -0,0 +1,25 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t public reads
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › public reads strip claim tokens recursively while claim and replay retain ownership token
expect(received).not.toContain(expected) // indexOf
Expected substring: not "claimToken"
Received string: "{\"data\":[{\"id\":\"df2e8641-026a-4ed0-80ca-36fc10db3b3c\",\"taskCode\":\"TSK-257421eb-e384-403f-837c-f09345000cf2\",\"title\":\"كيك ۱۲۳\",\"normalizedTitle\":\"کیک 123\",\"normalizedCode\":\"tsk-257421eb-e384-403f-837c-f09345000cf2\",\"description\":\"integration fixture\",\"department\":\"CONTENT_SEO\",\"priority\":\"CEO_EXPEDITE\",\"status\":\"TEST\",\"actionType\":\"CEO_DIRECTIVE\",\"dueCycle\":null,\"parentId\":\"cb3407eb-35f4-4a02-9c5e-993e2b5924f1\",\"goalId\":null,\"assignedAgent\":\"apikey:executor\",\"claimToken\":\"b57fc669-e7c8-41c3-8904-f3bc60d2dc51\",\"leasedUntil\":null,\"executionCount\":1,\"qaCount\":0,\"rejectionCount\":0,\"createdBy\":\"apikey:executor\",\"createdAt\":\"2026-10-28T12:37:42.198Z\",\"updatedAt\":\"2026-10-28T12:37:42.296Z\"},{\"id\":\"cb3407eb-35f4-4a02-9c5e-993e2b5924f1\",\"taskCode\":\"TSK-40ee89e7-7127-4e85-aac2-dad7ea156be6\",\"title\":\"كيك ۱۲۳\",\"normalizedTitle\":\"کیک 123\",\"normalizedCode\":\"tsk-40ee89e7-7127-4
145 | for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
146 | const r = await request(app.getHttpServer()).get('/admin/hermes/' + path).set('x-api-key', 'competitor').expect(200);
> 147 | expect(JSON.stringify(r.body)).not.toContain('claimToken');
| ^
148 | expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
149 | }
150 | });
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:147:42)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 9 skipped, 10 total
Snapshots: 0 total
Time: 3.842 s, estimated 6 s
Ran all test suites matching corporate.integration.spec with tests matching "public reads".
@@ -0,0 +1,32 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t malformed
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › rejects malformed artifact locators and mismatched digest URNs before persistence
expected 400 "Bad Request", got 201 "Created"
166 | 'urn:sha256:' + 'b'.repeat(64),
167 | ]) {
> 168 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
| ^
169 | 400,
170 | );
171 | }
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:168:73)
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 11 skipped, 12 total
Snapshots: 0 total
Time: 3.923 s, estimated 8 s
Ran all test suites matching corporate.integration.spec with tests matching "malformed".
@@ -0,0 +1,8 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec corporate-policy.spec
Test Suites: 2 passed, 2 total
Tests: 12 passed, 12 total
Snapshots: 0 total
Time: 6.595 s
Ran all test suites matching corporate.integration.spec|corporate-policy.spec.
@@ -0,0 +1,50 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t malformed|coercions
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › rejects malformed artifact locators and mismatched digest URNs before persistence
expected 400 "Bad Request", got 201 "Created"
119 | const body = { claimToken: claim.claimToken, artifactUri: '', sha256: 'a'.repeat(64), summary: 'receipt', tool: 'jest', result: 'passed' };
120 | for (const artifactUri of ['https://', 'https://?x', 'https://bad host/x', 'https://user:pass@host.org/a', 'https://localhost/a', 'https://127.1/a', 'https://[::1]/a', 'urn:sha256:', 'urn:sha256:' + 'b'.repeat(64)]) {
> 121 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(400);
| ^
122 | }
123 | expect(await db.corporateEvidence.count()).toBe(0);
124 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/' }).expect(201);
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:121:73)
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
● corporate API / disposable PostgreSQL › rejects implicit timestamp coercions in source and effect inputs
expect(received).rejects.toThrow()
Received promise resolved instead of rejected
Resolved to value: {"cadence": "MONTHLY", "category": "TREND", "createdAt": "2026-10-28T12:34:28.558Z", "createdBy": "fixture", "id": "8c847ae0-ff80-4ba2-9986-26a2abdd167a", "impact": "LOW", "opportunity": "investigate", "provenance": {"collector": "fixture", "context": "isolated", "method": "test"}, "recommendedAction": "measure", "source": "receipt", "sources": [{"excerpt": "receipt", "id": "108f61d9-0e90-4d53-804e-0330d129a299", "researchId": "8c847ae0-ff80-4ba2-9986-26a2abdd167a", "retrievedAt": "1970-01-01T00:00:00.000Z", "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "title": "source", "url": "https://pubmed.ncbi.nlm.nih.gov/"}], "status": "DISCOVERED", "title": "research"}
128 | const research = { title: 'research', category: 'TREND', source: 'receipt', opportunity: 'investigate', impact: 'LOW', recommendedAction: 'measure', cadence: 'MONTHLY', provenance: { method: 'test', collector: 'fixture', context: 'isolated' }, sources: [{ url: 'https://pubmed.ncbi.nlm.nih.gov/', title: 'source', excerpt: 'receipt', retrievedAt: '', sha256: 'a'.repeat(64) }] };
129 | for (const time of [null, 0, false, [], '2026-01-01', '2026-02-30T00:00:00Z']) {
> 130 | await expect(service.research('fixture', key(), { ...research, sources: [{ ...research.sources[0], retrievedAt: time }] })).rejects.toThrow();
| ^
131 | await expect(service.effect('fixture', key(), key(), { metric: 'views', availability: 'UNAVAILABLE', source: 'none', observedAt: time })).rejects.toThrow('Invalid observation time');
132 | }
133 | for (const url of ['https://', 'https://?bad', 'https://bad host'])
at expect (../../../corporate-backend/backend/node_modules/expect/build/index.js:2116:15)
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:130:13)
Test Suites: 1 failed, 1 total
Tests: 2 failed, 7 skipped, 9 total
Snapshots: 0 total
Time: 3.997 s, estimated 6 s
Ran all test suites matching corporate.integration.spec with tests matching "malformed|coercions".
@@ -0,0 +1,3 @@
# Plan
Dedicated human-principal guard after authentication and role guard. Keep scope rules unchanged. Reuse parent row lock. Centralize locator/time validation and public projection. Bound detail/report queries with deterministic ordering, counts and metadata; cap serialized operation responses.
Graph navigation: graphify-out/graph.json sha256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af, 4304 nodes, build provenance unverified (navigation only). ApiKeysController -> JwtAuthGuard -> ApiKeysService verified directly at cc365bc; CorporateController -> CorporateService -> Prisma verified directly (corporate absent from stale map).
@@ -0,0 +1,2 @@
# Corporate hardening
Base cc365bc. Backend only, no push/deploy. Humans retain admin key management; API keys cannot manage keys. Children attach only to TODO/BLOCKED under parent lock. Validate HTTPS locators/digest URNs and explicit ISO timestamp strings. Public reads omit claimToken recursively; claim retains it. Detail relations and report snapshots bounded with truncation metadata and idempotency response size guard. Acceptance: real disposable PG HTTP tests, ordering tests, backend build.
@@ -0,0 +1,7 @@
# Tasks
- [x] RED/GREEN human key-admin gate with real key authentication
- [x] RED/GREEN parent ordering on PostgreSQL
- [x] RED/GREEN locator/time validation
- [x] RED/GREEN public token projection
- [x] RED/GREEN bounded reads/report/replay
- [x] regression suite, backend build, commit (no push)
@@ -0,0 +1,14 @@
# Verification
Base cc365bc; backend isolated branch hardening/corporate-security. No push/deploy/runtime changes.
Real PostgreSQL 16.2 started locally on 127.0.0.1:55439, corporate_test. Prisma db push applied only to disposable fixture (existing fixture lacked api_keys); tests use explicit opt-in, never runtime DATABASE_URL. Dependencies symlinked from corporate-backend/backend/node_modules, unchanged lockfile.
- RED auth: four key-management verbs returned 200/201 instead of 403 with real ApiKeysService validation against PG. GREEN 5 tests. Human path uses signed test-only Passport strategy (does not claim production JWT user lookup).
- RED parent: child HTTP request observed waiting on PostgreSQL parent row lock; after IN_PROGRESS commit returned 201 instead of 409. GREEN includes TODO/BLOCKED child-first gating, existing SKIP LOCKED coverage.
- RED validation: malformed HTTPS accepted, null timestamp persisted as epoch. GREEN malformed hosts, userinfo, loopback, malformed/mismatched digest URN, numeric/null/boolean/array/date-only/invalid calendar timestamp rejected.
- RED projection: public reads exposed claimToken. GREEN list/detail/evidence/children omit it; claim and immutable claim replay retain ownership token.
- RED bounds: detail returned 106 logs and oversized response persisted. GREEN limits 100 for each detail relation/report section, counts/truncation metadata, report 1000-character fields and omitted payloads; immutable report replay after source deletion; oversized operation rolls back task and operation.
- Final targeted: 3 suites / 20 tests passed with real PG enabled. Backend tsc -b passed.
- Full suite without opt-in: 95 passed suites, 2 failed, 6 skipped; 818 passed tests, 1 failed, 25 skipped. Exact clean cc365bc same dependencies: 95 passed suites, same 2 failed (publication.postgres undefined datasource in skipped describe; wiki stale pagination/search expectation), 5 skipped; 818 passed, same 1 failed, 13 skipped. Extra skips are new/expanded opt-in security tests, not regressions.
Report snapshot is intentionally partial, not a complete daily export. Relation metadata supports explicit partial display; no frontend changes owned here. Public detail relation count is capped, not arbitrary legacy JSON field bytes. All newly created idempotency responses capped at 1,000,000 UTF-8 bytes before durable save; rejection rolls back transaction. Existing legacy idempotency records are unchanged.
@@ -0,0 +1,53 @@
import { Test, TestingModule } from "@nestjs/testing";
import { AdminController } from "./admin.controller";
import { AdminService } from "./admin.service";
import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
describe("AdminController - Stage Author Restoration endpoint", () => {
let controller: AdminController;
let mockStageAuthorRestorationService: any;
beforeEach(async () => {
mockStageAuthorRestorationService = {
restoreStageAuthors: jest.fn().mockResolvedValue({
success: true,
totalConfigured: 5,
restoredCount: 5,
existingCount: 0,
authors: [],
}),
};
const module: TestingModule = await Test.createTestingModule({
controllers: [AdminController],
providers: [
{ provide: AdminService, useValue: {} },
{ provide: SettingsService, useValue: {} },
{
provide: StageAuthorRestorationService,
useValue: mockStageAuthorRestorationService,
},
],
}).compile();
controller = module.get<AdminController>(AdminController);
});
it.each([undefined, "10.0.0.2", "127.0.0.1.evil", "::ffff:10.0.0.2"])("denies non-loopback socket %s despite forwarded headers", async (remoteAddress) => {
await expect(controller.restoreStageAuthors({ socket: { remoteAddress }, headers: { "x-forwarded-for": "127.0.0.1" }, ip: "127.0.0.1" } as any)).rejects.toThrow();
expect(mockStageAuthorRestorationService.restoreStageAuthors).not.toHaveBeenCalled();
});
it.each(["::1", "::ffff:127.0.0.1"])("accepts loopback socket %s", async remoteAddress => {
await controller.restoreStageAuthors({ socket: { remoteAddress } } as any);
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
});
it("delegates restoreStageAuthors to StageAuthorRestorationService", async () => {
const result = await controller.restoreStageAuthors({ socket: { remoteAddress: "127.0.0.1" } } as any);
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
expect(result.success).toBe(true);
expect(result.restoredCount).toBe(5);
});
});
@@ -0,0 +1,73 @@
import { ForbiddenException } from "@nestjs/common";
import { AdminService } from "./admin.service";
import { AdminController } from "./admin.controller";
// All identities and credentials here are disposable test fixtures.
describe("admin user privilege boundary", () => {
let service: any;
let prisma: any;
const owner = { id: "owner-fixture", role: "SUPER_ADMIN" };
const admin = { id: "admin-fixture", role: "ADMIN" };
beforeEach(() => {
prisma = {
user: {
findUnique: jest.fn().mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" }),
update: jest.fn().mockImplementation(async ({ data }) => ({ role: "SUPER_ADMIN", ...data })),
create: jest.fn(),
},
walletTransaction: { create: jest.fn() },
$transaction: jest.fn(),
};
service = new AdminService(prisma, {} as never, {} as never);
});
it("allows an authenticated superadmin password-only edit without changing the exact role", async () => {
const result = await service.updateUser("target-fixture", { password: "Fixture-only-123" }, owner);
expect(result.role).toBe("SUPER_ADMIN");
expect(prisma.user.update.mock.calls[0][0].data).not.toHaveProperty("role");
});
it.each(["ADMIN", "Admin", "User_PetOwner"])("denies %s assigning superadmin on create", async role => {
prisma.user.findUnique.mockResolvedValue(null);
await expect(service.createUser({ firstName: "Test", lastName: "Fixture", mobile: "09120000001", role: "SUPER_ADMIN" }, { id: "actor", role })).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.create).not.toHaveBeenCalled();
});
it.each(["SUPER_ADMIN", "super-admin", "AdminSuper"])("denies ordinary admin escalation to %s", async role => {
prisma.user.findUnique.mockResolvedValue({ id: admin.id, role: "Admin" });
await expect(service.updateUser(admin.id, { role }, admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it.each([{ password: "Fixture-only-123" }, { email: "fixture@example.test" }, { mobile: "09120000001" }, { role: "Admin" }, { walletBalance: 1 }, { firstName: "Changed" }])("denies ordinary admin editing superadmin", async dto => {
await expect(service.updateUser("target-fixture", dto, admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("denies alternate role endpoint revocation", async () => {
await expect(service.updateUserRole("target-fixture", "Admin", admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("denies deleting superadmin", async () => {
await expect(service.deleteUser("target-fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.$transaction).not.toHaveBeenCalled();
});
it("denies changing superadmin wallet", async () => {
await expect(service.adjustUserWallet("target-fixture", 1, "deposit", "fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.walletTransaction.create).not.toHaveBeenCalled();
});
it("accepts ADMIN alias for ordinary CRUD and authorized promotion/revocation", async () => {
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "User_PetOwner" });
await service.updateUser("target-fixture", { role: "ADMIN" }, admin);
await service.updateUser("target-fixture", { role: "SUPER_ADMIN" }, owner);
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" });
await service.updateUserRole("target-fixture", "Admin", owner);
expect(prisma.user.update).toHaveBeenCalledTimes(3);
});
it("fails closed without authenticated actor or with API key superadmin", async () => {
await expect(service.updateUser("target-fixture", { role: "Admin" })).rejects.toBeInstanceOf(ForbiddenException);
await expect(service.updateUser("target-fixture", { role: "Admin" }, { ...owner, isApiKey: true })).rejects.toBeInstanceOf(ForbiddenException);
});
it("controller forwards authenticated request identity, not DTO identity", async () => {
const svc = { updateUser: jest.fn().mockResolvedValue({}) };
const controller: any = new AdminController(svc as never, {} as never);
const dto = { firstName: "Test" };
await controller.updateUser("target-fixture", dto, { user: admin });
expect(svc.updateUser).toHaveBeenCalledWith("target-fixture", dto, admin);
});
});
@@ -0,0 +1,72 @@
import { Test } from "@nestjs/testing";
import { ExecutionContext } from "@nestjs/common";
import { firstValueFrom, of } from "rxjs";
import { AdminService } from "./admin.service";
import { AdminController } from "./admin.controller";
import { PrismaService } from "../prisma/prisma.service";
import { RedisService } from "../redis/redis.service";
import { RevalidationService } from "../common/revalidation/revalidation.service";
import { DecimalInterceptor } from "../common/interceptors/decimal.interceptor";
import { Prisma } from "@prisma/client";
describe("admin users list contract", () => {
const prisma = { user: { findMany: jest.fn(), count: jest.fn() } };
let service: AdminService;
beforeEach(async () => {
jest.clearAllMocks();
const module = await Test.createTestingModule({
providers: [
AdminService,
{ provide: PrismaService, useValue: prisma },
{ provide: RedisService, useValue: {} },
{ provide: RevalidationService, useValue: {} },
],
}).compile();
service = module.get(AdminService);
});
it("returns only allowlisted list fields with aggregates through the controller and decimal interceptor", async () => {
// Deliberately return extra fields even if the query selects safely.
prisma.user.findMany.mockResolvedValue([{
id: "fixture-user", firstName: "Fixture", lastName: "User",
mobile: "fixture-mobile", email: null, role: "ADMIN",
walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(12),
createdAt: new Date("2026-01-01T00:00:00Z"),
password: "test-only-password-hash", passwordHash: "test-only-hash",
refreshToken: "test-only-token", futureSecret: "must-not-leak",
walletTransactions: [{ transactionReference: "private-reference" }],
addresses: [], orders: [{ totalAmount: new Prisma.Decimal(100) }, { totalAmount: 25 }],
_count: { orders: 3, reviews: 2, blogComments: 1, pets: 4 },
}]);
prisma.user.count.mockResolvedValue(11);
const controller = new AdminController(service, {} as never);
const result = await controller.getUsers({ page: 2, limit: 10 });
const body = await firstValueFrom(new DecimalInterceptor().intercept({} as ExecutionContext, { handle: () => of(result) }));
expect(body).toEqual({
data: [{
id: "fixture-user", firstName: "Fixture", lastName: "User", mobile: "fixture-mobile",
email: null, role: "ADMIN", walletBalance: "0", charityDonationTotal: "12",
createdAt: new Date("2026-01-01T00:00:00Z"), addresses: [],
totalSpent: 125, ordersCount: 3, reviewsCount: 3, petsCount: 4,
}],
meta: { total: 11, page: 2, limit: 10, lastPage: 2 },
});
const query = prisma.user.findMany.mock.calls[0][0];
expect(query.select).toBeDefined();
expect(query.select.password).toBeUndefined();
expect(query.include).toBeUndefined();
expect(query.skip).toBe(10);
});
it("preserves the empty paginated list contract and filters", async () => {
prisma.user.findMany.mockResolvedValue([]);
prisma.user.count.mockResolvedValue(0);
expect(await service.getUsers({ search: "fixture", role: "ADMIN" })).toEqual({
data: [], meta: { total: 0, page: 1, limit: 10, lastPage: 1 },
});
expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({ role: "ADMIN", OR: expect.any(Array) }),
}));
});
});
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
import { AdminController } from "./admin.controller"; import { AdminController } from "./admin.controller";
import { AdminService } from "./admin.service"; import { AdminService } from "./admin.service";
import { SettingsService } from "../settings/settings.service"; import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
describe("AdminController", () => { describe("AdminController", () => {
let controller: AdminController; let controller: AdminController;
@@ -12,6 +13,7 @@ describe("AdminController", () => {
providers: [ providers: [
{ provide: AdminService, useValue: {} }, { provide: AdminService, useValue: {} },
{ provide: SettingsService, useValue: {} }, { provide: SettingsService, useValue: {} },
{ provide: StageAuthorRestorationService, useValue: {} },
], ],
}).compile(); }).compile();
+64 -11
View File
@@ -7,8 +7,10 @@ import {
Body, Body,
Param, Param,
Query, Query,
Req,
UseGuards, UseGuards,
BadRequestException, BadRequestException,
ForbiddenException,
} from "@nestjs/common"; } from "@nestjs/common";
import { AdminService, CouponInput } from "./admin.service"; import { AdminService, CouponInput } from "./admin.service";
import { ProductDto } from "./dto/product.dto"; import { ProductDto } from "./dto/product.dto";
@@ -27,7 +29,9 @@ import {
} from "@nestjs/swagger"; } from "@nestjs/swagger";
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto"; import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
import type { UserAdminActor } from "./user-role-policy";
import { SettingsService } from "../settings/settings.service"; import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
import { RolesGuard } from "../common/guards/roles.guard"; import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator"; import { Roles } from "../common/decorators/roles.decorator";
@@ -41,6 +45,7 @@ export class AdminController {
constructor( constructor(
private readonly adminService: AdminService, private readonly adminService: AdminService,
private readonly settingsService: SettingsService, private readonly settingsService: SettingsService,
private readonly stageAuthorRestorationService?: StageAuthorRestorationService,
) {} ) {}
@Get("dashboard/stats") @Get("dashboard/stats")
@@ -57,13 +62,13 @@ export class AdminController {
@ApiQuery({ name: "search", required: false, description: "جستجو" }) @ApiQuery({ name: "search", required: false, description: "جستجو" })
async getUsers(@Query() query: AdminQueryDto) { async getUsers(@Query() query: AdminQueryDto) {
const result = await this.adminService.getUsers(query); const result = await this.adminService.getUsers(query);
return { success: true, ...result }; return result;
} }
@Post("users") @Post("users")
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" }) @ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
async createUser(@Body() dto: CreateUserDto) { async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
const user = await this.adminService.createUser(dto); const user = await this.adminService.createUser(dto, req?.user);
return { return {
success: true, success: true,
message: "کاربر جدید با موفقیت ایجاد شد", message: "کاربر جدید با موفقیت ایجاد شد",
@@ -71,6 +76,22 @@ export class AdminController {
}; };
} }
@Post("users/stage-author-restoration")
@ApiOperation({
summary:
"بازیابی شناسه و مشخصات عمومی پنج نویسنده اورجینال مقالات در محیط استیج",
})
async restoreStageAuthors(@Req() req: { socket?: { remoteAddress?: string } }) {
const peer = req?.socket?.remoteAddress;
if (!peer || !["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(peer)) {
throw new ForbiddenException("Stage author restoration requires a loopback socket");
}
if (!this.stageAuthorRestorationService) {
throw new Error("StageAuthorRestorationService not initialized");
}
return this.stageAuthorRestorationService.restoreStageAuthors();
}
@Get("users/:id") @Get("users/:id")
@ApiOperation({ summary: "جزئیات کاربر" }) @ApiOperation({ summary: "جزئیات کاربر" })
async getUserDetails(@Param("id") id: string) { async getUserDetails(@Param("id") id: string) {
@@ -80,8 +101,8 @@ export class AdminController {
@Put("users/:id") @Put("users/:id")
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" }) @ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) { async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
const user = await this.adminService.updateUser(id, dto); const user = await this.adminService.updateUser(id, dto, req?.user);
return { return {
success: true, success: true,
message: "اطلاعات کاربر با موفقیت ویرایش شد", message: "اطلاعات کاربر با موفقیت ویرایش شد",
@@ -91,8 +112,8 @@ export class AdminController {
@Delete("users/:id") @Delete("users/:id")
@ApiOperation({ summary: "حذف کاربر و داده‌های مرتبط" }) @ApiOperation({ summary: "حذف کاربر و داده‌های مرتبط" })
async deleteUser(@Param("id") id: string) { async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
await this.adminService.deleteUser(id); await this.adminService.deleteUser(id, req?.user);
return { return {
success: true, success: true,
message: "کاربر با موفقیت از سیستم حذف شد", message: "کاربر با موفقیت از سیستم حذف شد",
@@ -101,8 +122,8 @@ export class AdminController {
@Put("users/:id/role") @Put("users/:id/role")
@ApiOperation({ summary: "تغییر نقش کاربر" }) @ApiOperation({ summary: "تغییر نقش کاربر" })
async updateUserRole(@Param("id") id: string, @Body("role") role: string) { async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
const user = await this.adminService.updateUserRole(id, role); const user = await this.adminService.updateUserRole(id, role, req?.user);
return { success: true, data: user }; return { success: true, data: user };
} }
@@ -113,6 +134,7 @@ export class AdminController {
@Body("amount") amount: number, @Body("amount") amount: number,
@Body("type") type: "deposit" | "withdrawal" | "refund", @Body("type") type: "deposit" | "withdrawal" | "refund",
@Body("description") description?: string, @Body("description") description?: string,
@Req() req?: { user?: UserAdminActor },
) { ) {
const numAmount = Number(amount); const numAmount = Number(amount);
if (!numAmount || isNaN(numAmount) || numAmount <= 0) { if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
@@ -130,6 +152,7 @@ export class AdminController {
numAmount, numAmount,
type, type,
description, description,
req?.user,
); );
return { return {
success: true, success: true,
@@ -145,7 +168,7 @@ export class AdminController {
@ApiQuery({ name: "search", required: false, description: "جستجو" }) @ApiQuery({ name: "search", required: false, description: "جستجو" })
async getProducts(@Query() query: AdminQueryDto) { async getProducts(@Query() query: AdminQueryDto) {
const result = await this.adminService.getProducts(query); const result = await this.adminService.getProducts(query);
return { success: true, ...result }; return result;
} }
@Post("products") @Post("products")
@@ -206,7 +229,7 @@ export class AdminController {
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" }) @ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
async getOrders(@Query() query: AdminQueryDto) { async getOrders(@Query() query: AdminQueryDto) {
const result = await this.adminService.getOrders(query); const result = await this.adminService.getOrders(query);
return { success: true, ...result }; return result;
} }
@Get("orders/:id") @Get("orders/:id")
@@ -354,4 +377,34 @@ export class AdminController {
await this.settingsService.updateBulkUiTexts(body); await this.settingsService.updateBulkUiTexts(body);
return { success: true, data: body }; return { success: true, data: body };
} }
@Get("symptoms")
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحه‌بندی، جستجو و متادیتا" })
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
const res = await this.adminService.getSymptoms(query);
return res;
}
@Post("symptoms")
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
const res = await this.adminService.createSymptom(body);
return { success: true, data: res };
}
@Put("symptoms/:id")
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
async updateSymptom(@Param("id") id: string, @Body() body: any) {
const res = await this.adminService.updateSymptom(id, body);
return { success: true, data: res };
}
@Delete("symptoms/:id")
@ApiOperation({ summary: "حذف علامت درمانی" })
async deleteSymptom(@Param("id") id: string) {
const res = await this.adminService.deleteSymptom(id);
return res;
}
} }
+10 -6
View File
@@ -1,3 +1,5 @@
import { CorporateController } from "./hermes/corporate.controller";
import { CorporateService } from "./hermes/corporate.service";
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { AdminController } from "./admin.controller"; import { AdminController } from "./admin.controller";
import { AdminService } from "./admin.service"; import { AdminService } from "./admin.service";
@@ -21,16 +23,17 @@ import { CompetitorPricingController } from "./competitor-pricing.controller";
import { B2BLeadsController } from "./b2b-leads.controller"; import { B2BLeadsController } from "./b2b-leads.controller";
import { PricingSuggestionsController } from "./pricing-suggestions.controller"; import { PricingSuggestionsController } from "./pricing-suggestions.controller";
import { SmsCampaignsController } from "./sms-campaigns.controller"; import { SmsCampaignsController } from "./sms-campaigns.controller";
import { ApprovalsController } from "./approvals.controller";
import { AuditLogsController } from "./audit-logs.controller";
import { DepartmentTasksController } from "./department-tasks.controller";
import { PrismaModule } from "../prisma/prisma.module"; import { PrismaModule } from "../prisma/prisma.module";
import { RedisModule } from "../redis/redis.module"; import { RedisModule } from "../redis/redis.module";
import { SettingsModule } from "../settings/settings.module"; import { SettingsModule } from "../settings/settings.module";
import { SupportChatAnalyticsController } from "./support-chat-analytics.controller";
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
@Module({ @Module({
imports: [PrismaModule, RedisModule, SettingsModule], imports: [PrismaModule, RedisModule, SettingsModule],
controllers: [ controllers: [
CorporateController,
AdminController, AdminController,
ReportsController, ReportsController,
MediaController, MediaController,
@@ -44,11 +47,10 @@ import { SettingsModule } from "../settings/settings.module";
B2BLeadsController, B2BLeadsController,
PricingSuggestionsController, PricingSuggestionsController,
SmsCampaignsController, SmsCampaignsController,
ApprovalsController, SupportChatAnalyticsController,
AuditLogsController,
DepartmentTasksController,
], ],
providers: [ providers: [
CorporateService,
AdminService, AdminService,
ReportsService, ReportsService,
MediaService, MediaService,
@@ -58,6 +60,8 @@ import { SettingsModule } from "../settings/settings.module";
PetsService, PetsService,
SslService, SslService,
ApiKeysService, ApiKeysService,
SupportChatAnalyticsService,
StageAuthorRestorationService,
], ],
exports: [ApiKeysService, MediaService], exports: [ApiKeysService, MediaService],
}) })
+235 -27
View File
@@ -61,15 +61,10 @@ export class CouponInput {
targets?: CouponTargetInput[]; targets?: CouponTargetInput[];
} }
const ALLOWED_USER_ROLES = [ import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
"User_PetOwner", import type { UserAdminActor } from "./user-role-policy";
"User_Vet", import { randomUUID } from "crypto";
"User_Clinic", import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
"User_PetShop",
"Customer",
"Admin",
"SUPER_ADMIN",
];
@Injectable() @Injectable()
export class AdminService { export class AdminService {
@@ -168,12 +163,17 @@ export class AdminService {
skip, skip,
take: limit, take: limit,
orderBy: { [sortField]: sortDirection }, orderBy: { [sortField]: sortDirection },
include: { select: {
id: true,
firstName: true,
lastName: true,
mobile: true,
email: true,
role: true,
walletBalance: true,
charityDonationTotal: true,
createdAt: true,
addresses: true, addresses: true,
walletTransactions: {
orderBy: { createdAt: "desc" },
take: 20,
},
orders: { orders: {
where: { status: { not: "CANCELLED" } }, where: { status: { not: "CANCELLED" } },
select: { totalAmount: true }, select: { totalAmount: true },
@@ -197,9 +197,19 @@ export class AdminService {
(acc, curr) => acc + (Number(curr.totalAmount) || 0), (acc, curr) => acc + (Number(curr.totalAmount) || 0),
0, 0,
) || 0; ) || 0;
const { orders: _orders, ...rest } = u; // Explicit response allowlist: never expose authentication fields or
// new model columns implicitly through this administrative list.
return { return {
...rest, id: u.id,
firstName: u.firstName,
lastName: u.lastName,
mobile: u.mobile,
email: u.email,
role: u.role,
walletBalance: u.walletBalance,
charityDonationTotal: u.charityDonationTotal,
createdAt: u.createdAt,
addresses: u.addresses,
totalSpent, totalSpent,
ordersCount: u._count?.orders || 0, ordersCount: u._count?.orders || 0,
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0), reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
@@ -227,7 +237,12 @@ export class AdminService {
return user; return user;
} }
async createUser(dto: CreateUserDto) { async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
assertUserMutationAllowed(actor, undefined, dto.role);
return this.persistUser(dto);
}
private async persistUser(dto: CreateUserDto, stage?: { session: string; expiresAt: Date; generation?: string }) {
const mobile = normalizeMobile(dto.mobile); const mobile = normalizeMobile(dto.mobile);
const existingMobile = await this.prisma.user.findUnique({ const existingMobile = await this.prisma.user.findUnique({
where: { mobile }, where: { mobile },
@@ -260,6 +275,7 @@ export class AdminService {
return this.prisma.user.create({ return this.prisma.user.create({
data: { data: {
...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:stage.generation || randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}),
firstName: dto.firstName.trim(), firstName: dto.firstName.trim(),
lastName: dto.lastName.trim(), lastName: dto.lastName.trim(),
mobile, mobile,
@@ -274,7 +290,30 @@ export class AdminService {
}); });
} }
async updateUser(id: string, dto: UpdateUserDto) { // Explicit CI seed authority, NOT a fabricated SUPER_ADMIN actor. Not controller-exposed.
async provisionStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, password: string) {
const grant = authorizeStageSession(env, sha);
const existing = await this.prisma.user.findFirst({where:{OR:[{id:STAGE_TEST_ID},{email:STAGE_TEST_EMAIL},{mobile:STAGE_TEST_MOBILE}]}});
if (existing) {
if (existing.id !== STAGE_TEST_ID || existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION) || existing.role !== 'SUPER_ADMIN' || !existing.authExpiresAt || existing.authExpiresAt.getTime() <= Date.now() || !await bcrypt.compare(password, existing.password || '')) throw new Error('Refusing existing or unowned principal');
return existing; // Never renew TTL on retry.
}
if (password.length < 32) throw new Error('Server generated secret required');
return this.persistUser({firstName:'Stage',lastName:'CI independent reviewer',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,role:'SUPER_ADMIN',password}, {session:grant.session,expiresAt:new Date(Date.now()+grant.ttl*1000),generation:env.STAGE_TEST_GENERATION});
}
async cleanupStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, onRevoked: () => void = () => undefined) {
const grant = authorizeStageSession(env, sha);
const existing = await this.prisma.user.findUnique({where:{id:STAGE_TEST_ID}});
if (!existing) { onRevoked(); return; }
if (existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || !existing.authExpiresAt || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION)) throw new Error('Refusing unowned principal cleanup');
// Revoke before relational cleanup; failed cleanup cannot leave valid tokens.
await this.prisma.user.update({where:{id:STAGE_TEST_ID,stageTestSession:grant.session,stageTestGeneration:existing.stageTestGeneration},data:{authExpiresAt:new Date(0),password:''}});
onRevoked();
return this.deleteUserRecords(STAGE_TEST_ID, {session:grant.session,generation:existing.stageTestGeneration});
}
async updateUser(id: string, dto: UpdateUserDto, actor?: UserAdminActor) {
if (id === "12345678-1234-1234-1234-123456789012") { if (id === "12345678-1234-1234-1234-123456789012") {
throw new BadRequestException( throw new BadRequestException(
"امکان ویرایش حساب ادمین پیش‌فرض وجود ندارد", "امکان ویرایش حساب ادمین پیش‌فرض وجود ندارد",
@@ -286,6 +325,8 @@ export class AdminService {
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`); throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
} }
assertUserMutationAllowed(actor, user.role, dto.role);
const normalizedMobile = dto.mobile const normalizedMobile = dto.mobile
? normalizeMobile(dto.mobile) ? normalizeMobile(dto.mobile)
: undefined; : undefined;
@@ -340,17 +381,11 @@ export class AdminService {
}); });
} }
async updateUserRole(id: string, role: string) { async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
if (!ALLOWED_USER_ROLES.includes(role)) { return this.updateUser(id, { role }, actor);
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
}
return this.prisma.user.update({
where: { id },
data: { role },
});
} }
async deleteUser(id: string) { async deleteUser(id: string, actor?: UserAdminActor) {
if (id === "12345678-1234-1234-1234-123456789012") { if (id === "12345678-1234-1234-1234-123456789012") {
throw new BadRequestException("امکان حذف حساب ادمین پیش‌فرض وجود ندارد"); throw new BadRequestException("امکان حذف حساب ادمین پیش‌فرض وجود ندارد");
} }
@@ -360,7 +395,17 @@ export class AdminService {
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`); throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
} }
assertUserMutationAllowed(actor, user.role);
return this.deleteUserRecords(id);
}
private async deleteUserRecords(id: string, stage?: {session:string; generation:string|null}) {
return this.prisma.$transaction(async (tx) => { return this.prisma.$transaction(async (tx) => {
if (stage) {
// Acquire the row lock with an exact fence before deleting any related rows.
await tx.user.update({where:{id,stageTestSession:stage.session,stageTestGeneration:stage.generation},data:{authExpiresAt:new Date(0),password:''}});
}
await tx.userAddress.deleteMany({ where: { userId: id } }); await tx.userAddress.deleteMany({ where: { userId: id } });
await tx.walletTransaction.deleteMany({ where: { userId: id } }); await tx.walletTransaction.deleteMany({ where: { userId: id } });
await tx.pet.deleteMany({ where: { userId: id } }); await tx.pet.deleteMany({ where: { userId: id } });
@@ -1397,12 +1442,15 @@ export class AdminService {
amount: number, amount: number,
type: "deposit" | "withdrawal" | "refund", type: "deposit" | "withdrawal" | "refund",
description?: string, description?: string,
actor?: UserAdminActor,
) { ) {
const user = await this.prisma.user.findUnique({ where: { id: userId } }); const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) { if (!user) {
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`); throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
} }
assertUserMutationAllowed(actor, user.role);
const transaction = await this.prisma.walletTransaction.create({ const transaction = await this.prisma.walletTransaction.create({
data: { data: {
userId, userId,
@@ -1869,4 +1917,164 @@ export class AdminService {
}; };
}); });
} }
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
const page = Math.max(1, Number(params?.page) || 1);
const limit = Math.max(1, Number(params?.limit) || 20);
const offset = (page - 1) * limit;
const search = params?.search?.trim() || '';
let items: any[] = [];
let total = 0;
if (search) {
const searchPattern = `%${search}%`;
const [listResult, countResult] = await Promise.all([
this.prisma.$queryRaw<any[]>`
SELECT
s.id,
s.name,
s.slug,
s.description,
s.meta_title as "metaTitle",
s.meta_description as "metaDescription",
s.keywords,
s.icon,
s.created_at as "createdAt",
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
FROM symptoms s
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
ORDER BY s.name ASC
LIMIT ${limit} OFFSET ${offset};
`,
this.prisma.$queryRaw<any[]>`
SELECT COUNT(*)::int as total
FROM symptoms s
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
`,
]);
items = listResult;
total = countResult[0]?.total || 0;
} else {
const [listResult, countResult] = await Promise.all([
this.prisma.$queryRaw<any[]>`
SELECT
s.id,
s.name,
s.slug,
s.description,
s.meta_title as "metaTitle",
s.meta_description as "metaDescription",
s.keywords,
s.icon,
s.created_at as "createdAt",
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
FROM symptoms s
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
ORDER BY s.name ASC
LIMIT ${limit} OFFSET ${offset};
`,
this.prisma.$queryRaw<any[]>`
SELECT COUNT(*)::int as total
FROM symptoms s;
`,
]);
items = listResult;
total = countResult[0]?.total || 0;
}
const lastPage = Math.ceil(total / limit) || 1;
return {
data: items,
meta: {
page,
limit,
total,
lastPage,
},
};
}
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
const name = dto.name.trim();
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
return await this.prisma.$queryRawUnsafe(`
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
}
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
// 1. Get existing symptom
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
const oldName = existing[0].name;
const newName = dto.name?.trim() || oldName;
const newSlug = dto.slug?.trim() || existing[0].slug;
return await this.prisma.$transaction(async (tx) => {
// Update symptoms table
const updated = await tx.$queryRawUnsafe(`
UPDATE symptoms
SET
name = $2,
slug = $3,
description = $4,
meta_title = $5,
meta_description = $6,
keywords = $7,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1::uuid
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
// If name changed, cascade update across product_symptoms & products JSON
if (oldName !== newName) {
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
await tx.$executeRaw`
UPDATE products
SET dosage_config = jsonb_set(
dosage_config,
'{symptoms}',
(
SELECT jsonb_agg(
CASE
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
ELSE elem
END
)
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
)
)
WHERE dosage_config ? 'symptoms'
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
`;
}
return updated;
});
}
async deleteSymptom(id: string) {
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
const name = existing[0].name;
return await this.prisma.$transaction(async (tx) => {
// Delete join links
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
// Delete symptom row
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
});
}
} }
+25 -24
View File
@@ -8,33 +8,34 @@ import {
Param, Param,
UseGuards, UseGuards,
HttpStatus, HttpStatus,
} from "@nestjs/common"; } from '@nestjs/common';
import { ApiKeysService } from "./api-keys.service"; import { ApiKeysService } from './api-keys.service';
import { CreateApiKeyDto } from "./dto/api-key.dto"; import { CreateApiKeyDto } from './dto/api-key.dto';
import { JwtAuthGuard } from "../auth/jwt-auth.guard"; import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { import {
ApiTags, ApiTags,
ApiBearerAuth, ApiBearerAuth,
ApiOperation, ApiOperation,
ApiResponse, ApiResponse,
} from "@nestjs/swagger"; } from '@nestjs/swagger';
import { RolesGuard } from "../common/guards/roles.guard"; import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from "../common/decorators/roles.decorator"; import { HumanAdminGuard } from '../common/guards/human-admin.guard';
import { Roles } from '../common/decorators/roles.decorator';
@ApiTags("Admin - مدیریت کلیدهای دسترسی (API Keys)") @ApiTags('Admin - مدیریت کلیدهای دسترسی (API Keys)')
@ApiBearerAuth() @ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard) @UseGuards(JwtAuthGuard, RolesGuard, HumanAdminGuard)
@Roles("Admin", "SUPER_ADMIN") @Roles('Admin', 'SUPER_ADMIN')
@Controller("admin/api-keys") @Controller('admin/api-keys')
export class ApiKeysController { export class ApiKeysController {
constructor(private readonly apiKeysService: ApiKeysService) {} constructor(private readonly apiKeysService: ApiKeysService) {}
@Get() @Get()
@ApiOperation({ summary: "دریافت لیست کلیدهای دسترسی API" }) @ApiOperation({ summary: 'دریافت لیست کلیدهای دسترسی API' })
@ApiResponse({ @ApiResponse({
status: HttpStatus.OK, status: HttpStatus.OK,
description: "لیست کلیدها با موفقیت دریافت شد", description: 'لیست کلیدها با موفقیت دریافت شد',
}) })
async findAll() { async findAll() {
const keys = await this.apiKeysService.findAll(); const keys = await this.apiKeysService.findAll();
@@ -45,39 +46,39 @@ export class ApiKeysController {
} }
@Post() @Post()
@ApiOperation({ summary: "ایجاد یک API Key جدید" }) @ApiOperation({ summary: 'ایجاد یک API Key جدید' })
@ApiResponse({ @ApiResponse({
status: HttpStatus.CREATED, status: HttpStatus.CREATED,
description: "کلید جدید با موفقیت ایجاد شد", description: 'کلید جدید با موفقیت ایجاد شد',
}) })
async create(@Body() dto: CreateApiKeyDto) { async create(@Body() dto: CreateApiKeyDto) {
const result = await this.apiKeysService.create(dto); const result = await this.apiKeysService.create(dto);
return { return {
success: true, success: true,
message: message:
"کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.", 'کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.',
data: result, data: result,
}; };
} }
@Patch(":id/toggle") @Patch(':id/toggle')
@ApiOperation({ summary: "تغییر وضعیت فعال/غیرفعال کلید" }) @ApiOperation({ summary: 'تغییر وضعیت فعال/غیرفعال کلید' })
async toggleStatus(@Param("id") id: string) { async toggleStatus(@Param('id') id: string) {
const updated = await this.apiKeysService.toggleStatus(id); const updated = await this.apiKeysService.toggleStatus(id);
return { return {
success: true, success: true,
message: "وضعیت کلید با موفقیت به‌روزرسانی شد", message: 'وضعیت کلید با موفقیت به‌روزرسانی شد',
data: updated, data: updated,
}; };
} }
@Delete(":id") @Delete(':id')
@ApiOperation({ summary: "حذف کلید دسترسی" }) @ApiOperation({ summary: 'حذف کلید دسترسی' })
async delete(@Param("id") id: string) { async delete(@Param('id') id: string) {
await this.apiKeysService.delete(id); await this.apiKeysService.delete(id);
return { return {
success: true, success: true,
message: "کلید دسترسی با موفقیت حذف شد", message: 'کلید دسترسی با موفقیت حذف شد',
}; };
} }
} }
@@ -0,0 +1,127 @@
import passport from 'passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { sign } from 'jsonwebtoken';
import { PrismaClient } from '@prisma/client';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { PrismaService } from '../prisma/prisma.service';
import { ApiKeysController } from './api-keys.controller';
import { ApiKeysService } from './api-keys.service';
const integration = process.env.CORPORATE_TEST_DATABASE_URL
? describe
: describe.skip;
integration(
'human-only key administration / real key authentication and PostgreSQL',
() => {
let app: INestApplication, db: PrismaService, service: ApiKeysService;
let rawKey: string, target: string;
const secret = 'isolated-test-jwt';
beforeAll(async () => {
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
throw new Error('Disposable DB required');
db = new PrismaClient({
datasources: { db: { url: url.toString() } },
}) as PrismaService;
passport.use(
'jwt',
new Strategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: secret,
},
(p, done) => done(null, { id: p.sub, role: p.role }),
),
);
const module = await Test.createTestingModule({
controllers: [ApiKeysController],
providers: [ApiKeysService, { provide: PrismaService, useValue: db }],
}).compile();
service = module.get(ApiKeysService);
app = module.createNestApplication();
await app.listen(0, '127.0.0.1');
rawKey = (
await service.create({
name: 'security-fixture-admin',
scopes: ['admin'],
})
).rawKey;
target = (
await service.create({
name: 'security-fixture-target',
scopes: ['read'],
})
).apiKey.id;
});
afterAll(async () => {
await db?.apiKey.deleteMany({
where: { name: { startsWith: 'security-fixture' } },
});
await app?.close();
await db?.$disconnect();
passport.unuse('jwt');
});
it.each(['get', 'post', 'patch', 'delete'] as const)(
'denies %s to authenticated admin API key without mutating keys',
async (method) => {
const before = await db.apiKey.count();
const path =
'/admin/api-keys' +
(method === 'patch'
? `/${target}/toggle`
: method === 'delete'
? `/${target}`
: '');
await request(app.getHttpServer())
[method](path)
.set('x-api-key', rawKey)
.send(
method === 'post'
? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] }
: {},
)
.expect(403);
expect(await db.apiKey.count()).toBe(before);
expect(
(await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status,
).toBe('ACTIVE');
},
);
it('retains human admin CRUD and rejects nonadmin humans and wildcard keys', async () => {
const auth =
'Bearer ' + sign({ sub: 'fixture-human', role: 'Admin' }, secret);
const created = await request(app.getHttpServer())
.post('/admin/api-keys')
.set('Authorization', auth)
.send({ name: 'security-fixture-human', scopes: ['read'] })
.expect(201);
const id = created.body.data.apiKey.id;
await request(app.getHttpServer())
.get('/admin/api-keys')
.set('Authorization', auth)
.expect(200);
await request(app.getHttpServer())
.patch(`/admin/api-keys/${id}/toggle`)
.set('Authorization', auth)
.expect(200);
await request(app.getHttpServer())
.delete(`/admin/api-keys/${id}`)
.set('Authorization', auth)
.expect(200);
await request(app.getHttpServer())
.get('/admin/api-keys')
.set(
'Authorization',
'Bearer ' + sign({ sub: 'fixture-user', role: 'USER' }, secret),
)
.expect(403);
const wildcard = await service.create({
name: 'security-fixture-wildcard',
scopes: ['*'],
});
expect((await service.validateKey(wildcard.rawKey)).role).toBe('USER');
});
},
);
-219
View File
@@ -1,219 +0,0 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
NotFoundException,
BadRequestException,
} from "@nestjs/common";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
import {
CreateApprovalRequestDto,
DecideApprovalDto,
QueryApprovalDto,
} from "./dto/approval-request.dto";
@ApiTags("Admin - CEO Approvals & Governance")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/approvals")
export class ApprovalsController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" })
async findAll(@Query() query: QueryApprovalDto) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 100;
const skip = (page - 1) * limit;
const where: any = {};
if (query.department) where.department = query.department;
if (query.category) where.category = query.category;
if (query.status) where.status = query.status;
const [total, items, pendingCount] = await Promise.all([
(this.prisma as any).approvalRequest.count({ where }),
(this.prisma as any).approvalRequest.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: "desc" },
}),
(this.prisma as any).approvalRequest.count({
where: { status: "PENDING" },
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
pendingCount,
},
};
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات یک آیتم کارتابل" })
async findOne(@Param("id") id: string) {
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
return { success: true, data: item };
}
@Post()
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمان‌ها)" })
async create(@Body() dto: CreateApprovalRequestDto) {
const item = await (this.prisma as any).approvalRequest.create({
data: {
department: dto.department,
category: dto.category,
title: dto.title,
payload: dto.payload,
testContext: dto.testContext || {},
status: "PENDING",
},
});
return { success: true, data: item };
}
@Post(":id/test")
@ApiOperation({ summary: "اجرای شبیه‌سازی تست زنده برای آیتم کارتابل" })
async runTestSimulation(@Param("id") id: string) {
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
// شبیه‌سازی بسته به دسته‌بندی
let testResult: any = { status: "SIMULATION_SUCCESS" };
if (item.category === "PRICING") {
const payload = item.payload as any;
testResult = {
impact: "Price change simulation",
currentPrice: payload.currentPrice,
newPrice: payload.newPrice,
marginDiff: payload.newPrice && payload.buyPrice
? (((payload.newPrice - payload.buyPrice) / payload.newPrice) * 100).toFixed(1) + "%"
: "N/A",
torobFeedReflectEstimate: "< 5 seconds",
};
} else if (item.category === "PURCHASE_ORDER") {
const payload = item.payload as any;
testResult = {
document: "PO Pre-check",
itemsCount: payload.items ? payload.items.length : 1,
totalEstimatedCost: payload.totalCost || "محاسبه بر اساس نرخ خرید",
fulfillmentCapacity: "انبار آماده پذیرش",
};
} else {
testResult = {
executionSafe: true,
summary: "تست سلامت اولیه و اعتبارسنجی مقادیر با موفقیت انجام شد.",
};
}
return { success: true, testResult };
}
@Put(":id/decide")
@ApiOperation({ summary: "تصمیم‌گیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
}
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
if (dto.decision === "REJECTED") {
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل می‌شوند
await (this.prisma as any).departmentTask.deleteMany({
where: { approvalId: id },
});
await (this.prisma as any).approvalRequest.delete({
where: { id },
});
return {
success: true,
message: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
};
}
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر می‌یابد
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: {
status: "APPROVED",
ceoNotes: dto.ceoNotes || null,
executedAt: new Date(),
},
});
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
const existingTask = await (this.prisma as any).departmentTask.findFirst({
where: { approvalId: id },
});
if (existingTask) {
await (this.prisma as any).departmentTask.update({
where: { id: existingTask.id },
data: {
status: "TODO",
description: dto.ceoNotes ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : existingTask.description,
},
});
} else {
await (this.prisma as any).departmentTask.create({
data: {
code: "TSK-" + Date.now().toString().slice(-6),
department: item.department,
title: item.title,
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: item.id,
},
});
}
return {
success: true,
message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.",
data: updated,
};
}
@Delete(":id")
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
async remove(@Param("id") id: string) {
await (this.prisma as any).approvalRequest.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -1,94 +0,0 @@
import {
Controller,
Get,
Post,
Body,
Query,
UseGuards,
Param,
} from "@nestjs/common";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
@ApiTags("Admin - System Audit & History")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/audit-logs")
export class AuditLogsController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست لاگ‌های تغییرات دیتابیس و سیستم" })
async findAll(@Query() query: any) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 30;
const skip = (page - 1) * limit;
const where: any = {};
if (query.entity) where.entity = query.entity;
if (query.action) where.action = query.action;
if (query.department) where.department = query.department;
if (query.search) {
where.OR = [
{ summary: { contains: query.search, mode: "insensitive" } },
{ actor: { contains: query.search, mode: "insensitive" } },
{ entityId: { contains: query.search, mode: "insensitive" } },
];
}
const [total, items] = await Promise.all([
(this.prisma as any).auditLog.count({ where }),
(this.prisma as any).auditLog.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: "desc" },
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
@Get("recent")
@ApiOperation({ summary: "آخرین رخدادهای سیستم برای ویجت داشبورد" })
async getRecent(@Query("limit") limitParam?: string) {
const limit = Number(limitParam) || 10;
const items = await (this.prisma as any).auditLog.findMany({
take: limit,
orderBy: { createdAt: "desc" },
});
return { success: true, data: items };
}
@Post()
@ApiOperation({ summary: "ثبت لاگ جدید در تاریخچه سیستم" })
async create(@Body() body: any) {
const item = await (this.prisma as any).auditLog.create({
data: {
entity: body.entity,
entityId: body.entityId ? String(body.entityId) : null,
action: body.action || "UPDATE",
department: body.department || "system",
actor: body.actor || "ADMIN",
summary: body.summary,
oldValues: body.oldValues || null,
newValues: body.newValues || null,
metadata: body.metadata || null,
},
});
return { success: true, data: item };
}
}
+117
View File
@@ -0,0 +1,117 @@
import { BadRequestException, ConflictException, NotFoundException } from "@nestjs/common";
import { BlogsService } from "./blogs.service";
// Stateful transactional double: deliberately interleave after snapshot read.
// Complements the DB integration test; it does not assert PostgreSQL locking.
describe("BlogsService atomic optimistic update", () => {
const token = "2026-10-24T23:36:08.501Z";
let row: any;
let service: BlogsService;
let prisma: any;
let revalidate: jest.Mock;
let afterRead: (() => void) | undefined;
let failRelations: boolean;
beforeEach(() => {
row = { id: "b1", slug: "post", title: "Original", updatedAt: new Date(token), tags: ["old"] };
afterRead = undefined;
failRelations = false;
const blog = {
findUnique: jest.fn(async () => {
const snapshot = { ...row };
afterRead?.();
return snapshot;
}),
updateMany: jest.fn(async ({ where, data }) => {
if (row.updatedAt >= where.updatedAt.gte && row.updatedAt < where.updatedAt.lt) {
row = { ...row, ...data };
return { count: 1 };
}
return { count: 0 };
}),
update: jest.fn(async ({ data }) => {
if (failRelations) throw new Error("relation failure");
row = { ...row, ...data };
return { ...row };
}),
};
// Serialize transactions like row locks. Rollback restores only transaction writes.
let tail = Promise.resolve();
prisma = { blog, $transaction: jest.fn((cb) => {
const next = tail.then(async () => {
const before = { ...row };
try { return await cb({ blog }); } catch (error) { row = before; throw error; }
});
tail = next.catch(() => undefined);
return next;
}) };
revalidate = jest.fn().mockResolvedValue(true);
service = new BlogsService(prisma, { revalidateBlog: revalidate } as any);
});
it.each([null, 0, 123, true, {}, [], "", "garbage", "2026-02-30T00:00:00.000Z", "2026-10-24", "2026-10-24T23:36:08.501001Z"])("rejects invalid token %p without mutations", async (value) => {
await expect(service.updateBlog("b1", { title: "bad", expectedUpdatedAt: value })).rejects.toBeInstanceOf(ConflictException);
expect(prisma.blog.update).not.toHaveBeenCalled();
expect(prisma.blog.updateMany).not.toHaveBeenCalled();
expect(revalidate).not.toHaveBeenCalled();
});
it("rejects stale token and leaves all relations untouched", async () => {
await expect(service.updateBlog("b1", { expectedUpdatedAt: "2026-10-20T00:00:00.000Z", tagNames: ["new"], categoryId: "c" })).rejects.toBeInstanceOf(ConflictException);
expect(row.tags).toEqual(["old"]);
expect(prisma.blog.update).not.toHaveBeenCalled();
expect(revalidate).not.toHaveBeenCalled();
});
it.each([token, "2026-10-25T01:36:08.501+02:00"])("accepts current token %s and atomically includes relations", async (expectedUpdatedAt) => {
const result = await service.updateBlog("b1", { title: "new", expectedUpdatedAt, authorId: "a", categoryId: "c", tagNames: ["new"] });
expect(result.title).toBe("new");
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
expect(prisma.blog.updateMany).toHaveBeenCalledWith({ where: { id: "b1", updatedAt: { gte: new Date(token), lt: new Date(new Date(token).getTime() + 1) } }, data: { updatedAt: expect.any(Date) } });
expect(prisma.blog.update.mock.calls[0][0].data).toMatchObject({ author: { connect: { id: "a" } }, category: { connect: { id: "c" } }, tags: { set: [], connectOrCreate: expect.any(Array) } });
expect(prisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("expectedUpdatedAt");
expect(result.updatedAt.getTime()).toBeGreaterThan(new Date(token).getTime());
expect(revalidate).toHaveBeenCalledTimes(1);
});
it("detects writer interleaving after read before write", async () => {
afterRead = () => { row = { ...row, title: "winner", updatedAt: new Date("2026-10-24T23:36:08.502Z"), tags: ["winner"] }; };
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "loser", tagNames: ["loser"] })).rejects.toBeInstanceOf(ConflictException);
expect(row.title).toBe("winner");
expect(row.tags).toEqual(["winner"]);
expect(prisma.blog.update).not.toHaveBeenCalled();
expect(revalidate).not.toHaveBeenCalled();
});
it("permits exactly one of two requests sharing a token", async () => {
const results = await Promise.allSettled([service.updateBlog("b1", { expectedUpdatedAt: token, title: "a" }), service.updateBlog("b1", { expectedUpdatedAt: token, title: "b" })]);
expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
const rejected = results.find(r => r.status === "rejected") as PromiseRejectedResult;
expect(rejected.reason).toBeInstanceOf(ConflictException);
expect(revalidate).toHaveBeenCalledTimes(1);
});
it("advances token even when clock is within same millisecond", async () => {
jest.useFakeTimers().setSystemTime(new Date(token));
try {
await service.updateBlog("b1", { expectedUpdatedAt: token, title: "first" });
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "second" })).rejects.toBeInstanceOf(ConflictException);
} finally { jest.useRealTimers(); }
});
it("rolls back claim on nested relation failure without invalidating cache", async () => {
failRelations = true;
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, tagNames: ["new"] })).rejects.toThrow("relation failure");
expect(row.updatedAt.toISOString()).toBe(token);
expect(row.tags).toEqual(["old"]);
expect(revalidate).not.toHaveBeenCalled();
});
it("preserves legacy omission without demanding a token", async () => {
await service.updateBlog("b1", { title: "legacy" });
expect(row.title).toBe("legacy");
expect(prisma.$transaction).not.toHaveBeenCalled();
});
it("returns 404 for a missing blog", async () => {
prisma.blog.findUnique.mockResolvedValue(null);
await expect(service.updateBlog("missing", { expectedUpdatedAt: token })).rejects.toBeInstanceOf(NotFoundException);
});
it("does not fail committed writes if revalidation throws", async () => {
revalidate.mockRejectedValue(new Error("cache down"));
const result = await service.updateBlog("b1", { expectedUpdatedAt: token, title: "saved" });
expect(result.cacheRevalidation).toBe("failed");
expect(row.title).toBe("saved");
});
});
@@ -229,6 +229,15 @@ describe("BlogsController (Admin)", () => {
expect(result).toEqual({ success: true, data: createdBlog }); expect(result).toEqual({ success: true, data: createdBlog });
}); });
it("propagates create validation failures", async () => {
const req = { user: { id: "admin-user-id" } };
const body = { title: "Bad date", contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
mockBlogsService.createBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
await expect(controller.createBlog(body, req)).rejects.toThrow("Invalid contentUpdatedAt");
expect(service.createBlog).toHaveBeenCalledWith(body, req.user.id);
});
it("updateBlog should update blog details and return success: true", async () => { it("updateBlog should update blog details and return success: true", async () => {
const blogId = "blog-10"; const blogId = "blog-10";
const body = { const body = {
@@ -244,6 +253,14 @@ describe("BlogsController (Admin)", () => {
expect(result).toEqual({ success: true, data: updatedBlog }); expect(result).toEqual({ success: true, data: updatedBlog });
}); });
it("propagates invalid content timestamp rejection without accepting createdAt", async () => {
const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt");
expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body);
});
it("deleteBlog should delete blog and return success: true", async () => { it("deleteBlog should delete blog and return success: true", async () => {
const blogId = "blog-10"; const blogId = "blog-10";
mockBlogsService.deleteBlog.mockResolvedValue(undefined); mockBlogsService.deleteBlog.mockResolvedValue(undefined);
+240 -3
View File
@@ -54,6 +54,8 @@ describe("Admin BlogsService", () => {
}).compile(); }).compile();
service = module.get<BlogsService>(BlogsService); service = module.get<BlogsService>(BlogsService);
mockRevalidationService.revalidateBlog.mockReset();
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
jest.clearAllMocks(); jest.clearAllMocks();
}); });
@@ -200,7 +202,54 @@ describe("Admin BlogsService", () => {
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith( expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
"new-health-post", "new-health-post",
); );
expect(result).toEqual(createdBlog); expect(result).toEqual({
...createdBlog,
cacheRevalidation: "success",
});
});
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
mockPrisma.blog.create.mockResolvedValue({ id: "created", slug: "safe-post" });
await service.createBlog(
{
title: "Safe post",
slug: "safe-post",
content: "Safe content",
id: "client-id",
createdAt: "2000-01-01T00:00:00.000Z",
updatedAt: "2000-01-01T00:00:00.000Z",
viewCount: 999999,
serverOwned: "must-not-pass",
},
"user-admin-1",
);
const payload = mockPrisma.blog.create.mock.calls[0][0].data;
expect(payload).toEqual(expect.objectContaining({
title: "Safe post",
slug: "safe-post",
content: "Safe content",
}));
expect(payload).not.toHaveProperty("id");
expect(payload).not.toHaveProperty("createdAt");
expect(payload).not.toHaveProperty("updatedAt");
expect(payload).not.toHaveProperty("viewCount");
expect(payload).not.toHaveProperty("serverOwned");
});
it.each([
["contentUpdatedAt", { contentUpdatedAt: "not-a-date" }, "Invalid contentUpdatedAt"],
["publishedAt", { publishedAt: "not-a-date" }, "Invalid publishedAt"],
["scheduledAt", { scheduledAt: "not-a-date" }, "Invalid scheduledAt"],
])("rejects invalid explicit %s", async (_field, timestamps, message) => {
await expect(
service.createBlog(
{ title: "Bad date", slug: "bad-date", content: "Content", ...timestamps },
"user-admin-1",
),
).rejects.toThrow(message);
expect(mockPrisma.blog.create).not.toHaveBeenCalled();
}); });
it("should create a SCHEDULED blog if scheduledAt is in the future", async () => { it("should create a SCHEDULED blog if scheduledAt is in the future", async () => {
@@ -228,6 +277,66 @@ describe("Admin BlogsService", () => {
}), }),
); );
}); });
it("should expose cacheRevalidation status on create result without failing persistence", async () => {
const blogData = {
title: "Health Post",
slug: "health-post",
content: "Content",
};
const createdBlog = { id: "blog-1", ...blogData };
mockPrisma.blog.create.mockResolvedValue(createdBlog);
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
const result = await service.createBlog(blogData, "user-admin-1");
expect(mockPrisma.blog.create).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
expect(result).toEqual({
...createdBlog,
cacheRevalidation: "success",
});
});
it("should return cacheRevalidation 'failed' when revalidation fails without failing persistence", async () => {
const blogData = {
title: "Health Post",
slug: "health-post",
content: "Content",
};
const createdBlog = { id: "blog-1", ...blogData };
mockPrisma.blog.create.mockResolvedValue(createdBlog);
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
const result = await service.createBlog(blogData, "user-admin-1");
expect(mockPrisma.blog.create).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
expect(result).toEqual({
...createdBlog,
cacheRevalidation: "failed",
});
});
it("should catch unexpected revalidation exceptions on create and return cacheRevalidation 'failed'", async () => {
const blogData = {
title: "Health Post",
slug: "health-post",
content: "Content",
};
const createdBlog = { id: "blog-1", ...blogData };
mockPrisma.blog.create.mockResolvedValue(createdBlog);
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Frontend offline"));
const result = await service.createBlog(blogData, "user-admin-1");
expect(mockPrisma.blog.create).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
expect(result).toEqual({
...createdBlog,
cacheRevalidation: "failed",
});
});
}); });
describe("updateBlog", () => { describe("updateBlog", () => {
@@ -270,7 +379,136 @@ describe("Admin BlogsService", () => {
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith( expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
"my-post", "my-post",
); );
expect(result).toEqual(updated); expect(result).toEqual({
...updated,
cacheRevalidation: "success",
});
});
it("should expose cacheRevalidation status on update result without failing persistence", async () => {
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
mockPrisma.blog.findUnique.mockResolvedValue(existing);
const updated = { ...existing, title: "New Title" };
mockPrisma.blog.update.mockResolvedValue(updated);
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
const result = await service.updateBlog("b1", { title: "New Title" });
expect(mockPrisma.blog.update).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
expect(result).toEqual({
...updated,
cacheRevalidation: "success",
});
});
it("should return cacheRevalidation 'failed' when revalidation fails on update without failing persistence", async () => {
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
mockPrisma.blog.findUnique.mockResolvedValue(existing);
const updated = { ...existing, title: "New Title" };
mockPrisma.blog.update.mockResolvedValue(updated);
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
const result = await service.updateBlog("b1", { title: "New Title" });
expect(mockPrisma.blog.update).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
expect(result).toEqual({
...updated,
cacheRevalidation: "failed",
});
});
it("should catch unexpected revalidation exceptions on update and return cacheRevalidation 'failed'", async () => {
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
mockPrisma.blog.findUnique.mockResolvedValue(existing);
const updated = { ...existing, title: "New Title" };
mockPrisma.blog.update.mockResolvedValue(updated);
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Revalidation timeout"));
const result = await service.updateBlog("b1", { title: "New Title" });
expect(mockPrisma.blog.update).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
expect(result).toEqual({
...updated,
cacheRevalidation: "failed",
});
});
});
describe("material freshness and scheduled publishing", () => {
it("sets contentUpdatedAt intentionally and never rewrites createdAt", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", createdAt: new Date("2025-01-01") });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { title: "Material edit", markContentUpdated: true });
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
expect(payload.contentUpdatedAt).toEqual(expect.any(Date));
expect(payload).not.toHaveProperty("markContentUpdated");
expect(payload).not.toHaveProperty("createdAt");
});
it("automatically marks freshness when material article content changes", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Old content" });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { content: "Meaningfully revised content" });
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toEqual(expect.any(Date));
});
it("does not mark freshness for attribution-only changes", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Same content" });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { authorTeam: "Clinical team", authorRole: "Review" });
expect(mockPrisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("contentUpdatedAt");
});
it("allows explicitly clearing contentUpdatedAt", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post" });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { contentUpdatedAt: null });
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
});
it("publishes due posts without rewriting createdAt", async () => {
const scheduledAt = new Date("2025-02-01T10:00:00Z");
mockPrisma.blog.findMany.mockResolvedValue([{ id: "b1", slug: "post", title: "Post", scheduledAt }]);
mockPrisma.blog.update.mockResolvedValue({});
await service.publishDueScheduledBlogs();
expect(mockPrisma.blog.update).toHaveBeenCalledWith({ where: { id: "b1" }, data: { status: "PUBLISHED", isPublished: true, publishedAt: scheduledAt } });
});
});
describe("updateBlog security and freshness validation", () => {
beforeEach(() => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "safe" });
mockPrisma.blog.update.mockResolvedValue({ id: "blog-1", slug: "safe" });
});
it("allowlists mutable fields and ignores createdAt and unrecognized fields", async () => {
await service.updateBlog("blog-1", {
title: "Allowed title",
createdAt: "2000-01-01T00:00:00.000Z",
serverOwned: "must-not-pass",
});
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
expect(payload.title).toBe("Allowed title");
expect(payload).not.toHaveProperty("createdAt");
expect(payload).not.toHaveProperty("serverOwned");
});
it("rejects an invalid explicit contentUpdatedAt", async () => {
await expect(
service.updateBlog("blog-1", { contentUpdatedAt: "not-a-date" }),
).rejects.toThrow("Invalid contentUpdatedAt");
expect(mockPrisma.blog.update).not.toHaveBeenCalled();
});
it("preserves explicit null clearing and markContentUpdated precedence", async () => {
await service.updateBlog("blog-1", { contentUpdatedAt: null });
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
await service.updateBlog("blog-1", {
contentUpdatedAt: "not-a-date",
markContentUpdated: true,
});
expect(mockPrisma.blog.update.mock.calls[1][0].data.contentUpdatedAt).toEqual(expect.any(Date));
}); });
}); });
@@ -468,7 +706,6 @@ describe("Admin BlogsService", () => {
status: "PUBLISHED", status: "PUBLISHED",
isPublished: true, isPublished: true,
publishedAt: scheduledDate, publishedAt: scheduledDate,
createdAt: scheduledDate,
}, },
}); });
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith( expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
+213 -31
View File
@@ -1,4 +1,6 @@
import { import {
BadRequestException,
ConflictException,
Injectable, Injectable,
NotFoundException, NotFoundException,
OnModuleInit, OnModuleInit,
@@ -141,16 +143,31 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
async createBlog(data: any, currentUserId: string) { async createBlog(data: any, currentUserId: string) {
const { const {
tags,
tagNames, tagNames,
categoryId, categoryId,
authorId, authorId,
publishedAt, publishedAt,
scheduledAt, scheduledAt,
readingTime, readingTime,
...rest markContentUpdated,
contentUpdatedAt,
} = data; } = data;
const parseOptionalDate = (value: unknown, field: string): Date | null => {
if (value === undefined || value === null || value === "") return null;
const parsed = new Date(value as string | number | Date);
if (!Number.isFinite(parsed.getTime())) {
throw new BadRequestException(`Invalid ${field}`);
}
return parsed;
};
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
const parsedContentUpdatedAt = markContentUpdated
? new Date()
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
// Connect or create tags // Connect or create tags
const tagConnectOrCreate = []; const tagConnectOrCreate = [];
if (Array.isArray(tagNames) && tagNames.length > 0) { if (Array.isArray(tagNames) && tagNames.length > 0) {
@@ -171,13 +188,12 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
const targetAuthorId = authorId || currentUserId; const targetAuthorId = authorId || currentUserId;
const now = new Date(); const now = new Date();
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now; const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
let finalStatus = rest.status || "PUBLISHED"; let finalStatus = data.status || "PUBLISHED";
let finalIsPublished = let finalIsPublished =
rest.isPublished !== undefined ? rest.isPublished : true; data.isPublished !== undefined ? data.isPublished : true;
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null; let finalPublishedAt = parsedPublishedAt;
if (isFutureSchedule) { if (isFutureSchedule) {
finalStatus = "SCHEDULED"; finalStatus = "SCHEDULED";
@@ -191,19 +207,45 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
finalPublishedAt = now; finalPublishedAt = now;
} }
const createPayload: Prisma.BlogCreateInput = { const createPayload = {
...rest, title: data.title,
slug: data.slug,
content: data.content,
excerpt: data.excerpt,
authorTeam: data.authorTeam,
authorRole: data.authorRole,
imageUrl: data.imageUrl,
imageAlt: data.imageAlt,
imageCaption: data.imageCaption,
metaTitle: data.metaTitle,
metaDescription: data.metaDescription,
keywords: data.keywords,
focusKeywords: data.focusKeywords,
canonicalUrl: data.canonicalUrl,
noIndex: data.noIndex,
noFollow: data.noFollow,
schemaType: data.schemaType,
ogTitle: data.ogTitle,
ogDescription: data.ogDescription,
ogImage: data.ogImage,
status: finalStatus, status: finalStatus,
isPublished: finalIsPublished, isPublished: finalIsPublished,
readingTime: readingTime ? Number(readingTime) : 3, featured: data.featured,
allowComments: data.allowComments,
showOnHome: data.showOnHome,
homeDisplayMode: data.homeDisplayMode,
relatedProductIds: data.relatedProductIds,
relatedBlogIds: data.relatedBlogIds,
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
publishedAt: finalPublishedAt, publishedAt: finalPublishedAt,
scheduledAt: parsedScheduledAt, scheduledAt: parsedScheduledAt,
contentUpdatedAt: parsedContentUpdatedAt,
author: { connect: { id: targetAuthorId } }, author: { connect: { id: targetAuthorId } },
...(categoryId ? { category: { connect: { id: categoryId } } } : {}), ...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
...(tagConnectOrCreate.length > 0 ...(tagConnectOrCreate.length > 0
? { tags: { connectOrCreate: tagConnectOrCreate } } ? { tags: { connectOrCreate: tagConnectOrCreate } }
: {}), : {}),
}; } satisfies Prisma.BlogCreateInput;
const created = await this.prisma.blog.create({ const created = await this.prisma.blog.create({
data: createPayload, data: createPayload,
@@ -214,8 +256,21 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
}, },
}); });
await this.revalidationService.revalidateBlog(created.slug); let cacheRevalidation: "success" | "failed" = "failed";
return created; try {
const revalidated = await this.revalidationService.revalidateBlog(created.slug);
cacheRevalidation = revalidated ? "success" : "failed";
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for created blog [${created.slug}]: ${err?.message}`,
);
cacheRevalidation = "failed";
}
return {
...created,
cacheRevalidation,
};
} }
async updateBlog(id: string, data: any) { async updateBlog(id: string, data: any) {
@@ -223,19 +278,105 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
if (!blog) throw new NotFoundException("Blog not found"); if (!blog) throw new NotFoundException("Blog not found");
const { const {
tags,
tagNames, tagNames,
categoryId, categoryId,
authorId, authorId,
publishedAt, publishedAt,
scheduledAt, scheduledAt,
readingTime, readingTime,
...rest markContentUpdated,
contentUpdatedAt,
expectedUpdatedAt,
} = data; } = data;
const conflict = () => new ConflictException(
"CONCURRENT_MODIFICATION: Blog has been modified by another process",
);
let expectedTime: number | undefined;
if (expectedUpdatedAt !== undefined) {
// Only accept the millisecond, timezone-qualified ISO token returned by GET
// (or an equivalent offset). Avoid Date's coercion of null, numbers, arrays,
// and its normalization of impossible calendar dates.
const match = typeof expectedUpdatedAt === "string" && expectedUpdatedAt.match(
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/,
);
if (!match) throw conflict();
expectedTime = Date.parse(expectedUpdatedAt);
const calendar = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`);
if (!Number.isFinite(expectedTime) ||
calendar.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` ||
Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
throw conflict();
}
}
const mutableScalarFields = [
"title",
"slug",
"content",
"excerpt",
"authorTeam",
"authorRole",
"imageUrl",
"imageAlt",
"imageCaption",
"metaTitle",
"metaDescription",
"keywords",
"focusKeywords",
"canonicalUrl",
"noIndex",
"noFollow",
"schemaType",
"ogTitle",
"ogDescription",
"ogImage",
"status",
"isPublished",
"featured",
"allowComments",
"showOnHome",
"homeDisplayMode",
"relatedProductIds",
"relatedBlogIds",
] as const;
const updatePayload: Prisma.BlogUpdateInput = {};
for (const field of mutableScalarFields) {
if (data[field] !== undefined) {
(updatePayload as Record<string, unknown>)[field] = data[field];
}
}
const now = new Date(); const now = new Date();
const updatePayload: Prisma.BlogUpdateInput = { const materialContentFields = [
...rest, "title",
"content",
"excerpt",
"imageUrl",
"imageAlt",
"imageCaption",
] as const;
const hasMaterialContentChange = materialContentFields.some(
(field) => data[field] !== undefined && data[field] !== blog[field],
);
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
} else if (contentUpdatedAt !== undefined) {
if (contentUpdatedAt === null || contentUpdatedAt === "") {
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
} else {
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
throw new BadRequestException("Invalid contentUpdatedAt");
}
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
}
}
Object.assign(updatePayload, {
...(readingTime !== undefined
? { readingTime: Number(readingTime) }
: {}),
...(readingTime !== undefined ...(readingTime !== undefined
? { readingTime: Number(readingTime) } ? { readingTime: Number(readingTime) }
: {}), : {}),
@@ -245,7 +386,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
? { category: { connect: { id: categoryId } } } ? { category: { connect: { id: categoryId } } }
: { category: { disconnect: true } } : { category: { disconnect: true } }
: {}), : {}),
}; });
if (scheduledAt !== undefined) { if (scheduledAt !== undefined) {
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null; const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
@@ -259,7 +400,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
updatePayload.status = "PUBLISHED"; updatePayload.status = "PUBLISHED";
updatePayload.isPublished = true; updatePayload.isPublished = true;
updatePayload.publishedAt = parsedScheduledAt; updatePayload.publishedAt = parsedScheduledAt;
updatePayload.createdAt = parsedScheduledAt;
} }
} else if (publishedAt !== undefined) { } else if (publishedAt !== undefined) {
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null; updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
@@ -286,25 +426,68 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
}; };
} }
const updated = await this.prisma.blog.update({ const include = {
where: { id }, author: { select: { firstName: true, lastName: true } },
data: updatePayload, category: true,
include: { tags: true,
author: { select: { firstName: true, lastName: true } }, };
category: true, // Legacy UI requests without a token intentionally retain last-write-wins.
tags: true, // Guarded requests claim the row using a DB predicate, not the earlier read.
}, const updated = expectedTime === undefined
}); ? await this.prisma.blog.update({ where: { id }, data: updatePayload, include })
: await this.prisma.$transaction(async (tx) => {
// PostgreSQL timestamptz defaults to microseconds; JSON/JS Dates expose
// milliseconds. Match the entire represented millisecond, then move
// strictly beyond it (including same-ms writes and clock rollback).
const claimedAt = new Date(Math.max(Date.now(), expectedTime + 1));
const claim = await tx.blog.updateMany({
where: {
id,
updatedAt: {
gte: new Date(expectedTime),
lt: new Date(expectedTime + 1),
},
},
data: { updatedAt: claimedAt },
});
if (claim.count !== 1) throw conflict();
// The claim holds the row lock until this nested mutation commits.
// Any relation failure rolls back both the claim and all data writes.
return tx.blog.update({
where: { id },
data: { ...updatePayload, updatedAt: claimedAt },
include,
});
});
await this.revalidationService.revalidateBlog(updated.slug); let cacheRevalidation: "success" | "failed" = "failed";
return updated; try {
const revalidated = await this.revalidationService.revalidateBlog(updated.slug);
cacheRevalidation = revalidated ? "success" : "failed";
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for updated blog [${updated.slug}]: ${err?.message}`,
);
cacheRevalidation = "failed";
}
return {
...updated,
cacheRevalidation,
};
} }
async deleteBlog(id: string) { async deleteBlog(id: string) {
const blog = await this.prisma.blog.findUnique({ where: { id } }); const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException("Blog not found"); if (!blog) throw new NotFoundException("Blog not found");
const res = await this.prisma.blog.delete({ where: { id } }); const res = await this.prisma.blog.delete({ where: { id } });
await this.revalidationService.revalidateBlog(blog.slug); try {
await this.revalidationService.revalidateBlog(blog.slug);
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`,
);
}
return res; return res;
} }
@@ -472,7 +655,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
status: "PUBLISHED", status: "PUBLISHED",
isPublished: true, isPublished: true,
publishedAt: publishDate, publishedAt: publishDate,
createdAt: publishDate,
}, },
}); });
@@ -1,208 +0,0 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
NotFoundException,
} from "@nestjs/common";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
@ApiTags("Admin - Department & Agent Tasks")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/department-tasks")
export class DepartmentTasksController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست تسک‌های دپارتمان‌ها و ایجنت‌ها" })
async findAll(@Query() query: any) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 100;
const skip = (page - 1) * limit;
const where: any = {};
if (query.department) where.department = query.department;
if (query.status) where.status = query.status;
if (query.priority) where.priority = query.priority;
if (query.search) {
where.OR = [
{ code: { contains: query.search, mode: "insensitive" } },
{ title: { contains: query.search, mode: "insensitive" } },
{ description: { contains: query.search, mode: "insensitive" } },
];
}
const [total, items] = await Promise.all([
(this.prisma as any).departmentTask.count({ where }),
(this.prisma as any).departmentTask.findMany({
where,
skip,
take: limit,
orderBy: [{ priority: "desc" }, { createdAt: "desc" }],
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
@Get("stats")
@ApiOperation({ summary: "آمار تسک‌ها به تفکیک استیت و دپارتمان" })
async getStats() {
const tasks = await (this.prisma as any).departmentTask.findMany({
select: { department: true, status: true, priority: true },
});
const statusCounts: Record<string, number> = {
TODO: 0,
IN_PROGRESS: 0,
TEST: 0,
DONE: 0,
BACKLOG: 0,
IN_REVIEW: 0,
APPROVED: 0,
DEPLOYING: 0,
};
const departmentCounts: Record<string, number> = {};
for (const t of tasks) {
statusCounts[t.status] = (statusCounts[t.status] || 0) + 1;
departmentCounts[t.department] = (departmentCounts[t.department] || 0) + 1;
}
return {
success: true,
data: {
total: tasks.length,
byStatus: statusCounts,
byDepartment: departmentCounts,
},
};
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات یک تسک" })
async findOne(@Param("id") id: string) {
const task = await (this.prisma as any).departmentTask.findUnique({
where: { id },
});
if (!task) throw new NotFoundException(`Task ${id} not found`);
return { success: true, data: task };
}
@Post()
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
async create(@Body() body: any) {
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
const task = await (this.prisma as any).departmentTask.create({
data: {
code,
department: body.department,
title: body.title,
description: body.description || null,
status: body.status || "TODO",
priority: body.priority || "MEDIUM",
assignee: body.assignee || "AI_AGENT",
acceptanceCriteria: body.acceptanceCriteria || null,
executionLogs: body.executionLogs || [],
deliverableUrl: body.deliverableUrl || null,
startedAt: body.status === "IN_PROGRESS" ? new Date() : null,
},
});
// ثبت در تاریخچه لاگ‌ها
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
entityId: task.id,
action: "CREATE",
department: task.department,
actor: task.assignee || "SYSTEM",
summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.",
newValues: task,
},
});
return { success: true, data: task };
}
@Put(":id/status")
@ApiOperation({ summary: "تغییر وضعیت تسک همراه با لاگ اجرا" })
async updateStatus(
@Param("id") id: string,
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
) {
const existing = await (this.prisma as any).departmentTask.findUnique({
where: { id },
});
if (!existing) throw new NotFoundException(`Task ${id} not found`);
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
if (body.logNote) {
logs.push({
timestamp: new Date().toISOString(),
status: body.status,
note: body.logNote,
});
}
const updateData: any = {
status: body.status,
executionLogs: logs,
};
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
if (body.status === "DONE") updateData.completedAt = new Date();
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه می‌شود
if (body.status === "TODO" && body.logNote) {
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
}
const updated = await (this.prisma as any).departmentTask.update({
where: { id },
data: updateData,
});
// ثبت در تاریخچه
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
entityId: updated.id,
action: "UPDATE",
department: updated.department,
actor: "SYSTEM",
summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.",
oldValues: { status: existing.status },
newValues: { status: updated.status, note: body.logNote },
},
});
return { success: true, data: updated };
}
@Delete(":id")
@ApiOperation({ summary: "حذف تسک" })
async remove(@Param("id") id: string) {
await (this.prisma as any).departmentTask.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -1,58 +0,0 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsString, IsOptional, IsObject } from "class-validator";
export class CreateApprovalRequestDto {
@ApiProperty({ description: "دپارتمان مبدا (DEV, SUPPLY, FINANCE, SEO, CRM, CONTENT)" })
@IsString()
department: string;
@ApiProperty({ description: "دسته‌بندی (PRICING, PURCHASE_ORDER, CAMPAIGN, DEPLOY, etc)" })
@IsString()
category: string;
@ApiProperty({ description: "عنوان مورد تایید" })
@IsString()
title: string;
@ApiProperty({ description: "داده‌های تغییرات پیشنهادی" })
@IsObject()
payload: Record<string, any>;
@ApiPropertyOptional({ description: "داده‌های سناریوی تست و ارزیابی" })
@IsOptional()
@IsObject()
testContext?: Record<string, any>;
}
export class DecideApprovalDto {
@ApiProperty({ description: "تصمیم: APPROVED یا REJECTED" })
@IsString()
decision: "APPROVED" | "REJECTED";
@ApiPropertyOptional({ description: "توضیحات و یادداشت مدیرعامل" })
@IsOptional()
@IsString()
ceoNotes?: string;
}
export class QueryApprovalDto {
@ApiPropertyOptional()
@IsOptional()
department?: string;
@ApiPropertyOptional()
@IsOptional()
category?: string;
@ApiPropertyOptional()
@IsOptional()
status?: string;
@ApiPropertyOptional()
@IsOptional()
page?: number;
@ApiPropertyOptional()
@IsOptional()
limit?: number;
}
+5
View File
@@ -5,9 +5,12 @@ import {
IsEmail, IsEmail,
MinLength, MinLength,
IsNumber, IsNumber,
IsIn,
} from "class-validator"; } from "class-validator";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { ALLOWED_USER_ROLES } from "../user-role-policy";
export class CreateUserDto { export class CreateUserDto {
@ApiProperty({ description: "نام کاربر", example: "علی" }) @ApiProperty({ description: "نام کاربر", example: "علی" })
@IsNotEmpty({ message: "نام الزامی است" }) @IsNotEmpty({ message: "نام الزامی است" })
@@ -41,6 +44,7 @@ export class CreateUserDto {
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" }) @ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
@IsOptional() @IsOptional()
@IsString() @IsString()
@IsIn(ALLOWED_USER_ROLES)
role?: string; role?: string;
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 }) @ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
@@ -85,6 +89,7 @@ export class UpdateUserDto {
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" }) @ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
@IsOptional() @IsOptional()
@IsString() @IsString()
@IsIn(ALLOWED_USER_ROLES)
role?: string; role?: string;
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 }) @ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
@@ -0,0 +1,69 @@
import {
normalizeSearch,
pagination,
taskInput,
monthlyPlanInput,
} from './corporate-policy';
describe('corporate contract policy', () => {
it.each([
['2027-02', 28],
['2028-02', 29],
['2028-04', 30],
['2028-01', 31],
])('enforces real calendar coverage for %s', (month, count) => {
const id = '11111111-1111-4111-8111-111111111111';
const body = {
roadmapId: id,
month,
needs: [],
dailyArticles: Array.from({ length: Number(count) }, (_, i) => ({
title: 'new article',
description: 'instruction',
actionType: 'BLOG_NEW',
department: 'CONTENT_SEO',
goalId: id,
sourceIds: [id],
dueCycle: `${month}-${String(i + 1).padStart(2, '0')}`,
})),
};
expect(monthlyPlanInput(body).dailyArticles).toHaveLength(Number(count));
expect(() =>
monthlyPlanInput({ ...body, dailyArticles: body.dailyArticles.slice(1) }),
).toThrow();
expect(() =>
monthlyPlanInput({
...body,
dailyArticles: [...body.dailyArticles, body.dailyArticles[0]],
}),
).toThrow();
});
it('normalizes Persian letters, digits and separators', () => {
expect(normalizeSearch('كيك ۱۲۳ (ة)‌')).toBe('کیک 123 ه');
});
it('bounds pagination and sort keys', () => {
expect(pagination({ limit: '100' }).limit).toBe(100);
expect(() => pagination({ limit: '101' })).toThrow();
expect(() => pagination({ page: '-1' })).toThrow();
expect(() => pagination({ sortBy: 'password' })).toThrow();
});
it('defaults CEO priority and rejects status/command injection', () => {
expect(
taskInput({
title: 'عنوان',
description: 'کار',
department: 'CONTENT_SEO',
}).priority,
).toBe('CEO_EXPEDITE');
expect(() =>
taskInput({
title: 'x',
description: 'x',
department: 'CONTENT_SEO',
status: 'DONE',
}),
).toThrow();
expect(() =>
taskInput({ title: '', description: 'x', department: 'CONTENT_SEO' }),
).toThrow();
});
});
@@ -0,0 +1,317 @@
import { BadRequestException } from '@nestjs/common';
export const departments = [
'CONTENT_SEO',
'CATALOG_COMMERCE',
'WIKI_SCIENTIFIC',
'TECH_DEVOPS',
'MARKET_INTELLIGENCE',
];
export const priorities = ['CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
export const statuses = [
'TODO',
'IN_PROGRESS',
'TEST',
'DONE',
'BLOCKED',
'REJECTED',
'CANCELLED',
];
export function object(value: unknown, keys: string[]): Record<string, any> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).some((k) => !keys.includes(k))
)
throw new BadRequestException('Invalid fields');
return value as Record<string, any>;
}
export function text(value: unknown, max = 10000): string {
if (typeof value !== 'string' || !value.trim() || value.length > max)
throw new BadRequestException('Invalid text');
return value.trim();
}
export function uuid(value: unknown): string {
const id = text(value, 36);
if (
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
id,
)
)
throw new BadRequestException('Invalid UUID');
return id.toLowerCase();
}
export function choice(value: unknown, values: string[]): string {
if (typeof value !== 'string' || !values.includes(value))
throw new BadRequestException('Invalid enum');
return value;
}
export function normalizeSearch(value: string): string {
return value
.normalize('NFKC')
.toLowerCase()
.replace(/[يى]/g, 'ی')
.replace(/ك/g, 'ک')
.replace(/ة/g, 'ه')
.replace(/[۰-۹٠-٩]/g, (c) =>
String(
'۰۱۲۳۴۵۶۷۸۹'.includes(c)
? '۰۱۲۳۴۵۶۷۸۹'.indexOf(c)
: '٠١٢٣٤٥٦٧٨٩'.indexOf(c),
),
)
.replace(/[\u200c\u200d()()]/g, ' ')
.replace(/[\u064b-\u065f]/g, '')
.replace(/\s+/g, ' ')
.trim();
}
export function pagination(q: Record<string, any>) {
const page = Number(q.page ?? 1),
limit = Number(q.limit ?? 20);
if (
!Number.isSafeInteger(page) ||
page < 1 ||
page > 1000000 ||
!Number.isInteger(limit) ||
limit < 1 ||
limit > 100
)
throw new BadRequestException('Invalid pagination');
const sortBy = choice(q.sortBy ?? 'createdAt', [
'createdAt',
'updatedAt',
'title',
'taskCode',
'priority',
'status',
]);
const sortOrder = choice(q.sortOrder ?? 'desc', ['asc', 'desc']) as
| 'asc'
| 'desc';
return { page, limit, skip: (page - 1) * limit, sortBy, sortOrder };
}
export function meta(total: number, page: number, limit: number) {
const totalPages = Math.ceil(total / limit);
return {
total,
page,
limit,
totalPages,
hasNextPage: page < totalPages,
hasPrevPage: page > 1,
};
}
export function taskInput(input: unknown) {
const b = object(input, [
'title',
'department',
'description',
'priority',
'parentId',
'goalId',
'actionType',
'dueCycle',
]);
return {
title: text(b.title, 300),
description: text(b.description),
department: choice(b.department, departments),
priority: choice(b.priority ?? 'CEO_EXPEDITE', priorities),
parentId: b.parentId === undefined ? undefined : uuid(b.parentId),
goalId: b.goalId === undefined ? undefined : uuid(b.goalId),
actionType: choice(b.actionType ?? 'CEO_DIRECTIVE', [
'CEO_DIRECTIVE',
'BLOG_NEW',
'BLOG_UPDATE',
'CATALOG_ENRICH',
'WIKI_ENRICH',
'RESEARCH',
'ENGINEERING',
]),
dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40),
};
}
export function planMonth(value: unknown): string {
const month = text(value, 7);
if (!/^(?:[2-9]\d{3})-(?:0[1-9]|1[0-2])$/.test(month))
throw new BadRequestException('Invalid YYYY-MM month');
return month;
}
export function monthlyPlanInput(input: unknown) {
const b = object(input, ['roadmapId', 'month', 'dailyArticles', 'needs']);
const month = planMonth(b.month);
const days = new Date(
Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5)), 0),
).getUTCDate();
if (
!Array.isArray(b.dailyArticles) ||
b.dailyArticles.length !== days ||
!Array.isArray(b.needs) ||
b.needs.length > 200
)
throw new BadRequestException(
'Full daily article coverage and bounded needs required',
);
const mapping: Record<string, string> = {
BLOG_NEW: 'CONTENT_SEO',
BLOG_UPDATE: 'CONTENT_SEO',
CATALOG_ENRICH: 'CATALOG_COMMERCE',
WIKI_ENRICH: 'WIKI_SCIENTIFIC',
ENGINEERING: 'TECH_DEVOPS',
};
const parse = (raw: unknown, daily: boolean) => {
const t = object(raw, [
'title',
'description',
'department',
'priority',
'goalId',
'actionType',
'dueCycle',
'sourceIds',
'target',
'reason',
]);
const actionType = choice(
t.actionType,
daily
? ['BLOG_NEW']
: ['BLOG_UPDATE', 'CATALOG_ENRICH', 'WIKI_ENRICH', 'ENGINEERING'],
);
const department = choice(t.department, [mapping[actionType]]);
const dueCycle = text(t.dueCycle, 10);
const date = new Date(dueCycle + 'T00:00:00Z');
if (
!/^\d{4}-\d{2}-\d{2}$/.test(dueCycle) ||
!dueCycle.startsWith(month + '-') ||
!Number.isFinite(date.getTime()) ||
date.toISOString().slice(0, 10) !== dueCycle
)
throw new BadRequestException('Invalid plan day');
if (
!Array.isArray(t.sourceIds) ||
!t.sourceIds.length ||
t.sourceIds.length > 30
)
throw new BadRequestException('Stored sources required');
const sourceIds = t.sourceIds.map(uuid);
if (new Set(sourceIds).size !== sourceIds.length)
throw new BadRequestException('Duplicate source');
if (daily && (t.target !== undefined || t.reason !== undefined))
throw new BadRequestException('Daily new articles cannot be needs');
return {
title: text(t.title, 300),
description: text(t.description),
department,
actionType,
dueCycle,
priority: choice(t.priority ?? 'MEDIUM', priorities),
goalId: uuid(t.goalId),
sourceIds,
...(daily
? {}
: { target: text(t.target, 2000), reason: text(t.reason) }),
};
};
const dailyArticles = b.dailyArticles.map((t) => parse(t, true));
if (new Set(dailyArticles.map((t) => t.dueCycle)).size !== days)
throw new BadRequestException(
'Exactly one new article per calendar day required',
);
const needs = b.needs.map((t) => parse(t, false));
if (
new Set(needs.map((t) => canonical([t.actionType, t.target, t.dueCycle])))
.size !== needs.length
)
throw new BadRequestException('Duplicate need');
return { roadmapId: uuid(b.roadmapId), month, dailyArticles, needs };
}
export function canonical(value: any): string {
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
if (value && typeof value === 'object')
return (
'{' +
Object.keys(value)
.sort()
.map((k) => JSON.stringify(k) + ':' + canonical(value[k]))
.join(',') +
'}'
);
return JSON.stringify(value);
}
/** Public projection must also cover nested evidence and child records. */
export function publicData(value: any): any {
if (value instanceof Date) return value;
if (Array.isArray(value)) return value.map(publicData);
if (value && typeof value === 'object')
return Object.fromEntries(
Object.entries(value)
.filter(([key]) => key !== 'claimToken')
.map(([key, item]) => [key, publicData(item)]),
);
return value;
}
export function httpsUrl(value: unknown): string {
const raw = text(value, 2000);
try {
if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw))
throw new Error();
const u = new URL(raw);
const host = u.hostname.toLowerCase();
if (
u.protocol !== 'https:' ||
u.username ||
u.password ||
!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) ||
host === 'localhost' ||
host.endsWith('.localhost') ||
/(^|\.)example\.(com|org|net)$/.test(host)
)
throw new Error();
return raw;
} catch {
throw new BadRequestException('Valid HTTPS host URL required');
}
}
export function timestamp(value: unknown, message: string): Date {
if (
typeof value !== 'string' ||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)
)
throw new BadRequestException(message);
const date = new Date(value);
if (
!Number.isFinite(date.getTime()) ||
date.getTime() > Date.now() ||
date.toISOString().slice(0, 19) !== value.slice(0, 19)
)
throw new BadRequestException(message);
return date;
}
export function evidenceInput(input: unknown) {
const b = object(input, [
'claimToken',
'artifactUri',
'sha256',
'summary',
'tool',
'result',
]);
const uri = text(b.artifactUri, 2000);
const sha = text(b.sha256, 64);
if (!/^[a-f0-9]{64}$/.test(sha))
throw new BadRequestException('Invalid digest');
if (uri.startsWith('urn:')) {
if (uri !== 'urn:sha256:' + sha)
throw new BadRequestException('Digest locator mismatch');
} else httpsUrl(uri);
return {
claimToken: uuid(b.claimToken),
artifactUri: uri,
sha256: sha,
summary: text(b.summary),
tool: text(b.tool, 100),
result: text(b.result),
};
}
@@ -0,0 +1,138 @@
import {
Body,
Controller,
Get,
Headers,
Param,
Post,
Query,
Req,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { CorporateService } from './corporate.service';
import { randomUUID } from 'crypto';
import { text } from './corporate-policy';
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'SUPER_ADMIN')
@Controller('admin/hermes')
export class CorporateController {
constructor(private readonly service: CorporateService) {}
private actor(req: any) {
// API keys must use their authenticated key identity, not an editable worker label.
const user = req.user;
const id = user?.id ?? user?.sub;
if (!id) throw new UnauthorizedException('Authenticated subject required');
return (user.isApiKey ? 'apikey:' : 'user:') + text(String(id), 200);
}
private key(key?: string) {
return text(key, 200);
}
@Get('runtime') runtime() {
return {
mode: 'MANUAL_DORMANT',
schedulesEnabled: false,
externalExecutionEnabled: false,
};
}
@Get('tasks') tasks(@Query() query: Record<string, any>) {
return this.service.tasks(query);
}
@Get('tasks/:id') detail(@Param('id') id: string) {
return this.service.detail(id);
}
@Post('tasks') create(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.create(this.actor(req), key ?? randomUUID(), body);
}
@Post('claims') claim(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.claim(this.actor(req), this.key(key), body);
}
@Post('tasks/:id/evidence') evidence(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.service.submitEvidence(
this.actor(req),
this.key(key),
id,
body,
);
}
@Post('tasks/:id/reviews') review(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.service.review(this.actor(req), this.key(key), id, body);
}
@Post('tasks/:id/effects') effect(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.service.effect(this.actor(req), this.key(key), id, body);
}
@Get('market-insights') insights(@Query() q: Record<string, any>) {
return this.service.collection('market-insights', q);
}
@Post('market-insights') research(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.research(this.actor(req), this.key(key), body);
}
@Get('monthly-roadmap') roadmaps(@Query() q: Record<string, any>) {
return this.service.collection('monthly-roadmap', q);
}
@Post('monthly-roadmap') roadmap(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.roadmap(this.actor(req), this.key(key), body);
}
@Post('monthly-plans') persistMonthlyPlan(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.persistMonthlyPlan(
this.actor(req),
this.key(key),
body,
);
}
@Get('monthly-plans/:roadmapId') monthlyPlan(
@Param('roadmapId') roadmapId: string,
@Query('month') month: string,
) {
return this.service.monthlyPlan(roadmapId, month);
}
@Get('reports') reports(@Query() q: Record<string, any>) {
return this.service.collection('reports', q);
}
@Post('reports') report(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.report(this.actor(req), this.key(key), body);
}
}
@@ -0,0 +1,969 @@
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
import passport from 'passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { PrismaClient } from '@prisma/client';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { createHash, randomUUID } from 'crypto';
import { canonical } from './corporate-policy';
import request from 'supertest';
import { PrismaService } from '../../prisma/prisma.service';
import { CorporateController } from './corporate.controller';
import { CorporateService } from './corporate.service';
import { ApiKeysService } from '../api-keys.service';
const integration = process.env.CORPORATE_TEST_DATABASE_URL
? describe
: describe.skip;
integration('corporate API / disposable PostgreSQL', () => {
let app: INestApplication, db: PrismaService;
const key = () => randomUUID();
const post = (path: string, body: any, actor = 'executor', op = key()) =>
request(app.getHttpServer())
.post('/admin/hermes/' + path)
.set('x-api-key', actor)
.set('Idempotency-Key', op)
.send(body);
const input = {
title: 'كيك ۱۲۳',
description: 'integration fixture',
department: 'CONTENT_SEO',
};
beforeAll(async () => {
// Explicit disposable loopback opt-in only; never consumes runtime DATABASE_URL.
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
throw new Error('Disposable loopback corporate_test DB required');
passport.use(
'jwt',
new Strategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'test-only-not-runtime',
},
(_payload, done) => done(null, false),
),
);
db = new PrismaClient({
datasources: { db: { url: process.env.CORPORATE_TEST_DATABASE_URL } },
}) as PrismaService;
const module = await Test.createTestingModule({
controllers: [CorporateController],
providers: [
CorporateService,
{ provide: PrismaService, useValue: db },
{
provide: ApiKeysService,
useValue: {
validateKey: async (id: string) => ({
id,
isApiKey: true,
role: 'Admin',
scopes: id === 'unscoped' ? [] : ['admin'],
}),
},
},
],
}).compile();
app = module.createNestApplication();
await app.listen(0, '127.0.0.1');
});
afterAll(async () => {
if (db)
await db.$executeRawUnsafe(
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
);
await app?.close();
await db?.$disconnect();
passport.unuse('jwt');
});
beforeEach(async () => {
await db.$executeRawUnsafe(
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
);
});
describe('exact task claim selector', () => {
it('claims only the exact task, leaving the older eligible task untouched', async () => {
const older = (await post('tasks', input).expect(201)).body;
const target = (
await post('tasks', { ...input, title: 'target' }).expect(201)
).body;
await db.corporateTask.update({
where: { id: older.id },
data: { updatedAt: new Date('2020-01-01T00:00:00Z') },
});
const result = (
await post('claims', { taskId: target.id.toUpperCase() }).expect(201)
).body;
expect(result.task.id).toBe(target.id);
expect(result.task.executionCount).toBe(1);
expect(
await db.corporateTask.findUniqueOrThrow({ where: { id: older.id } }),
).toMatchObject({
status: 'TODO',
executionCount: 0,
claimToken: null,
});
expect(
await db.corporateEvent.count({
where: { taskId: older.id, step: 'CLAIMED' },
}),
).toBe(0);
});
it('does not bypass the future PLANNED gate or fall back to another task', async () => {
const legacy = (await post('tasks', input).expect(201)).body;
const { body } = await planFixture();
const plan = (await post('monthly-plans', body).expect(201)).body;
const target = plan.tasks[0];
expect(
(await post('claims', { taskId: target.id }).expect(201)).body.task,
).toBeNull();
expect(
await db.corporateTask.findUniqueOrThrow({ where: { id: target.id } }),
).toMatchObject({
status: 'TODO',
executionCount: 0,
claimToken: null,
});
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
legacy.id,
);
});
it('rejects invalid UUID selectors before recording any operation', async () => {
for (const taskId of ['not-a-uuid', "' OR true --", '', null, 123])
await post('claims', { taskId }).expect(400);
expect(await db.corporateOperation.count()).toBe(0);
});
it('binds idempotency to the normalized selector and never claims a replacement', async () => {
const a = (await post('tasks', input).expect(201)).body;
const b = (await post('tasks', { ...input, title: 'other' }).expect(201))
.body;
const op = key();
const claimed = (
await post('claims', { taskId: a.id }, 'executor', op).expect(201)
).body;
expect(
(
await post(
'claims',
{ taskId: a.id.toUpperCase() },
'executor',
op,
).expect(201)
).body,
).toEqual(claimed);
await post('claims', { taskId: b.id }, 'executor', op).expect(409);
await post('claims', {}, 'executor', op).expect(409);
const legacyOp = key();
const legacy = (
await post('claims', {}, 'executor', legacyOp).expect(201)
).body;
expect(legacy.task.id).toBe(b.id);
await post('claims', { taskId: b.id }, 'executor', legacyOp).expect(409);
expect(
await db.corporateEvent.count({ where: { step: 'CLAIMED' } }),
).toBe(2);
});
it('preserves the historical no-selector hash and replay response', async () => {
const op = key();
const hash = (value: unknown) =>
createHash('sha256').update(canonical(value)).digest('hex');
const response = { task: null };
await db.corporateOperation.create({
data: {
key: hash(['apikey:executor', 'claim', op]),
payloadHash: hash({ department: null, seconds: 300 }),
response,
},
});
await post('tasks', input).expect(201);
expect(
(await post('claims', {}, 'executor', op).expect(201)).body,
).toEqual(response);
expect(
await db.corporateEvent.count({ where: { step: 'CLAIMED' } }),
).toBe(0);
});
});
async function planFixture(month = '2996-02') {
const research = (
await post('market-insights', {
title: 'monthly fixture',
category: 'TREND',
source: 'disposable receipt',
opportunity: 'test planning',
impact: 'LOW',
recommendedAction: 'plan',
cadence: 'MONTHLY',
provenance: {
method: 'fixture',
collector: 'jest',
context: 'disposable',
},
sources: [
{
url: 'https://pubmed.ncbi.nlm.nih.gov/',
title: 'fixture',
excerpt: 'test only',
retrievedAt: '2026-01-01T00:00:00Z',
sha256: 'a'.repeat(64),
},
],
}).expect(201)
).body;
const roadmap = (
await post('monthly-roadmap', {
researchId: research.id,
month,
cycleName: 'monthly fixture',
seasonalTheme: 'test',
strategicGoals: ['coverage'],
plannedArticlesCount: 29,
plannedRefreshesCount: 0,
plannedCatalogEnrichments: 0,
goals: [
'CONTENT_SEO',
'CATALOG_COMMERCE',
'WIKI_SCIENTIFIC',
'TECH_DEVOPS',
].map((department) => ({
title: department,
department,
acceptanceCriteria: 'independent QA',
metric: 'coverage',
})),
}).expect(201)
).body;
const task = (
actionType: string,
department: string,
dueCycle: string,
) => ({
title: actionType + ' ' + dueCycle,
description: 'Evidence-backed instruction requiring QA',
actionType,
department,
dueCycle,
goalId: roadmap.goals.find((g: any) => g.department === department).id,
sourceIds: [research.sources[0].id],
...(actionType === 'BLOG_NEW'
? {}
: {
target: 'https://canina.ir/identified-gap',
reason: 'Documented coverage gap',
}),
});
return {
research,
roadmap,
body: {
roadmapId: roadmap.id,
month,
dailyArticles: Array.from({ length: 29 }, (_, i) =>
task(
'BLOG_NEW',
'CONTENT_SEO',
`${month}-${String(i + 1).padStart(2, '0')}`,
),
),
needs: [
task('BLOG_UPDATE', 'CONTENT_SEO', month + '-01'),
task('CATALOG_ENRICH', 'CATALOG_COMMERCE', month + '-02'),
task('WIKI_ENRICH', 'WIKI_SCIENTIFIC', month + '-03'),
task('ENGINEERING', 'TECH_DEVOPS', month + '-04'),
],
},
};
}
it('runs manual planned inventory through HTTP, independent QA and persisted PMO without completing article', async () => {
const { body, research, roadmap } = await planFixture('2024-02');
// Real repository bytes, not invented clinical evidence or provider output.
const script = resolve(__dirname, '../../../../scripts/corporate_plan_inventory.py');
await db.corporateSource.update({
where: { id: research.sources[0].id },
data: { sha256: createHash('sha256').update(readFileSync(script)).digest('hex') },
});
const plan = (await post('monthly-plans', body).expect(201)).body;
const parent = plan.tasks.find((t: any) => t.actionType === 'BLOG_NEW');
const address = app.getHttpServer().address();
const result = await promisify(execFile)('python3', [
resolve(__dirname, '../../../../scripts/corporate_plan_inventory_http_test.py'),
`http://127.0.0.1:${address.port}`, roadmap.id, body.month, parent.id,
], { timeout: 20000 });
const receipt = JSON.parse(result.stdout);
expect(receipt).toMatchObject({ originalStatus: 'BLOCKED', independentQA: true,
selfReviewDenied: true, persistedPMOReadback: true });
console.log('MANUAL_PLAN_INVENTORY_RECEIPT', receipt);
});
it('persists a complete leap-month daily-new plan, separate needs and evidence lineage with readback', async () => {
const { body, research, roadmap } = await planFixture();
body.roadmapId = body.roadmapId.toUpperCase();
for (const entry of [...body.dailyArticles, ...body.needs]) {
entry.goalId = entry.goalId.toUpperCase();
entry.sourceIds = entry.sourceIds.map((id: string) => id.toUpperCase());
}
const op = key();
const created = (
await post('monthly-plans', body, 'planner', op).expect(201)
).body;
expect(created.tasks).toHaveLength(33);
const need = created.tasks.find((t: any) => t.actionType === 'WIKI_ENRICH');
expect(need.logs[0].payload).toMatchObject({
target: body.needs[2].target,
reason: body.needs[2].reason,
});
expect(
created.tasks.filter((t: any) => t.actionType === 'BLOG_NEW'),
).toHaveLength(29);
expect(created.tasks.every((t: any) => t.status === 'TODO')).toBe(true);
expect(
(await post('monthly-plans', body, 'planner', op).expect(201)).body,
).toEqual(created);
const read = await request(app.getHttpServer())
.get(
`/admin/hermes/monthly-plans/${roadmap.id.toUpperCase()}?month=${body.month}`,
)
.set('x-api-key', 'executor')
.expect(200);
expect(read.body).toEqual(created);
const detail = await request(app.getHttpServer())
.get('/admin/hermes/tasks/' + created.tasks[0].id)
.set('x-api-key', 'executor')
.expect(200);
expect(detail.body.logs[0].step).toBe('PLANNED');
expect(detail.body.logs[0].payload).toMatchObject({
researchId: research.id,
roadmapId: roadmap.id,
month: body.month,
dueCycle: body.month + '-01',
sourceIds: [research.sources[0].id],
});
expect(await db.corporateOperation.count()).toBe(3);
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
});
it('validates calendar, action separation, needs and stored lineage without partial writes', async () => {
const { body } = await planFixture();
const mutations: Array<[number, (b: any) => void]> = [
[400, (b) => b.dailyArticles.pop()],
[400, (b) => (b.dailyArticles[1].dueCycle = b.dailyArticles[0].dueCycle)],
[400, (b) => (b.dailyArticles[0].dueCycle = '2028-02-30')],
[400, (b) => (b.month = '2028-13')],
[400, (b) => (b.dailyArticles[0].actionType = 'BLOG_UPDATE')],
[400, (b) => (b.needs[0].actionType = 'BLOG_NEW')],
[400, (b) => (b.needs[0].reason = ' ')],
[400, (b) => delete b.needs[0].target],
[400, (b) => (b.needs[0].department = 'WIKI_SCIENTIFIC')],
[400, (b) => (b.dailyArticles[0].sourceIds = [])],
[409, (b) => (b.dailyArticles[0].sourceIds = [key()])],
[409, (b) => (b.dailyArticles[0].goalId = key())],
[409, (b) => (b.needs[0].goalId = b.needs[1].goalId)],
[409, (b) => (b.roadmapId = key())],
];
for (const [status, mutate] of mutations) {
const invalid = JSON.parse(JSON.stringify(body));
mutate(invalid);
await post('monthly-plans', invalid).expect(status);
expect(await db.corporateTask.count()).toBe(0);
expect(await db.corporateEvent.count()).toBe(0);
expect(await db.corporateOperation.count()).toBe(2);
}
});
it('serializes competing actors and keys on roadmap/month, rejects changed replay and keeps auth dormant', async () => {
const { body } = await planFixture();
await request(app.getHttpServer())
.post('/admin/hermes/monthly-plans')
.send(body)
.expect(401);
await post('monthly-plans', body, 'unscoped').expect(403);
const op = key();
const otherOp = key();
let release!: () => void;
let ready!: () => void;
const locked = new Promise<void>((r) => (ready = r));
const hold = new Promise<void>((r) => (release = r));
const scope = JSON.stringify(['monthly-plan', body.roadmapId, body.month]);
const blocker = db.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
ready();
await hold;
});
await locked;
const pending = [
post('monthly-plans', body, 'planner', op).then((r) => r),
post('monthly-plans', body, 'other', otherOp).then((r) => r),
];
try {
let waiters = 0;
for (let i = 0; i < 100; i++) {
const rows = await db.$queryRaw<any[]>`SELECT pid FROM pg_stat_activity
WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%pg_advisory_xact_lock%'`;
waiters = rows.length;
if (waiters >= 2) break;
await new Promise((r) => setTimeout(r, 10));
}
expect(waiters).toBeGreaterThanOrEqual(2);
} finally {
release();
await blocker;
}
const results = await Promise.all(pending);
expect(results.map((r) => r.status).sort()).toEqual([201, 409]);
expect(await db.corporateTask.count()).toBe(33);
expect(await db.corporateEvent.count({ where: { step: 'PLANNED' } })).toBe(
33,
);
const winner = results[0].status === 201 ? 'planner' : 'other';
const winningOp = winner === 'planner' ? op : otherOp;
await post(
'monthly-plans',
{ ...body, needs: [] },
winner,
winningOp,
).expect(409);
expect(
(await post('monthly-plans', body, winner, winningOp).expect(201)).body,
).toEqual(results[winner === 'planner' ? 0 : 1].body);
const runtime = await request(app.getHttpServer())
.get('/admin/hermes/runtime')
.set('x-api-key', 'executor')
.expect(200);
expect(runtime.body).toEqual({
mode: 'MANUAL_DORMANT',
schedulesEnabled: false,
externalExecutionEnabled: false,
});
});
it('rolls back a mid-plan database failure including tasks, events and idempotency receipt', async () => {
const { body } = await planFixture();
// Disposable-only trigger fails after the first task/event have been written.
await db.$executeRawUnsafe(
`CREATE FUNCTION reject_plan_event() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.step='PLANNED' AND NEW.payload->>'dueCycle'='2996-02-02' THEN RAISE EXCEPTION 'injected plan failure'; END IF; RETURN NEW; END $$`,
);
await db.$executeRawUnsafe(
'CREATE TRIGGER reject_plan_event BEFORE INSERT ON corporate_events FOR EACH ROW EXECUTE FUNCTION reject_plan_event()',
);
const op = key();
try {
await post('monthly-plans', body, 'planner', op).expect(500);
expect(await db.corporateTask.count()).toBe(0);
expect(await db.corporateEvent.count()).toBe(0);
expect(await db.corporateOperation.count()).toBe(2);
} finally {
await db.$executeRawUnsafe(
'DROP TRIGGER reject_plan_event ON corporate_events',
);
await db.$executeRawUnsafe('DROP FUNCTION reject_plan_event()');
}
await post('monthly-plans', body, 'planner', op).expect(201);
});
it('gates only PLANNED future tasks while legacy future dueCycle remains claimable and UTC today is eligible', async () => {
const { body } = await planFixture();
await post('monthly-plans', body).expect(201);
const legacy = (
await post('tasks', { ...input, dueCycle: '2999-12-31' }).expect(201)
).body;
expect((await post('claims', {}).expect(201)).body.task.id).toBe(legacy.id);
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
// Model the persisted event's due-day boundary in the disposable DB without changing system time.
const planned = await db.corporateTask.findFirstOrThrow({
where: { actionType: 'BLOG_NEW' },
});
const day = new Date().toISOString().slice(0, 10);
await db.corporateTask.update({
where: { id: planned.id },
data: { dueCycle: day },
});
expect((await post('claims', {}).expect(201)).body.task).toBeNull(); // mismatch fails closed
const event = await db.corporateEvent.findFirstOrThrow({
where: { taskId: planned.id, step: 'PLANNED' },
});
await db.corporateEvent.update({
where: { id: event.id },
data: { payload: { ...(event.payload as object), dueCycle: day } },
});
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
planned.id,
);
});
it('rejects children after a parent claim commits while child creation waits on its row lock', async () => {
const parent = (await post('tasks', input).expect(201)).body;
let release!: () => void, locked!: () => void;
const ready = new Promise<void>((r) => (locked = r));
const hold = new Promise<void>((r) => (release = r));
const claiming = db.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${parent.id}::uuid FOR UPDATE`;
await tx.corporateTask.update({
where: { id: parent.id },
data: {
status: 'IN_PROGRESS',
claimToken: key(),
assignedAgent: 'executor',
leasedUntil: new Date(Date.now() + 60000),
},
});
locked();
await hold;
});
await ready;
const pending = post('tasks', { ...input, parentId: parent.id }).then(
(r) => r,
);
try {
// Observe actual competing PostgreSQL lock wait, not a timing-only race.
let waiting = false;
for (let i = 0; i < 100; i++) {
const rows = await db.$queryRaw<
any[]
>`SELECT pid FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%corporate_tasks%'`;
if (rows.length) {
waiting = true;
break;
}
await new Promise((r) => setTimeout(r, 10));
}
expect(waiting).toBe(true);
} finally {
release();
await claiming;
}
expect((await pending).status).toBe(409);
expect(
await db.corporateTask.count({ where: { parentId: parent.id } }),
).toBe(0);
});
it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
for (const status of ['TODO', 'BLOCKED'] as const) {
const parent = (await post('tasks', input).expect(201)).body;
await db.corporateTask.update({
where: { id: parent.id },
data: { status },
});
const child = (
await post('tasks', { ...input, parentId: parent.id }).expect(201)
).body;
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
child.id,
);
}
});
it('rejects malformed artifact locators and mismatched digest URNs before persistence', async () => {
const task = (await post('tasks', input).expect(201)).body;
const claim = (await post('claims', {}).expect(201)).body.task;
const body = {
claimToken: claim.claimToken,
artifactUri: '',
sha256: 'a'.repeat(64),
summary: 'receipt',
tool: 'jest',
result: 'passed',
};
for (const artifactUri of [
'https://',
'https://?x',
'https:///pubmed.ncbi.nlm.nih.gov/x',
'https://pubmed.ncbi.nlm.nih.gov./x',
'https://bad host/x',
'https://user:pass@host.org/a',
'https://localhost/a',
'https://127.1/a',
'https://[::1]/a',
'urn:sha256:',
'urn:sha256:' + 'b'.repeat(64),
]) {
await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
400,
);
}
expect(await db.corporateEvidence.count()).toBe(0);
await post(`tasks/${task.id}/evidence`, {
...body,
artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/',
}).expect(201);
});
it('rejects implicit timestamp coercions in source and effect inputs', async () => {
const service = app.get(CorporateService);
const research = {
title: 'research',
category: 'TREND',
source: 'receipt',
opportunity: 'investigate',
impact: 'LOW',
recommendedAction: 'measure',
cadence: 'MONTHLY',
provenance: { method: 'test', collector: 'fixture', context: 'isolated' },
sources: [
{
url: 'https://pubmed.ncbi.nlm.nih.gov/',
title: 'source',
excerpt: 'receipt',
retrievedAt: '',
sha256: 'a'.repeat(64),
},
],
};
for (const time of [
null,
0,
false,
[],
'2026-01-01',
'2026-02-30T00:00:00Z',
]) {
await expect(
Promise.resolve().then(() =>
service.research('fixture', key(), {
...research,
sources: [{ ...research.sources[0], retrievedAt: time }],
}),
),
).rejects.toThrow();
await expect(
Promise.resolve().then(() =>
service.effect('fixture', key(), key(), {
metric: 'views',
availability: 'UNAVAILABLE',
source: 'none',
observedAt: time,
}),
),
).rejects.toThrow('Invalid observation time');
}
for (const url of ['https://', 'https://?bad', 'https://bad host'])
await expect(
Promise.resolve().then(() =>
service.research('fixture', key(), {
...research,
sources: [
{
...research.sources[0],
retrievedAt: '2026-01-01T00:00:00Z',
url,
},
],
}),
),
).rejects.toThrow();
expect(await db.corporateResearch.count()).toBe(0);
});
it('public reads strip claim tokens recursively while claim and replay retain ownership token', async () => {
const parent = (await post('tasks', input).expect(201)).body;
const child = (
await post('tasks', { ...input, parentId: parent.id }).expect(201)
).body;
const op = key();
const claim = (await post('claims', {}, 'executor', op).expect(201)).body
.task;
expect(claim.claimToken).toBeTruthy();
expect(
(await post('claims', {}, 'executor', op).expect(201)).body.task
.claimToken,
).toBe(claim.claimToken);
await post(`tasks/${child.id}/evidence`, {
claimToken: claim.claimToken,
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
sha256: 'a'.repeat(64),
summary: 'receipt',
tool: 'jest',
result: 'passed',
}).expect(201);
for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
const r = await request(app.getHttpServer())
.get('/admin/hermes/' + path)
.set('x-api-key', 'competitor')
.expect(200);
expect(JSON.stringify(r.body)).not.toContain('claimToken');
expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
}
});
it('bounds detail relations and report snapshots with explicit truncation and immutable replay', async () => {
const task = (await post('tasks', input).expect(201)).body;
await db.corporateEvent.createMany({
data: Array.from({ length: 105 }, () => ({
taskId: task.id,
speaker: 'SYSTEM',
speakerName: 'fixture',
step: 'FIXTURE',
content: 'x'.repeat(10000),
payload: { nested: ['x'.repeat(10000)] },
})),
});
const detail = await request(app.getHttpServer())
.get('/admin/hermes/tasks/' + task.id)
.set('x-api-key', 'executor')
.expect(200);
expect(detail.body.logs).toHaveLength(100);
expect(detail.body.relationsMeta.logs).toEqual({
total: 106,
returned: 100,
limit: 100,
truncated: true,
});
const op = key(),
body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
const report = (await post('reports', body, 'executor', op).expect(201))
.body;
expect(report.snapshot.events).toHaveLength(100);
expect(report.snapshot.meta.events).toEqual({
total: 106,
returned: 100,
limit: 100,
truncated: true,
});
expect(report.snapshot.events.every((e: any) => !('payload' in e))).toBe(
true,
);
expect(report.snapshot.meta.fieldsTruncated).toBe(true);
expect(
Buffer.byteLength(JSON.stringify(report.body ?? report)),
).toBeLessThan(1000000);
await db.corporateEvent.deleteMany();
expect(
(await post('reports', body, 'executor', op).expect(201)).body,
).toEqual(report);
});
it('rolls back oversized mutation responses instead of persisting huge idempotency values', async () => {
const service = app.get(CorporateService) as any;
const before = await db.corporateTask.count();
await expect(
service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
await tx.corporateTask.create({
data: {
title: 'rollback',
description: 'fixture',
taskCode: key(),
normalizedTitle: 'rollback',
normalizedCode: key(),
department: 'CONTENT_SEO',
createdBy: 'fixture',
},
});
return { value: 'x'.repeat(1100000) };
}),
).rejects.toThrow('Operation response exceeds limit');
expect(await db.corporateTask.count()).toBe(before);
expect(await db.corporateOperation.count()).toBe(0);
});
it('auth, UI list contract, normalized search, immutable idempotent replay', async () => {
await request(app.getHttpServer()).get('/admin/hermes/tasks').expect(401);
await post('tasks', input, 'unscoped').expect(403);
const op = key(),
a = await post('tasks', input, 'executor', op).expect(201);
const b = await post('tasks', input, 'executor', op).expect(201);
expect(b.body.id).toBe(a.body.id);
await post('tasks', { ...input, title: 'changed' }, 'executor', op).expect(
409,
);
const list = await request(app.getHttpServer())
.get('/admin/hermes/tasks?search=کیک%20123&limit=1')
.set('x-api-key', 'executor')
.expect(200);
expect(list.body.meta).toEqual({
total: 1,
page: 1,
limit: 1,
totalPages: 1,
hasNextPage: false,
hasPrevPage: false,
});
expect(list.body.data[0].priority).toBe('CEO_EXPEDITE');
await request(app.getHttpServer())
.get('/admin/hermes/tasks?limit=101')
.set('x-api-key', 'executor')
.expect(400);
await request(app.getHttpServer())
.get('/admin/hermes/tasks?sortBy=password')
.set('x-api-key', 'executor')
.expect(400);
});
it('claims exclusively, expires/reclaims, fences stale executor, requires independent QA', async () => {
const task = (await post('tasks', input).expect(201)).body;
const claims = await Promise.all([
post('claims', {}, 'executor'),
post('claims', {}, 'competitor'),
]);
expect(claims.filter((x) => x.body.task !== null)).toHaveLength(1);
const claimed = claims.find((x) => x.body.task !== null)!.body.task;
const oldActor = claimed.assignedAgent.replace('apikey:', '');
await db.$executeRaw`UPDATE corporate_tasks SET "leasedUntil"=clock_timestamp()-interval '1 second' WHERE id=${task.id}::uuid`;
const renewed = (await post('claims', {}, 'new-executor').expect(201)).body
.task;
expect(renewed.claimToken).not.toBe(claimed.claimToken);
const evidence = {
claimToken: claimed.claimToken,
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
sha256: 'a'.repeat(64),
summary: 'receipt',
tool: 'jest',
result: 'passed',
};
await post(`tasks/${task.id}/evidence`, evidence, oldActor).expect(409);
const e = (
await post(
`tasks/${task.id}/evidence`,
{ ...evidence, claimToken: renewed.claimToken },
'new-executor',
).expect(201)
).body;
const review = {
evidenceId: e.id,
passed: true,
findings: 'verified',
verification: {
artifactUri: e.artifactUri,
sha256: e.sha256,
method: 'digest readback',
result: 'match',
},
};
await post(`tasks/${task.id}/reviews`, review, 'new-executor').expect(409);
await post(`tasks/${task.id}/reviews`, review, 'reviewer').expect(201);
const detail = await request(app.getHttpServer())
.get('/admin/hermes/tasks/' + task.id)
.set('x-api-key', 'reviewer')
.expect(200);
expect(detail.body.status).toBe('DONE');
expect(detail.body.logs.map((x: any) => x.step)).toContain('QA_PASSED');
await post(`tasks/${task.id}/effects`, {
metric: 'engagement',
availability: 'UNAVAILABLE',
observed: 0,
source: 'provider unavailable',
observedAt: new Date().toISOString(),
}).expect(400);
});
it('skips a held row lock and gives CEO priority before lower priorities', async () => {
const urgent = (await post('tasks', input).expect(201)).body;
const low = (await post('tasks', { ...input, priority: 'LOW' }).expect(201))
.body;
let release!: () => void, locked!: () => void;
const ready = new Promise<void>((r) => (locked = r)),
hold = new Promise<void>((r) => (release = r));
const locking = db.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${urgent.id}::uuid FOR UPDATE`;
locked();
await hold;
});
await ready;
try {
const claim = (await post('claims', {}).expect(201)).body.task;
expect(claim.id).toBe(low.id);
} finally {
release();
await locking;
}
const next = (await post('claims', {}, 'other').expect(201)).body.task;
expect(next.id).toBe(urgent.id);
});
it('serializes simultaneous duplicate mutations into one durable record', async () => {
const op = key();
const responses = await Promise.all([
post('tasks', input, 'executor', op),
post('tasks', input, 'executor', op),
]);
expect(responses.map((r) => r.status)).toEqual([201, 201]);
expect(responses[0].body.id).toBe(responses[1].body.id);
expect(await db.corporateTask.count()).toBe(1);
});
it('gates parents on children, persists provenance, roadmap/goals and reports', async () => {
const parent = (await post('tasks', input).expect(201)).body;
const child = (
await post('tasks', { ...input, parentId: parent.id }).expect(201)
).body;
const claim = (await post('claims', {}).expect(201)).body.task;
expect(claim.id).toBe(child.id);
const e = (
await post(`tasks/${child.id}/evidence`, {
claimToken: claim.claimToken,
artifactUri: 'urn:sha256:' + 'b'.repeat(64),
sha256: 'b'.repeat(64),
summary: 'child artifact',
tool: 'jest',
result: 'receipt',
}).expect(201)
).body;
await post(
`tasks/${child.id}/reviews`,
{
evidenceId: e.id,
passed: false,
findings: 'needs correction',
verification: {
artifactUri: e.artifactUri,
sha256: e.sha256,
method: 'readback',
result: 'failed',
},
},
'reviewer',
).expect(201);
expect(
(await db.corporateTask.findUniqueOrThrow({ where: { id: parent.id } }))
.status,
).toBe('BLOCKED');
expect((await post('claims', {}).expect(201)).body.task.id).toBe(child.id);
const research = (
await post('market-insights', {
title: 'fixture research',
category: 'TREND',
source: 'study receipt',
opportunity: 'investigate',
impact: 'LOW',
recommendedAction: 'measure',
cadence: 'MONTHLY',
provenance: {
method: 'test fixture',
collector: 'integration',
context: 'disposable',
},
sources: [
{
url: 'https://pubmed.ncbi.nlm.nih.gov/',
title: 'fixture',
excerpt: 'test-only',
retrievedAt: '2026-01-01T00:00:00Z',
sha256: 'a'.repeat(64),
},
],
}).expect(201)
).body;
const roadmap = (
await post('monthly-roadmap', {
researchId: research.id,
cycleName: 'test',
month: '2026-10',
seasonalTheme: 'evidence pending seasonal analysis',
strategicGoals: ['measure'],
plannedArticlesCount: 31,
plannedRefreshesCount: 0,
plannedCatalogEnrichments: 0,
goals: [
{
title: 'goal',
department: 'CONTENT_SEO',
acceptanceCriteria: 'QA',
metric: 'engagement',
},
],
}).expect(201)
).body;
expect(roadmap.goals).toHaveLength(1);
await post('tasks', { ...input, goalId: roadmap.goals[0].id }).expect(201);
for (const path of ['market-insights', 'monthly-roadmap']) {
const r = await request(app.getHttpServer())
.get('/admin/hermes/' + path)
.set('x-api-key', 'executor')
.expect(200);
expect(r.body.meta.total).toBe(1);
}
const report = (
await post('reports', {
day: new Date().toISOString().slice(0, 10),
summary: 'test fixture daily report',
}).expect(201)
).body;
expect(report.snapshot.tasks).toHaveLength(3);
});
});
@@ -0,0 +1,845 @@
import {
Injectable,
BadRequestException,
ConflictException,
NotFoundException,
} from '@nestjs/common';
import { Prisma, CorporatePriority } from '@prisma/client';
import { createHash, randomUUID } from 'crypto';
import { PrismaService } from '../../prisma/prisma.service';
import {
canonical,
monthlyPlanInput,
planMonth,
publicData,
choice,
departments,
evidenceInput,
httpsUrl,
timestamp,
meta,
normalizeSearch,
object,
pagination,
priorities,
statuses,
taskInput,
text,
uuid,
} from './corporate-policy';
type Tx = Prisma.TransactionClient;
@Injectable()
export class CorporateService {
constructor(private readonly db: PrismaService) {}
private async operation(
actor: string,
op: string,
key: string,
body: unknown,
fn: (tx: Tx) => Promise<any>,
) {
text(key, 200);
const scoped = createHash('sha256')
.update(canonical([actor, op, key]))
.digest('hex');
const hash = createHash('sha256').update(canonical(body)).digest('hex');
return this.db.$transaction(
async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scoped}, 0))`;
const prior = await tx.corporateOperation.findUnique({
where: { key: scoped },
});
if (prior) {
if (prior.payloadHash !== hash)
throw new ConflictException('Idempotency key payload mismatch');
return prior.response;
}
const result = await fn(tx);
const serialized = JSON.stringify(result);
if (Buffer.byteLength(serialized, 'utf8') > 1000000)
throw new BadRequestException('Operation response exceeds limit');
const response = JSON.parse(serialized);
await tx.corporateOperation.create({
data: { key: scoped, payloadHash: hash, response },
});
return response;
},
{ maxWait: 10000, timeout: 20000 },
);
}
private event(
tx: Tx,
taskId: string,
actor: string,
step: string,
content: string,
speaker = 'SYSTEM',
payload?: any,
) {
return tx.corporateEvent.create({
data: { taskId, speaker, speakerName: actor, step, content, payload },
});
}
private async lock(tx: Tx, id: string) {
uuid(id);
const rows = await tx.$queryRaw<
{ id: string }[]
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid FOR UPDATE`;
if (!rows.length) throw new NotFoundException('Task not found');
return tx.corporateTask.findUniqueOrThrow({ where: { id } });
}
private async fenced(tx: Tx, id: string, token: string, actor: string) {
const t = await this.lock(tx, id);
const rows = await tx.$queryRaw<
{ id: string }[]
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid AND "claimToken"=${token}::uuid AND "assignedAgent"=${actor} AND "leasedUntil">clock_timestamp() AND status='IN_PROGRESS'`;
if (!rows.length) throw new ConflictException('Stale lease or owner');
return t;
}
async tasks(q: Record<string, any>) {
const p = pagination(q),
where: Prisma.CorporateTaskWhereInput = {};
if (q.department) where.department = choice(q.department, departments);
if (q.priority)
where.priority = choice(q.priority, priorities) as CorporatePriority;
if (q.status) where.status = choice(q.status, statuses) as any;
if (q.search) {
const search = normalizeSearch(text(q.search, 300));
where.OR = [
{ normalizedTitle: { contains: search } },
{ normalizedCode: { contains: search } },
];
}
if (q.goalId) where.goalId = uuid(q.goalId);
return this.db.$transaction(
async (tx) => {
const total = await tx.corporateTask.count({ where });
const data = await tx.corporateTask.findMany({
where,
skip: p.skip,
take: p.limit,
orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }],
});
const deptGroup = await tx.corporateTask.groupBy({
by: ['department'],
_count: { id: true },
});
const departmentCounts: Record<string, number> = {};
for (const d of departments) departmentCounts[d] = 0;
for (const row of deptGroup) {
departmentCounts[row.department] = row._count.id;
}
return publicData({
data,
meta: {
...meta(total, p.page, p.limit),
departmentCounts,
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
}
async detail(id: string) {
uuid(id);
return this.db.$transaction(
async (tx) => {
const order = { id: 'asc' as const };
const task = await tx.corporateTask.findUnique({
where: { id },
include: {
logs: { take: 100, orderBy: [{ timestamp: 'asc' }, order] },
evidence: { take: 100, orderBy: order },
reviews: { take: 100, orderBy: order },
effects: { take: 100, orderBy: order },
children: { take: 100, orderBy: order },
_count: {
select: {
logs: true,
evidence: true,
reviews: true,
effects: true,
children: true,
},
},
},
});
if (!task) throw new NotFoundException('Task not found');
const { _count, ...data } = task;
const relationsMeta = Object.fromEntries(
Object.entries(_count).map(([name, total]) => [
name,
{
total,
returned: Math.min(total, 100),
limit: 100,
truncated: total > 100,
},
]),
);
return publicData({ ...data, relationsMeta });
},
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
}
create(actor: string, key: string, input: unknown) {
const b = taskInput(input);
return this.operation(actor, 'create-task', key, b, async (tx) => {
if (b.parentId) {
const parent = await this.lock(tx, b.parentId);
if (!['TODO', 'BLOCKED'].includes(parent.status))
throw new ConflictException('Parent no longer accepts children');
}
const code = 'TSK-' + randomUUID();
const task = await tx.corporateTask.create({
data: {
...b,
priority: b.priority as CorporatePriority,
taskCode: code,
normalizedCode: normalizeSearch(code),
normalizedTitle: normalizeSearch(b.title),
createdBy: actor,
},
});
await this.event(tx, task.id, actor, 'CREATED', b.description, 'CEO');
return task;
});
}
private plannedWhere(
roadmapId: string,
month: string,
): Prisma.CorporateEventWhereInput {
return {
step: 'PLANNED',
AND: [
{ payload: { path: ['roadmapId'], equals: roadmapId } },
{ payload: { path: ['month'], equals: month } },
],
};
}
private async readPlan(tx: Tx, roadmapId: string, month: string) {
const roadmap = await tx.corporateRoadmap.findUnique({
where: { id: roadmapId },
});
const tasks = await tx.corporateTask.findMany({
where: { logs: { some: this.plannedWhere(roadmapId, month) } },
include: {
logs: {
where: this.plannedWhere(roadmapId, month),
orderBy: { id: 'asc' },
},
},
orderBy: [{ dueCycle: 'asc' }, { actionType: 'asc' }, { id: 'asc' }],
});
if (!roadmap || !tasks.length)
throw new NotFoundException('Monthly plan not found');
return publicData({
roadmapId,
month,
researchId: roadmap.researchId,
tasks,
});
}
monthlyPlan(roadmapId: string, month: unknown) {
roadmapId = uuid(roadmapId);
const cycle = planMonth(month);
return this.db.$transaction((tx) => this.readPlan(tx, roadmapId, cycle), {
isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead,
});
}
persistMonthlyPlan(actor: string, key: string, input: unknown) {
const b = monthlyPlanInput(input);
return this.operation(actor, 'monthly-plan', key, b, async (tx) => {
// Separate actor/key-independent fence: one complete plan per roadmap/month.
const scope = canonical(['monthly-plan', b.roadmapId, b.month]);
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
if (
await tx.corporateEvent.count({
where: this.plannedWhere(b.roadmapId, b.month),
})
)
throw new ConflictException('Monthly plan already persisted');
const roadmap = await tx.corporateRoadmap.findUnique({
where: { id: b.roadmapId },
include: { goals: true, research: { include: { sources: true } } },
});
if (
!roadmap ||
roadmap.month !== b.month ||
!roadmap.research.sources.length
)
throw new ConflictException(
'Matching evidence-backed roadmap required',
);
const entries = [...b.dailyArticles, ...b.needs];
for (const entry of entries) {
if (
!roadmap.goals.some(
(g) => g.id === entry.goalId && g.department === entry.department,
) ||
!entry.sourceIds.every((id) =>
roadmap.research.sources.some((s) => s.id === id),
)
)
throw new ConflictException(
'Goal/department and source lineage must match roadmap research',
);
}
for (const entry of entries) {
const { sourceIds, target, reason, ...data } = entry;
const taskCode = 'TSK-' + randomUUID();
const task = await tx.corporateTask.create({
data: {
...data,
priority: data.priority as CorporatePriority,
status: 'TODO',
taskCode,
normalizedCode: normalizeSearch(taskCode),
normalizedTitle: normalizeSearch(data.title),
createdBy: actor,
},
});
await this.event(
tx,
task.id,
actor,
'PLANNED',
entry.description,
'SYSTEM',
{
version: 1,
roadmapId: roadmap.id,
researchId: roadmap.researchId,
month: b.month,
goalId: entry.goalId,
department: entry.department,
actionType: entry.actionType,
dueCycle: entry.dueCycle,
sourceIds,
...(target ? { target, reason } : {}),
},
);
}
return this.readPlan(tx, b.roadmapId, b.month);
});
}
claim(actor: string, key: string, input: unknown) {
const b = object(input, ['department', 'leaseSeconds', 'taskId']);
const taskId = b.taskId === undefined ? undefined : uuid(b.taskId);
const department =
b.department === undefined ? null : choice(b.department, departments);
const seconds = Number(b.leaseSeconds ?? 300);
if (!Number.isInteger(seconds) || seconds < 30 || seconds > 900)
throw new BadRequestException('Lease must be 30..900 seconds');
return this.operation(
actor,
'claim',
key,
{ department, seconds, ...(taskId === undefined ? {} : { taskId }) },
async (tx) => {
const candidates = await tx.$queryRaw<
{ id: string }[]
>`SELECT t.id FROM corporate_tasks t
WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp()))
AND NOT EXISTS (SELECT 1 FROM corporate_events e WHERE e."taskId"=t.id AND e.step='PLANNED'
AND (t."dueCycle" IS NULL OR t."dueCycle" !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
OR e.payload->>'dueCycle' IS DISTINCT FROM t."dueCycle"
OR t."dueCycle">to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD')))
AND (${taskId ?? null}::text IS NULL OR t.id=${taskId ?? null}::uuid)
AND (${department}::text IS NULL OR t.department=${department})
AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE')
ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`;
if (!candidates.length) return { task: null };
const id = candidates[0].id,
token = randomUUID();
await tx.$executeRaw`UPDATE corporate_tasks SET status='IN_PROGRESS', "assignedAgent"=${actor}, "claimToken"=${token}::uuid, "leasedUntil"=clock_timestamp()+make_interval(secs=>${seconds}::int), "executionCount"="executionCount"+1,"updatedAt"=clock_timestamp() WHERE id=${id}::uuid`;
await this.event(tx, id, actor, 'CLAIMED', 'Manual lease acquired');
return {
task: await tx.corporateTask.findUniqueOrThrow({ where: { id } }),
};
},
);
}
submitEvidence(actor: string, key: string, id: string, input: unknown) {
const b = evidenceInput(input);
return this.operation(actor, 'evidence:' + id, key, b, async (tx) => {
await this.fenced(tx, id, b.claimToken, actor);
const e = await tx.corporateEvidence.create({
data: { ...b, taskId: id, executor: actor },
});
await tx.corporateTask.update({
where: { id },
data: { status: 'TEST', leasedUntil: null },
});
await this.event(
tx,
id,
actor,
'EVIDENCE_SUBMITTED',
b.summary,
'AGENT',
{ evidenceId: e.id },
);
return e;
});
}
review(actor: string, key: string, id: string, input: unknown) {
const b = object(input, [
'evidenceId',
'passed',
'findings',
'verification',
]);
const evidenceId = uuid(b.evidenceId),
findings = text(b.findings);
if (typeof b.passed !== 'boolean')
throw new BadRequestException('passed must be boolean');
const v = object(b.verification, [
'artifactUri',
'sha256',
'method',
'result',
]);
const verification = {
artifactUri: text(v.artifactUri, 2000),
sha256: text(v.sha256, 64),
method: text(v.method, 1000),
result: text(v.result),
};
return this.operation(actor, 'review:' + id, key, b, async (tx) => {
uuid(id);
const relation = await tx.corporateTask.findUnique({
where: { id },
select: { parentId: true },
});
if (relation?.parentId) await this.lock(tx, relation.parentId);
const task = await this.lock(tx, id);
const evidence = await tx.corporateEvidence.findUnique({
where: { id: evidenceId },
});
if (
task.status !== 'TEST' ||
!evidence ||
evidence.taskId !== id ||
evidence.claimToken !== task.claimToken
)
throw new ConflictException('Current execution evidence required');
if (evidence.executor === actor)
throw new ConflictException('Independent reviewer required');
if (
verification.sha256 !== evidence.sha256 ||
verification.artifactUri !== evidence.artifactUri
)
throw new ConflictException('QA must verify exact artifact');
if (
b.passed &&
(await tx.corporateTask.count({
where: { parentId: id, status: { not: 'DONE' } },
}))
)
throw new ConflictException('Unfinished children');
const r = await tx.corporateReview.create({
data: {
taskId: id,
evidenceId,
reviewer: actor,
passed: b.passed,
findings,
verification,
},
});
await tx.corporateTask.update({
where: { id },
data: {
status: b.passed ? 'DONE' : 'TODO',
claimToken: null,
leasedUntil: null,
qaCount: { increment: 1 },
rejectionCount: { increment: b.passed ? 0 : 1 },
},
});
if (!b.passed && task.parentId) {
await tx.corporateTask.update({
where: { id: task.parentId },
data: { status: 'BLOCKED' },
});
await this.event(
tx,
task.parentId,
actor,
'CHILD_QA_REJECTED',
'Parent blocked pending child correction',
'QA',
{ childId: id },
);
}
await this.event(
tx,
id,
actor,
b.passed ? 'QA_PASSED' : 'QA_REJECTED',
findings,
'QA',
{ reviewId: r.id },
);
return r;
});
}
async collection(
kind: 'market-insights' | 'monthly-roadmap' | 'reports',
q: Record<string, any>,
) {
const p = pagination(q);
return this.db.$transaction(
async (tx) => {
const model =
kind === 'market-insights'
? tx.corporateResearch
: kind === 'monthly-roadmap'
? tx.corporateRoadmap
: tx.corporateReport;
const where: any = {};
if (kind === 'market-insights' && q.category)
where.category = choice(q.category, [
'TREND',
'COMPETITOR',
'NEW_CHANNEL',
'CATALOG_GAP',
]);
if (kind === 'monthly-roadmap' && q.month)
where.month = text(q.month, 40);
const delegate = model as any;
const total = await delegate.count({ where });
const data = await delegate.findMany({
where,
skip: p.skip,
take: p.limit,
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
...(kind === 'market-insights'
? { include: { sources: true } }
: kind === 'monthly-roadmap'
? { include: { goals: true } }
: {}),
});
return publicData({ data, meta: meta(total, p.page, p.limit) });
},
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
}
research(actor: string, key: string, input: unknown) {
const b = object(input, [
'title',
'category',
'source',
'opportunity',
'impact',
'recommendedAction',
'cadence',
'provenance',
'sources',
]);
if (!Array.isArray(b.sources) || !b.sources.length || b.sources.length > 30)
throw new BadRequestException('1..30 sources required');
const sources = b.sources.map((raw) => {
const s = object(raw, [
'url',
'title',
'excerpt',
'retrievedAt',
'sha256',
]);
const url = httpsUrl(s.url),
sha256 = text(s.sha256, 64),
retrievedAt = timestamp(s.retrievedAt, 'Invalid source time');
if (
!url.startsWith('https://') ||
!/^[a-f0-9]{64}$/.test(sha256) ||
!Number.isFinite(retrievedAt.getTime()) ||
retrievedAt.getTime() > Date.now()
)
throw new BadRequestException('Invalid source');
return {
url,
sha256,
retrievedAt,
title: text(s.title, 300),
excerpt: text(s.excerpt),
};
});
const provenance = object(b.provenance, ['method', 'collector', 'context']);
const data = {
title: text(b.title, 300),
category: choice(b.category, [
'TREND',
'COMPETITOR',
'NEW_CHANNEL',
'CATALOG_GAP',
]),
source: text(b.source, 2000),
opportunity: text(b.opportunity),
impact: choice(b.impact, ['HIGH', 'MEDIUM', 'LOW']),
recommendedAction: text(b.recommendedAction),
cadence: choice(b.cadence, ['MONTHLY', 'EVENT']),
provenance: {
method: text(provenance.method),
collector: text(provenance.collector, 300),
context: text(provenance.context),
},
createdBy: actor,
};
return this.operation(actor, 'research', key, b, (tx) =>
tx.corporateResearch.create({
data: { ...data, sources: { create: sources } },
include: { sources: true },
}),
);
}
roadmap(actor: string, key: string, input: unknown) {
const b = object(input, [
'researchId',
'cycleName',
'month',
'seasonalTheme',
'strategicGoals',
'plannedArticlesCount',
'plannedRefreshesCount',
'plannedCatalogEnrichments',
'isActive',
'goals',
]);
if (
!Array.isArray(b.strategicGoals) ||
!b.strategicGoals.length ||
b.strategicGoals.length > 30 ||
!Array.isArray(b.goals) ||
!b.goals.length ||
b.goals.length > 100
)
throw new BadRequestException('Goals required');
for (const k of [
'plannedArticlesCount',
'plannedRefreshesCount',
'plannedCatalogEnrichments',
])
if (!Number.isInteger(b[k]) || b[k] < 0 || b[k] > 10000)
throw new BadRequestException('Invalid counts');
if (b.isActive !== undefined && typeof b.isActive !== 'boolean')
throw new BadRequestException('Invalid active flag');
const goals = b.goals.map((raw) => {
const g = object(raw, [
'title',
'department',
'acceptanceCriteria',
'metric',
'target',
]);
if (
g.target !== undefined &&
(typeof g.target !== 'number' || !Number.isFinite(g.target))
)
throw new BadRequestException('Invalid target');
return {
title: text(g.title, 300),
department: choice(g.department, departments),
acceptanceCriteria: text(g.acceptanceCriteria),
metric: text(g.metric, 300),
target: g.target,
};
});
const data = {
researchId: uuid(b.researchId),
cycleName: text(b.cycleName, 300),
month: text(b.month, 40),
seasonalTheme: text(b.seasonalTheme),
strategicGoals: b.strategicGoals.map((g) => text(g, 1000)),
plannedArticlesCount: b.plannedArticlesCount,
plannedRefreshesCount: b.plannedRefreshesCount,
plannedCatalogEnrichments: b.plannedCatalogEnrichments,
isActive: b.isActive ?? false,
createdBy: actor,
};
return this.operation(actor, 'roadmap', key, b, async (tx) => {
const research = await tx.corporateResearch.findUnique({
where: { id: data.researchId },
include: { sources: true },
});
if (!research || !research.sources.length)
throw new ConflictException('Evidence-backed research required');
const result = await tx.corporateRoadmap.create({
data: { ...data, goals: { create: goals } },
include: { goals: true },
});
await tx.corporateResearch.update({
where: { id: research.id },
data: { status: 'IN_BACKLOG' },
});
return result;
});
}
effect(actor: string, key: string, id: string, input: unknown) {
const b = object(input, [
'metric',
'availability',
'baseline',
'observed',
'source',
'observedAt',
]);
const availability = choice(b.availability, [
'MEASURED',
'UNAVAILABLE',
'UNINSTRUMENTED',
'BUSINESS_DISABLED',
]);
for (const k of ['baseline', 'observed'])
if (
b[k] !== undefined &&
b[k] !== null &&
(typeof b[k] !== 'number' || !Number.isFinite(b[k]))
)
throw new BadRequestException('Invalid metric');
if (availability === 'MEASURED' && typeof b.observed !== 'number')
throw new BadRequestException('Measured value required');
if (
availability !== 'MEASURED' &&
(b.observed != null || b.baseline != null)
)
throw new BadRequestException('Unavailable is not zero');
const observedAt = timestamp(b.observedAt, 'Invalid observation time');
if (
!Number.isFinite(observedAt.getTime()) ||
observedAt.getTime() > Date.now()
)
throw new BadRequestException('Invalid observation time');
return this.operation(actor, 'effect:' + id, key, b, async (tx) => {
const task = await this.lock(tx, id);
if (task.status !== 'DONE')
throw new ConflictException('Effects require completed QA');
const e = await tx.corporateEffect.create({
data: {
taskId: id,
metric: text(b.metric, 300),
availability,
baseline: b.baseline,
observed: b.observed,
source: text(b.source, 2000),
observedAt,
recordedBy: actor,
},
});
await this.event(tx, id, actor, 'EFFECT_RECORDED', e.metric, 'SYSTEM', {
effectId: e.id,
});
return e;
});
}
report(actor: string, key: string, input: unknown) {
const b = object(input, ['day', 'summary']);
const day = text(b.day, 10),
summary = text(b.summary);
if (
!/^\d{4}-\d{2}-\d{2}$/.test(day) ||
!Number.isFinite(Date.parse(day + 'T00:00:00Z'))
)
throw new BadRequestException('ISO day required');
return this.operation(actor, 'report', key, b, async (tx) => {
const start = new Date(day + 'T00:00:00Z'),
end = new Date(start.getTime() + 86400000);
const taskWhere = { updatedAt: { gte: start, lt: end } };
const eventWhere = { timestamp: { gte: start, lt: end } };
const effectWhere = { createdAt: { gte: start, lt: end } };
const totals = {
tasks: await tx.corporateTask.count({ where: taskWhere }),
events: await tx.corporateEvent.count({ where: eventWhere }),
effects: await tx.corporateEffect.count({ where: effectWhere }),
};
const tasks = await tx.corporateTask.findMany({
where: taskWhere,
take: 100,
orderBy: [{ updatedAt: 'asc' }, { id: 'asc' }],
select: {
id: true,
taskCode: true,
title: true,
status: true,
department: true,
updatedAt: true,
},
});
const events = await tx.corporateEvent.findMany({
where: eventWhere,
take: 100,
orderBy: [{ timestamp: 'asc' }, { id: 'asc' }],
select: {
id: true,
taskId: true,
timestamp: true,
speaker: true,
speakerName: true,
step: true,
content: true,
},
});
const effects = await tx.corporateEffect.findMany({
where: effectWhere,
take: 100,
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
select: {
id: true,
taskId: true,
metric: true,
availability: true,
baseline: true,
observed: true,
source: true,
observedAt: true,
createdAt: true,
},
});
let fieldsTruncated = false;
const project = (rows: any[]) =>
rows.map((row) =>
Object.fromEntries(
Object.entries(row).map(([name, value]) => {
if (typeof value === 'string' && value.length > 1000) {
fieldsTruncated = true;
return [name, value.slice(0, 1000)];
}
return [name, value];
}),
),
);
const bounded = {
tasks: project(tasks),
events: project(events),
effects: project(effects),
};
const counts = Object.fromEntries(
Object.entries(totals).map(([name, total]) => [
name,
{
total,
returned: Math.min(total, 100),
limit: 100,
truncated: total > 100,
},
]),
);
const snapshot = JSON.parse(
JSON.stringify({
timezone: 'UTC',
...bounded,
meta: {
...counts,
fieldsTruncated,
stringLimit: 1000,
eventPayloadsOmitted: true,
},
}),
);
return tx.corporateReport.create({
data: { day, summary, snapshot, createdBy: actor },
});
});
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ describe("MediaService", () => {
const validFile = { const validFile = {
originalname: "product-cover.webp", originalname: "product-cover.webp",
buffer: Buffer.from("dummy-image-bytes"), buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]),
mimetype: "image/webp", mimetype: "image/webp",
size: 5000, size: 5000,
} as any; } as any;
Loaded 100 of 624 files, more files were not shown because too many files have changed in this diff. Show more