@astrosheep/square 0.3.92 → 0.3.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/activity-feed.d.ts +3 -5
  2. package/dist/activity-feed.js +16 -14
  3. package/dist/artifact.js +2 -2
  4. package/dist/boundary-presentation.d.ts +2 -2
  5. package/dist/catch-decisions.d.ts +4 -6
  6. package/dist/catch-decisions.js +4 -4
  7. package/dist/claude-delivery-status.js +10 -4
  8. package/dist/claude-delivery.js +19 -11
  9. package/dist/claude-mod.js +24 -53
  10. package/dist/cli/context.d.ts +9 -4
  11. package/dist/cli/context.js +30 -25
  12. package/dist/cli/express-presentation.d.ts +3 -1
  13. package/dist/cli/express-presentation.js +26 -14
  14. package/dist/cli/json.d.ts +3 -0
  15. package/dist/cli/json.js +14 -0
  16. package/dist/cli/mcp-server-command.js +2 -2
  17. package/dist/cli/observation-commands.d.ts +1 -3
  18. package/dist/cli/observation-commands.js +43 -56
  19. package/dist/cli/program.js +2 -2
  20. package/dist/cli/registry.js +6 -3
  21. package/dist/cli/square-commands.d.ts +1 -1
  22. package/dist/cli/square-commands.js +46 -54
  23. package/dist/codex-hook.d.ts +3 -2
  24. package/dist/codex-hook.js +13 -4
  25. package/dist/codex-queue.js +4 -4
  26. package/dist/decisions.d.ts +5 -11
  27. package/dist/decisions.js +9 -20
  28. package/dist/delivery-deferral.js +2 -2
  29. package/dist/delivery-health.d.ts +0 -1
  30. package/dist/delivery-health.js +1 -3
  31. package/dist/delivery-operations.d.ts +2 -2
  32. package/dist/delivery-operations.js +38 -38
  33. package/dist/delivery.d.ts +1 -1
  34. package/dist/delivery.js +1 -1
  35. package/dist/harness-links.d.ts +1 -10
  36. package/dist/harness-links.js +144 -109
  37. package/dist/harness.js +4 -13
  38. package/dist/help.js +12 -10
  39. package/dist/inbox.d.ts +9 -22
  40. package/dist/inbox.js +23 -27
  41. package/dist/index.d.ts +1 -3
  42. package/dist/index.js +1 -1
  43. package/dist/mcp.d.ts +3 -0
  44. package/dist/mcp.js +23 -24
  45. package/dist/model.d.ts +8 -15
  46. package/dist/model.js +4 -7
  47. package/dist/notifications.d.ts +1 -1
  48. package/dist/notifications.js +6 -5
  49. package/dist/operation-presentation.d.ts +5 -4
  50. package/dist/operation-presentation.js +50 -45
  51. package/dist/owner.d.ts +11 -0
  52. package/dist/owner.js +32 -0
  53. package/dist/paseo-delivery.d.ts +4 -1
  54. package/dist/paseo-delivery.js +7 -12
  55. package/dist/paseo-state.d.ts +2 -2
  56. package/dist/paseo-state.js +6 -4
  57. package/dist/plugins/opencode/delivery.js +27 -15
  58. package/dist/ports.d.ts +13 -33
  59. package/dist/presentation-operations.js +4 -4
  60. package/dist/presentation.d.ts +5 -8
  61. package/dist/presentation.js +33 -43
  62. package/dist/runtime.d.ts +1 -7
  63. package/dist/runtime.js +0 -14
  64. package/dist/seats.d.ts +2 -3
  65. package/dist/seats.js +7 -15
  66. package/dist/session-lifecycle.d.ts +6 -2
  67. package/dist/session-lifecycle.js +39 -11
  68. package/dist/sqlite-square.d.ts +36 -22
  69. package/dist/sqlite-square.js +138 -161
  70. package/dist/square-api.d.ts +15 -10
  71. package/dist/square-api.js +26 -22
  72. package/dist/square-core.d.ts +0 -5
  73. package/dist/square-core.js +0 -9
  74. package/dist/square-domain.d.ts +4 -2
  75. package/dist/square-domain.js +56 -21
  76. package/dist/square-facade.d.ts +45 -87
  77. package/dist/square-index.d.ts +5 -13
  78. package/dist/square-index.js +13 -38
  79. package/dist/square-location.d.ts +1 -14
  80. package/dist/square-location.js +4 -69
  81. package/dist/square-migration-host-ledger.d.ts +2 -2
  82. package/dist/square-migration-host-ledger.js +6 -5
  83. package/dist/square-migration.d.ts +2 -1
  84. package/dist/square-migration.js +52 -30
  85. package/dist/square-sqlite.d.ts +6 -2
  86. package/dist/square-sqlite.js +54 -28
  87. package/dist/square-tools.d.ts +7 -10
  88. package/dist/square-tools.js +22 -54
  89. package/dist/stream.js +4 -5
  90. package/dist/views.d.ts +21 -10
  91. package/dist/views.js +38 -38
  92. package/dist/wakes.d.ts +1 -2
  93. package/dist/wakes.js +1 -1
  94. package/guides/application-facade-delivery-evidence.md +1 -1
  95. package/guides/claude-native.md +18 -9
  96. package/guides/codex-delivery.md +17 -6
  97. package/guides/mcp-connection-lifetime.md +1 -1
  98. package/guides/mcp.md +3 -3
  99. package/guides/migration.md +142 -151
  100. package/guides/operation-cancellation.md +1 -1
  101. package/guides/participant-ownership.md +78 -47
  102. package/guides/pi-tools.md +33 -4
  103. package/guides/primitive-history-consolidation.md +1 -1
  104. package/guides/row-storage-design.md +8 -8
  105. package/guides/square-api.md +244 -88
  106. package/package.json +2 -1
  107. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  108. package/plugins/codex/.codex-plugin/plugin.json +1 -1
  109. package/plugins/opencode/delivery.ts +27 -17
  110. package/plugins/paseo/client/palette.ts +18 -18
  111. package/plugins/paseo/client/square-message.tsx +17 -23
  112. package/plugins/pi/square-pi.js +17 -17
  113. package/dist/square-backend.d.ts +0 -13
  114. package/dist/square-backend.js +0 -1
  115. package/dist/square-stdio.d.ts +0 -22
  116. package/dist/square-stdio.js +0 -235
  117. package/dist/stdio-server.d.ts +0 -3
  118. package/dist/stdio-server.js +0 -212
  119. package/guides/backends.md +0 -193
