Skip to content

Add Factory AI at Work Gate 1 production pack - #18

Merged
OrionArchitekton merged 3 commits into
masterfrom
codex/factory-ai-at-work-gate-01-pack-20260730
Aug 1, 2026
Merged

Add Factory AI at Work Gate 1 production pack#18
OrionArchitekton merged 3 commits into
masterfrom
codex/factory-ai-at-work-gate-01-pack-20260730

Conversation

@OrionArchitekton

@OrionArchitekton OrionArchitekton commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Outcome

Turns the first Factory AI at Work episode from a script folder into a fail-closed production lane: one landscape master and three independent 9:16 cuts can be rendered from real evidence, reviewed against explicit claims, and promoted as an immutable closed set before an operator-authorized upload.

No media, credentials, publication approval, upload state, or channel-wide streak counter is committed. Real capture and paid voice rendering remain operator-gated.

Production flow

flowchart LR
  E["Captured evidence"] --> R["Fresh claimed render"]
  S["Merged source commit"] --> A["Detached frozen snapshot"]
  A --> R
  R --> P["Provenance and timeline probes"]
  P --> H["Human production review"]
  H --> C["Closed-world promoter"]
  C --> U["Operator-authorized upload"]
Loading

What changed

  • Adds the Gate 1 scripts, capture plan, claim ledger, publishing copy, receipt template, production spec, and operator runbook for the master plus three portrait cuts.
  • Adds independent title/end-card controls, full-bleed geometry and sample-aspect-ratio guards, fresh output claiming, and provenance over config, script, ordered clips, source build, and final media.
  • Adds a committed source-attested launcher that renders only from an exact detached snapshot, verifies commit objects and file modes, rejects remote rendering, and isolates Git, Bash startup, Node preload, loader, npm, and pnpm configuration surfaces.
  • Installs frozen dependencies in a separate secret-free environment with private package-manager state, disabled lifecycle scripts and pnpm hooks, and a disposable private store. The render process alone receives the ElevenLabs key.
  • Adds receipt validation and a recovery-aware, no-clobber promoter that admits only the exact reviewed inventory and revalidates archived media timelines before closing promotion.
  • Rejects unknown, duplicate, and surplus CLI options so production invocations cannot silently drift from the reviewed contract.

Verification

  • pnpm test: 40 files, 273 tests passed
  • pnpm typecheck: passed
  • pnpm build: local and remote entry builds passed
  • bash -n: all changed shell entrypoints passed
  • Runbook validation: all 8 Bash blocks parsed successfully
  • gitleaks detect --source . --no-banner --redact --exit-code 1: no leaks
  • Committed launcher --verify-only: exact commit snapshot verified
  • Hostile package-manager proof: real Node 24.13.1 and pnpm 9.12.0 completed the hardened frozen install without executing a caller-controlled pnpmfile; the intentionally absent nine clips then stopped preflight before narration
  • Exact pinned diff review: correctness, adversarial, and security reviewers returned no findings

Trust boundaries and follow-ups

  • Installed dependency bytes and the operator-selected Node, pnpm, and system-tool files remain declared toolchain boundaries.
  • Same-UID hostile pathname or system-tool mutation is outside this cooperative no-clobber boundary.
  • Source-attested Gate 1 intentionally rejects remote rendering. Content-addressed remote-bundle attestation is a separate follow-up, not an implied claim here.
  • The external ratified operator authority remains the sole owner of the channel's consecutive-publication counter; this pack cannot truthfully own future channel-wide state.
  • No production media demo is attached because the required real captures and paid voice credential are not present in source control.

Compound Engineering
Codex

Summary by Sourcery

Introduce a fail-closed, production-ready pack for the first Factory AI at Work episode, adding source-attested rendering, immutable output claiming, enhanced clip and aspect validation, and a reviewed promotion workflow for one master and three portrait cuts.

New Features:

  • Add a Factory AI at Work Gate 1 production pack with configs, scripts, capture plan, claim ledger, publishing copy, production receipt template, and operator runbook for one landscape master and three portrait cuts.
  • Introduce per-run CLI overrides for output directory, clips directory, script path, and a source-build attestation mode reserved for the committed detached-snapshot launcher.
  • Add immutable fresh-output claiming that binds writes to a private staging directory, retains an authenticated claim marker, and publishes outputs via no-clobber renames on Linux filesystems.
  • Extend render provenance to include full SHA-256 digests of config, script, and ordered prebaked clip bytes, plus optional source-build attestation for detached-snapshot runs.
  • Add full-bleed and sample-aspect-ratio guards in preflight and rendering so finished compositions must match canvas aspect and use square pixels.
  • Enable independent brand title and end-card selection while preserving the legacy cards flag as the shared default.

Enhancements:

  • Harden the local render pipeline to support source-attested runs, rejecting remote rendering in attested mode and blocking receipts if source changes during rendering.
  • Normalize concat list generation to use relative segment and audio basenames and require exact relative selections in the Factory AI at Work validator.
  • Refine shorts framing behavior so full-bleed clips bypass window framing only when geometry and SAR are valid, and ensure normalization pins the same video stream probed for geometry.
  • Improve CLI robustness by rejecting unknown options, duplicate singleton flags, surplus config paths, and pipeline-only flags on login, preventing silent drift from reviewed contracts.
  • Document the Factory AI at Work Gate 1 production flow, constraints, and gate protocol, including the separation between local evidence and channel gate authority.

