Reduce Codex context and add focused operational guides

This commit is contained in:
Nick Beckley 2026-10-29 14:03:23 +00:00
parent 729032ff0d
commit b7a17b8945
4 changed files with 313 additions and 131 deletions

213
AGENTS.md
View File

@ -1,166 +1,117 @@
# PlotDirector Codex Operations Guide
# PlotDirector Codex Guide
This repository is the PlotDirector ASP.NET Core application. Use this file as the first stop for operational knowledge that is not obvious from source.
PlotDirector is an ASP.NET Core .NET 10 MVC/Razor application using Dapper and Microsoft.Data.SqlClient.
## Environment Architecture
This file contains the rules and information needed on most development tasks. Detailed operational procedures are deliberately kept in separate documents. Read those only when the current task requires them.
- Main repo path: `/srv/repos/PlotDirector`.
- Web app project: `PlotLine/PlotLine.csproj`.
- Test project: `PlotLine.Tests/PlotLine.Tests.csproj`.
- Solution file: `PlotLine.slnx`.
- Word add-in project: `PlotDirector.WordCompanion/`.
- Development site host files: `/srv/apps/plotdirector-dev/current`.
- Development release archive: `/srv/apps/plotdirector-dev/releases/`.
- Development systemd service: `plotdirector-dev`.
- Service working directory: `/srv/apps/plotdirector-dev/current`.
- Service environment file: `/etc/plotdirector/plotdirector.env`.
- The dev app listens locally on `http://127.0.0.1:5050` behind nginx as `https://dev.plotdirector.com/`.
## Repository
## Database
- Repository: `/srv/repos/PlotDirector`
- Solution: `PlotLine.slnx`
- Web application: `PlotLine/PlotLine.csproj`
- Regression harness: `PlotLine.Tests/PlotLine.Tests.csproj`
- Word add-in: `PlotDirector.WordCompanion/`
- Development service: `plotdirector-dev`
- Development site: `https://dev.plotdirector.com/`
- Development database: `PlotDirector_Development`
- Production is a separate host and database. Development work does not authorise production changes.
- `Tools/` and `tools/`, and `Docs/` and `docs/`, are distinct paths on Linux.
- Production-style dev database name: `PlotDirector_Development`.
- Older/local default database name in appsettings may be `PlotLine`; do not assume that is the effective dev database.
- Runtime connection details come from `/etc/plotdirector/plotdirector.env`, key `ConnectionStrings__DefaultConnection`.
- Do not print, copy, or commit connection strings, passwords, API keys, SMTP secrets, Stripe secrets, or OpenAI keys.
- The SQL Server is reachable from the app host using the environment-file connection string. If a one-off SQL runner is needed, read the env file safely without shell-evaluating values:
## Core Development Rules
```bash
conn=""
while IFS= read -r line; do
case "$line" in
ConnectionStrings__DefaultConnection=*) conn="${line#ConnectionStrings__DefaultConnection=}" ;;
esac
done < /etc/plotdirector/plotdirector.env
export PLOT_DIRECTOR_SQL_CONNECTION="$conn"
```
- Use Dapper and stored procedures for application database access.
- Do not add inline SQL to application code.
- Do not introduce Entity Framework or EF migrations.
- SQL migrations are forward-only. Never modify an existing numbered migration to repair a live schema.
- PlotDirector must work for arbitrary books and authors. Never add production logic that recognises manuscript-specific names, places, vehicles, objects or relationships.
- Preserve existing user changes in a dirty worktree. Do not revert unrelated changes.
- Never expose or commit passwords, connection strings, API keys, SMTP credentials, Stripe secrets or OpenAI keys.
- Do not use `source /etc/plotdirector/plotdirector.env`; unquoted values with spaces or special characters can break the shell and leak confusion into the task.
- Use stored procedures for application database access. Do not add inline SQL in application code.
- Old SQL scripts are immutable. Never edit an existing numbered script to fix a live schema issue; add a new forward-only script.
- Before restarting/deploying during Story Intelligence work, check there are no active runs in `StoryIntelligenceRuns`, `StoryIntelligenceJobs`, or `WholeBookPlotSynthesisRuns`.
- Do not restore, reset, or overwrite `PlotDirector_Development` unless the user explicitly asks and the target backup has been verified. Restore backups only to disposable verification databases first.
## Context And Discovery Discipline
## SQL Migration Procedure
Context is a finite resource. Repository discovery must be targeted, incremental and evidence-led.
- Number new scripts under `PlotLine/Sql/` using the next available prefix, for example `175_...sql`.
- Scripts should be idempotent where practical: guard table/column/index creation with existence checks and use `CREATE OR ALTER PROCEDURE`.
- Apply database changes to dev deliberately and capture the script path in the final response.
- After applying SQL, run a smoke query that confirms the expected tables/procedures/columns exist and that the connection reports `PlotDirector_Development`.
- Permanent delete paths have historically exposed missing cascade/cleanup dependencies. When adding tables that reference projects, books, chapters, scenes, characters, candidates, or runs, design deletion behaviour intentionally.
Start from the implementation point most directly related to the requested change and trace dependencies outward only when evidence requires it.
Prefer:
- narrow `rg` searches within likely directories or files;
- specific symbols, methods, routes, stored procedures or view names;
- targeted line ranges instead of reading entire large files;
- one or a small number of directly relevant files at a time;
- existing focused documentation when it answers a question more cheaply than rediscovering the architecture from source;
- inspecting callers or dependencies only when relevant to the requested behaviour.
Avoid:
- broad repository-wide searches merely to build general context;
- searching application code, tests and all documentation trees simultaneously unless genuinely necessary;
- very large result limits such as hundreds or thousands of search matches;
- reading many large files in parallel;
- reading entire controllers, services, repositories or SQL files when only a method or section is relevant;
- speculative investigation of adjacent systems;
- repeatedly rereading material already available in the current context;
- loading detailed operational documentation unless the task actually needs it.
Do not attempt to understand the whole application before making a local change.
For broad tasks, identify the primary implementation path first. Expand discovery in stages and only where the previous stage demonstrates that more context is required.
Parallel tool calls are useful for latency but must not be used to load large amounts of speculative context simultaneously.
## Build And Test
- Full test gate:
Normal build gate:
```bash
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj
```
dotnet build PlotLine.slnx
- Build gate:
Full regression harness:
```bash
dotnet build PlotLine.slnx
```
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj
- Publish gate:
`PlotLine.Tests` is an executable regression harness, not a conventional test SDK project. `dotnet test` is not the normal test gate.
```bash
dotnet publish PlotLine/PlotLine.csproj -c Release -o /tmp/plotdirector-dev-publish-<commit>-<timestamp>
```
Run build and tests serially. Parallel execution can cause static web asset cache locking.
- Known quirk: running build and tests in parallel can cause static web asset cache file locks, especially around `*.staticwebassets*.json` or `rjsmrazor.dswa.cache.json`. Run build/test serially when verifying.
- Prefer `rg`/`rg --files` for repository searches.
Use verification proportionate to the change. Do not run unrelated specialist test suites merely for completeness.
## Running Locally
Detailed specialist testing instructions are in `Docs/Codex/Testing.md`.
- From `/srv/repos/PlotDirector`, run:
## Database Work
```bash
dotnet run --project PlotLine/PlotLine.csproj
```
For tasks requiring database inspection, schema changes, migrations or direct development-database access, read `Docs/Codex/Database.md`.
- For local database/API work, provide configuration through environment variables, user secrets, or a safe local appsettings override. Do not rely on secrets committed in appsettings, and do not add new secrets to source.
- The deployed dev service uses `/etc/plotdirector/plotdirector.env`; local terminal runs do not automatically use that file unless you explicitly provide equivalent environment variables.
Do not load that guide for tasks that do not require database work.
## Development Deployment
Essential rules that always apply:
Use the existing physical-directory deployment pattern. `current` is a real directory, not a symlink.
- The development database is `PlotDirector_Development`.
- Never assume the database named in appsettings is the effective development database.
- Never restore, reset or overwrite the development database unless explicitly requested and the target has been verified.
- Do not modify database state during a read-only investigation.
- Do not apply SQL during a read-only audit.
1. Confirm the commit to deploy:
## Deployment
```bash
git status --short --branch
git log -1 --oneline
```
For tasks that actually require deployment or detailed development-service operations, read `Docs/Codex/Deployment.md`.
2. Confirm no active Story Intelligence work is running before restart.
3. Publish to a fresh temp folder:
Do not load deployment procedures during ordinary implementation or investigation unless deployment is part of the requested task.
```bash
release="<shortsha>-$(date -u +%Y%m%d%H%M%S)"
publish_dir="/tmp/plotdirector-dev-publish-$release"
release_dir="/srv/apps/plotdirector-dev/releases/$release"
backup_dir="/srv/apps/plotdirector-dev/current-before-$release"
dotnet publish PlotLine/PlotLine.csproj -c Release -o "$publish_dir"
```
## Story Intelligence
4. Install the release:
For Story Intelligence work, use the existing authoritative documentation:
```bash
sudo mkdir -p "$release_dir"
sudo cp -a "$publish_dir"/. "$release_dir"/
sudo chown -R plotdirector:plotdirector "$release_dir"
sudo cp -a /srv/apps/plotdirector-dev/current "$backup_dir"
sudo chown -R plotdirector:plotdirector "$backup_dir"
sudo rsync -a --delete "$release_dir"/ /srv/apps/plotdirector-dev/current/
sudo chown -R plotdirector:plotdirector /srv/apps/plotdirector-dev/current
sudo systemctl restart plotdirector-dev
```
- `docs/story-intelligence/single-system-runtime.md`
- `Docs/StoryIntelligence_ExceptionReview.md`
5. Verify:
Read these only when the task concerns Story Intelligence or behaviour governed by those contracts.
```bash
systemctl is-active plotdirector-dev
systemctl status plotdirector-dev --no-pager -n 30
curl -k -L --max-time 20 -o /tmp/pd-dev-home.html -w 'http_code=%{http_code}\nfinal_url=%{url_effective}\nbytes=%{size_download}\n' https://dev.plotdirector.com/
sudo stat -c 'CurrentDll=%n %y %s bytes' /srv/apps/plotdirector-dev/current/PlotLine.dll
```
- A `HEAD` request to the dev site may return `405`; use `GET` with `curl -L` for the real smoke check.
- Keep the release folder and current-before backup named with the deployed short SHA and UTC timestamp for traceability.
## Project Structure
- `PlotLine/Controllers/`: MVC controllers.
- `PlotLine/Views/`: Razor views.
- `PlotLine/Services/`: application services, Story Intelligence workers, OpenAI integration, import/onboarding flow.
- `PlotLine/Data/`: repositories and database access.
- `PlotLine/Models/`: domain and DTO models.
- `PlotLine/ViewModels/`: UI view models.
- `PlotLine/Hubs/`: SignalR hubs.
- `PlotLine/wwwroot/`: static CSS/JS/assets.
- `PlotLine/Sql/`: forward-only SQL migration scripts and stored procedure definitions.
- `PlotLine.Tests/Program.cs`: lightweight integration/regression test harness.
- `docs/` and `Docs/`: project documentation stores; check both before creating new documentation.
## Story Intelligence Conventions
- PlotDirector must work for arbitrary books and authors. Do not add production special cases for Alpha Flame or any other manuscript-specific names, places, vehicles, objects, or relationships.
- Manuscript-specific examples may appear in regression fixtures only, and tests should include unrelated examples so production code cannot pass by recognising one fixture.
- Use generic evidence for significance: recurrence, scene/chapter presence, ownership, narrative prominence, title presence, knowledge significance, and participation in important events.
- Relationship classification must use generic interaction evidence and configured relationship types, not character-specific rules.
- Character/alias resolution should use canonical identities, aliases, and evidence rather than book-specific names.
- Scene manuscript text in `SceneManuscriptSources` is the durable source for canonical scene analysis.
- Core import and Story Intelligence are separate phases. Do not reintroduce the old visualisation/replay workflow as part of production import.
- Whole-book plot synthesis should happen after character resolution and should not add another per-scene AI pass.
- If prompt/source text is too large, fail the specific synthesis job clearly rather than silently truncating manuscript text.
Core invariant: manuscript-specific examples may be used in regression fixtures, but production behaviour must remain generic.
## Operational Safety
- Avoid destructive git commands such as `git reset --hard` or `git checkout --` unless the user explicitly asks.
- The worktree may include user changes. Inspect before editing and do not revert unrelated changes.
- Do not deploy while an import or Story Intelligence analysis is active unless the user explicitly accepts the interruption.
- Do not modify current database state for read-only investigation tasks.
- Do not apply SQL during read-only audit tasks.
- Use disposable verification databases for restore checks and drop them afterwards unless instructed otherwise.
- Keep deployment and SQL notes concise in final responses: commit, SQL script, tests, deployed release, service status, and any residual risks.
- Avoid destructive Git commands such as `git reset --hard` or `git checkout --` unless explicitly requested.
- Inspect the worktree before editing and preserve unrelated changes.
- Do not deploy while an import or Story Intelligence analysis is active unless interruption has explicitly been accepted.
- Production changes require explicit production authorisation.
- Prefer reversible, narrowly scoped actions.

