Skip to content

feat: notify users when they arrive or leave, using device location updates - #200867

Open
zigit wants to merge 10 commits into
openclaw:mainfrom
zigit:pr/location-update-clean
Open

zigit wants to merge 10 commits into
openclaw:mainfrom
zigit:pr/location-update-clean

Conversation

@zigit

@zigit zigit commented Nov 17, 2026 •

Copy link
Copy Markdown

Resolves #163480

What Problem This Solves

iOS nodes emit location.update events on significant location changes, but
the gateway drops them as unsupported_event — verified by two independent
users on current builds (#163480). This PR makes the event consumable and
closes the full chain: fix → significance detection → event-driven APNs
notification
, with no heartbeat, no session turn, and no coordinates in logs.

  • Gateway: location.update is validated, dispatched to the node-event
    consumer registry, and instrumented at the dispatch boundary. The response
    ack path no longer crashes (logGateway.info → warn — every event ack
    previously failed with UNAVAILABLE after dispatch).
  • Plugin surface: registerNodeEventConsumer — a plugin-API subscription
    hook for gateway-validated node events (currently allowlisted to
    location.update). This is the "plugin hook" requested in [Feature]: iOS app should send location updates in the background by itself (no location.update seen while travelling) #163480.
  • memory-core consumer: armed location intents evaluate each fix against
    fence geometry. Enter fences fire on the first inside fix when armed from
    afar (previously required a 0→1 crossing that never happened when the
    intent was armed while already outside); stale-facts-cache reads no longer
    mask fires.
  • Direction-gated crossings (bug fix): an exit fence no longer fires on an
    arrival fix, and an enter fence no longer fires on a departure fix — see
    below. This was found during live verification, not by the test suite.
  • Delivery: fires push an APNs alert at fire time (new plugin-SDK surface
    sendNodeIntentAlert, category openclaw.location-intent) — delivery no
    longer waits for the target session's next turn. The routed system-event
    enqueue is retained as an in-session record; push failures are logged and
    never re-arm the one-shot.

Direction-gating bug (found and fixed during live verification)

decideLocationFire gated only one side of each transition on direction.
The inside branch fired for previous === 0 regardless of direction, and the
outside branch fired for previous === 1 regardless of direction. Consequences
observed on real drives:

  • 2026-11-13 06:33 — a Göteborg arrival fence fired on the user's
    morning departure from inside the fence.
  • 2026-11-16 15:29 — a home exit fence fired while the user was
    arriving home (the fix that also correctly fired the Göteborg arrival
    fence in the same second).

Both branches are now direction-gated: enter fires only on 0→1 (including
the first inside fix when armed from afar), exit fires only on 1→0. Each
branch carries the live-fire evidence in a comment, and two regression tests
cover both directions — the existing test's comment promised this behavior but
never asserted it, which is how the bug survived review.

Evidence

  • 2026-11-14, live drive: Skene fence (1.5 km, enter) fired on a real
    outside→inside crossing from an unsolicited background fix; the APNs alert
    appeared on the owner's phone (screenshot-timestamped, matching the log
    fire and the intent description text). Exactly one fire, no duplicates.

  • 2026-11-16: home-exit fence (200 m) fired on a real departure; the
    ack-crash fix verified live (three fixes traced, zero UNAVAILABLE).

  • 2026-11-17, full drive test (3/3 fences, 0 evaluation errors):

    Time Fence Fix distance Accuracy Outcome
    10:58:46 home exit (200 m) 7 m inside 16 m baselined, no fire ✓
    11:21:49 home exit (200 m) 512 m outside 46 m fired — correct direction
    11:37:28 store (1000 m) 427 m from store 11 m fired
    11:42:51 destination (1000 m) 52 m from center 34 m fired
milk-notification-cropped Medium