Documentation:

  • Update README and add a dedicated Factory AI at Work Gate 1 production spec and runbook documenting production attempts, fresh output semantics, source-attested rendering, and full-bleed clip requirements.
  • Clarify config documentation for brand card controls, clipsDir overrides, and the behavior of --out, --clips-dir, and --script in production runs.

Tests:

  • Add comprehensive Factory AI at Work pack tests covering configs, manifests, clip resolution and SAR, receipt validation, promotion topology, manifest sealing, and source-build attestation behavior.
  • Extend smoke tests for pipeline, preflight, render-aspect guards, provenance, CLI, config, framing, and prebaked narration to cover fresh-output claiming, clip-geometry checks, SAR rejection, brand-card selection, and provenance persistence semantics.

Chores:

  • Introduce a sanitized Git environment helper to strip caller Git overrides from authority-sensitive calls used in source-build attestation.

Summary by CodeRabbit

  • New Features

    • Added independent title-card and end-card controls.
    • Added CLI overrides for output, clips, and scripts.
    • Added detailed render provenance, input hashing, and source-build attestations.
    • Added immutable output handling to prevent accidental overwrites.
    • Added the Factory AI at Work Gate 1 production pack and workflows.
  • Bug Fixes

    • Full-bleed clips now reject incorrect aspect ratios and non-square pixels before rendering.
    • Stricter CLI validation rejects unsupported, duplicate, or malformed options.
  • Documentation

    • Expanded production, publishing, capture, validation, and rollback guidance.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @OrionArchitekton, your pull request is larger than the review limit of 150000 diff characters

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@OrionArchitekton, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 8 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5f2fcb58-06d8-468e-b68a-a1e58df05216

📥 Commits

Reviewing files that changed from the base of the PR and between bfd39c2 and f170580.

📒 Files selected for processing (3)
  • docs/runbooks/factory-ai-at-work-gate-01-production.md
  • tests/factory-ai-at-work-pack.test.ts
  • tests/prebaked-input-binding.test.ts
📝 Walkthrough

Walkthrough

The PR adds a Factory AI production pack with source-attested rendering, immutable output claiming and promotion, expanded provenance reports, stricter CLI validation, independent brand cards, and full-bleed geometry checks.

Changes

Factory AI production workflow

Layer / File(s) Summary
Production pack contracts and documentation
specs/..., demos/factory-ai-at-work/..., docs/runbooks/..., README.md, CHANGELOG.md
Defines Gate 1 capture, evidence, receipts, publishing, demo inputs, production procedures, and validation requirements.
CLI, rendering, provenance, and output integrity
src/cli.ts, src/pipeline.ts, src/provenance.ts, src/ffmpeg.ts, src/framing.ts, src/preflight.ts, src/render.ts, src/types.ts, tests/...
Adds strict CLI options, independent title and end cards, input digests, fresh-output staging, source checks, and full-bleed geometry validation.
Detached source attestation and launcher
scripts/run-source-attested-render.sh, src/source-build.ts, src/source-build.test.ts
Creates and verifies detached committed snapshots, validates tools and source files, and rejects source drift or invalid execution contexts.
Receipt validation and immutable promotion
scripts/validate-factory-ai-at-work-inputs.ts, scripts/validate-factory-ai-at-work-receipt.sh, scripts/promote-factory-ai-at-work-attempt.sh, scripts/cleanup-stale-render-input-root.sh, tests/factory-ai-at-work-pack.test.ts, tests/prebaked-input-binding.test.ts
Validates archived artifacts and receipts, cleans stale private roots, seals reviewed roots, handles interrupted promotion, and prevents unsafe or clobbering publication.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Sequence Diagram(s)

sequenceDiagram
  participant Operator
  participant AttestedLauncher
  participant CLI
  participant runPipeline
  participant Validators
  participant Promotion
  Operator->>AttestedLauncher: start pinned render
  AttestedLauncher->>CLI: launch detached committed source
  CLI->>runPipeline: pass attestation and fresh-output options
  runPipeline->>Validators: produce provenance and media artifacts
  Validators->>Promotion: approve receipt and artifact set
  Promotion-->>Operator: publish sealed reviewed root
Loading

Poem

A rabbit checks the clips in line,
Hashes each leaf and card design.
The source stays still, the paths stay clean,
No clobber mars the rendered scene.
With ears held high, the pack is sealed—
“Hop approved!” the proofs revealed.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely identifies the main change: adding the Factory AI at Work Gate 1 production pack.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/factory-ai-at-work-gate-01-pack-20260730

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implements a fail-closed, source-attested production lane for the Factory AI at Work Gate 1 episode, adding immutable output claiming, stronger geometry/provenance guards, CLI contract enforcement, and a reviewed-pack promoter around a new Factory-specific demo bundle.

Sequence diagram for source-attested immutable render pipeline

