# Nyx Core — Complete Rebuild Goal

Rebuild Nyx into dependable autonomous application-building infrastructure, then
prove it by completing Helios mobile first and Wobbleby web and mobile second.

The objective is not to reduce Nyx's ambition. The objective is to remove
competing control mechanisms so Nyx can reliably take a product from research
through design, implementation, testing, deployment, and release without
stalling, duplicating plans, leaking processes, or continuously repairing
itself.

## Starting point and operating constraints

- Work from `/Users/ethanashihundu/projects/agent-orchestrator-nyx-core`.
- Begin from the clean `nyx-core-repair` branch at commit
  `860c658ef2a29f31074b83adc355598abee21461`.
- Preserve the stopped-state snapshot
  `4868be211433d0ab9fb5cc08eb7a6186b18798ea`.
- Do not modify, clean, reset, or discard the dirty production checkout.
- Keep every Nyx service stopped during the rebuild.
- Do not activate the prepared release until the rebuilt system passes all
  applicable acceptance tests.
- Nyx must not use its existing autonomous runtime to repair itself.
- Do not stop after analysis or an architecture proposal. Implement, migrate,
  test, and prove the rebuilt system.

## 1. One authoritative state machine

Create one durable state model for:

- Products
- Product contracts
- Stages
- Tasks
- Worker runs
- Artifacts
- Approvals
- Deployments
- Releases

Use explicit validated transitions with:

- Compare-and-swap protection
- Idempotency keys
- Durable worker leases
- Attempt budgets
- Append-only audit events
- Crash-safe recovery
- Clear ownership of every transition

The reconciler/state engine must be the only component that commits persistent
execution-state transitions. Other components may submit events or requests,
but they must not independently repair, retry, cancel, reset, or advance plans.

At all times Nyx must be able to report:

- Current product
- Current stage
- Running task
- Latest completed action
- Current blocker
- Exact next action
- Attempt count and remaining retries

## 2. Three control loops only

Keep only:

1. **Scheduler** — publishes events when scheduled work becomes due.
2. **Dispatcher** — launches work the state engine has declared ready.
3. **Reconciler** — owns state transitions, recovery, retries, and escalation.

Remove or convert the existing watchdogs, reapers, self-iteration loops,
failure-streak controllers, stuck detectors, semantic-stall detectors, marathon
alarms, stall alarms, judgment sentinels, supervisors, and resource monitors
into read-only detectors or pure functions feeding events to the reconciler.

Replacement means deletion. Do not wrap an old mechanism in a new abstraction
while leaving its timers, launch jobs, flags, tests, and recovery logic active.

The rebuilt control plane must contain materially fewer:

- Timers
- Background processes
- State writers
- Retry paths
- Launch agents
- Environment flags
- Recovery mechanisms
- Lines of control-plane code

Provide a before-and-after mechanism inventory demonstrating the reduction.

The operating-system service manager may restart the exact immutable Nyx daemon
if that process dies. It must never modify plans, tasks, sessions, or worker
state. The reconciler handles state recovery after startup.

## 3. Exactly six product stages

### A. Discover and contract

- Determine whether the target is a website, web app, native app,
  cross-platform app, desktop app, backend service, or library.
- Lock target platforms before architecture or production.
- Define users, primary journeys, features, integrations, non-goals, security
  needs, visual intent, and acceptance criteria.
- Accept uploaded screenshots, local images, URLs, named products, and written
  visual references.
- Research additional public UI references when research is authorized.
- Store original references with source, date, purpose, and licensing metadata.
- Curate a focused active reference set instead of forwarding hundreds of
  unranked images.
- Separate references into structural, visual, and interaction inspiration.
- Extract the useful patterns into a versioned visual-DNA packet.
- Pass actual curated images to VP2 and relevant implementation workers, not
  only text descriptions.
- Reject ambiguous product targets before proceeding.

Output: a locked product contract, reference packet, product map, and measurable
acceptance criteria.

### B. Feasibility and architecture

- Inspect the existing repository or establish the correct new project.
- Select platform-appropriate frameworks and infrastructure.
- Define authentication, API, data, state management, security, deployment,
  asset, observability, and testing architecture.
- Identify risks and prove uncertain integrations with bounded technical spikes.
- Define global contracts, database schema, API boundaries, shared types, and
  ownership boundaries.
- Build a dependency-ordered implementation graph.
- Define honest verification for every target platform.
- Freeze material architecture decisions before broad implementation.

Output: frozen architecture, risk report, dependency graph, ownership map, and
verification plan.

### C. Design and approval

- Create the design system, visual language, asset direction, and shared
  application chrome.
