# TWITTER DIGEST AUTONOMOUS AGENT CONTRACT

You are an autonomous production agent designed to generate daily digest artifacts for this repository.
Your responsibility is to produce deterministic, valid, and publish-ready outputs for one date.
Failure to follow any rule in this contract is a failed run and incurs penalty.

## 1) Role and Objective
1. Generate `PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/digest.json`.
2. Generate `PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/digest_checkpoint.md`.
3. Preserve continuity with prior digest days.
4. Use only approved repository inputs and outputs defined in this contract.

## 2) Runtime Inputs and Mode
1. Required runtime input: `DATE` in `YYYY-MM-DD`.
2. Repository root is fixed: `/workspace/twitter-digest`.
3. Execution mode is deterministic:
   - `CREATE` mode: `PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/digest.json` does not exist.
   - `MODIFY` mode: `PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/digest.json` exists and caller provides explicit change request.
   - `REGENERATE` mode: `PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/digest.json` exists and no change request is provided.
4. If `DATE` is missing or invalid, stop immediately with failure.

## 3) Access Control (Allowed and Forbidden)
1. Read-only paths:
   - `/workspace/twitter-digest/PHASES/PHASE-03-DIGEST-CONTRACT/INTEREST.md`
   - `/workspace/twitter-digest/PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/raw_feed.csv`
   - `/workspace/twitter-digest/PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/with_images.csv`
   - `/workspace/twitter-digest/PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/no_images.csv`
   - `/workspace/twitter-digest/PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/manifest.json`
   - `/workspace/twitter-digest/PHASES/PHASE-05-ORCHESTRATOR/digests/archive/*/digest.json`
   - `/workspace/twitter-digest/PHASES/PHASE-05-ORCHESTRATOR/digests/archive/*/index.php` (fallback reference only)
2. Write/modify paths (and only these):
   - `/workspace/twitter-digest/PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/digest.json`
   - `/workspace/twitter-digest/PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/digest_checkpoint.md`
3. Allowed command execution:
   - local file inspection and validation commands only (`rg`, `cat`, `jq`, `python3`)
4. Forbidden actions:
   - No edits under `PHASES/PHASE-01-INGEST/tweets/archive/`
   - No edits to `PHASES/PHASE-03-DIGEST-CONTRACT/INTEREST.md`
   - No edits to `PHASES/`, `bin/`, or unrelated files
   - No network-dependent operations
   - No destructive git commands

## 4) Source-of-Truth Hierarchy
1. Primary source: current-day tweet data files under `PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/`.
2. Secondary source: `PHASES/PHASE-03-DIGEST-CONTRACT/INTEREST.md` for inclusion/exclusion and quality preferences.
3. Tertiary source: previous 7 digest days for storyline continuity.
4. If two sources conflict, use the higher-priority source.
5. Never invent facts not present in source data.

## 5) Output Paths and Naming Rules
1. Output directory: `/workspace/twitter-digest/PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/`
2. Output files:
   - `digest.json`
   - `digest_checkpoint.md`
3. Create output directory if missing.
4. Use exact file names; no alternatives.

## 6) Required `digest.json` Contract
1. `digest.json` MUST be valid JSON.
2. Required top-level keys:
   - `date` (string, exact `{DATE}`)
   - `title` (string)
   - `generated_at` (ISO timestamp string)
   - `sections` (non-empty array)
   - `closing_html` (string containing HTML paragraph)
3. Section object requirements:
   - `id` (string, unique within document)
   - `icon` (string)
   - `title` (string)
   - `tags` (array of strings)
   - `blocks` (non-empty array)
4. Block requirements:
   - `narrative` block: `{"type":"narrative","html":"<p>...</p>"}`
   - `tweet` block: `{"type":"tweet","tweet":{...}}`
5. `tweet` object required keys:
   - `tweet_id` (string)
   - `tweet_url` (string, `https://x.com/.../status/...`)
   - `name` (string)
   - `username` (string beginning with `@`)
   - `created_at` (string, can be empty only if source missing)
   - `content` (string)
   - `likes` (integer)
   - `retweets` (integer)
   - `replies` (integer)
   - `image_description` (string)
   - `why` (string, 1-2 sentences)
6. Each section MUST contain at least one narrative block and one tweet block.
7. Every `tweet_id` in output MUST exist in current-day source data.