sequenceDiagram
  actor Operator
  participant Launcher as run_source_attested_render_sh
  participant Cli as main
  participant SourceBuild as attestSourceBuild
  participant Pipeline as runPipeline
  participant Provenance as buildRenderReport
  participant Output as claimFreshOutputDir

  Operator->>Launcher: invoke with repo_root, commit, node_bin, pnpm_cli, config_path
  Launcher->>Launcher: verify_fixed_commit
  Launcher->>Launcher: verify_snapshot_root
  Launcher->>Launcher: frozen_pnpm_install
  Launcher->>Cli: exec src_cli_ts with --attest-source-build

  Cli->>Cli: parseCommand
  Cli->>SourceBuild: attestSourceBuild
  SourceBuild-->>Cli: SourceBuildSession
  Cli->>Pipeline: runPipeline(config, { requireFreshOut, sourceBuild })

  Pipeline->>SourceBuild: assertSourceBuildExecutionContext
  Pipeline->>Output: claimFreshOutputDir
  Output-->>Pipeline: FreshOutputClaim
  Pipeline->>Pipeline: runPreflight
  Pipeline->>Pipeline: digestPrebakedInputs
  Pipeline->>Pipeline: renderVideo
  Pipeline->>SourceBuild: assertSourceBuildUnchanged

  Pipeline->>Provenance: buildRenderReport
  Provenance-->>Pipeline: RenderReport
  Pipeline->>Provenance: persistRenderReport(required=true)
  Pipeline->>Output: publishFreshOutput
  Output-->>Operator: final.mp4 and render_report.json in reviewed attempt
Loading

Flow diagram for Factory AI at Work Gate 1 production pack

flowchart LR
  A[evidence_source_files] --> B[rehearsal_render_FAKE_TTS]
  B --> C[real_captures_and_voice]
  C --> D[source_attested_render_attempt]
  D --> E[validate_factory_ai_at_work_inputs_ts]
  E --> F[promote_factory_ai_at_work_attempt_sh]
  F --> G[sealed_reviewed_pack_with_PRODUCTION_RECEIPT_sha256]
Loading

File-Level Changes

Change Details Files
Make pipeline outputs immutable per attempt and strengthen render provenance over config, script, and prebaked clips, with optional source-build attestation.
  • Introduce fresh output claiming that refuses existing paths, binds writes to a private staging directory via /proc handles, and publishes with a no-clobber rename while retaining a claim marker inside the output.
  • Hash prebaked clip inputs before spend, recheck them after capture and before render, and record full SHA-256 digests for config, script, and each ordered clip in render-report.json.
  • Allow the pipeline to run in a source-attested mode that blocks remote rendering, checks its execution context against a detached commit snapshot, and fails if the source tree changes during render or the report cannot be written.
src/pipeline.ts
src/provenance.ts
src/provenance.test.ts
tests/pipeline.smoke.test.ts
tests/prebaked-narration.smoke.test.ts
CHANGELOG.md
README.md
Tighten CLI contract parsing and integrate the source-snapshot launcher admission flags into the main entrypoint.
  • Extend CLI parsing with --out, --clips-dir, --script, and --attest-source-build flags, rejecting unknown options, duplicates, surplus positionals, and pipeline-only flags on login.
  • Defer module imports until after source-build admission, then thread fresh-output and sourceBuild options into runPipeline so production runs are immutable and source-attested when requested.
  • Add tests that exercise new flags, attested-mode environment requirements, and reject misuse such as combining attestation with remote rendering or using render-host on login.
src/cli.ts
src/cli.test.ts
Harden ffmpeg-based framing and full-bleed rendering with explicit geometry and sample-aspect-ratio guards, and simplify concat list semantics.
  • Extend ffprobe-based geometry probing to enforce square sample aspect ratio and reject anamorphic inputs, pin normalizeArgs to v:0, and guard full-bleed segments against padding both in preflight and render.
  • Reuse a shared padding calculator in framing, adding assertFullBleedCanvasAspect and tests to ensure framed and full-bleed content either fits within encoder slack or is rejected.
  • Change concat list generation to use basenames for video and audio segment files so manifests are locale-independent and promotion validation can require exact relative names.
src/ffmpeg.ts
src/ffmpeg.test.ts
src/framing.ts
src/framing.test.ts
src/render.ts
tests/render-aspect-guard.test.ts
tests/preflight.smoke.test.ts
specs/shorts-platform-profile-spec.md
src/types.ts
Introduce Factory AI at Work Gate 1 production pack assets plus a validator and promoter around the attempted pack, with source-build attestation plumbing.
  • Add Factory-specific configs, scripts, capture plan, claim ledger, publishing copy, production receipt template, and README under demos/factory-ai-at-work/gate-01/ for one master and three cuts.
  • Implement a TypeScript validator that checks the pack’s archived configs, scripts, clips, render reports, timelines, YouTube chapters, and source-build attestation against the production receipt’s commit.
  • Add a privileged Bash promoter that validates topology, refuses symlinks, nested mounts, and unexpected files, seals a private pack read-only, writes a manifest, moves to the reviewed root with no-clobber semantics, and supports post-promotion verification and interruption recovery.
  • Document the production runbook for Gate 1, including attested renders via the committed launcher, rehearsal vs. real runs, validation steps, and operator boundary notes.
  • Create a comprehensive pack-spec and tests that exercise pack layout, claim ledger content, publishing copy, receipt validator behaviour, attempt promoter semantics, and the closed-world promotion contract.