All three notifications owner-confirmed on the phone (screenshots matching
the log timestamps). The exit fence baseline-then-fire sequence is the live
proof of the direction-gate fix; the destination fire (52 m from a decoded
Plus code) validates arrival geometry end to end.

  • Consumer tests assert: single push per fire, fire-on-first-inside-fix,
    no re-arm on push failure, and both direction gates.

  • 2026-11-18, latest-stable upgrade proof: the review asked for upgrade
    evidence covering the changed standing_intents fields. The v2026.11.5
    release's shipped agent schema (schema version 38, pre-location
    standing_intents) is frozen as a fixture; a database built from it
    migrates to the current schema, the four additive location columns and
    idx_standing_intents_location arrive, an existing keyword-intent row
    survives untouched with absent-feature defaults, and a location intent in
    the stored kernel format is accepted by the migrated table's constraints.
    Covered by openclaw-agent-latest-stable-upgrade.test.ts; fence
    evaluation and delivery on the identical post-migration shape are covered
    by memory-core's suites. The added test lines carry a justified allocation
    record (config/test-lines-allocations/200867-location-update-consumer.txt).

  • 2026-11-18, PostgreSQL store upgrade (review P1): opening an existing
    PostgreSQL agent database previously failed schema admission after this
    change — the location columns changed the canonical DDL with no version
    bump or migration, so verifyPostgresSchemaDefinition threw a
    schema-drift error, and the migration derivator made every historical
    version inherit the new fields. The agent schema now advances 43 → 44 on
    both engines through the existing versioned-migration owners: a new
    PostgreSQL migration adds the columns, NOT VALID checks (all-new columns
    cannot be violated by existing rows), and the index in one transaction;
    the v43 migration entry now targets the pre-location historical shape so
    old versions keep their real catalog; SQLite converges through its
    existing additive machinery on every migration branch. Schema 43 remains
    a supported witness version. Verified by the same suites as above —
    55/55 across migration, latest-stable, and location kernel tests.

  • 2026-11-19, shipped PostgreSQL live-server upgrade (v2026.11.5,
    schema 38 -> current, the complete migration chain):
    the prior entry
    showed only the final v43 -> v44 hop. The test now builds the
    predecessor from the v39 migration step's fromSchema — the schema-38
    shape the v2026.11.5 release actually ships — so reopening at the
    current schema runs the full shipped 38 -> 44 chain through the engine's
    own reopen-driven migration on a live PostgreSQL 16 server. Terminal
    output (redacted; connection string and namespace elided):

    opened v38 (v2026.11.5) store, namespace: evidence_v44_agent_...
    pre-upgrade standing_intents columns (16): channel_scope, cooldown_seconds,
      created_at, creator_sender, description, expires_at, fire_count, id,
      intent_key, last_fired_at, max_fires, sender_scope, source_session_id,
      status, trigger_embedding, trigger_keywords
    confirmed: NO location columns in the pre-upgrade store
    --- reopening at schema v44 (destination admission) ---
    destination admission: SUCCESS (verifyAndRecordPostgresSchema passed, version 44)
    post-upgrade standing_intents columns (20): ... delivery_target ... last_inside,
      location_trigger ... trigger_kind
    idx_standing_intents_location: CREATE INDEX idx_standing_intents_location
      ON ... standing_intents USING btree (status, trigger_kind NULLS FIRST,
      location_trigger NULLS FIRST)
    existing keyword intent preserved: status='armed', location columns default NULL
    location intent accepted by the migrated constraints
    existing keyword intent still queryable on the upgraded store
    evidence namespace dropped; server clean
    EVIDENCE COMPLETE: shipped v2026.11.5 (schema 38) -> v44 PostgreSQL
      upgrade succeeds; existing data preserved and usable
    

    A keyword reminder armed on a real schema-38 v2026.11.5 store survives
    the complete shipped upgrade chain usable, destination admission
    validates the migrated schema against the canonical DDL, and a location
    intent is accepted by the migrated constraints — the shipped-upgrade
    evidence and the data-model compatibility proof for both remaining
    before-merge items. Reproducible as
    src/state/openclaw-agent-v44-postgres-upgrade.evidence.test.ts (infra
    project) against any PostgreSQL 16 server; the connection arrives only
    via the OPENCLAW_PG_EVIDENCE_CONNECTION environment variable (never
    committed) and the test skips without it.

Known limitation: fence radius cannot buy lead time at driving speed

Reported by the owner on the 2026-11-17 drive: the store fence fired after
he had passed the store. Measured along-track against the store→destination
leg, the firing fix was +404 m past the store (137 m cross-track, 427 m
straight-line — i.e. comfortably inside the 1 km circle, 573 m from the
edge).

The cause is fix cadence, not fence logic:

  • 4.28 km travelled between consecutive fixes → 49 km/h on a ~5-minute
    significant-change cadence
  • a 1 km circle is a 2 km-wide band; at 4.28 km spacing the chance any given
    fix lands inside is only ~47%, i.e. whether it fires before or after the POI
    is close to a coin flip

Enlarging the radius does not fix this. To gain one fix-interval of lead
you would need R > 4.2 km at 50 km/h and > 6.7 km at 80 km/h. At that size the
notification fires while the user is kilometres away, so "you're passing the
store" becomes false. Radius trades precision for reliability; there is no
setting that delivers both at driving speed.