86
Docs/Codex/Database.md Normal file
View File

@ -0,0 +1,86 @@
# PlotDirector Database Operations
Read this document only when the current task requires database inspection, SQL migration, schema work or direct development-database access.
## Environment
- Development database: `PlotDirector_Development`.
- Runtime connection details: `/etc/plotdirector/plotdirector.env`, key `ConnectionStrings__DefaultConnection`.
- SQL Server container: `atlas-sql-server`.
- Host endpoint: `192.168.10.10,1433`.
- `/sql/mssql` on the host maps to `/var/opt/mssql` in the container.
- Host `sqlcmd` is not installed.
- Container sqlcmd: `/opt/mssql-tools18/bin/sqlcmd`.
- Production is separate: host `www`, `192.168.10.8`, database `PlotLine`. Development authorisation does not authorise production changes.
Never print, copy or commit connection strings, passwords, API keys, SMTP secrets, Stripe secrets or OpenAI keys.
## Connecting Safely
Read the environment file in a privileged helper if necessary. Parse `ConnectionStrings__DefaultConnection` as data; never shell-evaluate it.
Do not `source /etc/plotdirector/plotdirector.env`. Values containing spaces or special characters can break shell parsing.
A small .NET runner using `Microsoft.Data.SqlClient` and `SqlConnectionStringBuilder` may consume the configured connection string safely.
When using sqlcmd:
- parse connection fields with `SqlConnectionStringBuilder`;
- pass the password via `SQLCMDPASSWORD`, not `-P`;
- explicitly select `-d PlotDirector_Development`;
- use `-C -I -b -V 16`;
- forward credentials through the process environment, not command arguments;
- use `-i` for SQL files or `docker exec -i` for stdin.
Host paths are not automatically visible inside the SQL Server container.
Before database work verify `SELECT DB_NAME()` reports `PlotDirector_Development`.
## Application Database Rules
- Use stored procedures for application database access.
- Do not add inline SQL in application code.
- Do not introduce Entity Framework migrations.
- Existing numbered SQL scripts are immutable.
- Repair live schema issues with a new forward-only migration.
- Design deletion behaviour deliberately for new tables referencing projects, books, chapters, scenes, characters, candidates or runs.
## Migration Procedure
New scripts live under `PlotLine/Sql/`.
Before choosing a migration number, inspect current scripts and select the next appropriate prefix. Historical duplicate prefixes exist, so do not assume numbering without checking.
Scripts should be idempotent where practical:
- guard table, column and index creation;
- use `CREATE OR ALTER PROCEDURE`.
Migrations are manual SQL. Do not blindly replay the entire SQL directory, `Admin/`, or `Stripe_Price_IDs_Prod.sql`.
Before schema or data changes:
1. Verify the development database.
2. Back up development using a unique SQL Server backup filename.
3. Verify the backup command succeeded and the backup exists.
4. Apply only required scripts in dependency order.
Apply scripts separately with `SET ANSI_NULLS ON` and `SET QUOTED_IDENTIFIER ON`.
`GO` is a sqlcmd batch separator, not executable SqlClient SQL. A custom runner must split batches appropriately.
Stop on the first migration error. Record the failed script and do not deploy dependent code. Earlier successful batches may already have persisted.
After migration, run a focused smoke query confirming required tables, columns and procedures exist, and verify `DB_NAME()` again.
A successful backup is not itself a restore test. Restore testing must use a disposable verification database.
Never restore, reset or overwrite `PlotDirector_Development` unless explicitly requested and the target backup has been verified.
## Specialist Database Regression Tests
Database regressions are under `PlotLine.Tests/Sql/`.
They run separately from the normal regression harness. Read the individual regression script before executing it because migration, fixture and rollback requirements differ.
Never run development database regression scripts against production.