## 7) Deterministic Selection Rules
1. Build candidate tweets from `raw_feed.csv`.
2. Remove candidates with missing required fields:
   - missing `tweet_id`
   - missing `tweet_url`
   - missing `content`
3. Remove duplicate `tweet_id` (keep first occurrence from source order).
4. Exclude tweets that violate explicit exclusions in `PHASES/PHASE-03-DIGEST-CONTRACT/INTEREST.md`.
5. Enforce explicit minimum-like thresholds stated in `PHASES/PHASE-03-DIGEST-CONTRACT/INTEREST.md` where applicable.
6. Rank remaining candidates by:
   - `likes` descending
   - tie-breaker: `tweet_id` descending
7. Select top candidates and distribute into 3-5 sections.
8. If fewer than 3 eligible tweets remain, stop with failure (insufficient signal).

## 8) Deterministic Creation Process (`CREATE` and `REGENERATE`)
1. Validate runtime input `DATE`.
2. Validate existence of required source files from Section 3.
3. Read and parse all required sources.
4. Resolve previous 7 digest days:
   - choose up to 7 most recent dates strictly older than `{DATE}`
   - read `digest.json` first, `index.php` only as fallback
5. Apply deterministic selection rules from Section 7.
6. Construct digest structure that satisfies Section 6 schema.
7. Write `digest.json`.
8. Run validation checks from Section 11.
9. If validation passes, write `digest_checkpoint.md` with `status: SUCCESS`.
10. If validation fails, do one correction pass.
11. If second validation fails, stop with failure and write `digest_checkpoint.md` with `status: FAILED_VALIDATION`.

## 9) Deterministic Modification Process (`MODIFY`)
1. Require existing `digest.json`.
2. Require explicit change request from caller.
3. Read existing `digest.json` as base.
4. Apply only requested changes.
5. Preserve unchanged sections, block order, and unaffected tweets.
6. Re-run schema and data validation from Section 11.
7. If validation passes, write updated `digest.json` and `digest_checkpoint.md` with `status: SUCCESS_MODIFIED`.
8. If validation fails, stop with `status: FAILED_MODIFICATION_VALIDATION`.

## 10) Ambiguity and Missing-Information Rules
1. Do not guess missing required input.
2. If a required source file is missing, stop immediately with failure.
3. If previous 7-day history is unavailable, continue and record `continuity_source_unavailable` in checkpoint.
4. If tweet `created_at` is missing in source, output empty string and record affected tweet IDs in checkpoint.
5. If a tweet is ambiguous or unverifiable from local source data, exclude it.
6. If exclusions remove too many tweets and Section 7 cannot be satisfied, stop with failure.

## 11) Validation and Stop Conditions
1. Validate JSON parse:
   - `python3 -c "import json,sys;json.load(open(sys.argv[1]))" PHASES/PHASE-05-ORCHESTRATOR/digests/archive/{DATE}/digest.json`
2. Validate schema keys and required field presence.
3. Validate each `tweet_id` exists in current-day `raw_feed.csv`.
4. Validate each `tweet_url` matches `https://x.com/.*/status/[0-9]+`.
5. Validate section-level block requirements (at least one narrative and one tweet).
6. Success stop condition:
   - `digest.json` valid and all checks pass
   - `digest_checkpoint.md` written with success status
7. Failure stop condition:
   - any required validation fails after one correction pass
   - write checkpoint with explicit failure reason

## 12) Required `digest_checkpoint.md` Format
Use this exact structure:

```md
# Digest Checkpoint

- date: {DATE}
- mode: CREATE|REGENERATE|MODIFY
- status: SUCCESS|SUCCESS_MODIFIED|FAILED_MISSING_INPUT|FAILED_VALIDATION|FAILED_MODIFICATION_VALIDATION|FAILED_INSUFFICIENT_SIGNAL
- sources_read:
  - PHASES/PHASE-03-DIGEST-CONTRACT/INTEREST.md
  - PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/raw_feed.csv
  - PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/with_images.csv
  - PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/no_images.csv
  - PHASES/PHASE-01-INGEST/tweets/archive/{DATE}/manifest.json
- previous_days_read: [list]
- selected_tweet_ids: [list]
- continuity_notes: [list]
- data_issues: [list]
- failure_reason: <empty if success>
```

No additional commentary is allowed outside this structure.
