@indigoai-us/hq-cloud 6.18.108 → 6.18.110

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 (148) hide show
  1. package/dist/bin/area-ledger-migration.d.ts.map +1 -1
  2. package/dist/bin/area-ledger-migration.js +5 -3
  3. package/dist/bin/area-ledger-migration.js.map +1 -1
  4. package/dist/bin/backup-prune-runner.js +2 -2
  5. package/dist/bin/backup-prune-runner.js.map +1 -1
  6. package/dist/bin/runner-output-guard.d.ts +39 -0
  7. package/dist/bin/runner-output-guard.d.ts.map +1 -0
  8. package/dist/bin/runner-output-guard.js +104 -0
  9. package/dist/bin/runner-output-guard.js.map +1 -0
  10. package/dist/bin/sync-runner-company.d.ts +9 -0
  11. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  12. package/dist/bin/sync-runner-company.js +76 -6
  13. package/dist/bin/sync-runner-company.js.map +1 -1
  14. package/dist/bin/sync-runner.d.ts +37 -1
  15. package/dist/bin/sync-runner.d.ts.map +1 -1
  16. package/dist/bin/sync-runner.js +37 -3
  17. package/dist/bin/sync-runner.js.map +1 -1
  18. package/dist/cli/conflict.d.ts +30 -1
  19. package/dist/cli/conflict.d.ts.map +1 -1
  20. package/dist/cli/conflict.js +69 -3
  21. package/dist/cli/conflict.js.map +1 -1
  22. package/dist/cli/reconcile-skip-reason.d.ts +1 -1
  23. package/dist/cli/reconcile-skip-reason.d.ts.map +1 -1
  24. package/dist/cli/reconcile-skip-reason.js +2 -0
  25. package/dist/cli/reconcile-skip-reason.js.map +1 -1
  26. package/dist/cli/reindex.d.ts.map +1 -1
  27. package/dist/cli/reindex.js +228 -43
  28. package/dist/cli/reindex.js.map +1 -1
  29. package/dist/cli/rescue-core.d.ts +160 -1
  30. package/dist/cli/rescue-core.d.ts.map +1 -1
  31. package/dist/cli/rescue-core.js +681 -162
  32. package/dist/cli/rescue-core.js.map +1 -1
  33. package/dist/cli/rescue-native-copy.d.ts +88 -0
  34. package/dist/cli/rescue-native-copy.d.ts.map +1 -0
  35. package/dist/cli/rescue-native-copy.js +823 -0
  36. package/dist/cli/rescue-native-copy.js.map +1 -0
  37. package/dist/cli/rescue.d.ts.map +1 -1
  38. package/dist/cli/rescue.js +37 -9
  39. package/dist/cli/rescue.js.map +1 -1
  40. package/dist/cli/share.d.ts +35 -8
  41. package/dist/cli/share.d.ts.map +1 -1
  42. package/dist/cli/share.js +437 -32
  43. package/dist/cli/share.js.map +1 -1
  44. package/dist/cli/sync.d.ts +70 -5
  45. package/dist/cli/sync.d.ts.map +1 -1
  46. package/dist/cli/sync.js +439 -77
  47. package/dist/cli/sync.js.map +1 -1
  48. package/dist/cognito-auth.d.ts +10 -0
  49. package/dist/cognito-auth.d.ts.map +1 -1
  50. package/dist/cognito-auth.js +162 -1
  51. package/dist/cognito-auth.js.map +1 -1
  52. package/dist/ignore.d.ts +5 -1
  53. package/dist/ignore.d.ts.map +1 -1
  54. package/dist/ignore.js +75 -23
  55. package/dist/ignore.js.map +1 -1
  56. package/dist/index.d.ts +4 -3
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +7 -2
  59. package/dist/index.js.map +1 -1
  60. package/dist/journal-row-store.d.ts +3 -0
  61. package/dist/journal-row-store.d.ts.map +1 -1
  62. package/dist/journal-row-store.js +21 -0
  63. package/dist/journal-row-store.js.map +1 -1
  64. package/dist/journal-snapshot-decoder.js +2 -0
  65. package/dist/journal-snapshot-decoder.js.map +1 -1
  66. package/dist/journal-snapshot-v4.d.ts.map +1 -1
  67. package/dist/journal-snapshot-v4.js +6 -1
  68. package/dist/journal-snapshot-v4.js.map +1 -1
  69. package/dist/journal.d.ts +1 -1
  70. package/dist/journal.d.ts.map +1 -1
  71. package/dist/journal.js +20 -20
  72. package/dist/journal.js.map +1 -1
  73. package/dist/lib/append-log-merge.d.ts +43 -0
  74. package/dist/lib/append-log-merge.d.ts.map +1 -0
  75. package/dist/lib/append-log-merge.js +424 -0
  76. package/dist/lib/append-log-merge.js.map +1 -0
  77. package/dist/lib/same-path-upload-lock.d.ts +27 -1
  78. package/dist/lib/same-path-upload-lock.d.ts.map +1 -1
  79. package/dist/lib/same-path-upload-lock.js +32 -1
  80. package/dist/lib/same-path-upload-lock.js.map +1 -1
  81. package/dist/object-io.d.ts +36 -1
  82. package/dist/object-io.d.ts.map +1 -1
  83. package/dist/object-io.js +93 -12
  84. package/dist/object-io.js.map +1 -1
  85. package/dist/operation-lock.d.ts +27 -1
  86. package/dist/operation-lock.d.ts.map +1 -1
  87. package/dist/operation-lock.js +94 -8
  88. package/dist/operation-lock.js.map +1 -1
  89. package/dist/outposts/client.d.ts +19 -6
  90. package/dist/outposts/client.d.ts.map +1 -1
  91. package/dist/outposts/client.js +16 -5
  92. package/dist/outposts/client.js.map +1 -1
  93. package/dist/outposts/command.d.ts +2 -1
  94. package/dist/outposts/command.d.ts.map +1 -1
  95. package/dist/outposts/command.js +81 -13
  96. package/dist/outposts/command.js.map +1 -1
  97. package/dist/outposts/self-deploy.d.ts.map +1 -1
  98. package/dist/outposts/self-deploy.js +3 -0
  99. package/dist/outposts/self-deploy.js.map +1 -1
  100. package/dist/private-folder-transport.d.ts +0 -2
  101. package/dist/private-folder-transport.d.ts.map +1 -1
  102. package/dist/private-folder-transport.js +17 -16
  103. package/dist/private-folder-transport.js.map +1 -1
  104. package/dist/push-identity-fence.d.ts +116 -3
  105. package/dist/push-identity-fence.d.ts.map +1 -1
  106. package/dist/push-identity-fence.js +625 -62
  107. package/dist/push-identity-fence.js.map +1 -1
  108. package/dist/qmd-reindex.d.ts.map +1 -1
  109. package/dist/qmd-reindex.js +3 -2
  110. package/dist/qmd-reindex.js.map +1 -1
  111. package/dist/s3.d.ts +30 -9
  112. package/dist/s3.d.ts.map +1 -1
  113. package/dist/s3.js +110 -82
  114. package/dist/s3.js.map +1 -1
  115. package/dist/sync/area-ledger-migration.d.ts +17 -0
  116. package/dist/sync/area-ledger-migration.d.ts.map +1 -1
  117. package/dist/sync/area-ledger-migration.js +37 -3
  118. package/dist/sync/area-ledger-migration.js.map +1 -1
  119. package/dist/sync/scattered-delete-burst.d.ts +61 -0
  120. package/dist/sync/scattered-delete-burst.d.ts.map +1 -0
  121. package/dist/sync/scattered-delete-burst.js +111 -0
  122. package/dist/sync/scattered-delete-burst.js.map +1 -0
  123. package/dist/sync/unattended-delete-hold.d.ts +102 -0
  124. package/dist/sync/unattended-delete-hold.d.ts.map +1 -0
  125. package/dist/sync/unattended-delete-hold.js +164 -0
  126. package/dist/sync/unattended-delete-hold.js.map +1 -0
  127. package/dist/sync-core.d.ts +5 -6
  128. package/dist/sync-core.d.ts.map +1 -1
  129. package/dist/sync-core.js +5 -6
  130. package/dist/sync-core.js.map +1 -1
  131. package/dist/types.d.ts +13 -2
  132. package/dist/types.d.ts.map +1 -1
  133. package/dist/vault-client.d.ts +6 -0
  134. package/dist/vault-client.d.ts.map +1 -1
  135. package/dist/vault-client.js +53 -8
  136. package/dist/vault-client.js.map +1 -1
  137. package/dist/vault-key-grammar.d.ts +44 -0
  138. package/dist/vault-key-grammar.d.ts.map +1 -0
  139. package/dist/vault-key-grammar.js +158 -0
  140. package/dist/vault-key-grammar.js.map +1 -0
  141. package/dist/watcher.d.ts.map +1 -1
  142. package/dist/watcher.js +4 -1
  143. package/dist/watcher.js.map +1 -1
  144. package/dist/windows-extended-path.d.ts +22 -0
  145. package/dist/windows-extended-path.d.ts.map +1 -0
  146. package/dist/windows-extended-path.js +55 -0
  147. package/dist/windows-extended-path.js.map +1 -0
  148. package/package.json +1 -1