93
Docs/Codex/Deployment.md Normal file
View File

@ -0,0 +1,93 @@
# PlotDirector Development Deployment
Read this document only when deployment or detailed development-service operation is part of the task.
## Environment
- Development host: Atlas.
- Repository: `/srv/repos/PlotDirector`.
- Development files: `/srv/apps/plotdirector-dev/current`.
- Release archive: `/srv/apps/plotdirector-dev/releases/`.
- Service: `plotdirector-dev`.
- Service user: `plotdirector:plotdirector`.
- Environment file: `/etc/plotdirector/plotdirector.env`.
- Persistent uploads: `/srv/apps/plotdirector-dev/uploads`.
- Default deployed data-protection keys: `/srv/apps/plotdirector-dev/App_Data/DataProtectionKeys`.
- Local endpoint: `http://127.0.0.1:5050`.
- Public development endpoint: `https://dev.plotdirector.com/`.
`current` is a physical directory, not a symlink.
Use `sudo -n` for protected service/configuration paths where appropriate.
## Before Deployment
Confirm the intended commit:
git status --short --branch
git log -1 --oneline
If the change involves database migration, apply and verify required SQL before deploying dependent code.
Before stopping the service, confirm there is no active import, Story Intelligence run, synthesis or character enrichment work. Check queued and processing work as well as core imports.
Do not deploy while such work is active unless interruption has explicitly been accepted.
## Publish
Use a fresh temporary publish directory. Set fail-fast shell behaviour and derive a release name from the short commit SHA and UTC timestamp.
Publish with:
dotnet publish PlotLine/PlotLine.csproj -c Release -o "$publish_dir"
The standard paths are:
release_dir="/srv/apps/plotdirector-dev/releases/$release"
backup_dir="/srv/apps/plotdirector-dev/current-before-$release"
## Install
Copy the fresh publish into the release archive and ensure ownership is `plotdirector:plotdirector`.
Stop `plotdirector-dev` before replacing the physical live directory.
Back up the existing `current` directory to the timestamped `current-before` path.
Use `rsync -a --delete` from the release directory into `current`, preserving:
- `appsettings*.json`
- `.env*`
- `App_Data/`
- `wwwroot/uploads/`
- `uploads/`
- `logs/`
- `Logs/`
Restore `plotdirector:plotdirector` ownership and start `plotdirector-dev`.
If installation or startup fails, stop and diagnose. Do not continue blindly or claim successful deployment.
An application rollback does not undo SQL migrations and must remain compatible with the migrated schema.
## Verification
Verify:
- `systemctl is-active plotdirector-dev`
- service status and recent warning/error logs;
- local GET to `http://127.0.0.1:5050/`;
- public HTTPS GET to `https://dev.plotdirector.com/`;
- deployed `PlotLine.dll` metadata;
- SHA-256 of published and deployed `PlotLine.dll`;
- the changed authenticated route when applicable.
Timestamps alone do not prove the intended build is running.
Use a real GET for public smoke testing. HEAD may return 405.
Normal verification must validate TLS. Use `-k` only for certificate diagnosis.
Review configuration changes separately because deployment preserves deployed appsettings files.
Keep the release directory and `current-before` backup named with the deployed short SHA and UTC timestamp for traceability.