demos/factory-ai-at-work/gate-01/README.md
demos/factory-ai-at-work/gate-01/CAPTURE_PLAN.md
demos/factory-ai-at-work/gate-01/CLAIM_LEDGER.md
demos/factory-ai-at-work/gate-01/PUBLISHING.md
demos/factory-ai-at-work/gate-01/PRODUCTION_RECEIPT_TEMPLATE.md
demos/factory-ai-at-work/gate-01/master/demo.config.json
demos/factory-ai-at-work/gate-01/master/DEMO_SCRIPT.md
demos/factory-ai-at-work/gate-01/cuts/cut-a/demo.config.json
demos/factory-ai-at-work/gate-01/cuts/cut-a/DEMO_SCRIPT.md
demos/factory-ai-at-work/gate-01/cuts/cut-b/demo.config.json
demos/factory-ai-at-work/gate-01/cuts/cut-b/DEMO_SCRIPT.md
demos/factory-ai-at-work/gate-01/cuts/cut-c/demo.config.json
demos/factory-ai-at-work/gate-01/cuts/cut-c/DEMO_SCRIPT.md
scripts/validate-factory-ai-at-work-inputs.ts
scripts/validate-factory-ai-at-work-receipt.sh
scripts/promote-factory-ai-at-work-attempt.sh
docs/runbooks/factory-ai-at-work-gate-01-production.md
specs/factory-ai-at-work-gate-01-production-pack-spec.md
tests/factory-ai-at-work-pack.test.ts
Add a source-build module and helper to compute, validate, and enforce detached-commit snapshot attestation for local renders.
  • Implement source-build attestation computation over a fixed set of scoped paths using Git trees and SHA-256 of package.json and pnpm-lock.yaml, with a validate helper that recomputes and compares all fields.
  • Introduce attestSourceBuild to admit only detached worktrees created by the committed launcher, verify the runner path, ensure scoped paths are clean and index flags are standard, and issue a module-local SourceBuildSession capability.
  • Provide runtime guards that tie the SourceBuildSession to the pipeline and source-build modules in the same snapshot graph and assert the source tree remains unchanged across render; expose a sanitized Git environment helper for authority-sensitive calls.
  • Add thorough tests for the source-build module covering clean snapshot attestation, dirty and untracked source rejection, hard-link and assume-unchanged/skip-worktree handling, Git repo override resistance, global config isolation, and structural session forgery rejection.
src/source-build.ts
src/source-build.test.ts
src/git-environment.ts
Refine brand card configuration so title and end cards can be controlled independently while preserving legacy behaviour.
  • Extend DemoConfigSchema.brand to include titleCard and endCard booleans with a transform that defaults both from the existing cards flag for backward compatibility.
  • Update pipeline card insertion logic to respect the new titleCard/endCard flags, allowing artifact-first masters to suppress only the opening card while keeping the closing disclosure card.
  • Add config and smoke tests that exercise legacy card defaulting, partial overrides, and timelines for title-only, end-only, and both-card configurations.
src/types.ts
src/config.test.ts
src/pipeline.ts
tests/brand-card-selection.smoke.test.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f20f4169e7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/pipeline.ts Outdated
Comment thread scripts/validate-factory-ai-at-work-receipt.sh Outdated
Comment thread scripts/promote-factory-ai-at-work-attempt.sh

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (3)
scripts/validate-factory-ai-at-work-inputs.ts (1)

304-350: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Deep-compare the report fields by canonical form, not by JSON.stringify key order.

Line 304 uses stableConfigJson for the config, which is the repository's canonical-serialization helper. Lines 310, 336, and 343 then compare clips, voice, and sourceBuildAttestation with raw JSON.stringify. Raw JSON.stringify is sensitive to property insertion order.

The comparison therefore depends on the key order that src/provenance.ts and src/source-build.ts happen to use when they build these objects. A future reorder of { shotId, sha256 } to { sha256, shotId } breaks this validator and reports "input hashes do not match the archived config, script, and ordered clip bytes", which points at the wrong cause.

