Skip to content

feat(go): implement safe event writes (#167) - #189

Merged
KalebCole merged 3 commits into
mainfrom
feat/167-event-writes
Aug 12, 2026
Merged

KalebCole merged 3 commits into
mainfrom
feat/167-event-writes

Conversation

@KalebCole

@KalebCole KalebCole commented Aug 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements the evidence-backed Go event-write contract for #167.

  • adds events create, events update, and confirmed events cancel through app.Execute
  • uses persistent five-minute account/input/request/precondition-bound single-use plans
  • validates exact create defaults, poster selection, update allowlists/date ranges, Firestore masks and preconditions, and cancel safeguards
  • re-reads bound event facts before update/cancel dispatch and fails stale plans closed
  • consumes plans before one mutation attempt with no automatic retry
  • validates reviewed callable and Firestore completion shapes and returns submitted-only results
  • promotes shipped contract revision to 2026-08-12.4

No live Partiful mutation or credential access was used.

Validation

  • go test -race ./...
  • go vet ./...
  • go build ./...
  • go mod verify
  • npm test -- tests/remote-api-contract.test.js
  • npm run typecheck
  • privacy guard and diff check

Closes #167.

Summary by CodeRabbit

  • New Features
    • Added event creation, updating, and cancellation workflows.
    • Added validation for event details, links, time zones, date ranges, ownership, and event state.
    • Added confirmation and safety checks for consequential actions.
    • Added support for submitting event changes and updating event records remotely.
    • Event details now include guest information and preserve additional event data.
  • Documentation
    • Updated product and remote API contracts to approved, owner-reviewed revision 2026-08-12.4.
  • Tests
    • Added comprehensive coverage for event workflows, validation, safety checks, and contract consistency.

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 50 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b818b4de-41c6-4706-9dca-dde42d14f7ee

📥 Commits

Reviewing files that changed from the base of the PR and between a6a2b9c and 6f29b3e.

📒 Files selected for processing (6)
  • internal/app/app.go
  • internal/app/event_write.go
  • internal/app/events_write_test.go
  • internal/app/execute_test.go
  • internal/remote/event_writes.go
  • internal/remote/events.go
📝 Walkthrough

Walkthrough

The CLI now supports events.create, events.update, and events.cancel. It adds normalized input handling, mutation plans, consequential confirmation, remote callable and Firestore writes, event decoding fields, contract revision 2026-08-12.4, and comprehensive tests.

Changes

Event write commands

Layer / File(s) Summary
Command contracts and input validation
internal/app/app.go, internal/app/event_write_input.go
Registers the three event write commands with schemas, failure types, mutation policies, and execution dispatch. Parses and validates flag and JSON inputs.
Remote event mutation transport
internal/remote/event_writes.go, internal/remote/events.go, internal/remote/posters.go
Adds authenticated event create and cancel calls, Firestore event patches, recursive response validation, event metadata decoding, and optional poster blur hashes.
Mutation workflows
internal/app/event_write.go
Implements create, update, and cancel planning and application, including authorization, preconditions, poster binding, stale-plan detection, protected confirmation, remote submission, and structured results.
Workflow and contract tests
internal/app/events_write_test.go, internal/app/execute_test.go, tests/remote-api-contract.test.js, spec/partiful.api-evidence.json, docs/CLI-PRODUCT-CONTRACT.md, docs/REMOTE-API-CONTRACT.md
Validates exact requests, plan lifecycle, input failures, preconditions, response failures, command registration, and revision consistency. Marks the contracts owner-reviewed and approved at revision 2026-08-12.4.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant Execute
  participant EventWriteWorkflow
  participant PartifulClient
  participant Firestore

  CLI->>Execute: Invoke event write command
  Execute->>EventWriteWorkflow: Parse and execute request
  EventWriteWorkflow->>PartifulClient: Submit create or cancel mutation
  EventWriteWorkflow->>Firestore: Apply update patch
  PartifulClient-->>EventWriteWorkflow: Return validated mutation response
  Firestore-->>EventWriteWorkflow: Return validated patch response
  EventWriteWorkflow-->>CLI: Return planned or submitted result
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 summarizes the primary change: implementing safe Go event writes.
Linked Issues check ✅ Passed The changes implement events create/update/cancel, safe planning and confirmation, field masks, precondition checks, response validation, and fixture coverage required by [#167].
Out of Scope Changes check ✅ Passed The contract, remote models, application workflows, tests, and documentation changes directly support the event-write objectives in [#167].
✨ 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 feat/167-event-writes

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.

@github-actions

github-actions Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-08-12 17:52 UTC

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01

@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: 4

🧹 Nitpick comments (5)
internal/app/event_write_input.go (1)

376-381: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Validate flag values before you place them in the JSON document.

Lines 377 and 380 insert the raw flag text into json.RawMessage without validation. decodeNullablePositiveInteger then decodes with a stream decoder and does not check for trailing tokens, so --guest-limit '5 garbage' decodes as 5. --notify-guests TRUE works only because of the strings.ToLower call, and any other text falls through to a decode error. Parse both values explicitly so the accepted input set matches the documented input schema.

♻️ Proposed stricter flag decoding
 	if value, ok := values["--notify-guests"]; ok {
-		document["notifyGuests"] = json.RawMessage(strings.ToLower(value))
+		switch strings.ToLower(strings.TrimSpace(value)) {
+		case "true":
+			document["notifyGuests"] = json.RawMessage("true")
+		case "false":
+			document["notifyGuests"] = json.RawMessage("false")
+		default:
+			return nil, eventWriteInputFailure("NOTIFY_GUESTS_INVALID", "notifyGuests must be true or false.")
+		}
 	}
 	if value, ok := values["--guest-limit"]; ok {
-		document["guestLimit"] = json.RawMessage(value)
+		parsed, err := strconv.Atoi(strings.TrimSpace(value))
+		if err != nil || parsed < 1 {
+			return nil, eventWriteInputFailure("GUEST_LIMIT_INVALID", "Guest limit must be a positive integer or null.")
+		}
+		document["guestLimit"] = json.RawMessage(strconv.Itoa(parsed))
 	}
🤖 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 `@internal/app/event_write_input.go` around lines 376 - 381, Validate and parse
the --notify-guests and --guest-limit values before assigning
document["notifyGuests"] and document["guestLimit"], rather than wrapping raw
text in json.RawMessage. Use strict parsing that rejects trailing tokens,
accepts only the documented boolean values for notify-guests, and enforces the
documented positive-integer constraints for guest-limit; return the appropriate
validation error instead of inserting invalid JSON.
tests/remote-api-contract.test.js (1)

2151-2158: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce the duplicated revision literals.

The revision string 2026-08-12.4 is asserted at lines 502-503, 1619-1620, and 2158. Line 2155 and line 2157 also assert spec.info.version twice, which is redundant once shippedRevision equals documentedRevision. Define one module-level constant for the expected revision and reuse it, so the next promotion changes one line.

🤖 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/remote-api-contract.test.js` around lines 2151 - 2158, Define a single
module-level expected revision constant in the test and replace the duplicated
2026-08-12.4 literals across the assertions, including the checks near
shippedRevision, documentedRevision, and appSource. Remove the redundant
duplicate spec.info.version assertion, retaining the comparison against the
shared expected revision through the existing shippedRevision/documentedRevision
values.
internal/app/event_write.go (1)

497-533: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the redundant check and the unused parameters.

Three items reduce clarity in these functions:

  • Line 498 rejects remote.FieldAbsent, and line 510 then rejects any state other than remote.FieldValue. The second check makes the first one redundant. Keep one check.
  • buildUpdatePreconditions discards currentUserID with _ = currentUserID at line 531. The caller already verified ownership at line 222. Drop the parameter.
  • buildUpdateRequest discards event with _ = event at line 611. Drop the parameter.

Also applies to: 537-546, 607-613

🤖 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 `@internal/app/event_write.go` around lines 497 - 533, Simplify the event
update helpers by removing redundant checks and unused parameters: in
buildUpdatePreconditions, keep only the HasGuests state validation, remove the
unused currentUserID parameter and its discard assignment, and update all
callers; in buildUpdateRequest, remove the unused event parameter and its
discard assignment, updating callers accordingly.
internal/app/events_write_test.go (1)

544-609: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the host check and the structured input path.

The suite does not cover two reviewed safeguards:

  • events.cancel and events.update with an ownerIds list that excludes the session user, which must return permission.denied.
  • --input with a JSON document, plus the INPUT_SOURCE_CONFLICT failure when --input is combined with a field flag.

Also note that these subtests mutate the shared dependencies value and consume the shared MutationRandom reader, so the cases depend on execution order. Build the dependencies inside each subtest to remove that coupling.

🤖 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 `@internal/app/events_write_test.go` around lines 544 - 609, Expand
TestExecuteEventCancelFailsClosedOnMalformedFactsAndSubmissionUncertainty to
cover events.cancel and events.update ownerIds that exclude the session user,
asserting permission.denied, and cover JSON --input plus INPUT_SOURCE_CONFLICT
when combined with a field flag. Create fresh eventWriteDependencies and
MutationRandom state inside each subtest instead of sharing them across cases,
preserving existing assertions while removing execution-order coupling.
internal/remote/event_writes.go (1)

265-280: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Reject an empty update mask in the transport.

FirestorePatchEvent sends the patch even when updateMask is empty. Firestore then replaces the whole document with document, which deletes every unlisted field. buildUpdateRequest always appends updatedBy, so the current callers are safe. Add the guard so a future caller cannot destroy event data.

🛡️ Proposed guard
 	if client.HTTP == nil {
 		return fmt.Errorf("%w: firestore transport", ErrUnavailable)
 	}
+	if len(updateMask) == 0 {
+		return fmt.Errorf("%w: firestore update mask", ErrProtocolChanged)
+	}
 	payload, _ := json.Marshal(document)
🤖 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 `@internal/remote/event_writes.go` around lines 265 - 280, Update
FirestorePatchEvent to reject an empty updateMask before marshaling or sending
the patch request, returning the package’s established invalid-argument error
with a clear message. Preserve the existing behavior for non-empty masks,
including updatedBy handling by current callers.
🤖 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 `@internal/app/app.go`:
- Around line 350-381: Update schemaSuccessSchema’s safety.kind enum to include
the consequential-action value used by consequentialActionSafety(). Preserve the
existing read-only, local-mutation, and standard-mutation values so success
envelopes for all commands remain valid.

In `@internal/app/event_write.go`:
- Around line 747-764: Update requiredCurrentEventTime and
optionalCurrentEventTime to accept command and pretty parameters, and pass them
to eventWriteProtocolChangedFailure instead of hardcoding events.update,
EVENT_UPDATE_PROTOCOL_CHANGED, and false. Update buildCancelPreconditions and
all other callers to provide their command path and --pretty state, and
propagate pretty through eventPreconditionFailure. Remove the prettyFalse
package variable and preserve caller-specific command metadata, protocol codes,
and output formatting.

In `@internal/remote/event_writes.go`:
- Line 238: Update both deferred response body cleanup calls in the relevant
event-writing functions to explicitly discard the return value from
response.Body.Close(), satisfying errcheck while preserving deferred cleanup
behavior.

In `@internal/remote/events.go`:
- Around line 440-447: Update internal/remote/events.go lines 440-447 in the
event decoding path to pass nullAllowed=true when decoding guestCount and
hasGuests, while preserving the strict remote.FieldValue requirement in
buildCancelPreconditions. In internal/remote/posters.go lines 175-190, update
the blurHash decoder to map explicit JSON null to a nil pointer instead of
returning ErrProtocolChanged, unless the reviewed remote contract explicitly
forbids null.

---

Nitpick comments:
In `@internal/app/event_write_input.go`:
- Around line 376-381: Validate and parse the --notify-guests and --guest-limit
values before assigning document["notifyGuests"] and document["guestLimit"],
rather than wrapping raw text in json.RawMessage. Use strict parsing that
rejects trailing tokens, accepts only the documented boolean values for
notify-guests, and enforces the documented positive-integer constraints for
guest-limit; return the appropriate validation error instead of inserting
invalid JSON.

In `@internal/app/event_write.go`:
- Around line 497-533: Simplify the event update helpers by removing redundant
checks and unused parameters: in buildUpdatePreconditions, keep only the
HasGuests state validation, remove the unused currentUserID parameter and its
discard assignment, and update all callers; in buildUpdateRequest, remove the
unused event parameter and its discard assignment, updating callers accordingly.

In `@internal/app/events_write_test.go`:
- Around line 544-609: Expand
TestExecuteEventCancelFailsClosedOnMalformedFactsAndSubmissionUncertainty to
cover events.cancel and events.update ownerIds that exclude the session user,
asserting permission.denied, and cover JSON --input plus INPUT_SOURCE_CONFLICT
when combined with a field flag. Create fresh eventWriteDependencies and
MutationRandom state inside each subtest instead of sharing them across cases,
preserving existing assertions while removing execution-order coupling.

In `@internal/remote/event_writes.go`:
- Around line 265-280: Update FirestorePatchEvent to reject an empty updateMask
before marshaling or sending the patch request, returning the package’s
established invalid-argument error with a clear message. Preserve the existing
behavior for non-empty masks, including updatedBy handling by current callers.

In `@tests/remote-api-contract.test.js`:
- Around line 2151-2158: Define a single module-level expected revision constant
in the test and replace the duplicated 2026-08-12.4 literals across the
assertions, including the checks near shippedRevision, documentedRevision, and
appSource. Remove the redundant duplicate spec.info.version assertion, retaining
the comparison against the shared expected revision through the existing
shippedRevision/documentedRevision values.
🪄 Autofix

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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d9feb18a-2c4a-4817-a5ac-8a972f12b244

📥 Commits

Reviewing files that changed from the base of the PR and between 0d57e67 and a6a2b9c.

📒 Files selected for processing (12)
  • docs/CLI-PRODUCT-CONTRACT.md
  • docs/REMOTE-API-CONTRACT.md
  • internal/app/app.go
  • internal/app/event_write.go
  • internal/app/event_write_input.go
  • internal/app/events_write_test.go
  • internal/app/execute_test.go
  • internal/remote/event_writes.go
  • internal/remote/events.go
  • internal/remote/posters.go
  • spec/partiful.api-evidence.json
  • tests/remote-api-contract.test.js

Comment thread internal/app/app.go Resolved
Comment thread internal/app/event_write.go Resolved
Comment thread internal/remote/event_writes.go Resolved
Comment thread internal/remote/events.go Resolved
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
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.

Implement event writes and consequential confirmation in Go

1 participant