- Use the reference packet and original images directly.
- Design approximately three representative screens first: a primary screen, a
  complex workflow, and a state-heavy screen.
- Include applicable mobile, desktop, loading, empty, error, success, offline,
  and accessibility states.
- Establish typography, spacing, color, iconography, responsive behavior,
  component anatomy, interaction, motion, and content rules.
- Evaluate visual hierarchy, consistency, responsiveness, usability, and
  originality.
- Reject generic AI-looking output such as repetitive card grids, arbitrary
  gradients, excessive rounded containers, placeholder copy, inconsistent
  spacing, and decorative elements without product purpose.
- Do not generate the complete screenshot matrix before the direction is
  approved.

Output: approved representative screens, tokens, component system, global
chrome, asset direction, interaction rules, and remaining screen map.

### D. Production

- Implement bounded vertical product slices in dependency order.
- Use isolated worktrees.
- Give every task explicit ownership, inputs, outputs, acceptance criteria, and
  tests.
- Run affected tests during implementation.
- Integrate completed slices continuously through one serialized merge queue.
- Use durable leases and idempotent completion.
- Retry failures only within the configured budget.
- Route exhausted tasks to `needs_review` with a precise diagnosis.
- Never manufacture a replacement plan or restart an entire venture because
  one task failed.

Output: complete integrated product implementation with passing feature-level
tests.

### E. Validation and deployment

Run layered verification:

- Unit tests
- Component tests
- Integration tests
- End-to-end user journeys
- Authentication and RBAC tests
- Security and privacy tests
- Accessibility checks
- Responsive verification
- Performance checks
- Visual regression review
- Real platform builds
- Deployment smoke tests

Platform verification must be truthful:

- Web must run in supported real browsers.
- iOS must produce an iOS build and run in a simulator or device.
- Android must produce an Android build and run in an emulator or device.
- Native work cannot pass through an Expo web or static-browser substitute.
- Backend services must pass migration, contract, and API verification.
- Desktop products must run in their desktop runtime.

Generate the complete screenshot matrix during this stage. A validation failure
must create one bounded repair task owned by the responsible feature; it must
not reset unrelated work.

Output: tested release candidate, deployment, screenshot evidence, test
evidence, accessibility evidence, performance evidence, and security evidence.

### F. Release approval

- Compare the deployed candidate with every product-contract requirement.
- Review visual quality, security, migrations, observability, known limitations,
  and rollback instructions.
- Perform a final independent Sol/high review.
- Promote only the exact tested commit and artifact.
- Record an immutable release and rollback target.

Output: either a released product or a precise `needs_review` result. “Mostly
finished” is not a valid terminal state.

## 4. Production asset pipeline

Treat production assets as versioned product deliverables.

Nyx may generate or prepare:

- Original illustrations
- Character artwork
- Empty-state artwork
- Onboarding artwork
- Background textures
- App icons and splash artwork
- Badges and branded imagery
- Transparent PNG assets
- Mobile density variants
- Optimized web variants

Every asset must have a manifest containing:

- Stable identifier
- Purpose
- Origin and provenance
- Ownership or license
- Prompt and reference lineage when generated
- Format
- Dimensions and aspect ratio
- Transparency
- Light/dark variants
- Platform density variants
- Compression status
- Screens and components using it

Use the appropriate format:

- Prefer SVG or code-native vectors for icons and logos.
- Use real UI components for controls and surfaces.
- Never bake interface copy into an image.
- Prefer WebP or AVIF for web photography and large raster imagery.
- Use PNG where raster transparency, character art, or a platform requirement
  makes it appropriate.

Review generated assets inside their real application context. A standalone
attractive image is not accepted if it breaks hierarchy, accessibility,
responsive layout, or product tone when placed in a screen.

## 5. Global application shell

Design, approve, and implement shared application chrome before parallel screen
implementation.

This includes:

- Mobile bottom navigation and tab bars
- Top navigation and headers
- Web sidebars
- Toolbars and action bars
- Page containers and grids
- Operating-system status-bar appearance
- Mobile safe-area handling
- Modals, sheets, dialogs, and menus
- Toasts and notifications
- Loading, error, empty, offline, and permission states
- Typography, spacing, color, radius, elevation, and motion tokens
- Keyboard behavior
- Responsive breakpoints
- Light and dark themes when contracted

The operating system continues to own its status bar or desktop taskbar. Nyx
may configure the supported appearance, app icon, notification behavior, and
safe-area integration, but it must not render a fake operating-system bar in
production.

Global elements must be shared components with explicit ownership. Individual
feature workers must not reinvent headers, navigation, buttons, spacing, or
global states.

## 6. Characters are optional

Add an explicit character mode to every product contract:

- `none`
- `decorative`
- `supporting`
- `core_product_identity`