The failure mode is a false rejection, not a false acceptance, so this is not urgent. Reuse the canonical serializer or a small deep-equal helper for these three comparisons.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/validate-factory-ai-at-work-inputs.ts` around lines 304 - 350,
Replace the raw JSON.stringify comparisons for report.inputs.clips,
report.voice, and report.sourceBuildAttestation with canonical-form deep
comparisons using stableConfigJson or an equivalent shared deep-equality helper.
Keep the existing validation semantics and failure messages unchanged, while
preserving array ordering and value equality.
src/cli.ts (1)

73-114: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract one value-taking helper for the string options.

Lines 59-114 repeat the same parse-and-validate structure four times, once per flag and once per syntax. The blocks differ only in the flag name, the noun in the message, and the assigned variable. One helper removes about 40 lines and makes the validation rule identical for every flag.

♻️ Proposed helper
   const requireOnce = (flag: string) => {
     if (seenFlags.has(flag)) {
       throw new Error(`${flag} may be supplied once`);
     }
     seenFlags.add(flag);
   };
+  const values = new Map<string, string>();
+  const takeValue = (flag: string, noun: string, inline: string | undefined, next: string | undefined): number => {
+    requireOnce(flag);
+    const value = inline ?? next;
+    if (!value || value.startsWith("-")) {
+      throw new Error(`${flag} requires a non-empty ${noun} argument that does not start with '-'`);
+    }
+    values.set(flag, value);
+    return inline === undefined ? 1 : 0;
+  };

Then drive the four options from one table of flag → noun pairs and read the results from values after the loop.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/cli.ts` around lines 73 - 114, Extract the repeated value parsing and
validation from the CLI argument loop into one helper for string options,
parameterized by flag and its error-message noun. Define a table mapping --out,
--clips-dir, --script, and the other string option to their nouns, use the
helper for both separate-argument and --flag=value forms, and retrieve parsed
values from a shared values object before assigning the corresponding variables.
scripts/promote-factory-ai-at-work-attempt.sh (1)

56-127: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider collapsing the two entry-check helpers into one.

factory_require_exact_entries and factory_require_allowed_entries are identical except for the entry-count check. A single helper with a mode argument removes about 30 duplicated lines and keeps the glob save/restore logic in one place.