@@ -10,37 +10,19 @@
10
10
  * other direction.
11
11
  *
12
12
  * Contract:
13
- * - A machine switch marker is written whenever the personal journal bind sees
14
- * a different person (or an interrupted or unproven switch). It carries a new
15
- * id each time.
16
- * - One record per sync scope (journal slug) names the person who last pushed
17
- * it: the personal vault uid, or the Cognito sub for a company vault, plus
18
- * the Cognito sub when known, and the id of the last machine switch the scope
19
- * has seen.
20
- * - A scope is fenced for the pushing person when: its record names someone
21
- * else; its record is unreadable; a machine switch happened since the scope
22
- * last pushed (this covers every company scope, not only the personal one);
23
- * or the scope has no record and this machine shows any sign of another
24
- * person (a switch marker, another scope's record naming a different person,
25
- * or the caller's evidence from the personal journal identity state). So
26
- * deleting the fence state does not lift a fence on a machine that more than
27
- * one person has used.
28
- * - A company scope is also fenced when this machine's personal sync belongs
29
- * to someone (hq-cloud#1028 owner record) and the pusher cannot be proven to
30
- * be that person: the runner records each signed-in person's Cognito sub and
31
- * personal vault uid before any push, so a company push that runs before the
32
- * new person's personal sync still fails closed.
33
- * - A push with no identity at all is held whenever this machine has seen a
34
- * switch (see share.ts); it cannot be released, and the next push with an
35
- * identity is admitted normally.
36
- * - While a scope is fenced, its push uploads nothing and deletes nothing
37
- * remotely. Local files are never touched. This does not depend on file
38
- * timestamps, so clock skew, future modification times and coarse
39
- * filesystem timestamps (FAT, exFAT) cannot let a file through. The cost is
40
- * that the signed-in person's own new files also wait until they decide.
41
- * - A fence ends only by an explicit release from the person it was written
42
- * for ({@link releasePushIdentityFence}). A single-person machine never sees
43
- * the fence.
13
+ * - Unknown legacy ownership, corrupt state, and real switches fail closed.
14
+ * - Company uploads require a sub-to-person mapping matching the personal
15
+ * owner, unless that scope was explicitly released for the observed owner.
16
+ * - Automatic release needs a readable marker whose preserved origin matches
17
+ * the signed-in identity and no conflicting journal or scope evidence.
18
+ * A pre-fix marker has no origin proof and requires explicit release.
19
+ * - A corrupt marker or scope record keeps uploads held. Recovery may replace
20
+ * a corrupt record only with an upload hold, and that hold never
21
+ * auto-releases. A scope is cleared only when that scope's own readable
22
+ * record proves the signed-in person. Another scope is not evidence.
23
+ * A sign-in by someone else after that scope last synced keeps the hold.
24
+ * - Fenced uploads and remote deletes stay blocked; local files are untouched.
25
+ * - Pull quarantine and its bulk-asymmetry guard remain independent.
44
26
  */
45
27
  import * as crypto from "crypto";
46
28
  import * as fs from "fs";
@@ -50,20 +32,23 @@ const RECORD_FORMAT = "hq-push-identity@2";
50
32
  const MACHINE_FORMAT = "hq-push-identity-machine@1";
51
33
  const PERSON_FORMAT = "hq-push-identity-person@1";
52
34
  const HELD_SAMPLE_CAP = 50;
35
+ /** Command that restores a held upload, including a corrupt identity file. */
36
+ export const PUSH_IDENTITY_RELEASE_COMMAND = "hq sync release-held";
53
37
  /**
54
38
  * Record that Cognito `sub` signs in as personal vault `personalUid` on this
55
39
  * machine. The sync runner writes it before any scope pushes; a personal push
56
40
  * writes it too. Company pushes use it to check the pusher against the
57
41
  * personal vault owner.
42
+ *
43
+ * `sinceMs` is written on every sign-in, including when the mapping is
44
+ * unchanged. A later sign-in would otherwise keep the old file time, and
45
+ * recovery could not tell it happened after the last proven sync. Old files
46
+ * without `sinceMs` still parse.
58
47
  */
59
- export function recordSignedInPerson(stateDir, sub, personalUid) {
48
+ export function recordSignedInPerson(stateDir, sub, personalUid, now = Date.now()) {
60
49
  if (!sub || !personalUid)
61
50
  return;
62
- const filePath = personPath(stateDir, sub);
63
- const current = readPerson(filePath);
64
- if (current.kind === "ok" && current.value === personalUid)
65
- return;
66
- writeJsonAtomic(filePath, { format: PERSON_FORMAT, sub, personalUid });
51
+ writeJsonAtomic(personPath(stateDir, sub), { format: PERSON_FORMAT, sub, personalUid, sinceMs: now });
67
52
  }
68
53
  /** True when a switch marker exists (or cannot be read) on this machine. */
69
54
  export function machineIdentitySwitchRecorded(stateDir) {
@@ -71,16 +56,237 @@ export function machineIdentitySwitchRecorded(stateDir) {
71
56
  }
72
57
  /**
73
58
  * Record that a different person signed in on this machine. Every scope is
74
- * fenced on its next push.
59
+ * fenced on its next push. `fromUid` is the personal-vault uid they moved
60
+ * away from; a marker without it is ambiguous and cannot auto-release.
75
61
  */
76
- export function recordMachineIdentitySwitch(stateDir, now = Date.now()) {
62
+ export function recordMachineIdentitySwitch(stateDir, now = Date.now(), fromUid) {
77
63
  const marker = {
78
64
  format: MACHINE_FORMAT,
79
65
  id: `${now}-${process.pid}-${crypto.randomBytes(4).toString("hex")}`,
80
66
  sinceMs: now,
67
+ ...(fromUid ? { fromUid } : {}),
81
68
  };
82
69
  writeJsonAtomic(machinePath(stateDir), marker);
83
70
  }
71
+ /** Resume an interrupted bind without discarding its existing switch id.
72
+ * The pending journal supplies origin proof only when no marker exists.
73
+ * Existing markers, including legacy and corrupt ones, are never relabelled.
74
+ */
75
+ export function resumeMachineIdentitySwitch(stateDir, fromUid) {
76
+ const marker = readMachine(stateDir);
77
+ if (marker.kind === "unreadable")
78
+ return;
79
+ if (marker.kind === "none") {
80
+ recordMachineIdentitySwitch(stateDir, Date.now(), fromUid);
81
+ }
82
+ }
83
+ /**
84
+ * State of the sign-in mapping file for `sub`: `none` only when the file is
85
+ * truly missing, `unreadable` when it exists but is corrupt or cannot be read.
86
+ */
87
+ export function signedInPersonMappingState(stateDir, sub) {
88
+ if (!sub)
89
+ return "none";
90
+ return readPerson(personPath(stateDir, sub)).kind;
91
+ }
92
+ /** Personal-vault uid recorded for Cognito `sub`, when the mapping is readable. */
93
+ export function signedInPersonalUid(stateDir, sub) {
94
+ if (!sub)
95
+ return undefined;
96
+ const mapped = readPerson(personPath(stateDir, sub));
97
+ return mapped.kind === "ok" ? mapped.value : undefined;
98
+ }
99
+ /**
100
+ * True when this machine has positive evidence that someone other than the
101
+ * signed-in person used it, or the available state cannot safely prove
102
+ * continuity. Unknown legacy markers and corrupt state fail closed.
103
+ */
104
+ export function holdIsProvenDifferentPerson(stateDir, options) {
105
+ if (options.otherIdentityEvidence === true)
106
+ return true;
107
+ const marker = readMachine(stateDir);
108
+ const signedIn = options.personalUid;
109
+ if (marker.kind === "unreadable" || (marker.kind === "ok" && !marker.value.fromUid))
110
+ return true;
111
+ if (marker.kind === "ok" && marker.value.fromUid && (!signedIn || marker.value.fromUid !== signedIn))
112
+ return true;
113
+ const machineOwnerUid = options.machineOwnerUid;
114
+ if (machineOwnerUid === "unreadable")
115
+ return true;
116
+ if (typeof machineOwnerUid !== "string")
117
+ return false;
118
+ if (signedIn && signedIn !== machineOwnerUid)
119
+ return true;
120
+ if (options.sub) {
121
+ const mapped = readPerson(personPath(stateDir, options.sub));
122
+ if (mapped.kind === "ok" && mapped.value !== machineOwnerUid)
123
+ return true;
124
+ if (mapped.kind !== "ok")
125
+ return true;
126
+ }
127
+ else if (otherSubOwnsPersonalVault(stateDir, machineOwnerUid, undefined)) {
128
+ return true;
129
+ }
130
+ return false;
131
+ }
132
+ /**
133
+ * Release only a proven same-person marker and its matching scope fences.
134
+ * Legacy and corrupt markers never auto-release. Returns released scope slugs.
135
+ */
136
+ export function releaseUnprovenPushIdentityHold(stateDir, identities) {
137
+ const marker = readMachine(stateDir);
138
+ if (marker.kind !== "ok" || !marker.value.fromUid || !identities.includes(marker.value.fromUid)) {
139
+ return { released: [], clearedMarker: false };
140
+ }
141
+ // Only a marker with an affirmative matching origin can auto-release.
142
+ // A legacy marker carries no such proof, even after bind writes a new owner.
143
+ const records = recordFiles(stateDir).map((file) => parseRecord(file));
144
+ if (records.some((record) => record.kind !== "ok" ||
145
+ !identities.includes(record.value.owner) ||
146
+ (record.value.fence && (record.value.machineSwitchId !== marker.value.id ||
147
+ !record.value.fenceOrigin || !identities.includes(record.value.fenceOrigin))))) {
148
+ return { released: [], clearedMarker: false };
149
+ }
150
+ const released = releasePushIdentityFences(stateDir, identities);
151
+ let clearedMarker = false;
152
+ try {
153
+ fs.rmSync(machinePath(stateDir), { force: true });
154
+ clearedMarker = true;
155
+ }
156
+ catch {
157
+ clearedMarker = false;
158
+ }
159
+ return { released, clearedMarker };
160
+ }
161
+ /**
162
+ * True when the machine marker is unreadable, or when `journalSlug`'s scope
163
+ * record is. With no slug, true when any scope record is unreadable.
164
+ * Read-only: a corrupt file is not repaired here.
165
+ */
166
+ export function corruptPushIdentityHold(stateDir, journalSlug) {
167
+ if (readMachine(stateDir).kind === "unreadable")
168
+ return true;
169
+ if (journalSlug)
170
+ return readRecord(stateDir, journalSlug).kind === "unreadable";
171
+ return recordFiles(stateDir).some((filePath) => parseRecord(filePath).kind === "unreadable");
172
+ }
173
+ /**
174
+ * The signed-in person asks to restore an unreadable identity marker or scope
175
+ * record. `identities` are the session's Cognito sub and personal uid.
176
+ *
177
+ * A corrupt scope record is restored with an upload hold. Its bytes are not
178
+ * an owner, and no other scope is used to clear it. A scope is cleared only
179
+ * when that scope's own readable record names the signed-in person. A corrupt
180
+ * marker is replaced with a hold that has no origin, so it never auto-releases
181
+ * and does not invent who switched. Readable history that names nobody, names
182
+ * someone else, or names more than one person is refused and left unchanged.
183
+ * Someone else signing in after the last proven sync counts as more than one
184
+ * person, even when they never synced. `confirmUnproven` restores those
185
+ * refusals as a hold and does not clear a scope. It does not accept a
186
+ * different person.
187
+ */
188
+ export function recoverCorruptPushIdentity(stateDir, identities, options = {}) {
189
+ const none = {
190
+ recovered: false, reason: "none", clearedMarker: false, clearedScopeFiles: 0, heldScopeFiles: 0,
191
+ };
192
+ const marker = readMachine(stateDir);
193
+ const slugs = recoverySlugs(stateDir, options);
194
+ const corruptSlugs = slugs.filter((slug) => readRecord(stateDir, slug).kind === "unreadable");
195
+ const markerCorrupt = marker.kind === "unreadable";
196
+ if (!markerCorrupt && corruptSlugs.length === 0)
197
+ return none;
198
+ const proof = proveSignedInPerson(stateDir, identities, options.personalOwnerUid);
199
+ // Check sign-in records before any quarantine or restamp. A refusal writes
200
+ // nothing, so a later person's unsynced edits cannot upload.
201
+ const keepHold = proof !== "proven";
202
+ if (keepHold && (options.confirmUnproven !== true || proof === "different-person")) {
203
+ return { recovered: false, reason: proof, clearedMarker: false, clearedScopeFiles: 0, heldScopeFiles: 0 };
204
+ }
205
+ const allowed = identities.filter((identity) => identity.length > 0);
206
+ let clearedScopeFiles = 0;
207
+ if (markerCorrupt) {
208
+ // Quarantine keeps the corrupt bytes. The replacement has no fromUid, so
209
+ // auto-release will not drop it and the lost switch is not invented.
210
+ if (!quarantineUnreadable(machinePath(stateDir))) {
211
+ return { recovered: false, reason: "unproven", clearedMarker: false, clearedScopeFiles: 0, heldScopeFiles: 0 };
212
+ }
213
+ recordMachineIdentitySwitch(stateDir, Date.now());
214
+ const restored = readMachine(stateDir);
215
+ if (restored.kind !== "ok" || restored.value.fromUid) {
216
+ return { recovered: false, reason: "unproven", clearedMarker: false, clearedScopeFiles: 0, heldScopeFiles: 0 };
217
+ }
218
+ // Only a proven same-person scope is cleared. Any other recovery leaves
219
+ // the old switch id in place, so the next push stays held.
220
+ if (!keepHold) {
221
+ for (const filePath of recordFiles(stateDir)) {
222
+ const read = parseRecord(filePath);
223
+ if (read.kind !== "ok")
224
+ continue;
225
+ if (options.limitToSlugs && !slugs.includes(read.value.slug))
226
+ continue;
227
+ if (!identitiesOwn(stateDir, read.value.owner, read.value.sub, allowed))
228
+ continue;
229
+ if (read.value.machineSwitchId === restored.value.id)
230
+ continue;
231
+ writeRecord(stateDir, { ...read.value, machineSwitchId: restored.value.id });
232
+ if (!read.value.fence)
233
+ clearedScopeFiles += 1;
234
+ }
235
+ }
236
+ }
237
+ const machineNow = readMachine(stateDir);
238
+ let heldScopeFiles = 0;
239
+ for (const slug of corruptSlugs) {
240
+ const owner = holdOwnerForSlug(slug, allowed);
241
+ if (!owner)
242
+ continue;
243
+ const sub = subForRecoveredScope(allowed, owner);
244
+ // No fenceOrigin: releaseUnprovenPushIdentityHold refuses a fence that
245
+ // lacks one, so this hold cannot auto-release.
246
+ writeRecord(stateDir, {
247
+ format: RECORD_FORMAT,
248
+ slug,
249
+ owner,
250
+ ...(sub ? { sub } : {}),
251
+ ...(machineNow.kind === "ok" ? { machineSwitchId: machineNow.value.id } : {}),
252
+ fence: { uid: owner, sinceMs: Date.now() },
253
+ requiresHeldList: true,
254
+ });
255
+ heldScopeFiles += 1;
256
+ }
257
+ if (!markerCorrupt && heldScopeFiles === 0) {
258
+ return { recovered: false, reason: "unproven", clearedMarker: false, clearedScopeFiles: 0, heldScopeFiles: 0 };
259
+ }
260
+ return {
261
+ recovered: true,
262
+ clearedMarker: false,
263
+ clearedScopeFiles,
264
+ heldScopeFiles,
265
+ ...(keepHold ? { uploadsStayHeld: true } : {}),
266
+ };
267
+ }
268
+ /** Plain-language hold line. Names `hq sync release-held` for both causes. */
269
+ export function pushIdentityHoldMessage(count, sample, reason) {
270
+ const shown = sample.slice(0, 20);
271
+ const list = shown.join(", ");
272
+ const more = count > shown.length ? ` and ${count - shown.length} more` : "";
273
+ const names = list ? `: ${list}${more}` : "";
274
+ if (reason === "corrupt-identity") {
275
+ if (count <= 0) {
276
+ return "Uploads from this computer are held because the identity file on this computer can't be read. Nothing was uploaded. Run `hq sync release-held` to restore it from the account you are signed in as.";
277
+ }
278
+ const noun = count === 1 ? "file is" : "files are";
279
+ const stay = count === 1 ? "It stays" : "They stay";
280
+ return `${count} ${noun} held because the identity file on this computer can't be read${names}. ${stay} on this computer. Nothing was uploaded. Run \`hq sync release-held\` to restore it from the account you are signed in as.`;
281
+ }
282
+ if (count <= 0) {
283
+ return "Uploads from this computer are held because someone else was signed in here. Nothing was uploaded. If the files are yours, run `hq sync release-held`.";
284
+ }
285
+ const noun = count === 1 ? "file is" : "files are";
286
+ const stay = count === 1 ? "It stays" : "They stay";
287
+ const action = `If ${count === 1 ? "it is" : "they are"} yours, run \`hq sync release-held\`.`;
288
+ return `${count} ${noun} held because someone else was signed in on this computer${names}. ${stay} on this computer. ${action}`;
289
+ }
84
290
  /**
85
291
  * Admit `uid` as the pusher for `journalSlug` and return the fence that
86
292
  * applies to this push, if any. Fails closed on unreadable state.
@@ -88,11 +294,7 @@ export function recordMachineIdentitySwitch(stateDir, now = Date.now()) {
88
294
  export function admitPushIdentity(stateDir, journalSlug, uid, options = {}) {
89
295
  const now = options.now ?? Date.now();
90
296
  const sub = options.sub;
91
- let marker = readMachine(stateDir);
92
- if (marker.kind === "unreadable") {
93
- recordMachineIdentitySwitch(stateDir, now);
94
- marker = readMachine(stateDir);
95
- }
297
+ const marker = readMachine(stateDir);
96
298
  const machine = marker.kind === "ok" ? marker.value : undefined;
97
299
  const personalOwner = options.personalOwnerUid;
98
300
  if (options.personalScope === true && sub)
@@ -100,42 +302,58 @@ export function admitPushIdentity(stateDir, journalSlug, uid, options = {}) {
100
302
  const fenceNow = (previous) => {
101
303
  const fence = { uid, sinceMs: machine?.sinceMs ?? now };
102
304
  const recordSub = sub ?? previous?.sub;
305
+ const origin = previous?.fence ? previous.fenceOrigin : previous?.owner ?? machine?.fromUid ??
306
+ (personalOwner !== "unreadable" ? personalOwner : undefined);
103
307
  writeRecord(stateDir, {
104
308
  format: RECORD_FORMAT,
105
309
  slug: journalSlug,
106
310
  owner: uid,
107
311
  ...(recordSub ? { sub: recordSub } : {}),
108
312
  ...(machine ? { machineSwitchId: machine.id } : {}),
109
- ...(typeof personalOwner === "string" ? { personalOwnerSeen: personalOwner } : {}),
313
+ ...(typeof personalOwner === "string" && personalOwner !== "unreadable" ? { personalOwnerSeen: personalOwner } : {}),
314
+ ...(origin ? { fenceOrigin: origin } : {}),
110
315
  fence,
111
316
  });
112
317
  return fence;
113
318
  };
114
319
  const read = readRecord(stateDir, journalSlug);
115
- // A company pusher must be provably the person this machine's personal sync
116
- // belongs to. When the signed-in person's personal uid is unknown, unreadable
117
- // or different, fence the scope once for this owner state.
320
+ // Corrupt state is never rewritten into permission to upload.
321
+ if (marker.kind === "unreadable" || read.kind === "unreadable") {
322
+ const fence = { uid, sinceMs: now, reason: "corrupt-identity" };
323
+ // A diagnostic receipt, never ownership evidence. Keep the corrupt bytes
324
+ // untouched, but let older list/release callers discover the held scope.
325
+ writeJsonAtomic(corruptHoldPath(stateDir, journalSlug), {
326
+ format: RECORD_FORMAT, slug: journalSlug, owner: uid, fence,
327
+ });
328
+ return fence;
329
+ }
118
330
  if (options.personalScope !== true && typeof personalOwner === "string") {
331
+ if (personalOwner === "unreadable")
332
+ return fenceNow(read.kind === "ok" ? read.value : undefined);
119
333
  const seen = read.kind === "ok" ? read.value.personalOwnerSeen : undefined;
120
334
  if (seen !== personalOwner) {
121
335
  const mapped = sub ? readPerson(personPath(stateDir, sub)) : { kind: "none" };
122
- const proven = personalOwner !== "unreadable" && mapped.kind === "ok" && mapped.value === personalOwner;
123
- if (!proven)
336
+ if (mapped.kind !== "ok" || mapped.value !== personalOwner) {
124
337
  return fenceNow(read.kind === "ok" ? read.value : undefined);
338
+ }
125
339
  }
126
340
  }
127
- if (read.kind === "unreadable")
128
- return fenceNow();
129
341
  if (read.kind === "none") {
130
- if (machine || options.otherIdentityEvidence === true || (sub && anotherPersonPushedHere(stateDir, sub))) {
342
+ if (machine || options.otherIdentityEvidence === true || (sub && anotherPersonPushedHere(stateDir, uid, sub))) {
131
343
  return fenceNow();
132
344
  }
133
345
  writeRecord(stateDir, { format: RECORD_FORMAT, slug: journalSlug, owner: uid, ...(sub ? { sub } : {}) });
134
346
  return undefined;
135
347
  }
136
- const record = read.value;
137
- if (record.owner !== uid || (sub && record.sub && record.sub !== sub))
138
- return fenceNow();
348
+ let record = read.value;
349
+ if (record.owner !== uid || (sub && record.sub && record.sub !== sub)) {
350
+ if (!samePushIdentity(stateDir, record.owner, record.sub, uid, sub))
351
+ return fenceNow(record);
352
+ record = { ...record, owner: uid, ...(sub ? { sub } : {}),
353
+ ...(record.fence ? { fence: { ...record.fence, uid } } : {}),
354
+ };
355
+ writeRecord(stateDir, record);
356
+ }
139
357
  if (machine && record.machineSwitchId !== machine.id)
140
358
  return fenceNow(record);
141
359
  if (sub && !record.sub)
@@ -166,6 +384,24 @@ export function listPushIdentityFences(stateDir) {
166
384
  ...(read.value.held ? { held: read.value.held } : {}),
167
385
  });
168
386
  }
387
+ const dir = path.join(stateDir, "push-identity");
388
+ if (fs.existsSync(dir)) {
389
+ for (const name of fs.readdirSync(dir)) {
390
+ if (!name.startsWith("corrupt-hold-") || !name.endsWith(".json"))
391
+ continue;
392
+ const read = parseRecord(path.join(dir, name));
393
+ if (read.kind !== "ok" || !read.value.fence)
394
+ continue;
395
+ if (!corruptPushIdentityHold(stateDir, read.value.slug))
396
+ continue;
397
+ const listing = { slug: read.value.slug, uid: read.value.owner, sinceMs: read.value.fence.sinceMs };
398
+ const index = out.findIndex((item) => item.slug === listing.slug);
399
+ if (index === -1)
400
+ out.push(listing);
401
+ else
402
+ out[index] = listing;
403
+ }
404
+ }
169
405
  return out.sort((a, b) => a.slug.localeCompare(b.slug));
170
406
  }
171
407
  /**
@@ -173,9 +409,17 @@ export function listPushIdentityFences(stateDir) {
173
409
  * push. Only the person the fence was written for can release it.
174
410
  */
175
411
  export function releasePushIdentityFence(stateDir, journalSlug, uid) {
412
+ // Recovery needs the complete signed-in identity set. Never claim a
413
+ // release while corrupt state would still block the next push.
414
+ if (corruptPushIdentityHold(stateDir, journalSlug))
415
+ return false;
176
416
  const read = readRecord(stateDir, journalSlug);
177
417
  if (read.kind !== "ok" || read.value.owner !== uid || read.value.fence?.uid !== uid)
178
418
  return false;
419
+ // Restored corrupt ownership needs a fresh held-file list before the
420
+ // confirmation can authorize uploads (the hq-cli #2443 contract).
421
+ if (read.value.requiresHeldList && !read.value.held)
422
+ return false;
179
423
  const released = {
180
424
  format: RECORD_FORMAT,
181
425
  slug: read.value.slug,
@@ -291,23 +535,132 @@ export function releasePushIdentityFences(stateDir, identities, slugs) {
291
535
  const allowed = new Set(identities.filter((identity) => identity.length > 0));
292
536
  const only = slugs ? new Set(slugs) : undefined;
293
537
  const released = [];
294
- for (const listing of listPushIdentityFences(stateDir)) {
538
+ const listings = listPushIdentityFences(stateDir);
539
+ const selected = listings.filter((listing) => allowed.has(listing.uid) && (!only || only.has(listing.slug)));
540
+ const corrupt = selected.filter((listing) => corruptPushIdentityHold(stateDir, listing.slug));
541
+ const restoredSlugs = new Set(corrupt.map((listing) => listing.slug));
542
+ if (corrupt.length > 0) {
543
+ // Explicit release is the compatibility entry point for pre-#2443 CLIs.
544
+ // The receipt above supplies a slug only, never proof of ownership.
545
+ const recovery = recoverCorruptPushIdentity(stateDir, identities, {
546
+ slugs: corrupt.map((listing) => listing.slug), limitToSlugs: true,
547
+ confirmUnproven: true,
548
+ });
549
+ if (!recovery.recovered)
550
+ return [];
551
+ if (recovery.uploadsStayHeld) {
552
+ // Materialize the selected holds, including a scope with no record.
553
+ // This call repairs state only; a later confirmation releases uploads.
554
+ for (const listing of corrupt) {
555
+ admitPushIdentity(stateDir, listing.slug, listing.uid);
556
+ const read = readRecord(stateDir, listing.slug);
557
+ if (read.kind === "ok" && read.value.fence) {
558
+ writeRecord(stateDir, { ...read.value, held: undefined, requiresHeldList: true });
559
+ }
560
+ }
561
+ return [];
562
+ }
563
+ for (const listing of corrupt) {
564
+ const record = readRecord(stateDir, listing.slug);
565
+ if (record.kind === "ok" && record.value.owner === listing.uid && !record.value.fence &&
566
+ !corruptPushIdentityHold(stateDir, listing.slug))
567
+ released.push(listing.slug);
568
+ }
569
+ }
570
+ for (const listing of listings) {
295
571
  if (!allowed.has(listing.uid))
296
572
  continue;
297
573
  if (only && !only.has(listing.slug))
298
574
  continue;
575
+ if (restoredSlugs.has(listing.slug))
576
+ continue;
299
577
  if (releasePushIdentityFence(stateDir, listing.slug, listing.uid))
300
578
  released.push(listing.slug);
301
579
  }
302
580
  return released;
303
581
  }
304
- /** True when any scope's record on this machine names a different person, or cannot be read. */
305
- function anotherPersonPushedHere(stateDir, sub) {
582
+ /** True when any readable scope record names a person other than `uid` / `sub`. */
583
+ function anotherPersonPushedHere(stateDir, uid, sub) {
306
584
  for (const filePath of recordFiles(stateDir)) {
307
585
  const read = parseRecord(filePath);
308
586
  if (read.kind === "unreadable")
309
587
  return true;
310
- if (read.kind === "ok" && read.value.sub && read.value.sub !== sub)
588
+ if (read.kind !== "ok")
589
+ continue;
590
+ if (samePushIdentity(stateDir, read.value.owner, read.value.sub, uid, sub))
591
+ continue;
592
+ return true;
593
+ }
594
+ return false;
595
+ }
596
+ /**
597
+ * True when `uid` is the same person as the recorded owner. Owners that differ
598
+ * as strings are the same person when both resolve to one personal-vault uid.
599
+ * A sub change is admitted only when both subs map to the same personal uid.
600
+ */
601
+ function samePushIdentity(stateDir, recordOwner, recordSub, uid, sub) {
602
+ if (recordOwner === uid) {
603
+ if (!sub || !recordSub || recordSub === sub)
604
+ return true;
605
+ const recorded = personalUidFor(stateDir, recordSub);
606
+ const incoming = personalUidFor(stateDir, sub);
607
+ return recorded !== undefined && recorded === incoming;
608
+ }
609
+ const recorded = personalUidFor(stateDir, recordOwner);
610
+ const incoming = personalUidFor(stateDir, uid);
611
+ return recorded !== undefined && recorded === incoming;
612
+ }
613
+ function personalUidFor(stateDir, identity) {
614
+ if (!identity)
615
+ return undefined;
616
+ if (identity.startsWith("prs_"))
617
+ return identity;
618
+ return signedInPersonalUid(stateDir, identity);
619
+ }
620
+ function readPersonRecord(filePath) {
621
+ const raw = readText(filePath);
622
+ if (raw.kind !== "ok")
623
+ return raw;
624
+ try {
625
+ const parsed = JSON.parse(raw.value);
626
+ if (parsed?.format !== PERSON_FORMAT ||
627
+ typeof parsed.sub !== "string" ||
628
+ !parsed.sub ||
629
+ typeof parsed.personalUid !== "string" ||
630
+ !parsed.personalUid ||
631
+ (parsed.sinceMs !== undefined && typeof parsed.sinceMs !== "number")) {
632
+ return { kind: "unreadable" };
633
+ }
634
+ return {
635
+ kind: "ok",
636
+ value: {
637
+ sub: parsed.sub,
638
+ personalUid: parsed.personalUid,
639
+ ...(typeof parsed.sinceMs === "number" ? { sinceMs: parsed.sinceMs } : {}),
640
+ },
641
+ };
642
+ }
643
+ catch {
644
+ return { kind: "unreadable" };
645
+ }
646
+ }
647
+ /** True when a different Cognito sub is already mapped to `personalUid`. */
648
+ function otherSubOwnsPersonalVault(stateDir, personalUid, sub) {
649
+ const dir = path.join(stateDir, "push-identity");
650
+ let names;
651
+ try {
652
+ names = fs.readdirSync(dir);
653
+ }
654
+ catch {
655
+ return false;
656
+ }
657
+ for (const name of names) {
658
+ if (!name.startsWith("person-") || !name.endsWith(".json"))
659
+ continue;
660
+ const record = readPersonRecord(path.join(dir, name));
661
+ if (record.kind !== "ok")
662
+ continue;
663
+ if (record.value.personalUid === personalUid && record.value.sub !== sub)
311
664
  return true;
312
665
  }
313
666
  return false;
@@ -353,6 +706,10 @@ function recordPath(stateDir, journalSlug) {
353
706
  const id = crypto.createHash("sha256").update(journalSlug).digest("hex").slice(0, 32);
354
707
  return path.join(stateDir, "push-identity", `scope-${id}.json`);
355
708
  }
709
+ function corruptHoldPath(stateDir, journalSlug) {
710
+ const id = crypto.createHash("sha256").update(journalSlug).digest("hex").slice(0, 32);
711
+ return path.join(stateDir, "push-identity", `corrupt-hold-${id}.json`);
712
+ }
356
713
  function readMachine(stateDir) {
357
714
  const raw = readText(machinePath(stateDir));
358
715
  if (raw.kind !== "ok")
@@ -362,7 +719,18 @@ function readMachine(stateDir) {
362
719
  if (parsed?.format !== MACHINE_FORMAT || typeof parsed.id !== "string" || typeof parsed.sinceMs !== "number") {
363
720
  return { kind: "unreadable" };
364
721
  }
365
- return { kind: "ok", value: { format: MACHINE_FORMAT, id: parsed.id, sinceMs: parsed.sinceMs } };
722
+ if (parsed.fromUid !== undefined && (typeof parsed.fromUid !== "string" || parsed.fromUid.length === 0)) {
723
+ return { kind: "unreadable" };
724
+ }
725
+ return {
726
+ kind: "ok",
727
+ value: {
728
+ format: MACHINE_FORMAT,
729
+ id: parsed.id,
730
+ sinceMs: parsed.sinceMs,
731
+ ...(typeof parsed.fromUid === "string" ? { fromUid: parsed.fromUid } : {}),
732
+ },
733
+ };
366
734
  }
367
735
  catch {
368
736
  return { kind: "unreadable" };
@@ -387,12 +755,14 @@ function parseRecord(filePath) {
387
755
  typeof parsed.owner !== "string" ||
388
756
  !parsed.owner ||
389
757
  (parsed.sub !== undefined && typeof parsed.sub !== "string") ||
758
+ (parsed.requiresHeldList !== undefined && typeof parsed.requiresHeldList !== "boolean") ||
759
+ (parsed.fenceOrigin !== undefined && (typeof parsed.fenceOrigin !== "string" || !parsed.fenceOrigin)) ||
390
760
  (parsed.machineSwitchId !== undefined && typeof parsed.machineSwitchId !== "string") ||
391
761
  (parsed.personalOwnerSeen !== undefined && typeof parsed.personalOwnerSeen !== "string")) {
392
762
  return { kind: "unreadable" };
393
763
  }
394
764
  const fence = parsed.fence;
395
- if (fence !== undefined && (typeof fence?.uid !== "string" || typeof fence.sinceMs !== "number")) {
765
+ if (fence !== undefined && (typeof fence?.uid !== "string" || fence.uid !== parsed.owner || typeof fence.sinceMs !== "number")) {
396
766
  return { kind: "unreadable" };
397
767
  }
398
768
  return { kind: "ok", value: parsed };
@@ -414,6 +784,199 @@ function readText(filePath) {
414
784
  function writeRecord(stateDir, record) {
415
785
  writeJsonAtomic(recordPath(stateDir, record.slug), record);
416
786
  }
787
+ const JOURNAL_FILE_PREFIX = "sync-journal.";
788
+ const JOURNAL_FILE_SUFFIX = ".json";
789
+ function recoverySlugs(stateDir, options) {
790
+ const slugs = new Set(options.slugs ?? []);
791
+ if (options.limitToSlugs === true)
792
+ return [...slugs];
793
+ let names = [];
794
+ try {
795
+ names = fs.readdirSync(stateDir);
796
+ }
797
+ catch {
798
+ names = [];
799
+ }
800
+ for (const name of names) {
801
+ if (!name.startsWith(JOURNAL_FILE_PREFIX) || !name.endsWith(JOURNAL_FILE_SUFFIX))
802
+ continue;
803
+ const slug = name.slice(JOURNAL_FILE_PREFIX.length, name.length - JOURNAL_FILE_SUFFIX.length);
804
+ if (slug)
805
+ slugs.add(slug);
806
+ }
807
+ return [...slugs];
808
+ }
809
+ /**
810
+ * True when someone other than the signed-in person signed in after the last
811
+ * proven sync, or that time cannot be proven. No person file is not another
812
+ * person. Two subs that map to the signed-in personal uid are one person.
813
+ * An unreadable person file fails closed: it could hide a later sign-in.
814
+ * The last proven sync is the newest modification time of an unfenced scope
815
+ * record this person owns.
816
+ */
817
+ function laterOtherPersonSignIn(stateDir, identities) {
818
+ const dir = path.join(stateDir, "push-identity");
819
+ let names;
820
+ try {
821
+ names = fs.readdirSync(dir);
822
+ }
823
+ catch (error) {
824
+ if (error.code === "ENOENT")
825
+ return false;
826
+ return true;
827
+ }
828
+ const personFiles = names.filter((name) => name.startsWith("person-") && name.endsWith(".json"));
829
+ if (personFiles.length === 0)
830
+ return false;
831
+ let provenMs;
832
+ for (const filePath of recordFiles(stateDir)) {
833
+ const read = parseRecord(filePath);
834
+ if (read.kind !== "ok" || read.value.fence)
835
+ continue;
836
+ if (!identitiesOwn(stateDir, read.value.owner, read.value.sub, identities))
837
+ continue;
838
+ let mtimeMs;
839
+ try {
840
+ mtimeMs = fs.statSync(filePath).mtimeMs;
841
+ }
842
+ catch {
843
+ return true;
844
+ }
845
+ if (provenMs === undefined || mtimeMs > provenMs)
846
+ provenMs = mtimeMs;
847
+ }
848
+ for (const name of personFiles) {
849
+ const record = readPersonRecord(path.join(dir, name));
850
+ if (record.kind === "none")
851
+ continue;
852
+ if (record.kind !== "ok")
853
+ return true;
854
+ if (sameSignedInPerson(stateDir, record.value, identities))
855
+ continue;
856
+ if (typeof record.value.sinceMs !== "number")
857
+ return true;
858
+ if (provenMs === undefined || record.value.sinceMs > provenMs)
859
+ return true;
860
+ }
861
+ return false;
862
+ }
863
+ function sameSignedInPerson(stateDir, record, identities) {
864
+ if (identities.includes(record.sub) || identities.includes(record.personalUid))
865
+ return true;
866
+ for (const identity of identities) {
867
+ if (identity.startsWith("prs_") || identity.startsWith("agt_")) {
868
+ if (identity === record.personalUid)
869
+ return true;
870
+ continue;
871
+ }
872
+ const mapped = signedInPersonalUid(stateDir, identity);
873
+ if (mapped !== undefined && mapped === record.personalUid)
874
+ return true;
875
+ }
876
+ return false;
877
+ }
878
+ function proveSignedInPerson(stateDir, identities, personalOwnerUid) {
879
+ const allowed = identities.filter((identity) => identity.length > 0);
880
+ if (allowed.length === 0)
881
+ return "unproven";
882
+ let affirmative = false;
883
+ let contradiction = false;
884
+ const companyOwners = new Set();
885
+ const personalUids = new Set();
886
+ const noteOwner = (owner) => {
887
+ if (!owner)
888
+ return;
889
+ if (owner.startsWith("prs_") || owner.startsWith("agt_"))
890
+ personalUids.add(owner);
891
+ else
892
+ companyOwners.add(owner);
893
+ };
894
+ const note = (owned) => {
895
+ if (owned)
896
+ affirmative = true;
897
+ else
898
+ contradiction = true;
899
+ };
900
+ for (const filePath of recordFiles(stateDir)) {
901
+ const read = parseRecord(filePath);
902
+ if (read.kind !== "ok")
903
+ continue;
904
+ noteOwner(read.value.owner);
905
+ noteOwner(read.value.sub);
906
+ note(identitiesOwn(stateDir, read.value.owner, read.value.sub, allowed));
907
+ }
908
+ const marker = readMachine(stateDir);
909
+ if (marker.kind === "ok" && marker.value.fromUid) {
910
+ noteOwner(marker.value.fromUid);
911
+ note(allowed.includes(marker.value.fromUid));
912
+ }
913
+ if (typeof personalOwnerUid === "string" && personalOwnerUid !== "unreadable" && personalOwnerUid.length > 0) {
914
+ noteOwner(personalOwnerUid);
915
+ note(identitiesOwn(stateDir, personalOwnerUid, undefined, allowed));
916
+ }
917
+ const companyPeople = new Set();
918
+ for (const owner of companyOwners) {
919
+ const mapped = personalUidFor(stateDir, owner);
920
+ companyPeople.add(mapped && (mapped.startsWith("prs_") || mapped.startsWith("agt_")) ? mapped : owner);
921
+ }
922
+ // Two company identities, or two personal uids, means this computer's
923
+ // history names more than one person. One sub plus that account's personal
924
+ // uid, with no mapping that says otherwise, is one person.
925
+ if (personalUids.size > 1 || companyPeople.size > 1)
926
+ return "several-people";
927
+ if (personalUids.size === 1 && companyPeople.size === 1) {
928
+ const company = [...companyPeople][0];
929
+ const personal = [...personalUids][0];
930
+ const mapped = personalUidFor(stateDir, company);
931
+ if (company !== personal && mapped && mapped !== personal)
932
+ return "several-people";
933
+ }
934
+ if (contradiction)
935
+ return "different-person";
936
+ if (!affirmative)
937
+ return "unproven";
938
+ if (laterOtherPersonSignIn(stateDir, allowed))
939
+ return "several-people";
940
+ return "proven";
941
+ }
942
+ function identitiesOwn(stateDir, owner, sub, identities) {
943
+ if (identities.includes(owner))
944
+ return true;
945
+ if (sub && identities.includes(sub))
946
+ return true;
947
+ return identities.some((identity) => samePushIdentity(stateDir, owner, sub, identity, undefined));
948
+ }
949
+ /**
950
+ * Who a restored hold is written for. Taken from the signed-in session only.
951
+ * Another scope's record is not an owner for this slug. Undefined when the
952
+ * session does not name exactly one owner of the right kind, so the corrupt
953
+ * file is left unchanged instead of assigned.
954
+ */
955
+ function holdOwnerForSlug(slug, identities) {
956
+ const personal = slug === "__hq_personal_vault__" || slug === "personal";
957
+ const matches = identities.filter((identity) => identity.length > 0 && (personal
958
+ ? identity.startsWith("prs_") || identity.startsWith("agt_")
959
+ : !identity.startsWith("prs_") && !identity.startsWith("agt_")));
960
+ return matches.length === 1 ? matches[0] : undefined;
961
+ }
962
+ function subForRecoveredScope(identities, owner) {
963
+ if (!owner.startsWith("prs_") && !owner.startsWith("agt_"))
964
+ return owner;
965
+ const subs = identities.filter((identity) => identity.length > 0 && !identity.startsWith("prs_") && !identity.startsWith("agt_"));
966
+ return subs.length === 1 ? subs[0] : undefined;
967
+ }
968
+ function quarantineUnreadable(filePath) {
969
+ const dest = `${filePath}.unreadable`;
970
+ try {
971
+ if (fs.existsSync(dest))
972
+ fs.rmSync(dest, { force: true });
973
+ fs.renameSync(filePath, dest);
974
+ return !fs.existsSync(filePath);
975
+ }
976
+ catch {
977
+ return false;
978
+ }
979
+ }
417
980
  function writeJsonAtomic(filePath, value) {
418
981
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
419
982
  const tmp = `${filePath}.${process.pid}.tmp`;