When character mode is `none`:

- Do not generate characters.
- Do not add mascots, cartoon figures, or playful decorative people.
- Use professional product imagery, diagrams, icons, photography, or restrained
  abstract visuals only when appropriate.

When characters are requested:

- Define purpose, personality, audience, style, placement, expressions, poses,
  outfits, animation needs, and licensing during discovery.
- Produce an original character bible during VP2.
- Include canonical front, side, and three-quarter views, proportions, colors,
  expression sheets, poses, scale rules, and do/don’t examples.
- Use the approved character bible as an image reference throughout production.
- Maintain consistency across screens and platforms.
- Never reproduce or ship an unlicensed protected character.

## 7. Bounded parallelism

Maintain exactly one authoritative product run and state engine while allowing
multiple isolated workers for dependency-independent tasks.

Work that must normally remain sequential:

- Product contract
- Architecture freeze
- Brand and visual direction
- Design tokens
- Global application shell
- Database schema and shared API contracts
- Integration
- Full validation
- Release approval

Work that may run in parallel after foundations are frozen:

- Independent vertical feature slices
- Backend and frontend implementations against locked contracts
- Unrelated screens
- Tests for separate modules
- Asset production
- Documentation
- Platform packaging
- Accessibility and security analysis

Parallel workers must:

- Use isolated worktrees.
- Own explicit files or subsystems.
- Never edit the same shared foundation concurrently.
- Work from a pinned contract and commit.
- Submit through one merge and verification queue.
- Pass affected tests before integration.
- Revalidate after merging.
- Use durable leases and idempotent completion.

Start with a default maximum of three production workers. Adjust bounded
concurrency based on the dependency graph and measured conflict rate. Never run
multiple independent planners, reconcilers, or product-state owners.

## 8. Simple model routing

Codex must remain the only execution harness and must use the authenticated
ChatGPT subscription, not an API key.

- Sol/high: architecture, difficult diagnosis, consequential planning, VP2
  judgment, and final release review.
- Terra/medium: implementation, routine tests, monitoring, bounded repairs, and
  evidence collection.

Do not build a broad provider-fallback system. Monitoring must be read-only and
must not consume a production worker merely to observe state.

## 9. Fast reliable testing

Boot verification must be deterministic, finish in under 30 seconds, avoid the
full suite, avoid shared mutable fixtures, and leave no process or port behind.

Task verification must run relevant affected tests, isolate databases, ports,
temporary directories, and child processes, and enforce teardown after failure
or timeout.

Release verification must run the complete suite separately, serialize tests
that manipulate processes, ports, services, or shared databases, and assert
that no fixture process or temporary service remains.

Do not use the full test suite as a daemon boot requirement.

## 10. Immutable runtime and releases

- Never run production Nyx from a mutable TypeScript checkout.
- Build and test a specific clean commit.
- Create a versioned release directory and manifest.
- Atomically switch the current release only after verification succeeds.
- Expose the running build SHA through health.
- Preserve the previous release as a rollback target.
- Never edit the running control plane.
- Build and test source changes separately before activation.

## 11. Safe migration

- Preserve existing plans, sessions, attempts, screenshots, and artifacts as
  read-only historical evidence.
- Do not resume stale Helios retry plans as authoritative work.
- Import useful artifacts only after validating them against the new contract.
- Provide deterministic, repeatable durable-data migrations.
- Prevent duplicate records and transitions during repeated migration tests.

## 12. Helios is the first canary

Helios replaces Wobbleby as the first end-to-end canary.

Helios target:

- A real mobile application for its explicitly contracted mobile platforms
- Real native builds and simulator/device verification
- No web-only substitute
- Professional, trustworthy visual direction
- Character mode: `none`

Helios visual direction:

- Preserve the recognizable core colors from the old Helios application.
- Extract and lock the existing brand palette from old screenshots or source.
- Derive accessible tonal variants when needed, but do not silently replace the
  recognizable base colors.
- Give the mobile application an entirely new feel.
- Redesign information architecture, navigation, typography, spacing,
  components, hierarchy, states, and interactions.
- Do not merely reskin the old interface.
- Do not use characters, mascots, or cartoon illustrations.
- Avoid generic AI-generated dashboard aesthetics.
- Use existing Helios screenshots as source material and curate the strongest
  references for VP2.
- Import accepted research, feasibility work, and wireframes only as candidate
  artifacts.
- Revalidate everything through the new six-stage workflow.

Helios must include all contracted authentication, RBAC, privacy, PHI safety,
backend, and deployment requirements.

Helios is complete only when:

- The product contract is satisfied.
- The visual direction is approved.
- The mobile implementation is complete.
- Real platform builds pass.
- Critical journeys pass end to end.
- Authentication, RBAC, privacy, and security gates pass.
- The release candidate is deployed where applicable.
- The exact tested release is approved and versioned.
- Rollback instructions exist.

Do not count old screenshots or accepted legacy stages as proof that the new
Helios run passed.

## 13. Wobbleby is the second canary

Do not begin Wobbleby production until Helios reaches release approval.

Wobbleby target:

- Complete web implementation
- Complete mobile implementation
- Real browser and native verification
- Shared product identity with platform-appropriate interaction patterns
- Character mode: `core_product_identity`, unless its approved contract selects
  `supporting`
- Canonical character: an original Wobbleby penguin. Do not use the owl as the
  product character.

For Wobbleby:

- Inspect and preserve working code and tests where they remain valid.
- Start from a fresh authoritative product plan rather than stale state.
- Use its visual research during discovery and VP2.
- Produce and approve an original penguin character bible.
- Keep characters consistent across web, mobile, states, and marketing.
- Integrate characters intentionally instead of placing them on every screen.
- Generate transparent PNG and optimized web/mobile character variants from the
  approved references.
- Build the complete contracted experience, not another partial prototype.
- Verify web in real browsers.
- Verify mobile through real iOS and Android builds and simulators/devices.
- Deploy and release web and mobile deliverables.

The overall goal is not complete after the Nyx rebuild or after Helios. It is
complete only after Wobbleby web and mobile also pass release approval.

## 14. Recovery and autonomy proof

Add fault tests for:

- Worker crash
- Nyx daemon restart
- Stale worker lease
- Duplicate completion event
- Network timeout
- Model failure
- Test failure
- Deployment failure
- Approval rejection
- Machine or service restart
- Interrupted state transition

For each fault, prove Nyx:

- Does not duplicate plans.
- Does not lose accepted work.
- Does not create competing state owners.
- Does not retry forever.
- Does not leak processes.
- Produces one clear blocker and next action.
- Resumes from the last valid durable state.

Run a minimum two-hour soak test with:

- Zero leaked fixture processes
- Zero duplicate tasks
- Zero duplicate stage transitions
- Zero state mutations outside the state engine
- No polling or retry storm
- No unexplained idle state while runnable work exists

## 15. Performance and observability

Expose one concise operational view containing:

- Runtime mode
- Running build SHA
- Current product and stage
- Active task and worker
- Lease expiration
- Latest event
- Current blocker
- Next action
- Retry count
- Queue depth
- Deployment and release status

Use structured events with stable identifiers. Avoid model calls for status
checking. Boot must complete in under 30 seconds, and ready work should normally
dispatch within seconds rather than waiting through overlapping poll intervals.

## 16. Preserve the valuable parts

Preserve and strengthen:

- Durable persistence
- Isolated worktrees
- Audit evidence
- Crash recovery
- Screenshot-driven visual research
- VP2 visual review
- Subscription enforcement
- Security and privacy gates
- Platform-specific verification
- Deployment verification
- Immutable releases
- Rollback support

Do not preserve legacy complexity merely because tests exist for it.

## 17. Final deliverables

Provide:

- Rebuilt Nyx Core
- State-machine specification
- Allowed-transition table
- Old-to-new migration
- Deleted-mechanism inventory
- Before-and-after process, timer, state-writer, and control-plane LOC counts
- Boot smoke suite
- Full isolated release suite
- Fault-injection results
- Two-hour soak-test evidence
- Immutable Nyx release and rollback instructions
- Completed and released Helios mobile application
- Completed and released Wobbleby web and mobile applications
- Visual-review evidence for both products
- Exact remaining limitations, if any

## Execution rules

- Keep Nyx stopped while rebuilding it.
- Preserve the snapshot and dirty production checkout.
- Do not activate untested code.
- Do not hide missing native verification behind browser tests.
- Do not regenerate valid work without a documented reason.
- Do not create redundant plans after failures.
- Do not allow unbounded retries.
- Do not add a controller to solve a problem caused by existing controllers.
- Do not claim success without test, visual, build, deployment, and release
  evidence.
- Make reasonable implementation decisions autonomously.
- Pause only for genuinely subjective approval or a material product decision
  that cannot safely be inferred.
- Continue until the complete definition of done is satisfied.

## Intended final behavior

The user gives Nyx a clear product goal, target platforms, and optional visual
references. Nyx researches and contracts the product, freezes a viable
architecture, establishes an approved visual direction and global shell,
creates the required assets, builds independent work safely in parallel,
verifies the integrated product on its real platforms, deploys it, and releases
an immutable tested version—without competing control loops, repeated plans,
unexplained stalls, or constant supervision.