52
Docs/Codex/Testing.md Normal file
View File

@ -0,0 +1,52 @@
# PlotDirector Specialist Testing
Read this document when the change requires specialist testing beyond the normal build and regression harness.
## Normal Gates
From the repository root:
dotnet build PlotLine.slnx
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj
`PlotLine.Tests` is an executable regression harness. `dotnet test` is not the normal test gate.
Build and regression execution should be serial. Parallel execution can cause static web asset cache locking.
## Browser Tests
Browser tests are under `PlotLine.Tests/Browser`.
When relevant:
npm ci
npx playwright install chromium
npm test
npm run test:locations
npm run test:characters
`CHROMIUM_PATH` can select an existing Chromium installation.
These tests use isolated fixtures rather than the live application/database.
Run only suites relevant to the changed behaviour unless a full browser regression has specifically been requested.
## Database Regression Tests
Database regression scripts are under `PlotLine.Tests/Sql/`.
These are separate from the normal application regression harness. Read the individual script before execution for migration, fixture and rollback prerequisites.
Never run development regression scripts against production.
## Word Companion
For changes affecting `PlotDirector.WordCompanion`, use its npm workflow:
npm install
npm run build
npm run validate
This generates and validates the manifest for the application-hosted `/word-companion` route.
Do not run Word Companion validation for unrelated application changes merely for completeness.