package/dist/wakes.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type WatchLease, type WatchOptions } from './model.js';
1
+ import { type WatchOptions } from './model.js';
2
2
  import type { SquareArtifactPort } from './ports.js';
3
3
  import type { Seat } from './model.js';
4
4
  export type WatchLeaseStart = {
@@ -8,7 +8,6 @@ export type WatchLeaseStart = {
8
8
  readonly heartbeatAt: number;
9
9
  } | {
10
10
  readonly type: 'active';
11
- readonly lease: WatchLease;
12
11
  };
13
12
  export type WatchLeasePulse = {
14
13
  readonly type: 'replaced';
package/dist/wakes.js CHANGED
@@ -9,7 +9,7 @@ export async function acquireWatchLease(artifact, seat, at, leaseId, options, si
9
9
  const { value } = await artifact.transactAs({ kind: 'participant', seat }, facts => {
10
10
  const known = resolveKnownName(facts, name), existing = freshWatchLease(facts, known, at);
11
11
  if (existing !== undefined && !options.replace)
12
- return { type: 'active', lease: existing };
12
+ return { type: 'active' };
13
13
  facts.putLease(known, newLease(leaseId, at, options), seat.generation);
14
14
  return { type: 'started', leaseId, replaced: existing !== undefined, heartbeatAt: at };
15
15
  }, signal);
@@ -176,7 +176,7 @@ These are deliverer closures, not a reviewer verdict. Rows distinguish behavior
176
176
  | Express cleanup/enrichment erases commit or calls it unsent | Resource close cannot replace a completed result. Action route/host publication is best effort after commit. Commit observation replaces duplicate post-read. Boundary fixtures prove postcommit host-publication failure returns the activity, projection-clock failure retains landed ID without replay, and selected-row corruption is unknown rather than proven unsent. Operation-cancellation has before-return commit abort coverage. |
177
177
  | Catch completion/enrichment erases a committed page | Raw page, ordinals/count/cap/hold/terminal facts travel with receipt selection; completion never rereads them. Only optional `catchPresence` can be unavailable. `performance`: real selection hydrates exactly its page; presence/rendering adds no hydration/reads. Operation-cancellation preserves committed consumption after abort. |
178
178
  | Replaced/cancelled waiter consumes later activity or releases new lease | Catch selection transaction checks lease ID. Finally cleanup is non-aborted and ID-fenced. Boundary fixtures prove replacement owns consumption, old waiter returns replaced, cancelled waiter releases lease, later attention stays pending. Hold/expiry and CLI watch-wait heartbeat fixtures pass. |
179
- | SDK projection roundtrip / leaked observations | SDK express uses `prepareExpression` + `landExpression`, strips observation/waited and retains delivery; SDK catch uses `catchOwned` and returns only established CatchResult. SDK test asserts established fields and avoids application body projections. SDK Square history stays unbounded, Participant recent-ten; parity history fixture proves both, and projection test preserves detached delivered predicate. |
179
+ | SDK projection roundtrip / leaked observations | The current SDK result shapes are documented in [Square/Participant API](square-api.md); parity tests exercise the real resource and projection tests preserve the detached delivered predicate. |
180
180
  | Duplicate contracts, aliases and dead mixed views | Private status/unread producers import/re-export facade contracts; catch observation extends shared expression facts and enriched projection reuses it; required express participant replaces name alias. Retired helper search is empty. Recovery selects only gates/bounded unread summaries, not discarded feed/ordinals/perceptions. |
181
181
  | Packed owner orchestration hides effects/count integrity | History, lifecycle branches, maintenance/discovery/recovery, catch conflict and SDK recognize are expanded into readable steps. Remaining one-line SDK delegates are supported simple resource calls, not packed async policy. Inspect implementation diff; all new source is included in count. |
182
182
  | Invalid reply / done repair regressions | Typed `invalid_reply` covers malformed and valid-but-absent IDs; typed reach/done reasons stay domain facts, CLI owns glyphs/flags. Express-recovery tests execute printed repaired commands, preserving raw drafts, body candidates and other recipients. Unknown/landed effects offer reconciliation, never replay. |
@@ -5,6 +5,10 @@ contains only `{"modules":["./register.js"]}`. Install with `square install clau
5
5
  and load/approve it in a trusted interactive Claude terminal. Installation is
6
6
  not evidence of a live receiver.
7
7
 
8
+ Public `Square.at` and `Square.build` use the default Claude/Codex/Paseo wake transport when
9
+ `wakeTransport` is omitted. Supply a port to replace it or `false` to disable proactive wake;
10
+ synchronous `Square.inMemory` uses only an explicit port. See [square-api.md](square-api.md).
11
+
8
12
  ## Validated capability
9
13
 
10
14
  The supported baseline is **macOS Claude Code with the mod actually loaded**;
@@ -24,7 +28,7 @@ An absent/broken endpoint is unavailable; it does not consume Square activity.
24
28
  Native delivery is preferred, including under Paseo. CLI and call-local MCP Codex
25
29
  joins register the native queue for their thread. Claude and OpenCode receivers
26
30
  register their native wake addresses only through their loaded integrations. An
27
- ordinary reconnect or implicit join cannot replace a current native address with a
31
+ ordinary reconnect or reattachment cannot replace a current native address with a
28
32
  generic Paseo proposal. Addresses belong to the artifact seat generation, not an
29
33
  expiring routes table: explicit receiver withdrawal permits fallback, and a new
30
34
  seat generation cannot inherit the previous generation's native registration.
@@ -95,15 +99,20 @@ Initial activation and hot reload use `session.start`. New conversations use
95
99
  `classic.SessionStart`: clear reads the new API coordinate; **resume's event
96
100
  `session_id` is already the resumed coordinate while `$.session.id()` still reads
97
101
  the ending one (observed in 2.1.295)**. The event coordinate is used at that boundary, with
98
- API cwd/version/socket. Modern `session.end` retires only its pinned `e.sessionId`
99
- and captured ownership epochs, within the event budget. Late committed joins
102
+ API cwd/version/socket. Modern `session.end` detaches only its pinned `e.sessionId`
103
+ and captured owner/join generations, within the event budget. Late committed joins
100
104
  are discovered at the pinned end timestamp. A process crash can omit end.
101
105
 
102
- A resumed conversation restores only memberships whose last lifecycle activity
103
- is exactly the `done` recorded by its previous confirmed end in the existing
104
- host ledger. It never takes another owner's participant or re-enters a later
105
- explicit user `done`. Restoration advances the binding epoch, so callbacks and
106
- old ends cannot retire that replacement. Unchanged reload preserves epochs.
106
+ Host end is not a participant departure: no `done` lands, and membership, listens,
107
+ read horizon and generation remain intact. Catch ownership, deferrals and wake readiness
108
+ are cleared; the participant appears away and keeps accumulating unread audience without
109
+ proactive delivery. Before arming a receiver, start/resume discovers the exact owner's
110
+ standing seats through `seatsOf(owner)` and restores only detached ones with
111
+ `reattach(name, {owner, wakeAddress?})`. The adapter obtains that owner with
112
+ `harnessOwner({channel: 'claude-code', session, agent?})`. One failed seat or location does not block the
113
+ others. New/forked harness owners restore nothing. Neither a voluntary `done` nor a takeover is
114
+ revived; there is no completed-seat recovery path or timeout that turns away into done.
115
+ See [participant-ownership.md](participant-ownership.md).
107
116
 
108
117
  ## Body, admission, and presentation
109
118
 
@@ -143,7 +152,7 @@ Explicit plugin `turn.abort` and terminal `turn.complete(reason:'aborted')`
143
152
  suppress the outstanding local batch without recording seen. Ordinary answer,
144
153
  refusal, and error completion are not user cancellation. Separate engine-owned
145
154
  family state survives hot reload, containing the abort timestamp and frozen
146
- membership epochs. Same-epoch host-ledger presence stores a monotonic activity
155
+ membership generations. The artifact stores a generation-scoped monotonic activity
147
156
  cutoff; replacement generations cannot inherit the old abort.
148
157
 
149
158
  Engine state reads are snapshots of one dispatch. Confirmation therefore uses
@@ -5,14 +5,22 @@ maintaining a second hook protocol, boundary store or CLI sender. The standalone
5
5
  package's [README](../packages/agent-delivery/README.md) describes both its native
6
6
  app-server capability and its host-owned hook integration.
7
7
 
8
+ Public `Square.at` and `Square.build` use the default Claude/Codex/Paseo wake transport when
9
+ `wakeTransport` is omitted. Supply a port to replace it or `false` to disable proactive wake;
10
+ synchronous `Square.inMemory` uses only an explicit port. See [square-api.md](square-api.md).
11
+
8
12
  ## Square's hook path
9
13
 
10
14
  `plugins/codex/hooks/hooks.json` invokes `square codex-hook`:
11
15
 
12
16
  - `SessionStart`, `SessionResume` and `UserPromptSubmit` invalidate the previous
13
- Stop observation. `SessionEnd` marks the session ended and ends Square's owned
14
- memberships. Later Stop/tool callbacks cannot re-enable queue until a new
15
- `SessionStart` or `SessionResume`.
17
+ Stop observation. `SessionEnd` marks the host session ended and detaches its exact
18
+ owner's seats without landing `done`, ending membership, dropping listens or resetting
19
+ the read horizon. Later Stop/tool callbacks cannot re-enable queue until a new
20
+ `SessionStart` or `SessionResume`. Before enabling delivery, those start paths use
21
+ `seatsOf(owner)` and `reattach(name, {owner, wakeAddress?})` to restore only detached
22
+ standing seats of that exact owner; voluntary departures and takeovers are never revived.
23
+ A new/forked session restores nothing.
16
24
  - `PostToolUse` asks Square for current pending activity and returns the existing
17
25
  bounded `additionalContext` presentation.
18
26
  - `Stop` records queue eligibility and sweeps pending work, but does not itself
@@ -20,7 +28,7 @@ app-server capability and its host-owned hook integration.
20
28
 
21
29
  The shared handler owns hook framing, lifecycle sequencing, its cancellation
22
30
  budget and bounded sweeps. Square supplies activity selection, formatting,
23
- artifact-owned presentation claims, cancellation, membership cleanup and
31
+ artifact-owned presentation claims, cancellation, attachment cleanup and
24
32
  pending-work sweeps. The handler cooperatively awaits Square's pull: the signal
25
33
  cancels work before presentation, but a successful presentation's `settleAs`
26
34
  finishes independently of request cancellation. Even when that settlement crosses
@@ -28,11 +36,14 @@ the internal budget, the hook waits for it and returns the associated context;
28
36
  it never abandons settlement that can mark activity seen without returning text.
29
37
  After expiry, no sweep starts, and a sweep timeout cannot erase successful pull
30
38
  output. Settlement must still finish within Codex's external hook timeout. Hook inbox lookup uses
31
- an exact Body (`{ channel: 'codex', session }`), not a bare session id. The shared
39
+ an exact owner from `harnessOwner({ channel: 'codex', session })`, not a bare session id. The shared
32
40
  boundary store uses Square's caller-selected `SQUARE_CODEX_BOUNDARIES` file,
33
41
  defaulting to `~/.square/codex-boundaries.json`; its JSON observations are not
34
42
  conversation storage and are not proof of current native execution or consumption.
35
- Square's format5 artifact remains authoritative for seats and delivery evidence.
43
+ Square's format-7 artifact remains authoritative for membership, attachment and delivery evidence.
44
+ Detached members appear away indefinitely and keep accumulating unread audience, but have no
45
+ write or proactive delivery eligibility until same-owner reattachment. Only a host-confirmed
46
+ permanent deletion uses fenced membership-ending cleanup; Codex SessionEnd is not that proof.
36
47
 
37
48
  `CodexQueueTransport` implements the existing `WakeTransportPort` and uses the public
38
49
  `connect({ harness: 'codex', transport: 'cli', sessionId, boundaries, ... })`
@@ -1,6 +1,6 @@
1
1
  # MCP connection lifetime
2
2
 
3
- An MCP server owns one artifact connection for its configured square. Its lifetime ends on close or disconnect; create a new server instance for a new connection. Replacing an artifact file under a running server remains unsupported. Every tool call opens an actual `Square` handle with that request's captured environment, default participant and harness session; `square.participant()` performs nonmutating name selection. Calls with an explicit `location` override instead open and close a per-call connection, leaving the configured-square owner untouched. Only the default connection is shared: authorization, presence, activity facts and cancellation remain operation-scoped. The artifact port already serializes transactions on its connection.
3
+ An MCP server owns one artifact connection for its configured square. Its lifetime ends on close or disconnect; create a new server instance for a new connection. Replacing an artifact file under a running server remains unsupported. Every tool call opens an identity-free `Square` handle with that request's resource environment; harness identity is passed to `join(name, {body, wakeAddress?})` or `selectOwnSeat(square, body, as?)`, never captured by the resource. Calls with an explicit `location` override instead open and close a per-call connection, leaving the configured-square owner untouched. Only the default connection is shared: authorization, presence, activity facts and cancellation remain operation-scoped. The artifact port already serializes transactions on its connection.
4
4
 
5
5
  `createSquareResourceOwner()` is the explicit lifetime boundary. `Square.at({resources, ...})` borrows its connection; closing a request handle leaves the owner open. Ordinary callers open and close their own Square. Cross-square `inbox()` reads remain independent. The connection captures no request abort signal. Explicit server close and transport disconnect share one shutdown path: the SDK cancels requests, handlers finish their cleanup, then the connection closes.
6
6
 
package/guides/mcp.md CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  Square provides a stdio MCP server through `square mcp-server`.
4
4
 
5
- Set `SQUARE_LOCATION` to the default `.square` artifact path; calls may override it with `location`. Relative paths use the server's startup working directory. Join with an explicit `as` name. Later calls may omit `as` only when the artifact recognizes exactly one current name held by the call's exact Body (`channel`, `session`, optional `agent`); zero or multiple matches refuse and require explicit selection. An explicit name selects a voice but never grants custody. Request metadata supplies the live Codex (`threadId`) or OpenCode (`ai.opencode/sessionID`) coordinate when present; otherwise a reliable startup coordinate is required for participant writes. Read-only calls do not need a Body.
5
+ Set `SQUARE_LOCATION` to the default `.square` artifact path; calls may override it with `location`. Relative paths use the server's startup working directory. Join with an explicit `as` name. Later calls may omit `as` only when the artifact recognizes exactly one current name held by the call's exact opaque owner; zero or multiple matches refuse and require explicit selection. An explicit name selects a voice but never grants custody. Request metadata supplies the live Codex (`threadId`) or OpenCode (`ai.opencode/sessionID`) coordinate when present, encoded through `harnessOwner`; otherwise the server-configured owner applies. CLI startup resolves `--owner`/`SQUARE_OWNER`, a complete harness coordinate, or the local user owner in that order, refusing incomplete harness identity. Owner is never a model tool argument. Read-only calls do not need an owner.
6
6
 
7
- The server exposes `join`, `express`, `catch`, `history`, `attention`, `hold`, `done`, and `status`. `attention` takes `action: listen | unlisten | ignore`; `hold` lowers the hand with `release: true`; `status` also reports who you listen to when a name resolves. `catch` consumes activities. `history` is read-only and accepts stable `act/<index>` cursors. Tool results include JSON `structuredContent` and a text representation of the same data. Square failures are returned as tool errors with a structured `{ error: { code, message, facts? } }` value.
7
+ The server exposes `join`, `express`, `catch`, `history`, `attention`, `hold`, `done`, and `status`. `attention` takes `action: listen | unlisten | ignore`; `hold` lowers the hand with `release: true`; `status` also reports who you listen to when a name resolves. `catch` consumes activities. `history` is read-only and accepts stable `act/<index>` cursors. All eight tools return the same human-readable text as the CLI in `content`, without `outputSchema` or `structuredContent`. Square failures set `isError: true` and return readable refusal and recovery text in `content`. Clients keep their native MCP result envelope; machine-readable domain results remain available through the SDK.
8
8
 
9
9
  Claude's bundled plugin configures this server automatically. Its mod supplies live session/cwd/subagent attribution through an out-of-band tool-use-ID association, not AI-visible arguments; see [Claude call identity](claude-native.md#mcp-tools-and-call-identity). The bundled endpoint requires that association rather than falling back to its startup environment.
10
10
 
11
- Tool definitions and argument-to-`Square`/`Participant` calls live in `square-tools.ts`, shared with the [Pi native tools](pi-tools.md). Join serializes the handle's name and receipt fields, never resource internals. All callers use the [same concrete resource API](square-api.md), with no alternate factory or generic outcome envelope. `express.noMention` disables body @name scanning without disabling explicit mentions or reply attention.
11
+ Tool definitions and argument-to-`Square`/`Participant` calls live in `square-tools.ts`, shared with the [Pi native tools](pi-tools.md). Domain receipts stay internal to these adapters; tools return only their rendered text. All callers use the [same concrete resource API](square-api.md), with no alternate factory or generic outcome envelope. `express.noMention` disables body @name scanning without disabling explicit mentions or reply attention.
12
12
 
13
13
  Configure a client with command `npx` and arguments `--yes --package @astrosheep/square square mcp-server`, or use the installed `square` executable with argument `mcp-server`. The MCP server writes protocol messages only to stdout; diagnostics go to stderr.
@@ -1,159 +1,150 @@
1
1
  # Migrating an existing square
2
2
 
3
- Square stores its authority in one versioned SQLite artifact. Format 1 kept the
4
- history as one JSON snapshot; format 2 introduced typed rows; format 3 added the
5
- `unlisten` activity; format 4 added artifact-owned participant seats and delivery
6
- evidence; format 5 adds independent expiring delivery deferrals. Existing artifacts are never
7
- converted implicitly.
3
+ Square stores its authority in one versioned SQLite artifact. Format 1 kept a snapshot;
4
+ format 2 introduced typed facts; format 3 added `unlisten`; format 4 moved participant custody
5
+ and delivery evidence into the artifact; format 5 added independent delivery deferrals.
6
+ **Format 6 separates participant membership from host attachment; format 7 replaces harness Body
7
+ coordinates with opaque owners.** Existing artifacts are never converted implicitly.
8
8
 
9
- Use the explicit command while all processes using the artifact are stopped:
9
+ Stop all processes using the artifact, make an offline backup, then run:
10
10
 
11
11
  ```sh
12
12
  square --location /path/to/SQUARE.square migrate
13
+ square --location /path/to/SQUARE.square doctor
13
14
  ```
14
15
 
15
- The command handles supported formats 2, 3 and 4 in place and publishes only final format 5.
16
- It does not create a
17
- backup, stop processes, install a runtime, or update another artifact. A legacy
18
- HostLedger that needs its own format conversion must be prepared separately with
19
- the old runtime's offline tooling.
20
-
21
- ## Format 4 additive conversion
22
-
23
- An exact format-4 artifact needs no legacy owner or route import: that authority already lives
24
- inside the artifact. Read-only preflight checks framing and stored facts. One SQLite transaction
25
- adds the empty `delivery_deferrals` table and its owner/generation/expiry lookup index, then
26
- publishes format 5. The dedicated table stores participant key, captured generation, opaque ID,
27
- validated match and expiry, separately from catch leases and delivery evidence. All existing
28
- activities (including metadata), audience, receipts, seats, catch leases, delivery evidence,
29
- cancellation boundaries and both revision values remain unchanged. No lease is manufactured.
30
- The conversion does not consult or mutate HostLedger. Failure rolls back the table, index and
31
- format marker together.
32
-
33
- ## Format 3 preflight and conversion
34
-
35
- Before writing, migration validates the exact format-3 schema, header, and legacy
36
- rows read-only. The configured legacy HostLedger must be frozen along with the
37
- artifact. Its latest owner row for each participant at this artifact is selected
38
- by source `(effectiveAt, seq)` only: no wall clock, retention, expiry, or ownership
39
- history reconstruction is involved.
40
-
41
- - A legacy owner Body (`channel`, `session`, optional `agent`) establishes a
42
- standing seat only when it agrees with all of that name's local route Bodies
43
- and the establishing last join is verified. An owner without routes needs no
44
- wake address. Without a legacy owner, one unambiguous Body recorded by that
45
- participant's own routes establishes its seat instead. An absent agent means
46
- the top-level body; a known agent is preserved and compared exactly. Repeated
47
- matching registrations are acceptable; a wake address is carried forward only
48
- when the routes agree on it. Routes are location-bound: moving an artifact copy
49
- to another path does not establish that its original routes apply there. An
50
- off-location copy is not ownership-recovery evidence for the original location.
51
- - Without an owner or any route Body, the participant stays standing without a
52
- seat. Its source participant state, activities, attention, receipts, landed
53
- audience and catch lease are preserved. No Body, route or departure is invented;
54
- the name has no write authority or delivery eligibility. Doctor retains its
55
- strict history-derived consistency checks.
56
- - A Body may own several participant seats. Each name retains its own seat,
57
- establishing join generation and wake address; sharing does not merge names or
58
- choose one name over another. All evidence for each name must agree: if its
59
- routes disagree with each other or with its legacy owner Body, that name stays
60
- standing without a seat. Disagreement does not abort migration and neither side
61
- is chosen as authoritative. Unverifiable joins still refuse before publication.
62
- Migration does not guess or synthesize authority.
63
- - Evidence structure is validated before placement, including rows that cannot be
64
- imported. Malformed fields, invalid activity IDs or malformed native correlation
65
- still refuse without changing either source.
66
- - Wake/presentation evidence for a recovered seat is imported only when its Body
67
- agrees and it names an existing directed say after the verified current join.
68
- A missing seat, conflicting session/agent/channel or native harness, unknown
69
- participant, or activity outside the generation causes the row to be skipped,
70
- not a failed conversion. Nothing is reassigned to another owner.
71
- - Done participants get **no seat or completed coordinate**. Only native wake
72
- correlation directly attributable to their verified latest join and a directed
73
- activity between that join and done is retained for retired-token recognition.
74
- It does not authorize admission, completion, or presentation. Conflicting
75
- completed Body mappings, duplicate claim tokens and ambiguous attempt numbering
76
- cause all affected rows to be skipped, rather than selecting a winner. A single
77
- record without an attempt number receives attempt 0. Migrated Claude native
78
- addresses include `sessionId` on both seats and evidence routes.
79
-
80
- This is deliberately a narrow, lossy conversion, not a general history importer.
81
- Conversation facts (activity IDs, bodies and audience), receipts and source revision
82
- meaning survive. Replay-critical delivery coordinates, outcomes and native
83
- correlation survive direct mappings. Completed non-native evidence and noncritical
84
- metadata—including old presence history, epochs, diagnostic messages, native
85
- observation histories and arbitrary legacy fields—are not imported. The legacy
86
- ledger is read-only and remains untouched, so it is still available for offline
87
- diagnostics. An absent ledger still permits route-derived seats; an unreadable
88
- or unsupported ledger refuses before changing the square. Evidence without a
89
- current or verified completed owner is skipped and counted. The source ledger is
90
- retained for offline diagnosis; skipped evidence never grants delivery authority.
91
-
92
- After successful preflight, one SQLite transaction imports seats and evidence
93
- and adds delivery deferral support, then publishes the current format. All
94
- existing activities, their indices and audience, participant state, attention,
95
- receipts, lease contents, and the source revision are preserved. Legacy routes
96
- are consumed only during migration. Lease generations are resolved only for exact
97
- owner spellings that match a standing participant; other lease rows retain their
98
- legacy, unbound generation. The command reports recovered seats and unowned
99
- standing names, and recovered seats whose Body is shared with another recovered
100
- seat, and skipped evidence rows, alongside the activity, receipt, lease and source
101
- route counts. The shared count measures seats, not distinct Bodies or shared groups.
102
- The skipped count includes every wake/presentation row read from the selected
103
- legacy ledger but not imported, including completed non-native diagnostics.
104
- The new delivery revision starts at zero. There is no intermediate published
105
- format, and any failure before commit rolls back the conversion.
106
-
107
- Format 2 first rebuilds only the activity table and its indexes to accept
108
- `unlisten`, then follows the same row-format preflight and conversion. Snapshot
109
- format 1 is not accepted by this migration. Formats 2/3 never publish an intermediate format 4.
110
-
111
- ## What migration refuses
112
-
113
- Migration validates each source's exact row schema. Formats 2/3 include the legacy routes table,
114
- read using migration-local codecs; format 4 already has seats and delivery evidence. Current
115
- format 5 has no routes table or runtime route
116
- reader; migration consumes the old rows only to resolve seats, then drops the legacy
117
- table as part of the format change.
118
-
119
- Unrelated databases, unsupported formats, non-`DELETE` journal modes, unknown
120
- schemas, malformed headers, rows or native correlation are refused. The source artifact is preserved on every
121
- refusal. Migration is not a repair command and never rewrites journal mode to make
122
- conversion possible. A HostLedger that itself requires migration must be migrated
123
- separately before Square migration can import its delivery evidence.
124
-
125
- ## Conservative retired-token restriction
126
-
127
- For an old artifact conversion, **any nonempty legacy `host_native_tokens` table
128
- makes preflight refuse**, including tokens for other sessions. Those token-only
129
- Claude tombstones are replay protection, not diagnostics: they contain only a
130
- session and token, with no artifact, participant or activity coordinate. The
131
- converter cannot safely assign them a join generation. This is deliberately a
132
- ledger-wide ambiguity refusal, not a claim that each token belongs to the square
133
- being converted. Even a tombstone duplicated by retained evidence is refused by
134
- this conservative implementation; no deduplication or history inference is done.
135
-
136
- Keep the original ledger and artifact intact. Resolve the ambiguity offline with
137
- replay protection preserved; **do not delete tombstones just to bypass preflight**.
138
- An already-current artifact returns without consulting the legacy ledger and
139
- remains a byte-preserving no-op.
140
-
141
- ## Before and after migration
142
-
143
- Stop every session or service using the square, and for formats 2/3 freeze any process writing its
144
- legacy HostLedger. Make an offline backup, or use SQLite's backup facilities rather than
145
- copying a live database. Migration does not revoke an in-flight remote delivery or
146
- modify HostLedger evidence. Square writes use ordinary SQLite `DELETE` journals:
147
- the artifact must be writable and its containing directory must permit journal
148
- creation and removal. The legacy ledger needs read access only. After conversion,
149
- participation and delivery authority live in the artifact, not writable HOME;
150
- loss of the rebuildable HOME discovery index may limit automatic discovery but
151
- does not transfer custody or erase durable delivery evidence.
152
-
153
- Upgrade all attached runtimes before reopening the format-5 artifact; older runtimes
154
- must not be mixed with it. Updating a package does not migrate an artifact, and migrating an
155
- artifact does not install upgraded runtimes. For rollback after a committed conversion, stop all
156
- clients and restore the offline backup with its compatible older runtime; do not downgrade the
157
- format marker or drop tables in place. Run the read-only `doctor` command after migration and
158
- before restarting clients. Repeating migration on a current artifact is a
159
- byte-preserving no-op.
16
+ The command handles supported formats 2–6 in place and publishes only final format 7, in one
17
+ transaction. It does not make a backup, stop processes, install a runtime or update another
18
+ artifact. For formats 2/3, also freeze and back up the legacy HostLedger used for owner/evidence
19
+ import. A legacy ledger needing its own conversion must be prepared separately with its old
20
+ runtime's offline tooling. Snapshot format 1 is not accepted by this conversion.
21
+
22
+ ## Membership and attachment after conversion
23
+
24
+ Membership owns a participant's join/done history, read horizon and outgoing listens. Attachment
25
+ says whether its exact owner is currently executing for it. There are three distinct endings:
26
+
27
+ - A participant's voluntary `done` ends membership. A later explicit participant join is required
28
+ to return; no host start/resume revives it.
29
+ - Pi shutdown, Codex SessionEnd and Claude session end detach only. No activity lands; membership,
30
+ listens, read horizon, receipts and delivery evidence stay intact. Wake readiness, catch ownership
31
+ and delivery deferrals are cleared. Away participants still receive landed audience and accumulate
32
+ unread activity, but cannot write or receive proactive delivery. Away has no timeout.
33
+ - Host-confirmed permanent deletion ends membership through fenced
34
+ `endHeld(name, {owner, generation})`, including for a detached seat. OpenCode `session.deleted`
35
+ uses this path.
36
+
37
+ On start/resume, hosts discover only their exact owner's standing seats with `seatsOf(owner)` and
38
+ restore the detached ones with `reattach(name, {owner, wakeAddress?})` before arming delivery.
39
+ Same-owner `join` or `reattach` preserves the generation, read horizon and listens, so mentions
40
+ received while away remain unread. Reattachment returns `null` for absent, foreign or done seats;
41
+ it never creates membership. Explicit takeover still performs `done -> join` with a fresh
42
+ generation, even when taking over an away participant; old cleanup/recovery cannot reclaim it.
43
+ The owner API requires this explicit format migration; see the
44
+ [SDK breaking migration](square-api.md#sdk-breaking-migration-opaque-owners).
45
+
46
+ ## Conversion from formats 6, 5 and 4
47
+
48
+ Format 6 -> 7 maps each seat's `channel`, `session` and optional `agent` through the adapter codec
49
+ into one owner string, preserving its generation, attachment and wake. Evidence, deferrals, catch
50
+ leases, cancellations, conversation facts and both revisions stay unchanged. Unmappable legacy
51
+ coordinates (for example an encoded owner exceeding 512 UTF-8 bytes) refuse without changing the
52
+ source; they are never truncated or reassigned. Keep the source backup for offline resolution.
53
+
54
+ Formats 4/5 first acquire format 6 semantics in that same transaction: every existing seat becomes
55
+ attached. Format 4 also gains empty deferral support. No detached seat is invented. Formats 4–6
56
+ never consult HostLedger; any failure rolls back schema changes and final publication together.
57
+
58
+ Existing done participants stay done. Before format 6, a host-cleanup `done` was indistinguishable
59
+ from a voluntary leave; migration conservatively treats both as voluntary. It does not infer
60
+ attachment history, reconstruct departures or provide a host recovery path for completed seats.
61
+
62
+ ## Verified import from formats 3 and 2
63
+
64
+ Formats 2/3 need owner and delivery evidence import. Before writing, migration validates exact
65
+ source framing, header and legacy facts read-only. The frozen legacy HostLedger's latest owner
66
+ for each participant at this artifact is selected by source `(effectiveAt, seq)` only: no wall
67
+ clock, retention, expiry or ownership-history reconstruction is involved.
68
+
69
+ - A legacy owner Body (`channel`, `session`, optional `agent`) establishes a standing, attached
70
+ seat only when it agrees with all of that name's local route Bodies and the establishing join
71
+ is verified. An owner without routes needs no wake address. Without an owner, one unambiguous
72
+ route Body can establish the seat. An absent agent means the top-level Body; a known agent is
73
+ preserved and compared exactly. Matching repeated registrations are acceptable; wake readiness
74
+ carries forward only when the routes agree. Routes are location-bound: moving an artifact copy
75
+ does not establish that its original routes apply there.
76
+ - Without a verifiable owner or route Body, the participant stays standing without custody.
77
+ Membership, history, attention, receipts, landed audience and catch ownership are preserved.
78
+ No Body, route, attachment or departure is guessed. Its name grants no write/delivery authority.
79
+ - A Body may own several names; each retains its own generation and wake readiness. Sharing
80
+ does not merge names or choose a winner. Conflicting owner/route Bodies leave that name
81
+ standing without custody; disagreement does not abort conversion. An unverifiable establishing
82
+ join still refuses before publication.
83
+ - Evidence structure is validated before placement, including evidence that cannot be imported.
84
+ Malformed facts, activity IDs or native correlation refuse without changing either source.
85
+ - Wake/presentation evidence imports only when its Body agrees and it names an existing directed
86
+ say after the verified current join. Missing custody, conflicting session/agent/channel or native
87
+ harness, unknown participants and activity outside the generation cause evidence to be skipped,
88
+ never reassigned to another owner.
89
+ - Done participants gain no seat or recovery authority. Only native correlation directly
90
+ attributable to their verified latest join and directed activity before departure is retained
91
+ for retired-token recognition. It authorizes neither admission nor presentation. Ambiguous
92
+ completed-Body mappings, duplicate claim tokens and ambiguous attempt numbering cause all
93
+ affected evidence to be skipped, rather than selecting a winner. A record without an attempt
94
+ number receives attempt 0. Migrated Claude wake addresses retain their native session identity.
95
+
96
+ This is a narrow, deliberately lossy conversion, not a general history importer. Conversation,
97
+ activity IDs, bodies, audience, receipts, source revision meaning and directly verified replay
98
+ protection survive. Completed non-native evidence and noncritical metadata—including old presence
99
+ history, epochs, diagnostic messages, native observation histories and arbitrary legacy extras—do
100
+ not import. Evidence without current or verified completed ownership is skipped and counted. The
101
+ read-only legacy ledger remains available for offline diagnosis; an absent ledger permits route-
102
+ derived custody, but an unreadable or unsupported ledger refuses before changing the square.
103
+
104
+ One transaction imports verified authority/evidence, adds deferral and attachment support and
105
+ publishes format 7. Existing conversation and membership facts are preserved; no intermediate
106
+ format is published. Legacy catch ownership is generation-bound only for exact standing owner
107
+ spellings; otherwise it stays unbound. Legacy routes are consumed only during migration and are
108
+ not a live authority source. The new delivery revision starts at zero. Format 2 first adds support
109
+ for `unlisten`, then follows the same conversion.
110
+
111
+ The receipt reports recovered seats, unowned standing names, seats sharing a recovered Body,
112
+ skipped evidence, and source activity/receipt/catch/route counts. The shared count measures seats,
113
+ not distinct Bodies or groups. Skipped includes every legacy wake/presentation record read but
114
+ not imported, including completed non-native diagnostics.
115
+
116
+ ## Conservative refusal and retired-token protection
117
+
118
+ Unrelated databases, unsupported formats, non-`DELETE` journal mode, unknown framing, malformed
119
+ headers/facts or native correlation refuse without source changes. Migration is not repair and
120
+ never rewrites journal mode to make conversion possible.
121
+
122
+ For formats 2/3, **any nonempty legacy token-only tombstone collection makes preflight refuse**,
123
+ including tokens for other sessions. Those Claude tombstones are replay protection, not diagnostics:
124
+ they identify only a session and token, without artifact, participant, activity or join generation.
125
+ The converter cannot safely assign them. This is a ledger-wide conservative ambiguity refusal,
126
+ not a claim that each token belongs to the artifact being converted. Even a token duplicated by
127
+ retained evidence refuses; conversion does not deduplicate or infer history to bypass protection.
128
+
129
+ Keep the original ledger and artifact intact. Resolve ambiguity offline with replay protection
130
+ preserved; **do not delete tombstones just to bypass preflight**. An already-current artifact
131
+ returns without consulting the legacy ledger and remains a byte-preserving no-op.
132
+
133
+ ## Before reopening and rollback
134
+
135
+ Freeze every artifact user and, for formats 2/3, every legacy-ledger writer. Make an offline backup
136
+ or use SQLite backup facilities rather than copying a live database. Migration cannot revoke an
137
+ in-flight remote delivery. Writes use ordinary SQLite `DELETE` journals: the artifact and its
138
+ containing directory must permit writing and journal creation/removal. A legacy ledger needs read
139
+ access only. Losing the rebuildable HOME discovery index may delay restoration/delivery but cannot
140
+ transfer custody or erase evidence. The disposable index changes to `{location, owner}`; old index
141
+ rows are ignored. Rejoin with the exact migrated owner to republish discovery (or let that same
142
+ harness reconnect). This preserves generation, listens and unread activity; do not use takeover
143
+ merely to rebuild the index.
144
+
145
+ Upgrade all attached runtimes before reopening format 7; older runtimes must not be mixed with it.
146
+ Updating a package does not migrate an artifact, and migration does not install upgraded runtimes.
147
+ After conversion, run read-only `doctor` before restarting clients. To roll back a committed
148
+ conversion, stop all clients and restore the offline backup with its compatible older runtime;
149
+ do not downgrade the format marker or remove facts in place. Repeating current-format migration
150
+ is a byte-preserving no-op.
@@ -21,7 +21,7 @@ Ownership and delivery have the same limitation: cancellation can stop work that
21
21
  Presentation checks cancellation and eligibility before invoking its sink. A rejected sink is not
22
22
  success, including a native notification whose landing acknowledgement was cancelled. Once the sink
23
23
  succeeds, recording its evidence and seen receipts is mandatory settlement, not a new cancellable
24
- presentation attempt. It uses the same artifact connection and captured Body/join generation, without
24
+ presentation attempt. It uses the same artifact connection and captured owner/join generation, without
25
25
  inheriting the pre-effect operation signal or a signal captured when opening that artifact. Claim
26
26
  release after a cancelled/failed attempt uses the same independent cleanup lifetime and writes no
27
27
  success receipt. Both settle through the normal authority gate, with a five-second storage budget;