This is a property of the fix-delivery platform, not of the fence evaluator.
The mechanism that actually fixes approach timing is device-side region
monitoring
(CLCircularRegion, 20-region limit): the OS surfaces a callback
at the boundary crossing, independent of the significant-change cadence. That
is the planned device-fence direction, and this drive is its concrete
justification. Until then, a fence that fires shortly after a high-speed POI
is behaving as designed given the fixes it receives.

Consent and privacy (answers the labels on #163480)

Scope boundaries

  • One consumer per event by design (registrar rejects a second subscriber
    for location.update; dispatch uses first-match). Fan-out to multiple
    consumers is a deliberate follow-up, not included here — it widens the
    location access surface and deserves its own security review.
  • No fix history is stored; fixes are evaluated against armed intents and
    dropped. A bounded presence/fix store is a separate proposal.
  • The event-driven push is the interim surfacing policy ("fired ⇒ notify").
    Whether and how to notify is a policy layer question; the follow-up
    direction (below) explores a tunable local judge for it.
  • Device-side region monitoring (the fix for the lead-time limitation above)
    is out of scope for this PR.
  • File structure is ratchet-driven, not stylistic. location.update
    handling lives in server-node-events-location.ts alongside the existing
    server-node-events-*.ts handlers. The chat subscribe/unsubscribe arm
    moved to server-node-events-chat-subscription.ts for one reason: the
    dispatcher is grandfathered in config/max-lines-baseline.txt, and that
    ratchet rejects any growth, so a two-line case arm plus its import had to
    be offset. That extraction is behaviour-preserving and covered by the
    existing chat subscribe/unsubscribe tests, but it is unrelated to this
    feature — call it out if you would rather it land separately.

Follow-up direction (not in this PR)

Significance is currently declared geometry. The next layer separates
geometry (deterministic, in code) from interruption policy (a local decision
model, evaluated only on events, with the fence verdict as the fail-open
baseline). An 11-case eval (incl. negative controls and a conjunction
scenario: "passing a store × open shopping-list need") found local decision
models (clef-flash, d3:2b via Ollama's /v1/systemone) that
discriminate correctly with ~160-token calls. Full methodology and results:
https://gist.github.com/zigit/8c765c33d1edea1435f9b26d6d22c896
This PR intentionally ships only the deterministic layer.

Why this shape (the box, not the cloud)

"It ain't gonna be some cloud… then I don't know who has my shit. It will be
like a box that knows what I need, and when I pass by Ralph's on my way home
I get a message: 'You know we ain't got no milk.' That's what I expect we
have in the future."

— will.i.am, on stage at CES 2013, as recalled by this PR's author

That quote is the reason this PR is shaped the way it is, and the reason the
example notification in the drive-test screenshot reads "We ain't even got no
milk."

Thirteen years later the box is an OpenClaw gateway on a Mac, the milk is a
reminder in a local database, and the message arrives within a few hundred
metres of the store — verified on a real drive, with the notification landing
on the phone as the car passed.

Two parts of the quote turned out to be design constraints rather than
rhetoric:

  • "not some cloud… I don't know who has my shit" — fixes are evaluated
    against armed intents and discarded; coordinates never reach a log, a
    prompt, a system event, or a third-party API. The follow-up judge layer runs
    on a local decision model precisely so that the one component that reasons
    about where you are does not require sending where you are anywhere.
  • "knows what I need" — the trigger is a conjunction the user declared
    (an armed intent, an open shopping need), not an inference over harvested
    behaviour. Consent is the mechanism, and it is per-intent and revocable.

This PR ships the deterministic half: geometry in code, significance declared
by the user. The contextual half — a small local model deciding whether a
crossing is worth interrupting you — is the follow-up below.

Change type

  • Bug fix (ack-path crash; enter-fence miss when armed from afar;
    direction-ungated crossings)
  • Feature (node-event plugin hook; event-driven location-intent push)
  • Refactor
  • Docs
  • Tests (covered by existing consumer tests; new asserts added for both
    direction gates)

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime extensions: memory-core Extension: memory-core scripts Repository scripts size: XL triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Nov 17, 2026
@zigit
zigit force-pushed the pr/location-update-clean branch from 3c23613 to 606d131 Compare November 17, 2026 23:53
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Nov 17, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: ready, awaiting a maintainer decision.

What this changes

This PR connects device location updates to user-armed location reminders and immediate APNs notifications.

Example: An iPhone leaves a user-armed 200-meter home fence.

  • Before: The Gateway rejects location.update as unsupported_event.
  • After: A definite inside-to-outside transition consumes the reminder once and sends its description as a phone notification.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Real device and upgrade evidence support the change, but contract direction remains undecided and product CI has not validated this head.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (screenshot): The inspected iPhone notification image and recorded drive scenarios exercise native fixes through fence evaluation to APNs delivery; the newly supplied live PostgreSQL trace now shows the complete schema-38-to-44 upgrade rather than only its final hop.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: Users cannot turn native background location changes into arrival or departure reminders without manually sharing location through another channel.
Reason: Real drive evidence establishes value, but the new plugin API, persisted location fields, interruption policy, and SQLite-only evaluation need an owner decision; the added evidence-connection environment variable is test-only.

Merge readiness

⏳ Ready, awaiting maintainer decision

Keep open: this PR supplies a missing location-event consumer and demonstrated arrival/departure notifications; its new contracts still need an owner decision, and product CI has not completed for the reviewed head.

Priority: P2
Reviewed head: 8b19bac0b2da237333c85a27e8251ef28ab880ac
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should memory-core consume Always-authorized location fixes for explicitly armed reminders through these new plugin and push contracts, with location evaluation initially limited to SQLite agents?
  • Recommendation: Approve the bounded reminder feature: Accept explicit per-intent arming, discarded raw fixes, passive session records, immediate APNs delivery, and the stated SQLite-only limitation.
  • Why: The user problem and live results are concrete, but neither this PR nor its linked discussion records an owner decision approving the added contracts and initial engine limitation.

Before merge

None.

Findings

  • [P3] Document the actual push-result field types — docs/plugins/sdk-subpaths.md:211-212

Tests

  • Low-value test src/plugins/registry-registrars.node-events.test.ts: Remove the final assertion equating NODE_EVENT_CONSUMER_EVENTS to its literal declaration; registration tests already exercise the supported and unsupported event contract.
Agent review details

How this fits together

Paired devices send location fixes through Gateway node events; the plugin registry delivers validated fixes to memory-core, whose existing standing-intent worker records crossings and returns reminders for APNs delivery and passive session context.

flowchart LR
  A[Paired iPhone] --> B[Gateway payload validation]
  B --> C[Active plugin consumer]
  C --> D[Standing intent worker]
  D --> E[Agent database]
  D --> F[APNs notification]
  D --> G[Passive session record]
Loading

Technical review

Best possible solution:

Retain the validated plugin seam and existing standing-intent owner, with an explicit owner-approved scope for location consumption, notification delivery, and SQLite-only evaluation.

Do we have a high-confidence way to reproduce the issue?

Current-main source connects the native location.update producer to an unsupported dispatcher default, corroborated by two users in #163480; no target code was executed during this review.

Is this the best way to solve the issue?

Using the plugin registry and existing standing-intent worker is coherent and avoids autonomous model turns; the unresolved question is whether the proposed reminder, push, persistence, and engine-support contracts are the intended first stage.

Full review comments:

  • [P3] Document the actual push-result field types — docs/plugins/sdk-subpaths.md:211-212
    The remaining previously reported documentation mismatch is still present: NodePushIntentAlertResult declares optional ok and numeric status, but this example promises required ok and string status. A plugin following the documented type can mishandle an unattempted push or numeric HTTP status. Change the example to ok?: boolean and status?: number.
    Confidence: 1

Overall correctness: patch is correct
Overall confidence: 0.87

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against eedb353df007.

Provenance checked

  • Unsupported node events changes intended behavior with a stated reason (2b31cf1: Make unsupported node-event handling observable rather than silently dropping events.)
  • Standing-intent execution ownership keeps the original intent (2663c6b: Run standing-intent database operations in the existing agent worker.)
  • Missing agent database handling keeps the original intent (97a1b4c: Avoid creating unused agent databases during maintenance; the new location path preserves that absence check.)
  • Chat subscription extraction keeps the original intent (1f62a03: Canonicalize session keys for subscribe and unsubscribe; the extracted handler retains canonical keys and connection ownership.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main lacks the consumer: The native significant-location monitor emits location.update, while the current-main node-event dispatcher has no matching case and returns unsupported_event. (src/gateway/server-node-events.ts:791, eedb353df007)
  • Introduced implementation and prior repairs: The pinned introduced diff adds validated registry dispatch, ordered fix evaluation, one-shot standing-intent transitions, APNs delivery, and versioned schema migration; async consumer rejections are now observed. (src/gateway/server-node-events-location.ts:56, 8b19bac0b2da)
  • Real device proof inspected: The downloaded phone image visibly shows the reminder notification; the full PR body records a real departure followed by two arrival notifications, with matching fix geometry and timestamps. (8b19bac0b2da)
  • Upgrade evidence now covers the complete chain: The updated body supplies live PostgreSQL schema-38-to-44 destination-admission output and preservation of an existing keyword reminder. The SQLite test uses an independently frozen release schema. Latest stable v2026.11.6 also uses schema 38; its SQLite DDL differences from v2026.11.5 are unrelated indexes, with no standing_intents layout change. (src/state/openclaw-agent-v44-postgres-upgrade.evidence.test.ts:70, 8b19bac0b2da)
  • Independent affected-user reports: [Feature]: iOS app should send location updates in the background by itself (no location.update seen while travelling) #163480 contains booshtukka's background-location request and daemic24's official-release report of unsupported_event, explicitly requesting a handler or plugin hook; no maintainer direction was recorded in the inspected discussion.
  • Exact-head checks and mergeability: GitHub reports the reviewed head mergeable with mergeable_state blocked. Its check runs are administrative/review jobs; openclaw/ci-gate remains failure because CI must complete. This establishes neither a merge conflict nor a diff-caused test failure. (8b19bac0b2da)

Likely related people:

  • Peter Steinberger: Raw commit 7d4f66a adds extensions/memory-core/src/standing-intents.ts:58 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7d4f66aac342; files: extensions/memory-core/src/standing-intents.ts)

PR surface

Source +1281, Tests +2266, Docs +24, Config +4, Other +39. Total +3614 across 53 files. Added test files: 9.

View PR surface stats
Area Files Added Removed Net
Source 36 1372 91 +1281
Tests 11 2266 0 +2266
Docs 3 27 3 +24
Config 1 4 0 +4
Generated 0 0 0 0
Other 2 39 0 +39
Total 53 3708 94 +3614

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Agent schema 43 → 44; four nullable columns and one index The change affects existing agent databases on both engines, even though location evaluation is initially SQLite-only.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #163480
Summary: This PR implements the missing Gateway consumer requested by the canonical background-location issue; the earlier closed PR used a different, prompt-delivery design.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This adds useful location reminders for an established background-device workflow with limited blast radius.
  • merge-risk: 🚨 compatibility: The PR expands plugin contracts and the persisted agent schema, requiring an explicit contract decision despite the supplied migration evidence.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • proof: sufficient: Contributor real behavior proof is sufficient.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record the feature owner's decision on the proposed contracts and initial engine support.
  • Obtain the required product CI results for the reviewed head.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-11-18T12:49:18.667Z sha f9fac83 :: needs real behavior proof before merge. :: [P2] Evaluate location reminders on PostgreSQL | [P2] Preserve distinct fixes received during an active evaluation | [P2] Document the new public plugin contracts
  • reviewed 2026-11-18T12:58:49.379Z sha f9fac83 :: needs real behavior proof before merge. :: [P2] Evaluate location reminders on PostgreSQL | [P2] Preserve distinct fixes received during an active evaluation | [P2] Document the new public plugin contracts
  • reviewed 2026-11-18T16:32:14.192Z sha 4577c0b :: needs real behavior proof before merge. :: [P1] Migrate existing PostgreSQL stores before expanding canonical DDL
  • reviewed 2026-11-18T21:03:37.945Z sha e644ea2 :: needs real behavior proof before merge. :: [P1] Validate the new PostgreSQL checks before destination admission
  • reviewed 2026-11-18T21:36:38.908Z sha a619441 :: needs real behavior proof before merge. :: [P1] Match canonical null ordering in the PostgreSQL migration index
  • reviewed 2026-11-19T05:49:28.449Z sha d5f7d18 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-19T07:30:25.725Z sha 0ae1a3b :: needs real behavior proof before merge. :: [P2] Observe promise rejections from node-event consumers | [P2] Remove private host details from the evidence test | [P2] Cover the evidence test in the enforced test-line budget
  • reviewed 2026-11-19T12:30:47.972Z sha 1c0295e :: needs real behavior proof before merge. :: [P3] Document the actual push-result field types

Reviewed November 19, 2026, 3:12 PM ET / 20:12 UTC (Revision 10).

@zigit
zigit force-pushed the pr/location-update-clean branch from 218c210 to f2bf15c Compare November 18, 2026 07:13
@zigit zigit changed the title feat(location): consume location.update events; notify on fence crossings feat: notify users when they arrive or leave, using device location updates Nov 18, 2026
@zigit

zigit commented Nov 18, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Nov 18, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation plugin: file-transfer labels Nov 18, 2026
@zigit

zigit commented Nov 18, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Nov 18, 2026
@clawsweeper clawsweeper Bot added the rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. label Nov 18, 2026
@zigit

zigit commented Nov 19, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@zigit

zigit commented Nov 19, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Nov 19, 2026
@zigit

zigit commented Nov 19, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Nov 19, 2026
Fredrik Garneij added 10 commits November 19, 2026 13:49
…ings

iOS nodes emit `location.update` on significant location changes, but the
gateway dropped them as `unsupported_event` (openclaw#163480). This makes the event
consumable and closes the chain: fix -> significance detection -> event-driven
APNs notification, with no heartbeat, no session turn, and no coordinates in
logs.

Gateway and plugin surface
- Validate `location.update` against a closed payload schema (lat, lon,
  accuracyMeters, source) and dispatch it to the node-event consumer registry;
  drop with `no_consumer` when nothing subscribes, and isolate consumer
  failures so one consumer cannot break the event path.
- `registerNodeEventConsumer` is a plugin-API surface now; the gateway reads
  the active plugin registry at dispatch time rather than a process-global map,
  so it rides plugin reload and rollback.
- The dispatch log line records event name and node id only.

Significance
- Armed location intents evaluate each fix against fence geometry with an
  accuracy-resolved haversine decision and a baseline-first state machine.
- Enter fences fire on the first inside fix when armed from afar, instead of
  requiring a 0->1 crossing that can never happen when the fence was armed
  while already outside.
- Crossings are direction-gated. `decideLocationFire` previously gated only
  one side of each transition, so an exit fence could fire on an arrival fix
  and an enter fence on a departure fix. Both were observed on real drives: a
  Goeteborg arrival fence fired on the user's morning departure, and a home
  exit fence fired while the user was arriving home. Two regression tests now
  cover the directions the existing test's comment promised but never
  asserted.

Delivery
- A fire pushes an APNs alert at fire time through the new
  `sendNodeIntentAlert` plugin-SDK surface (category
  `openclaw.location-intent`), so delivery no longer waits for the target
  session's next turn. The routed system-event enqueue stays as an in-session
  record; push failures are logged and never re-arm the one-shot.

Structure
- `location.update` handling and the chat subscribe/unsubscribe arm move to
  sibling modules (`server-node-events-location.ts`,
  `server-node-events-chat-subscription.ts`) alongside the existing
  `server-node-events-*.ts` handlers, keeping the dispatcher within its
  line-cap ratchet.

Privacy
- Fixes are evaluated only against intents the user explicitly armed and are
  then discarded: no coordinates reach logs, prompts, system events, or a
  third-party service. A fire pushes a notification and enqueues a passive
  record; it never starts an agent turn.

Verified by a live drive with three fences (home exit, and two 1 km arrival
fences): the exit fence baselined inside without firing, then fired once at
512 m out; both arrival fences fired on genuine crossings; zero evaluation
errors. Consumer tests assert single push per fire, fire-on-first-inside-fix,
no re-arm on push failure, and both direction gates.
…admission

Two P1 findings from the automated review, both verified against the code
before fixing:

1. The queued session record embedded the exact fix coordinates. That record
   drains into ordinary reply preparation on the target session's next turn,
   so a fired reminder followed by a normal conversation would send precise
   device location to the configured model — beyond the purpose the user
   consented to when arming the fence, and contradicting the PR's own
   evaluate-and-discard boundary. The record now carries the intent
   description only; a regression assert pins that no coordinate-like digits
   appear in the queued text.

2. Existing agent databases were rejected before the location columns could
   be added. The four additive standing_intents columns were absent from the
   schema-compatibility allowlist, so admission refused a pre-location
   database outright; and even past admission, both the canonical-section
   exec and the migration's canonical index repair created
   idx_standing_intents_location before trigger_kind existed, failing with
   "no such column" on exactly the databases the repair exists to serve.

   The fix follows the existing additive-column pattern: the columns join
   allowedMissingColumns (admission lets the pre-location database through),
   the index joins allowedMissingIndexes (lazy ensure repairs it), a minimal
   ensureStandingIntentsLocationColumns runs inside mutate() before any
   canonical repair so columns exist before the index, and the migration
   witness excludes the columns and the migration-created index from its
   crossing comparison — the same contracts the session additive columns and
   their repaired indexes already use.

Verified: the previously failing schema-20 and schema-24 migration suites
now pass (21/21), and the consumer, intents, and admission suites stay green
(53/53 across the four affected files). The rig's own drive database
(through which all fires were validated) never exercised these paths because
it was created after the columns existed — that is precisely the gap the
review caught.
…mports

The plugin contract boundary invariant ("keeps core tests off bundled
extension deep imports") rejects core tests that import anything under
extensions/ other than a plugin's public api.js surface. The gateway
location-update e2e test deep-imported memory-core internals
(location-intent-consumer.js, standing-intents.js) to arm an intent and
observe the routed wake, so test:contracts failed on the boundary check.

Restructure the test to verify what its position in src/gateway/ actually
owns: the gateway dispatch contract over a real paired-node WebSocket.
A recording consumer stub registers through the same core plugin-registry
surfaces the gateway reads at dispatch time, and the test now proves the
full boundary behavior end to end — a validated fix reaches the registered
consumer exactly once with the typed payload and sender node id, distinct
fixes are both delivered without gateway-side dedupe or transformation, a
malformed payload is rejected before any consumer runs, and retiring the
registry generation stops dispatch with no_consumer.

The removed coverage — the fire-to-wake chain with the real memory-core
consumer — is not lost: it is the exact subject of the extension's own
integration suites (location-intent-consumer.test.ts,
location-intents.test.ts), which own those internals and remain green.
…ation schema

The automated review asked for exactly this evidence: no latest-stable
upgrade run covered the changed standing_intents fields. Freeze the
v2026.11.5 release's shipped agent schema (schema version 38, with the
pre-location keywords-only standing_intents table) as a fixture, migrate a
database seeded with a live keyword-intent row to the current schema, and
prove:

- the migration accepts the latest-stable database and advances it,
- the four additive location columns and idx_standing_intents_location
  arrive,
- the existing intent row survives untouched with absent-feature defaults,
- a location intent in the stored kernel format is accepted by the migrated
  table's constraints.

Fence evaluation and delivery on the post-migration shape are covered by
memory-core's own suites; the schema they run against is identical to the
post-migration shape proven here.

The new test registers in the infra project (it needs the host-owned SQLite
broker that the maintenance lease acquires), and the added test lines carry
a justified allocation record per the test-lines ratchet.
Three findings from the automated review, each verified before fixing:

PostgreSQL: location-intent creation is rejected with an actionable error
("location-triggered standing intents are not supported on PostgreSQL
agents; this agent needs SQLite storage before fences can be armed").
Previously the tool reported the fence as armed while the fire path
silently discarded every fix, so the reminder could never fire. Keyword
intents keep working: their turn matching is engine-neutral. Regression
test in standing-intents.postgres.test.ts asserts the rejection and that
keyword intents still arm and match.

Fix-dropping: the consumer's in-flight set was keyed only by nodeId, so a
fix arriving mid-evaluation was discarded — an exit crossing that lands
while the inside baseline is still evaluating loses the reminder, and a
later return inside masks it. Replaced with an ordered per-node queue:
identical consecutive fixes coalesce, distinct fixes are preserved and
drained in order, and each fix is fully evaluated before the next.
Regression test drives back-to-back synchronous handle() calls so the
mid-evaluation arrival is deterministic.

SDK docs: the new public contracts are documented per the plugin SDK's
documentation requirement. registerNodeEventConsumer is documented in
docs/plugins/sdk-runtime.md (validated payload shape, single-consumer
registration, registry-generation retirement, no_consumer drop, handler
error isolation), and node-push-runtime's sendNodeIntentAlert in
docs/plugins/sdk-subpaths.md (payload, UTF-16-safe truncation budget,
result contract, stale-registration clearing, no-retry ownership).

The allocation record is extended to cover the two regression tests.
…n columns

The review found that opening an existing PostgreSQL agent database after
this change failed schema admission even for keyword-only users: the four
location columns, their checks, and the new index changed the canonical
PostgreSQL DDL, but no version bump or migration added them, so the DDL
hash check at verifyPostgresSchemaDefinition threw a schema-drift error —
and createAgentPostgresMigrations derived every historical definition from
that same runtime DDL, silently making old versions inherit the new fields.

Fix, following the existing versioned-migration pattern (schema 43 as the
template):

- Agent schema advances 43 -> 44 on both engines through the versioned
  owners. Schema 43 stays a supported witness version, and the backup
  descriptor's source list gains 43.
- New AGENT_LOCATION_INTENTS_POSTGRES_MIGRATION_SQL adds the columns,
  NOT VALID checks (existing rows never violate: the columns are all-new),
  and the index to an existing standing_intents table in one transaction;
  fresh databases get them from the canonical DDL.
- The PostgreSQL migration chain derives v43 as the pre-location shape
  (withoutAgentPostgresLocationIntents): the v43 entry migrates INTO that
  historical shape (fixing the inherited-fields drift), and the new v44
  entry migrates v43 -> v44. Older derivations inherit it transitively.
- SQLite mirrors through its existing additive machinery: the versioned
  cross-version step runs migrateAgentLocationIntentsInTransaction, which
  also converges pre-44 tables on every early-return migration branch, so
  no SQLite admission or index-repair path sees missing columns.
- The now-duplicated ensureStandingIntentsLocationColumns is consolidated
  into migrateAgentLocationIntentsInTransaction (same body, one owner).

Verified: the v2026.11.5 latest-stable upgrade test, the schema-20 and
schema-24 migration suites, and the location kernel suites all pass
(55/55); the SQLite catalog regenerates from source with zero drift.
…fication passes

The review found the remaining upgrade failure: the three CHECK constraints
were created NOT VALID, and PostgreSQL's pg_get_constraintdef records that
suffix, so verifyAndRecordPostgresSchema — which compares exact constraint
definitions against the canonical DDL's validated checks — reported
"PostgreSQL schema drift detected against generated DDL" when the migration
adapter validated the destination.

The optimization was unnecessary anyway: ALTER TABLE ADD COLUMN fills
existing rows with NULL, which satisfies each constraint's IS NULL guard
trivially, so validation is instant. Create all three constraints validated
so the migrated destination's constraint definitions are byte-identical to
the canonical DDL the fingerprint comparison expects.
… index

The review's remaining P1: the migration's CREATE INDEX used PostgreSQL's
default ASC NULLS LAST for the two nullable keys, but the canonical DDL
explicitly declares NULLS FIRST. pg_get_indexdef records the difference, so
verifyAndRecordPostgresSchema rejected the upgraded destination with
"PostgreSQL schema drift detected against generated DDL" even after the
NOT VALID repair — affecting keyword-only users too.

Declare NULLS FIRST on both nullable keys so the migrated index definition
is byte-identical to the canonical DDL the fingerprint comparison expects.
…eal adapter

Evidence for the review's before-merge items: an existing PostgreSQL agent
store (built from the v2026.11.5 shipped schema, schema 43, pre-location)
migrates to schema 44 through the engine's own reopen-driven migration, and
verifyAndRecordPostgresSchema validates the destination — the exact step the
review's P1 said failed.

The test seeds a live keyword standing-intent row, runs the upgrade, and
proves: the four additive location columns and
idx_standing_intents_location (NULLS FIRST, matching canonical DDL) arrive;
the existing row survives untouched with absent-feature defaults; a location
intent in the stored kernel format is accepted by the migrated constraints;
and the existing keyword intent stays queryable. The evidence namespace is
dropped afterwards so the server stays clean.

Registered in the infra project (needs the host-owned SQLite broker). The
connection arrives via OPENCLAW_PG_EVIDENCE_CONNECTION or the workspace
connection file (never committed); the test skips without either.

Also remove the manual migration.sql application from my earlier draft: the
drift error it produced was a test artifact (schema advanced while
schema_meta still recorded v43), not a product defect — the engine's
reopen-driven migration is the code path a real upgrade takes.
…n, evidence privacy, budget, and the shipped-upgrade chain

Four findings from the latest review, each verified against the live
PostgreSQL server:

1. Async consumer rejections escaped isolation. A consumer declared
   `async` is assignable to the void callback, but the dispatcher
   discarded its promise, so a rejection reached the process-level
   unhandled-rejection handler (which exits the Gateway). The consumer
   type now allows `void | Promise<void>`, and the dispatcher observes
   the returned promise: a rejection is caught and logged, and the
   event still acks. A regression test drives an async consumer that
   rejects, asserts dispatch success, and asserts the logged warning
   — it fails without the fix.

2. Private host details in the evidence test. The committed header
   referenced a private server address and the connection resolution
   fell back to a named personal home directory. Removed: the
   connection now arrives only via the OPENCLAW_PG_EVIDENCE_CONNECTION
   environment variable (matching the workboard connection convention),
   the debug log block and unused fs/os imports are gone, and the test
   skips without the env var — no committed private details.

3. Test-line budget. The evidence test (258 lines) pushed introduced
   growth past the recorded allocation. The allocation record now
   covers the full growth (954) with per-block justification.

4. The evidence predecessor was v43, but the shipped v2026.11.5
   release carries schema 38. The test now builds the predecessor from
   the v39 migration step's fromSchema — the real release shape —
   so the upgrade run exercises the complete shipped 38 -> 44
   migration chain through the engine. Verified against the live
   PostgreSQL 16 server: destination admission succeeds (version 44),
   the four location columns and the NULLS FIRST index arrive, the
   existing keyword reminder survives usable, and a location intent is
   accepted by the migrated constraints.
@zigit
zigit force-pushed the pr/location-update-clean branch from 1c0295e to 8b19bac Compare November 19, 2026 20:02
@zigit

zigit commented Nov 19, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: iOS app should send location updates in the background by itself (no location.update seen while travelling)

1 participant