♻️ Suggested shape
+factory_require_entries() {
+  local mode="$1"   # exact | allowed
+  local root="$2"
+  local label="$3"
+  shift 3
+  # ... shared glob collection ...
+  if [ "$mode" = exact ] && [ "${`#entries`[@]}" -ne "$#" ]; then
+    echo "$label does not contain the exact required entry count" >&2
+    return 1
+  fi
+  # ... shared name membership loop ...
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/promote-factory-ai-at-work-attempt.sh` around lines 56 - 127,
Consolidate factory_require_exact_entries and factory_require_allowed_entries
into one shared entry-validation helper, preserving the existing
dotglob/nullglob save-and-restore behavior and unexpected-entry checks. Add a
mode or optional argument to control whether the helper enforces an exact entry
count, and update both callers to use the unified helper with the appropriate
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@demos/factory-ai-at-work/gate-01/CAPTURE_PLAN.md`:
- Line 43: Update the sentence in CAPTURE_PLAN.md to hyphenate the compound
modifier, changing “15 second disclosure card” to “15-second disclosure card.”

In `@scripts/validate-factory-ai-at-work-inputs.ts`:
- Around line 455-475: Update validateChapters to validate each chapter’s
duration from the masterReport timeline before comparing YOUTUBE_CHAPTERS.txt.
Ensure every chapter entry is at least 10 seconds long, using the next chapter’s
start time or the timeline’s ending duration for the final chapter, and fail
with a clear message identifying any shorter chapter; preserve the existing
duplicate, missing, and exact-content checks.

In `@src/cli.ts`:
- Around line 59-72: The CLI option parsing in src/cli.ts lines 59-72 and 73-114
duplicates validation and lets --render-host accept an empty space-form value.
Add a shared takeValue(flag, noun, inline, next) helper that calls requireOnce,
rejects empty values and values beginning with "-", then replace both
--render-host forms and the --out, --clips-dir, and --script parsing blocks with
it; specifically ensure the --render-host space form uses the same !next
validation.
- Around line 191-193: Unify relative-path handling for the --script and
--clips-dir overrides in the CLI configuration assignment block. Either validate
and require both options to be absolute in their help/validation, or resolve
both relative values against the same config directory before assigning
config.script and config.clipsDir; ensure subsequent readFileSync and
resolveClipPath calls use the intended common base.

In `@tests/factory-ai-at-work-pack.test.ts`:
- Around line 37-46: Avoid running the parent-commit lookup during module
evaluation: resolve OTHER_SOURCE_COMMIT lazily within the unrelated-commit
assertion, treating a failed HEAD^ lookup as unavailable and skipping that
assertion. Also defer SOURCE_BUILD_ATTESTATION creation until
writeProductionArtifacts or otherwise ensure its rejection is awaited and
reported as a test failure rather than becoming an unhandled rejection.

---

Nitpick comments:
In `@scripts/promote-factory-ai-at-work-attempt.sh`:
- Around line 56-127: Consolidate factory_require_exact_entries and
factory_require_allowed_entries into one shared entry-validation helper,
preserving the existing dotglob/nullglob save-and-restore behavior and
unexpected-entry checks. Add a mode or optional argument to control whether the
helper enforces an exact entry count, and update both callers to use the unified
helper with the appropriate behavior.

In `@scripts/validate-factory-ai-at-work-inputs.ts`:
- Around line 304-350: Replace the raw JSON.stringify comparisons for
report.inputs.clips, report.voice, and report.sourceBuildAttestation with
canonical-form deep comparisons using stableConfigJson or an equivalent shared
deep-equality helper. Keep the existing validation semantics and failure
messages unchanged, while preserving array ordering and value equality.

In `@src/cli.ts`:
- Around line 73-114: Extract the repeated value parsing and validation from the
CLI argument loop into one helper for string options, parameterized by flag and
its error-message noun. Define a table mapping --out, --clips-dir, --script, and
the other string option to their nouns, use the helper for both
separate-argument and --flag=value forms, and retrieve parsed values from a
shared values object before assigning the corresponding variables.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 862f0dc1-c59e-4753-9dc2-e8a4301d8e01

📥 Commits

Reviewing files that changed from the base of the PR and between b582288 and f20f416.

📒 Files selected for processing (45)
  • CHANGELOG.md
  • README.md
  • demos/factory-ai-at-work/gate-01/CAPTURE_PLAN.md
  • demos/factory-ai-at-work/gate-01/CLAIM_LEDGER.md
  • demos/factory-ai-at-work/gate-01/PRODUCTION_RECEIPT_TEMPLATE.md
  • demos/factory-ai-at-work/gate-01/PUBLISHING.md
  • demos/factory-ai-at-work/gate-01/README.md
  • demos/factory-ai-at-work/gate-01/cuts/cut-a/DEMO_SCRIPT.md
  • demos/factory-ai-at-work/gate-01/cuts/cut-a/demo.config.json
  • demos/factory-ai-at-work/gate-01/cuts/cut-b/DEMO_SCRIPT.md
  • demos/factory-ai-at-work/gate-01/cuts/cut-b/demo.config.json
  • demos/factory-ai-at-work/gate-01/cuts/cut-c/DEMO_SCRIPT.md
  • demos/factory-ai-at-work/gate-01/cuts/cut-c/demo.config.json
  • demos/factory-ai-at-work/gate-01/master/DEMO_SCRIPT.md
  • demos/factory-ai-at-work/gate-01/master/demo.config.json
  • docs/runbooks/factory-ai-at-work-gate-01-production.md
  • scripts/promote-factory-ai-at-work-attempt.sh
  • scripts/run-source-attested-render.sh
  • scripts/validate-factory-ai-at-work-inputs.ts
  • scripts/validate-factory-ai-at-work-receipt.sh
  • specs/factory-ai-at-work-gate-01-production-pack-spec.md
  • specs/shorts-platform-profile-spec.md
  • src/cli.test.ts
  • src/cli.ts
  • src/config.test.ts
  • src/ffmpeg.test.ts
  • src/ffmpeg.ts
  • src/framing.test.ts
  • src/framing.ts
  • src/git-environment.ts
  • src/pipeline.ts
  • src/preflight.ts
  • src/provenance.test.ts
  • src/provenance.ts
  • src/render.ts
  • src/source-build.test.ts
  • src/source-build.ts
  • src/types.ts
  • tests/brand-card-selection.smoke.test.ts
  • tests/cli.test.ts
  • tests/factory-ai-at-work-pack.test.ts
  • tests/pipeline.smoke.test.ts
  • tests/prebaked-narration.smoke.test.ts
  • tests/preflight.smoke.test.ts
  • tests/render-aspect-guard.test.ts

Comment thread demos/factory-ai-at-work/gate-01/CAPTURE_PLAN.md Outdated
Comment thread scripts/validate-factory-ai-at-work-inputs.ts
Comment thread src/cli.ts
Comment thread src/cli.ts
Comment thread tests/factory-ai-at-work-pack.test.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (6)
tests/prebaked-input-binding.test.ts (3)

857-860: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the specific rejection reason for the trailing-slash symlink case.

expect(runRecovery).toThrow() accepts any failure, including a usage error. The script rejects a trailing slash at a dedicated guard with the message "render-input root must be one exact canonical directory path without a trailing slash". Match that text, so the test proves the trailing-slash guard fired and not some earlier check.

♻️ Proposed assertion
-      expect(runRecovery).toThrow();
+      expect(runRecovery).toThrow(/without a trailing slash/);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/prebaked-input-binding.test.ts` around lines 857 - 860, Update the
runRecovery assertion in the trailing-slash symlink test to match the exact
rejection message “render-input root must be one exact canonical directory path
without a trailing slash” instead of accepting any thrown error. Preserve the
existing marker and outsideRoot assertions.

788-814: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

This test uses the shared tmpdir() as --tmp-root.

The script requires the temporary root to be root-owned with the sticky bit, or owned by the current user without group or world write. The shared tmpdir() satisfies the first rule on a typical Linux host, but the test then depends on host /tmp permissions. Every other recovery test in this file creates a private mkdtemp root and passes that. Use a private root here too, so the happy path does not depend on the host temporary-directory mode.

♻️ Proposed change to use a private temporary root
-    const staleRoot = await mkdtemp(
-      join(
-        tmpdir(),
-        `agent-demo-video-render-inputs-${DEAD_RECOVERY_PID}-`,
-      ),
-    );
+    const selectedTmpRoot = await mkdtemp(join(tmpdir(), "prebaked-recovery-happy-"));
+    const staleRoot = await mkdtemp(
+      join(
+        selectedTmpRoot,
+        `agent-demo-video-render-inputs-${DEAD_RECOVERY_PID}-`,
+      ),
+    );
     const recoveryScript = join(
       process.cwd(),
       "scripts/cleanup-stale-render-input-root.sh",
     );
     await markPrivateInputRoot(staleRoot);
     const runRecovery = () => execFileSync(
       "/usr/bin/bash",
       [
         "--noprofile",
         "--norc",
         "-p",
         recoveryScript,
         "--tmp-root",
-        tmpdir(),
+        selectedTmpRoot,
         "--older-than-seconds",
         "3600",
         staleRoot,
       ],
       { encoding: "utf8" },
     );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/prebaked-input-binding.test.ts` around lines 788 - 814, Update the
recovery test around “recovers only one explicitly named owned stale
render-input root” to create a private temporary root with mkdtemp, pass that
root to the script’s --tmp-root option, and create the stale input root beneath
it. Keep the test’s existing recovery assertions and cleanup behavior unchanged.

38-56: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The await import("node:fs/promises") calls in cleanup blocks resolve to this mock, not to the real module.

vi.mock intercepts the specifier for dynamic imports too. Every finally block that calls (await import("node:fs/promises")).rm(...) therefore goes through the override at line 42. The tests pass today only because each fault-injecting test sets cleanupFault.enabled = false before its rm call. A future test that throws before resetting the flag will silently skip its own cleanup and leak a temporary directory.

Capture the real rm once and use it in cleanup blocks, so cleanup never depends on the fault flag.

♻️ Proposed helper for unmocked cleanup
 vi.mock("node:fs/promises", async (importOriginal) => {
   const actual = await importOriginal<typeof import("node:fs/promises")>();
   return {
     ...actual,

Then add a helper near the top of the file and use it in every finally block:

const realFs = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
const removeTree = (path: string) => realFs.rm(path, { recursive: true, force: true });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/prebaked-input-binding.test.ts` around lines 38 - 56, Capture the
unmocked fs/promises module once using vi.importActual and define a removeTree
helper near the test setup that calls the real rm with recursive and force
options. Update every finally-block cleanup in the tests to use removeTree
instead of dynamically importing node:fs/promises, ensuring cleanup is
independent of cleanupFault.enabled while preserving the existing
fault-injection mock.
scripts/promote-factory-ai-at-work-attempt.sh (1)

46-127: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

factory_require_node_binary is maintained as two verbatim copies. Both scripts define the same 80-line Node admission function. The two copies must stay identical, because the promotion gate and the receipt gate are supposed to give the same guarantee about the interpreter that evaluates receipts. Nothing enforces that today, and the neighboring environment scrub lists already diverge: the receipt validator filters RIPGREP_CONFIG_PATH and the promote script does not.

  • scripts/promote-factory-ai-at-work-attempt.sh#L46-L127: extract this definition into a shared helper that both scripts source from a path pinned relative to $0, or add a test that compares the two function bodies.
  • scripts/validate-factory-ai-at-work-receipt.sh#L33-L114: replace this copy with the shared helper, and align the environment scrub list with the promote script in the same change.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/promote-factory-ai-at-work-attempt.sh` around lines 46 - 127, The
duplicated factory_require_node_binary definitions must be maintained through
one shared implementation. In scripts/promote-factory-ai-at-work-attempt.sh
lines 46-127, extract the function into a shared helper sourced using a path
pinned relative to $0; in scripts/validate-factory-ai-at-work-receipt.sh lines
33-114, remove the local copy and source that helper. Align the receipt
validator’s environment scrub list with the promote script, including the
RIPGREP_CONFIG_PATH handling.
src/pipeline.ts (2)

328-331: 🩺 Stability & Availability | 🔵 Trivial

Document the temporary-root capacity requirement.

Every prebaked clip is copied into the binding root under tmpdir(). On many hosts /tmp is a memory-backed tmpfs, so the Gate 1 master plus the three cuts require roughly the full size of all thirteen captures in RAM. If tmpfs runs out, binding fails with ENOSPC after the operator has already staged evidence.

trustedPrivateInputParent reads tmpdir(), so TMPDIR already gives operators a disk-backed override. State the space requirement and the TMPDIR override in the runbook preconditions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pipeline.ts` around lines 328 - 331, Update the runbook preconditions for
the temporary binding root created after trustedPrivateInputParent to state that
it must have capacity for roughly the full size of all thirteen captures,
including the Gate 1 master and three cuts, and document TMPDIR as the operator
override for selecting a disk-backed location instead of tmpdir().

111-119: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider handling SIGHUP for the private binding root.

The handlers cover SIGINT and SIGTERM only. SIGHUP terminates the process by default, and it arrives whenever a controlling terminal or SSH session closes. In that case the binding root survives with full copies of the capture media, and recovery needs scripts/cleanup-stale-render-input-root.sh. The attested launcher already treats HUP as a cleanup trigger, so adding it here restores parity.

If you accept this change, update the SIGINT/SIGTERM wording in docs/runbooks/factory-ai-at-work-gate-01-production.md (line 534) and in specs/factory-ai-at-work-gate-01-production-pack-spec.md (AC8, line 143) as well.

♻️ Proposed change
 function removePrivateInputSignalHandlers(): void {
   process.removeListener("SIGINT", handlePrivateInputSignal);
   process.removeListener("SIGTERM", handlePrivateInputSignal);
+  process.removeListener("SIGHUP", handlePrivateInputSignal);
 }
 
 function addPrivateInputSignalHandlers(): void {
   process.prependListener("SIGINT", handlePrivateInputSignal);
   process.prependListener("SIGTERM", handlePrivateInputSignal);
+  process.prependListener("SIGHUP", handlePrivateInputSignal);
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pipeline.ts` around lines 111 - 119, Extend addPrivateInputSignalHandlers
and removePrivateInputSignalHandlers to register and remove
handlePrivateInputSignal for SIGHUP alongside SIGINT and SIGTERM, preserving the
existing listener behavior. Update the corresponding SIGINT/SIGTERM-only wording
in the production runbook and production pack specification to include SIGHUP.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/runbooks/factory-ai-at-work-gate-01-production.md`:
- Around line 373-374: Update the Node probe block that writes
YOUTUBE_CHAPTERS.txt to emit its output to a temporary file first, such as
YOUTUBE_CHAPTERS.txt.tmp, so failures leave the existing destination unchanged.
Replace the final non-empty check to validate the temporary file, then move it
into YOUTUBE_CHAPTERS.txt only after validation succeeds.

In `@tests/prebaked-input-binding.test.ts`:
- Around line 800-814: Gate the stale-root recovery tests around runRecovery and
their related cases to Linux, or otherwise skip them on macOS and Windows before
invoking /usr/bin/bash. Document the Linux-only requirement for npm test if the
tests remain ungated, while preserving the existing recovery assertions on
Linux.

---

Nitpick comments:
In `@scripts/promote-factory-ai-at-work-attempt.sh`:
- Around line 46-127: The duplicated factory_require_node_binary definitions
must be maintained through one shared implementation. In
scripts/promote-factory-ai-at-work-attempt.sh lines 46-127, extract the function
into a shared helper sourced using a path pinned relative to $0; in
scripts/validate-factory-ai-at-work-receipt.sh lines 33-114, remove the local
copy and source that helper. Align the receipt validator’s environment scrub
list with the promote script, including the RIPGREP_CONFIG_PATH handling.

In `@src/pipeline.ts`:
- Around line 328-331: Update the runbook preconditions for the temporary
binding root created after trustedPrivateInputParent to state that it must have
capacity for roughly the full size of all thirteen captures, including the Gate
1 master and three cuts, and document TMPDIR as the operator override for
selecting a disk-backed location instead of tmpdir().
- Around line 111-119: Extend addPrivateInputSignalHandlers and
removePrivateInputSignalHandlers to register and remove handlePrivateInputSignal
for SIGHUP alongside SIGINT and SIGTERM, preserving the existing listener
behavior. Update the corresponding SIGINT/SIGTERM-only wording in the production
runbook and production pack specification to include SIGHUP.

In `@tests/prebaked-input-binding.test.ts`:
- Around line 857-860: Update the runRecovery assertion in the trailing-slash
symlink test to match the exact rejection message “render-input root must be one
exact canonical directory path without a trailing slash” instead of accepting
any thrown error. Preserve the existing marker and outsideRoot assertions.
- Around line 788-814: Update the recovery test around “recovers only one
explicitly named owned stale render-input root” to create a private temporary
root with mkdtemp, pass that root to the script’s --tmp-root option, and create
the stale input root beneath it. Keep the test’s existing recovery assertions
and cleanup behavior unchanged.
- Around line 38-56: Capture the unmocked fs/promises module once using
vi.importActual and define a removeTree helper near the test setup that calls
the real rm with recursive and force options. Update every finally-block cleanup
in the tests to use removeTree instead of dynamically importing
node:fs/promises, ensuring cleanup is independent of cleanupFault.enabled while
preserving the existing fault-injection mock.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ccc34c4a-5fd1-4c77-bbad-9e1ad03fefcb

📥 Commits

Reviewing files that changed from the base of the PR and between f20f416 and bfd39c2.

📒 Files selected for processing (16)
  • README.md
  • demos/factory-ai-at-work/gate-01/CAPTURE_PLAN.md
  • docs/runbooks/factory-ai-at-work-gate-01-production.md
  • scripts/cleanup-stale-render-input-root.sh
  • scripts/promote-factory-ai-at-work-attempt.sh
  • scripts/run-source-attested-render.sh
  • scripts/validate-factory-ai-at-work-inputs.ts
  • scripts/validate-factory-ai-at-work-receipt.sh
  • specs/factory-ai-at-work-gate-01-production-pack-spec.md
  • src/cli.test.ts
  • src/cli.ts
  • src/pipeline.ts
  • src/preflight.ts
  • tests/factory-ai-at-work-pack.test.ts
  • tests/prebaked-input-binding.test.ts
  • tests/preflight.smoke.test.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • demos/factory-ai-at-work/gate-01/CAPTURE_PLAN.md
  • README.md
  • src/cli.test.ts
  • tests/preflight.smoke.test.ts
  • scripts/run-source-attested-render.sh
  • tests/factory-ai-at-work-pack.test.ts
  • src/preflight.ts
  • scripts/validate-factory-ai-at-work-inputs.ts

Comment thread docs/runbooks/factory-ai-at-work-gate-01-production.md Outdated
Comment thread tests/prebaked-input-binding.test.ts
@OrionArchitekton
OrionArchitekton merged commit e105b9f into master Aug 1, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants