KB-6989

P3D Pack 1 Phase 4 — Implementation DRAFT v5 Patch Report

11 min read Revision 1
p3dpack1phase4patch-reportdraft-v5opus

P3D Pack 1 Phase 4 — Implementation DRAFT v5 Patch Report

Date: 2026-05-11 Author: Opus 4.7 (patch executor) Triggered by: GPT directive — gpt-directive-opus-p3d-pack1-phase4-draft-v5-single-session-no-hardcode-2026-05-11.md Handoff: handoff-p3d-pack1-phase4-draft-v5-no-hardcode-opus-resume-2026-05-11.md Action: Patch DRAFT v4 (REJECTED) → DRAFT v5 Execution: None. No agent dispatched. No seed run. No migration.


1. Final status flags

phase4_draft_v5_status=PATCHED
vocab_executable_candidate=true
species_mapping_executable=false
hash_provenance_document_only=true
single_session_transaction=true
executable_stop_gates=true
temp_table_cross_session_bug_fixed=true
no_hardcoded_seed_list=true
psql_run_marker_fixed=true
requires_GPT_User_review_before_dispatch=true

2. Paths

Artifact Path
DRAFT v5 prompt (patched in place) knowledge/dev/laws/dieu44-trien-khai/prompts/p3d-pack1-phase4-governance-vocab-species-prep-implementation-prompt-DRAFT.md
This patch report knowledge/dev/laws/dieu44-trien-khai/reports/p3d-pack1-phase4-implementation-draft-v5-patch-report.md
Source directive knowledge/dev/laws/dieu44-trien-khai/directives/gpt-directive-opus-p3d-pack1-phase4-draft-v5-single-session-no-hardcode-2026-05-11.md
Source handoff knowledge/dev/laws/dieu44-trien-khai/handoffs/handoff-p3d-pack1-phase4-draft-v5-no-hardcode-opus-resume-2026-05-11.md
v4 rejection review knowledge/dev/laws/dieu44-trien-khai/reviews/gpt-review-p3d-pack1-phase4-implementation-draft-v4-not-approved-2026-05-11.md

3. Scope by mode

Item Mode Authoritative source declared in v5
vocab.section_type.* Executable candidate live public.tac_logical_unit.section_type DISTINCT non-null
vocab.publication_type.* Executable candidate live public.tac_publication.publication_type DISTINCT non-null
vocab.unit_kind.law_unit Executable candidate Pack 1 EVOLVE contract (no TAC column to derive from)
Species mapping (entity_species, species_collection_map) Read-only candidate only n/a — no executable path
Hash provenance (unit_version.content_profile.source_hashes.tac_v1) Document-only n/a — target field not provisioned

4. Top 7 fixes from v4

  1. Cross-session temp table bug eliminated. v4 created _delta_section_type / _delta_pub_type / _delta_unit_kind in one psql call and tried to use them in a second psql call; Postgres temp tables are session-scoped so the second session never saw them. v5 places all gates, delta tables, INSERTs, the _inserted_keys capture and the planner verification inside one psql invocation wrapped in a single BEGIN..COMMIT. Every temp table is ON COMMIT DROP and lives only inside this transaction.

  2. Prose STOP gates converted to executable DO $$ ... RAISE EXCEPTION ... END $$; blocks. v4's "STOP if no unique constraint/index on key" was a comment only. v5's G1..G7 are real PL/pgSQL gates that raise on failure; ON_ERROR_STOP=1 plus the surrounding transaction guarantees automatic rollback and a non-zero script exit.

  3. Exact dot_config schema gate (G1). v4 said "agent MUST adapt INSERT columns to match GATE 0 schema results", which is unsafe schema inference. v5 requires the exact column set (key, value, description, updated_at); if any column is missing, G1 raises and the transaction aborts before any INSERT.

  4. Strict unique-key gate (G2). v4 only printed constraints/indexes. v5 verifies via pg_constraint and pg_index that dot_config(key) is backed by a single-column UNIQUE/PK constraint or a single-column unique index whose first key column is key. ON CONFLICT (key) DO NOTHING is allowed only after G2 passes.

  5. Inserted keys captured inside the transaction via RETURNING. v4 reported inserted rows by WHERE description = :'run_marker' after a separate-session INSERT — fragile, and impossible if the temp-table bug aborted the INSERT entirely. v5 wraps each INSERT in WITH ins AS (INSERT ... RETURNING key, value) INSERT INTO _inserted_keys ... inside the same transaction, then prints _inserted_keys before COMMIT. This list is the authoritative input to rollback.

  6. Executable planner verification before COMMIT (G7). v4 ran fn_iu_create_plan(...) after the seed but only as a SELECT printout — no gate. v5 wraps the planner call in a DO block and raises if status ILIKE '%unresolved_vocab%', if resolved_unit_kind <> 'law_unit', or if status is NULL. Failure rolls the transaction back before COMMIT, so a partially-seeded but planner-broken state cannot persist.

  7. run_marker propagated via SET LOCAL p3d.run_marker + current_setting(). v4 used :'run_marker' directly, including inside dollar-quoted contexts where psql client-side substitution into $$..$$ is fragile (escape ambiguity for any value containing a quote). v5 sets a custom session GUC at the top of the transaction (SET LOCAL p3d.run_marker = :'run_marker') and reads it from DO blocks via current_setting('p3d.run_marker'). Plain SQL outside DO blocks continues to use :'run_marker' where the substitution is safe (e.g. Section C, Section F cross-check).

