Worked Examples
Validate scientifically engagement closure — Contact and Engagement Platform
Validate engagement closure through lifecycle-state integrity, completion evidence, audit consistency, unresolved obligations, and privacy-aware retention controls. This guide provides developers with reproducible tests, SQL diagnostics, and verification procedures to identify closure failures and establish defensible, auditable outcomes.
Application: Contact and Engagement Platform
Component: Engagement Lifecycle & Closure (proposed Knowledge Base component; select the registered component in editor)
Source version: Engagement Intake 2.0.2, commit 3f246974276a5e582d09f8c48d21628b82626bc7
Review status: Source-reviewed protocol; synthetic checker verified; independent staging and privacy acceptance pending
Audience: WordPress/PHP, database, integration, QA, security, privacy, and research engineers
Estimated reading time: 23 minutes
Engagement closure is a terminal state change in an operational record, not by itself proof that contracted work was delivered, obligations were discharged, or personal data was lawfully retained. This guide defines a falsifiable validation protocol for completed and canceled engagements, reconciles SQL state with audit events and immutable handoff evidence, and supplies offline tests that distinguish existing behavior from proposed controls.
1. Purpose, research question, and evidence boundary
Primary question: Can an independent reviewer reconstruct why, when, and by whom an engagement entered a terminal status; determine whether the transition was authorized; corroborate the state against audit records and source evidence; and verify that closure-related retention or disclosure decisions were separately documented?
Unit of analysis: One terminal engagement transition, identified by engagement ID, prior row version, final status, actor, and event timestamp. Count transition attempts separately from successful terminal transitions and separately from completed deliverables. If the research concerns outcomes, separately specify the deliverable-level evidence model, reviewer rubric, intervention and comparison design.
A test passing with synthetic data verifies the diagnostic utility’s behavior against those fixtures. A source-reviewed method establishes intended implementation constraints. Neither establishes that production records satisfy the constraints or that a closed engagement achieved its stated impact.
2. Implemented lifecycle contract and developer terminology
| Source status | Permitted terminal transition | Meaning and evidence |
|---|---|---|
handoff_pending |
canceled |
Handoff not active; cancellation reason required |
ready_for_setup |
canceled |
Readiness passed, but delivery not activated |
active |
completed, canceled |
Delivery begun; completion and cancellation must not be conflated |
paused |
completed, canceled |
Paused work can reach a terminal state |
completed, canceled |
None in current transition map | Terminal; no ordinary reopen transition present |
Implementation source: SC_EI_Engagement_Schema::statuses() and SC_EI_Engagement_Repository::change_status(). The terminal audit event types are engagement_completed and engagement_canceled; completion metadata uses completed_by, completed_at, and completion_note; cancellation uses canceled_by, canceled_at, and cancellation_reason.
The handler enforces capability sc_intake_complete_engagements, a WordPress nonce and a typed confirmation (COMPLETE <ENGAGEMENT_NUMBER> or CANCEL <ENGAGEMENT_NUMBER>). The repository also sanitizes and rejects a blank transition note. These are code-level checks; effective role assignments and deployed HTTP behavior require staging confirmation.
3. Verification plan and falsifiable acceptance hypotheses
| Hypothesis | Observable evidence | Counterexample / failure |
|---|---|---|
| H1: valid terminal transition | Allowed prior status, terminal status, transition note, actor and timestamp | Direct handoff_pending → completed or missing completion metadata |
| H2: auditable lifecycle | One matching engagement event and independently checked audit trail | Committed terminal row with missing event |
| H3: snapshot integrity | Recorded SHA-256 equals SHA-256 of stored exact payload bytes | Changed payload with unchanged digest |
| H4: delivery reconciliation (proposed policy) | Obligation register, acceptance/waiver evidence and reasoned disposition | Unresolved contracted deliverable with status completed |
| H5: controlled disclosure | Restricted records never appear in public reports or evidence bundles | Internal notes, identifiers, or personal fields in closure export |
| H6: retention legality is separately assessed | Versioned policy, hold review, approval, disposal evidence | Erasure despite active hold or blanket indefinite retention |
H1–H3 are tied to existing implementation structures. H4–H6 are additional recommended verification and governance controls, not proven closure prerequisites in the current repository. Test each independently, and publish the evidence status for each hypothesis.
4. Dataset, observation window, and measurement definitions
Select a fixed UTC interval [t0, t1) and freeze the plugin commit, database schema version, environment label, configuration hash, exclusion rules, and reviewer protocol. For a closure cohort, filter on completed_at or canceled_at; do not substitute created_at without explicitly changing the research question. Separate preactivation cancellations from cancellations after activation. Include suppressed or privacy-restricted records in an authorized internal denominator only if the lawful study protocol permits them; never export their identifying fields into a public sample.
Recommended indicators:
- Traceability:
n_terminal_with_matching_event / n_terminal. - Closure metadata completeness:
n_terminal_with_actor_timestamp_and_note / n_terminal. - Reconciliation completeness:
n_closures_with_all_policy_obligations_disposed / n_eligible_closures(proposed additional control). - Audit gap count: unmatched terminal records, plus duplicate and misordered events, reported separately.
- Latency: median and range of
terminal_timestamp - activated_atfor completed or postactivation canceled engagements only; exclude unknown or negative intervals and report exclusions.
Report numerators and denominators internally with uncertainty where estimating a population rate. For external reporting, apply disclosure review before exposing counts. A confidence interval cannot transform unverified or nonrandom operational data into a scientific causal result; missing events may be systematically related to failure.
Cause
Closure validation failures commonly originate in mismatched status transitions, authorization drift, incomplete notes, optimistic-lock conflicts, audit-write failures, unresolved obligations, snapshot payload corruption, inconsistent definitions of completion, or incomplete data-disposition handling.
Source-reviewed risk requiring a specific fault-injection test: SC_EI_Engagement_Repository::transition() performs the engagement row update and then calls record_event() and SC_EI_Audit_Log::record() without examining their return values. record_event() is declared void and does not propagate a database insert failure. Consequently, the code path does not by itself demonstrate fail-closed audit persistence. Whether this causes missing records depends on actual database/runtime behavior and must be tested in isolated staging.
Separate policy limitation: change_status() verifies a permitted transition and a nonblank note; it does not call a closure-specific delivery-completeness or retention-readiness gate. The earlier readiness() method applies to handoff/activation, not terminal closure. Do not present onboarding-readiness checks as an implemented closure checklist.
5. Inspect environment and operational preconditions
- Determine deployed plugin version, source commit and schema migration state before comparing expected behavior. Review the actual version rather than trusting an article’s version label.
- Confirm the actor has
sc_intake_complete_engagements; confirm the admin route checks its nonce and typed confirmation. - Use a disposable WordPress installation with isolated MySQL/MariaDB, synthetic engagements, and no outbound mail or production integrations.
- Capture query-safe metadata: engagement ID, row version, permitted status code, event IDs, timestamp, actor ID, boolean completeness flags, and digests. Avoid contact names, project descriptions, free-text notes, messages, and private documents in shared logs.
- Establish a traceable test run ID and preserve the SQL schema, plugin build checksum, test command and output under restricted access.
Do not use production database snapshots, production email accounts, production portals or production storage mounts to exercise failure injection. Dynamic WordPress table prefixes must be resolved from the isolated test environment.
6. Read-only SQL reconciliation
The WordPress database uses {prefix}sc_ei_engagements, {prefix}sc_ei_engagement_events, {prefix}sc_ei_engagement_requirements and {prefix}sc_ei_engagement_snapshots. Replace wp_ below with the actual test database prefix. SQL shown is read-only; run it only with authorized database access and do not publish row-level results.
-- Staging-only: find terminal states lacking a matching event.
SELECT e.id, e.status, e.row_version,
CASE WHEN e.status='completed' THEN e.completed_at
ELSE e.canceled_at END AS terminal_at,
CASE WHEN e.status='completed' THEN (e.completed_by IS NOT NULL AND TRIM(e.completion_note)<>'')
ELSE (e.canceled_by IS NOT NULL AND TRIM(e.cancellation_reason)<>'') END AS metadata_complete,
COUNT(ev.id) AS matching_event_count
FROM wp_sc_ei_engagements AS e
LEFT JOIN wp_sc_ei_engagement_events AS ev
ON ev.engagement_id=e.id
AND ev.to_status=e.status
AND ev.event_type=CASE e.status WHEN 'completed' THEN 'engagement_completed'
ELSE 'engagement_canceled' END
AND ev.actor_id=CASE e.status WHEN 'completed' THEN e.completed_by ELSE e.canceled_by END
WHERE e.status IN ('completed','canceled')
GROUP BY e.id,e.status,e.row_version,e.completed_at,e.canceled_at,
e.completed_by,e.canceled_by,e.completion_note,e.cancellation_reason
HAVING matching_event_count<>1 OR metadata_complete=0;
This checks event existence and metadata, not full source authenticity or event chronology. Investigate duplicate matches, actor mismatch, from_status, and timestamp skew separately. Because the SQL reads sensitive operational fields to compute booleans, keep query output restricted.
-- Staging-only: identify unresolved mandatory onboarding items on terminal engagements.
-- This is a policy review query, NOT a native terminal-transition constraint.
SELECT e.id, e.status, COUNT(r.id) AS unresolved_required_items
FROM wp_sc_ei_engagements e
JOIN wp_sc_ei_engagement_requirements r ON r.engagement_id=e.id
WHERE e.status IN ('completed','canceled')
AND r.is_required=1 AND r.status NOT IN ('complete','waived')
GROUP BY e.id,e.status;
-- Snapshot metadata only. Never include payload_json in shared diagnostic output.
SELECT e.id,e.current_snapshot_id,s.id AS snapshot_id,
(s.id IS NULL) AS snapshot_missing,
(s.proposal_version_id<>e.proposal_version_id) AS source_version_mismatch
FROM wp_sc_ei_engagements e
LEFT JOIN wp_sc_ei_engagement_snapshots s ON s.id=e.current_snapshot_id
WHERE e.status IN ('completed','canceled');
7. Verify immutable handoff evidence correctly
At handoff creation, the repository serializes a contracted-proposal snapshot with wp_json_encode(..., JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) and records hash('sha256', $snapshot_json). verify_snapshot() recomputes the hash from the stored raw JSON string; it does not establish legal, accounting or delivery correctness.
// Offline/staging verification against a trusted snapshot row.
// Hash the EXACT stored UTF-8 byte string; do not pretty-print first.
$payload = (string) $snapshot['payload_json'];
$expected = (string) $snapshot['content_hash'];
$integrity_ok = strlen($expected) === 64
&& hash_equals(strtolower($expected), hash('sha256', $payload));
if (! $integrity_ok) {
throw new RuntimeException('Snapshot integrity mismatch');
}
Preserve distinction between (a) immutable original handoff evidence, (b) current engagement operational state, and (c) a privacy-redacted tombstone. In the current privacy-redaction path, the snapshot payload and content hash are intentionally replaced with a tombstone and a new hash. A matching post-redaction hash therefore does not mean the original full proposal evidence is still present. Reconcile retention and preservation obligations before applying any transformation.
8. Prove transactional state and audit persistence under failure
On a disposable database, inject an event-table write failure while attempting active → completed. Record separately whether the engagement row committed, whether engagement_events contains engagement_completed, whether the general audit ledger contains the corresponding event, and whether the UI reported success. Never assume a state transition and its audit event were committed atomically simply because both operations appear in the same method.
Recommended fix if staging reproduces a gap: make event persistence return an explicit success/failure result; run the status update and both mandatory audit writes in a transaction on transactional storage; rollback and report failure if any required write fails; add a regression test for insert failure, optimistic-lock conflict and duplicate request. Consider reliable transactional outbox treatment for external notifications. This is a proposed remediation, not a claim that such a patch is deployed.
9. Inspect concurrency, idempotency and retries
The current transition uses a conditional update requiring matching engagement id, prior row_version and prior status. Reproduce two requests from the same prior version; the second should not overwrite the first. A retry after a successful terminal transition must not create another completion event or silently reopen the record. Confirm that duplicate browser submissions cannot emit duplicate outward communications. Query the event ledger by engagement ID and timestamp, not by free-text notes.
Synthetic race (isolated staging):
A reads status=active, row_version=7
B reads status=active, row_version=7
A submits completed, note="Synthetic delivery accepted"
B submits canceled, note="Synthetic cancellation"
EXPECTED: exactly one terminal state update, one canonical event,
other request returns engagement_transition_conflict,
no contradictory portal notification.
10. Distinguish scientific claims from operational labels
completed is an administrative classification. To substantiate a scientific assertion such as “closure indicates satisfactory delivery,” pre-register a separate outcome rubric: defined deliverables, evidence sources, acceptance thresholds, independent reviewer qualifications, sampling strategy, review blinding where feasible, inter-rater disagreement handling, and treatment of missing data. Treat cancellation reasons as qualitative categories that require a stable codebook and double-coding protocol. Do not infer user satisfaction, causal impact, or contractual discharge from a status flag alone.
Estimate the proportion of eligible closures with verified traceability as p = x/n with explicit exclusions and observation period. When appropriate, accompany descriptive estimates with Wilson intervals and disclose selection bias; do not report an interval as evidence of production safety when the record sample is unrepresentative. Report n=0 as not estimable, never 0%.
11. Validate obligations, approvals, privacy and retention separately
At closure, collect a minimally necessary, access-controlled disposition register: deliverables accepted/waived with evidence reference; open service commitments; outstanding invoices/payments handled by their owning systems; access revocation; external integration exports; legal holds; approved retention policy/version; responsible actor; and follow-up rights. The current engagement closure code does not enforce this complete register. Use it as an explicit policy-level acceptance requirement in a proposed closure gate.
Privacy review: distinguish closing the engagement from deleting a person’s data. The repository’s redact_for_privacy() replaces selected narrative fields and snapshot JSON; it does not on its own prove that every remaining field, external export, backup or third-party copy has been assessed. Examine identifiers, title/contract references, retained hash values, audit contexts, downstream products, portal permissions and backups according to the actual data inventory. Never erase records in violation of an active hold. A hash may remain linkable to an individual even after direct strings are removed.
The European Commission’s GDPR principles describe data minimization and storage limitation where applicable. This guide supplies technical checks, not a jurisdiction-specific legal determination.
12. Minimal reproducible synthetic evidence format
The accompanying closure_checker.py accepts a synthetic JSON document containing engagement, events, snapshot, requirements, privacy and public_evidence. This is a companion diagnostic contract, not an existing platform endpoint or official database export. Source-informed findings are marked source; additional proposed governance checks are marked recommended.
{
"engagement": {
"previous_status": "active", "status": "completed",
"completed_by": 42, "completed_at": "2026-11-20T19:30:00Z",
"completion_note": "Synthetic delivery accepted", "privacy_status": "active"
},
"events": [{"event_type":"engagement_completed","from_status":"active",
"to_status":"completed","actor_id":42}],
"snapshot": {"payload_json":"{\"schema\":\"synthetic-engagement-snapshot/1.0\"}",
"content_hash":"<SHA256-of-exact-payload-bytes>"},
"requirements": [{"is_required":true,"status":"complete"}],
"privacy": {"disposition_recorded":true,"retention_policy_version":"demo-v1",
"hold_active":false,"deletion_executed":false},
"public_evidence": {"result":"synthetic_only"}
}
The illustrative digest placeholder above is deliberately not valid executable fixture data. Run the complete fixtures/valid_closure.json supplied with the package; it contains a computed SHA-256 digest.
# Python 3.10+; no third-party packages required.
cd engagement_closure_validation
python3 -m unittest -v tests_closure_checker.py
python3 closure_checker.py fixtures/valid_closure.json
python3 closure_checker.py fixtures/invalid_closure.json
# The deliberately invalid fixture exits with status 1; do not treat that as a tool failure.
13. Test matrix, fault injection and required negatives
| Test | Expected result | Level |
|---|---|---|
| Valid active → completed | Note, actor, timestamp, matching event and hash | Offline + staging |
| Pending → completed | Reject engagement_transition_invalid |
Staging |
| Empty completion note | Reject engagement_transition_note_required |
Staging |
| Nonprivileged account | 403 / no state change | Staging |
| Incorrect confirmation / nonce | No state change | Staging |
| Two writers, same row version | One succeeds; one conflict | Staging |
| Audit INSERT blocked | Escalate if closure commits without required audit | Staging fault injection |
| Corrupted snapshot payload | Integrity failure; no false verification | Offline + staging |
| Open obligation | Flag policy gap, not an existing native error | Offline / new gate |
| Active hold with deletion | Flag prohibited-policy scenario for review | Offline / privacy staging |
| Private note or email in public evidence | Reject output; apply independent content review | Offline + staging |
| Privacy tombstone replay | Recomputed tombstone digest, preserved lawful minimal audit | Staging |
Use a dedicated isolated staging installation for the runtime checks. The companion checker is not a substitute for application integration tests, database failure injection, authorization tests, legal review, or an external privacy inspection.
14. Diagnosing audit gaps without altering evidence
For a suspected missing event, compare the terminal engagement row, engagement_events, the general audit ledger, WordPress request logs and deployment revision under authorized access. Do not fabricate a backdated original event. Preserve original timestamps and source hashes; if a repair is approved, create a distinct, clearly labeled reconciliation event referencing the incident and reviewer decision. A post hoc record is evidence of the repair, not evidence that the historical event originally occurred.
For a snapshot mismatch, halt affected automated handoffs; preserve database and artifact evidence; compare serialized bytes and proposal-version linkage; investigate truncation, encoding changes, migrations and unauthorized edits. Do not overwrite the digest to silence the validator.
Resolution
- Classify and contain: mark incident severity, disable unsafe exports/notifications or future closure actions if warranted; preserve evidence first.
- Reproduce: exercise the smallest failing synthetic fixture against the exact plugin revision in isolated staging; document setup, expected output, actual output and evidence hash.
- Repair the invariant: apply a reviewed code migration, access-control fix, transactional event-writing fix or documented governance change. Never change historical statuses directly to make reports look correct.
- Verify: rerun happy-path, negative, concurrency and fault-injection tests; check row version, terminal timestamps, event ledger, exports, privacy inventory and notifications.
- Review independently: obtain separate engineering and privacy/security approval where closure involves restricted data, legal holds or deletion.
- Close the incident: record corrective action, regression-test ID, reviewer, source revision, residual risk and deployment evidence without copying personal contact content into public tickets.
15. Developer CI and version-specific release evidence
Separate contract assertions (classes/functions and schema fields exist) from behavioral tests (a transactional database actually enforces the intended invariant). The repository contains tests/engagement-operations.php, a source-contract suite; it is useful for checking release wiring but cannot demonstrate that audit records persist when writes fail.
Minimum CI sequence: PHP syntax checks; existing repository contract tests; isolated WordPress integration tests against disposable InnoDB tables; test-only permission matrix; transaction-failure injection; duplicate concurrent transitions; privacy/erasure fixtures; reproducible snapshot verification; structured acceptance receipt including revision, DB schema, environment isolation, assertions and reviewer signoff. Do not import production records to simulate a realistic sample.
16. Reporting results without overstating scientific certainty
Provide a version-bound evidence table with four separate results: (1) source code behavior, (2) offline synthetic validator results, (3) isolated staging behavior, and (4) authorized production observation. Label unexecuted cases pending. For each indicator publish its unit, inclusion and exclusion criteria, observation window, missingness, numerator/denominator, uncertainty and privacy disclosure review. For any outcome claim, identify an independent assessment protocol and conflict-of-interest handling.
Known evidence at publication: Engagement Intake source commit 3f246974276a5e582d09f8c48d21628b82626bc7 reviewed for the stated method names and lifecycle logic. Companion offline synthetic tests: 18 passed. No staging database acceptance, production audit fault injection or independent scientific outcome review was performed as part of this article. The validator’s static checks are not a substitute for execution of the deployed plugin.
17. Acceptance criteria and change-control decision
- Every tested terminal transition has a permitted source state, actor, timestamp, nonblank reason and one verified corresponding event.
- Unauthorized actors, invalid nonce/confirmation, invalid transitions and stale row versions cannot change the terminal status.
- Snapshot integrity is reproducibly validated against the original stored byte string, with explicit handling of privacy tombstones.
- A failed required audit write is detected and handled according to an approved atomicity policy, with incident evidence retained.
- A documented obligation/disposition register is complete for claims of delivery reconciliation; this remains a proposed product requirement until implemented and tested.
- No identifiable or restricted case content is present in public evidence or logs, including nested metadata and copies in connected systems.
- Retention and preservation decisions are documented separately from operational closure and respect active holds.
- An independent reviewer can reproduce the approved metrics and explain limitations without access to unnecessary private data.
18. Technical references and source inspection
- SC_EI_Engagement_Repository (pinned commit) — transitions, readiness, event recording, snapshot checks, privacy redaction.
- Engagement schema (pinned commit) — state vocabulary, requirements and settings.
- Engagement admin (pinned commit) — nonce, capabilities and typed confirmations.
- Engagement handoff operations — commercial record and lifecycle boundaries.
- Engagement contract test source — limitations of static assertions.
- Privacy and retention operations — holds, review, erasure and tombstones.
- OWASP Logging Cheat Sheet — security logging, sensitive data and verification.
- OWASP ASVS 5.0, Security Logging — event protection, timing and validation.
- NIST SP 800-53 Rev. 5 — AU-3, AU-6, AU-9 and accountability controls.
- European Commission, GDPR Principles — minimization and storage limitation where applicable.
- PHP
hash_equals()— timing-safe hash comparison. - WordPress
check_admin_referer()— admin request nonce verification. - MySQL InnoDB transaction model — locking and transactional behavior.
Publication boundary: Source review, synthetic tests and technically motivated remediation recommendations do not certify scientific correctness, privacy compliance or a production release. For unresolved defects, attach a versioned staging acceptance receipt to the internal issue rather than adding unsupported public assertions.