5. Other improvements (not in top 7)

  • G3 also gates the planner function existence (public.fn_iu_create_plan) via pg_proc, so G7 cannot fail for a missing-function reason without first emitting a clear G3 message.
  • G4 gates the exact source columns (tac_logical_unit.section_type, tac_publication.publication_type) needed by the delta queries.
  • G5 (value-conflict gate) added as defence in depth. The delta queries already exclude existing keys, but if a concurrent writer inserts a conflicting row between delta and INSERT, G5 catches it before COMMIT.
  • Authoritative source declared per category in §0 with the reason why that source is authoritative — directly addressing the "no hardcode" philosophy that "every value is derived from a declared authoritative source at execution time, and the prompt states why".
  • Rollback model rewritten to use exact keys from the report (key = ANY(ARRAY[...])). Description-LIKE rollback is explicitly forbidden in v5; description-equality is allowed only as a post-rollback cross-check expected to return zero.
  • Read-only preflight (Section A) cleanly separated from the executable transaction. Section A makes no temp tables and may safely run in independent psql sessions; only Section B is single-session.
  • Species section explicitly flagged non-executable with three status flags the agent must write verbatim into the report.

6. Forbidden patterns explicitly removed from v5

Forbidden in v5 Where it appeared in v4
Temp tables created in one psql call, referenced in another Section 3 → Section 4 boundary
Prose-only STOP gates "STOP if no unique constraint/index on key", "STOP if any source table missing"
Agent-adapted INSERT columns "Agent MUST adapt INSERT columns to match GATE 0 schema results"
Hand-typed seed list None present, but reinforced in §0 + §10 of v5
Description-LIKE primary rollback Section 7 of v4 (description-equality was the sole predicate)
Fuzzy ILIKE '%law%' in executable path Not in v4 executable, explicitly banned in v5 §1
Hardcoded composition_level / subordinate / target-collection literals None in v4, explicitly banned in v5 §6

7. Why each authoritative source is correct

  • section_type <- live tac_logical_unit.section_type. TAC content rows already carry the section_type values that production needs. Migrating TAC→IU requires those values to exist in dot_config first. Reading them from the live table at execution time guarantees the prompt cannot be stale: if production has acquired a new section_type since the last review, v5 picks it up; if a section_type was retired and no longer appears in live rows, v5 will not seed it.
  • publication_type <- live tac_publication.publication_type. Same reasoning, for the publication side.
  • law_unit <- Pack 1 EVOLVE contract. TAC has no unit_kind column. The single value law_unit is not a "snapshot of current data"; it is a migration-contract identifier saying "TAC logical units become native IU rows of kind law_unit". The prompt declares this as a contract value, and G7 (planner resolution) is the executable check that the seed correctly satisfies the contract — if the planner does not resolve to law_unit, COMMIT does not happen.

8. Known constraints and gaps

  • fn_iu_create_plan return signature is assumed to expose status, resolved_unit_kind, would_create. This matches v4's already-running probe call, so production behaviour is already validated. If the planner signature is changed in a future migration, G7's SELECT ... INTO declaration must be updated correspondingly.
  • G2 covers single-column UNIQUE/PK on key via pg_constraint and single-column unique index via pg_index (indnkeyatts = 1, first key column = key). Multi-column unique indexes that include key plus other columns are intentionally not accepted: ON CONFLICT (key) requires a constraint/index whose key set is exactly (key).
  • SET LOCAL p3d.run_marker relies on PostgreSQL's acceptance of dotted custom GUC names (true for PG 9.2+; production is PG 16). No additional configuration is required.
  • current_setting('p3d.run_marker', true) uses the missing_ok = true form in G6 so the gate's own error message ("run_marker GUC empty") is what surfaces if bash omits -v run_marker=..., instead of an opaque PG error.

9. What still requires GPT/User review

  • The patch is at the prompt level only. No execution has occurred. GPT must review v5 against the directive and either approve for dispatch or request another patch round.
  • Species mapping remains unresolved and explicitly cannot be promoted to executable inside this prompt. A separate, GPT/User-approved species-mapping prompt is the required next artifact whenever the team decides to advance that workstream.
  • Hash provenance is documented in §7 of v5 but not implemented. A future phase will need its own prompt to provision the target field and backfill.

10. Final response to chat

The accompanying chat message returns only:

  1. v5 prompt path.
  2. This report's path.
  3. The top 7 fixes (summarized).
  4. Scope: executable candidate (vocab prep only) / read-only candidate (species) / document-only (hash provenance).
  5. Confirmation: GPT/User review required before any dispatch.
phase4_draft_v4=REJECTED_FOR_DISPATCH
phase4_draft_v5=PATCHED_READY_FOR_GPT_REVIEW
agent_dispatch_allowed=false
seed_execution_allowed=false
species_mapping_executable=false
migration_allowed=false
next_action=GPT_REVIEW_DRAFT_V5

Patched: 2026-05-11 | Opus 4.7 | One transaction, executable gates, exact-key rollback, no hardcode.

Back to Knowledge Hub knowledge/dev/laws/dieu44-trien-khai/reports/p3d-pack1-phase4-implementation-draft-v5-patch-report.md