@koed-labs/server 0.0.0-stage → 0.11.1

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 (67) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +64 -2
  3. package/bin/koed.js +7 -0
  4. package/package.json +26 -4
  5. package/third-party-notices.json +92 -0
  6. package/vendor/chunk-2XKSVKQA.js +49 -0
  7. package/vendor/chunk-4OO6VAU3.js +259 -0
  8. package/vendor/chunk-53ZFCDHP.js +332 -0
  9. package/vendor/chunk-6JRWGOQG.js +236 -0
  10. package/vendor/chunk-6KS67EQE.js +75 -0
  11. package/vendor/chunk-7EGSY3E4.js +8 -0
  12. package/vendor/chunk-7FSHVVTZ.js +128 -0
  13. package/vendor/chunk-7NOQSX4T.js +14 -0
  14. package/vendor/chunk-7NXKPDF3.js +1586 -0
  15. package/vendor/chunk-ALJUSOF7.js +175 -0
  16. package/vendor/chunk-AVQCUFYQ.js +16 -0
  17. package/vendor/chunk-BGENSONI.js +18 -0
  18. package/vendor/chunk-BTS4ZTF3.js +43 -0
  19. package/vendor/chunk-BUIM2M4R.js +22 -0
  20. package/vendor/chunk-C4V72GXC.js +194 -0
  21. package/vendor/chunk-C5SNDPAP.js +2472 -0
  22. package/vendor/chunk-CHMH4LH5.js +2497 -0
  23. package/vendor/chunk-EA4QDDQA.js +58 -0
  24. package/vendor/chunk-EDPNYIX5.js +5448 -0
  25. package/vendor/chunk-FN3HUUO2.js +1974 -0
  26. package/vendor/chunk-FSNLU46W.js +14548 -0
  27. package/vendor/chunk-FYYRFX4U.js +4423 -0
  28. package/vendor/chunk-GFASBPV2.js +42 -0
  29. package/vendor/chunk-HC76426R.js +48 -0
  30. package/vendor/chunk-IY2HRXOZ.js +99 -0
  31. package/vendor/chunk-JBGD4JLR.js +3779 -0
  32. package/vendor/chunk-JYK6UL6D.js +261 -0
  33. package/vendor/chunk-LRP66XEY.js +13907 -0
  34. package/vendor/chunk-NOU7RHYZ.js +26 -0
  35. package/vendor/chunk-NVTMIAAF.js +113 -0
  36. package/vendor/chunk-O7DW2VAV.js +14 -0
  37. package/vendor/chunk-OCILJ737.js +299 -0
  38. package/vendor/chunk-PL3LWC5C.js +754 -0
  39. package/vendor/chunk-QRKHHWJJ.js +104 -0
  40. package/vendor/chunk-QT24SAW6.js +110 -0
  41. package/vendor/chunk-RCR4XPE3.js +26020 -0
  42. package/vendor/chunk-SHLRINKO.js +73 -0
  43. package/vendor/chunk-SNKWETM5.js +35 -0
  44. package/vendor/chunk-SRKIBFOE.js +242 -0
  45. package/vendor/chunk-T6UB5PNX.js +124 -0
  46. package/vendor/chunk-TG26CZGQ.js +23 -0
  47. package/vendor/chunk-TISYUUEJ.js +188 -0
  48. package/vendor/chunk-TSAYTRX3.js +89 -0
  49. package/vendor/chunk-TVYEB2GN.js +343 -0
  50. package/vendor/chunk-UB6JCVQ3.js +461 -0
  51. package/vendor/chunk-V67IQB7H.js +153 -0
  52. package/vendor/chunk-VGIYSDNU.js +522 -0
  53. package/vendor/chunk-W2HNI6AA.js +75 -0
  54. package/vendor/chunk-W2OJZZ6X.js +20 -0
  55. package/vendor/chunk-WDFERJG3.js +2208 -0
  56. package/vendor/chunk-WPIEF4LY.js +1647 -0
  57. package/vendor/chunk-XIZVLPHZ.js +18 -0
  58. package/vendor/chunk-YZLQZU5E.js +46 -0
  59. package/vendor/chunk-Z5WCAUA6.js +148 -0
  60. package/vendor/chunk-ZIOKV2X6.js +1589 -0
  61. package/vendor/chunk-ZOHNXUDY.js +12501 -0
  62. package/vendor/chunk-ZUDSZGVO.js +11 -0
  63. package/vendor/cli.js +7 -0
  64. package/vendor/component-manifest-catalog.js +9 -0
  65. package/vendor/control-plane.js +28 -0
  66. package/vendor/package.json +1 -0
  67. package/vendor/privacy-service-bootstrap.js +6 -0
@@ -0,0 +1,754 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ resolveActiveIntegrationApiToken
4
+ } from "./chunk-QT24SAW6.js";
5
+ import {
6
+ applyPersistedLocalPorts
7
+ } from "./chunk-TISYUUEJ.js";
8
+ import {
9
+ loadRepoEnv,
10
+ resolveApiUrl
11
+ } from "./chunk-W2HNI6AA.js";
12
+ import {
13
+ readActiveRuntimeState,
14
+ withFileLock
15
+ } from "./chunk-T6UB5PNX.js";
16
+ import "./chunk-7NXKPDF3.js";
17
+ import {
18
+ deriveLocalProjectId,
19
+ fetchBoundedJsonObject,
20
+ hmacProjectValue,
21
+ isLoopbackHostname,
22
+ isPortableGitRemote,
23
+ normalizeGitRemoteUrl,
24
+ normalizeProjectDisplayName,
25
+ normalizeRecordedProjectDirectory,
26
+ repositoryChangeInputSchema,
27
+ repositoryIdentityMatches,
28
+ repositoryIdentitySchema
29
+ } from "./chunk-ZOHNXUDY.js";
30
+ import {
31
+ external_exports
32
+ } from "./chunk-FSNLU46W.js";
33
+ import "./chunk-BTS4ZTF3.js";
34
+
35
+ // packages/koed-server/dist/project-metadata.js
36
+ import { execFile as nodeExecFile } from "node:child_process";
37
+ import { randomUUID } from "node:crypto";
38
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, statSync as statSync2, rmSync } from "node:fs";
39
+ import path, { dirname as dirname2, relative, resolve as resolve2 } from "node:path";
40
+
41
+ // packages/koed-server/dist/git-project-probe.js
42
+ import { execFile } from "node:child_process";
43
+ import { statSync } from "node:fs";
44
+ import { dirname, resolve } from "node:path";
45
+ var createGitProjectProbe = (deps = {}) => {
46
+ const execute = deps.execFile ?? execFile;
47
+ const stat = deps.statSync ?? statSync;
48
+ const now = deps.now ?? Date.now;
49
+ const ttl = deps.ttlMs ?? 2e3;
50
+ const cache = /* @__PURE__ */ new Map();
51
+ const signature = (paths) => JSON.stringify(paths.map((file) => {
52
+ try {
53
+ const value = stat(file);
54
+ return [
55
+ file,
56
+ value.dev,
57
+ value.ino,
58
+ value.size,
59
+ value.mtimeMs,
60
+ value.ctimeMs
61
+ ];
62
+ } catch {
63
+ return [file, null];
64
+ }
65
+ }));
66
+ const command = (cwd, args) => new Promise((done) => {
67
+ const finish = (error, stdout, stderr) => {
68
+ done({
69
+ value: error ? null : String(stdout).trim() || null,
70
+ failed: Boolean(error),
71
+ nonGit: Boolean(error) && /not a git repository/i.test(typeof stderr === "string" ? stderr : "")
72
+ });
73
+ };
74
+ try {
75
+ execute("git", ["-C", cwd, ...args], {
76
+ timeout: 5e3,
77
+ maxBuffer: 1024 * 1024,
78
+ encoding: "utf8"
79
+ }, finish);
80
+ } catch (error) {
81
+ finish(error instanceof Error ? error : new Error("Git execution failed"), "");
82
+ }
83
+ });
84
+ return async (input) => {
85
+ const cwd = resolve(input.cwd);
86
+ const key = JSON.stringify([
87
+ resolve(input.profile),
88
+ cwd,
89
+ input.deviceSalt,
90
+ input.configurationRevision ?? ""
91
+ ]);
92
+ const cached = cache.get(key);
93
+ if (cached && cached.expiresAt > now() && cached.signature === signature(cached.watchedPaths)) {
94
+ return structuredClone(cached.result);
95
+ }
96
+ const result = {
97
+ status: "non_git",
98
+ failedCommands: [],
99
+ root: null,
100
+ remotes: [],
101
+ branch: null,
102
+ headCommit: null,
103
+ commonDir: null,
104
+ gitDir: null
105
+ };
106
+ const root = await command(cwd, ["rev-parse", "--show-toplevel"]);
107
+ if (root.failed) {
108
+ result.status = root.nonGit ? "non_git" : "failed";
109
+ if (!root.nonGit)
110
+ result.failedCommands.push("rev-parse --show-toplevel");
111
+ return result;
112
+ }
113
+ if (!root.value || root.value.includes("\n")) {
114
+ result.status = "ambiguous";
115
+ return result;
116
+ }
117
+ result.root = resolve(root.value);
118
+ result.status = "git";
119
+ const read = async (args) => {
120
+ const observation = await command(result.root, args);
121
+ if (observation.failed) {
122
+ result.failedCommands.push(args.join(" "));
123
+ result.status = "failed";
124
+ }
125
+ return observation.value;
126
+ };
127
+ const rawRemotes = await read(["remote", "-v"]);
128
+ const remotes = /* @__PURE__ */ new Map();
129
+ for (const line of rawRemotes?.split("\n") ?? []) {
130
+ const match = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)$/);
131
+ if (!match) {
132
+ if (result.failedCommands.length === 0)
133
+ result.status = "ambiguous";
134
+ continue;
135
+ }
136
+ const [, name, url] = match;
137
+ remotes.set(`${name}
138
+ ${url}`, normalizeGitRemoteUrl(url, name));
139
+ }
140
+ result.remotes = [...remotes.values()].sort((a, b) => `${a.name}:${a.fingerprint}`.localeCompare(`${b.name}:${b.fingerprint}`));
141
+ result.branch = await read(["branch", "--show-current"]);
142
+ result.headCommit = await read(["rev-parse", "HEAD"]);
143
+ const commonDir = await read(["rev-parse", "--git-common-dir"]);
144
+ const gitDir = await read(["rev-parse", "--git-dir"]);
145
+ result.commonDir = commonDir ? resolve(result.root, commonDir) : null;
146
+ result.gitDir = gitDir ? resolve(result.root, gitDir) : null;
147
+ if (result.status === "git") {
148
+ const watchedPaths = /* @__PURE__ */ new Set();
149
+ for (let parent = cwd; ; parent = dirname(parent)) {
150
+ watchedPaths.add(resolve(parent, ".git"));
151
+ if (dirname(parent) === parent)
152
+ break;
153
+ }
154
+ for (const directory of [result.commonDir, result.gitDir]) {
155
+ if (!directory)
156
+ continue;
157
+ watchedPaths.add(directory);
158
+ for (const file of [
159
+ "config",
160
+ "config.worktree",
161
+ "HEAD",
162
+ "commondir",
163
+ "packed-refs"
164
+ ]) {
165
+ watchedPaths.add(resolve(directory, file));
166
+ }
167
+ if (result.branch)
168
+ watchedPaths.add(resolve(directory, "refs", "heads", result.branch));
169
+ }
170
+ if (cache.size >= 256)
171
+ cache.delete(cache.keys().next().value);
172
+ const paths = [...watchedPaths];
173
+ cache.set(key, {
174
+ result: structuredClone(result),
175
+ watchedPaths: paths,
176
+ signature: signature(paths),
177
+ expiresAt: now() + ttl
178
+ });
179
+ }
180
+ return result;
181
+ };
182
+ };
183
+ var probeGitProject = createGitProjectProbe();
184
+
185
+ // packages/koed-server/dist/repository-identity.js
186
+ var resolveRepositoryIdentity = (input) => {
187
+ const { observation, deviceSalt, checkoutId } = input;
188
+ const base = {
189
+ root: observation.root ?? input.cwd,
190
+ branch: observation.branch,
191
+ checkoutId,
192
+ originatingDeviceId: deviceSalt,
193
+ selectedRemote: null,
194
+ anchorDisplay: null
195
+ };
196
+ const unresolved = (reason, selectedRemote = null) => ({
197
+ ...base,
198
+ kind: "unresolved",
199
+ key: null,
200
+ reason,
201
+ selectedRemote
202
+ });
203
+ if (observation.status === "failed" && (!observation.root || observation.failedCommands.some((command) => !["branch --show-current", "rev-parse HEAD"].includes(command))))
204
+ return unresolved("probe_failed");
205
+ if (observation.status === "ambiguous")
206
+ return unresolved("probe_ambiguous");
207
+ if (!checkoutId)
208
+ return unresolved("checkout_unavailable");
209
+ const selected = (remoteName, reason) => {
210
+ const candidates = observation.remotes.filter((remote2) => remote2.name === remoteName);
211
+ if (!candidates.length)
212
+ return unresolved("selection_missing", remoteName);
213
+ const keys = new Set(candidates.map((remote2) => remote2.fingerprint));
214
+ if (keys.size !== 1)
215
+ return unresolved("selection_conflict", remoteName);
216
+ const remote = candidates[0];
217
+ if (!isPortableGitRemote(remote))
218
+ return unresolved("selection_not_portable", remoteName);
219
+ return {
220
+ ...base,
221
+ kind: "portable_repository",
222
+ key: remote.fingerprint,
223
+ reason,
224
+ selectedRemote: remoteName,
225
+ anchorDisplay: remote.display
226
+ };
227
+ };
228
+ if (input.localSelection !== void 0)
229
+ return selected(input.localSelection, "local_selection");
230
+ if (input.associatedSelection) {
231
+ const { selection } = input.associatedSelection;
232
+ if (selection.state === "conflict")
233
+ return unresolved("selection_conflict");
234
+ const remote = observation.remotes.find((entry) => isPortableGitRemote(entry) && entry.fingerprint === selection.anchorFingerprint);
235
+ if (!remote)
236
+ return unresolved("replicated_anchor_missing");
237
+ return selected(remote.name, "replicated_selection");
238
+ }
239
+ if (observation.status === "non_git") {
240
+ return {
241
+ ...base,
242
+ kind: "non_git_project",
243
+ key: `ng_${hmacProjectValue(deviceSalt, `${input.cwd}
244
+ ${checkoutId}`).slice(12)}`,
245
+ reason: "non_git"
246
+ };
247
+ }
248
+ for (const remoteName of ["upstream", "origin"]) {
249
+ const remotes = observation.remotes.filter((remote) => remote.name === remoteName);
250
+ if (remotes.some(isPortableGitRemote))
251
+ return selected(remoteName, remoteName);
252
+ }
253
+ if (!observation.commonDir || !input.commonDirMarker)
254
+ return unresolved("probe_failed");
255
+ return {
256
+ ...base,
257
+ kind: "device_local_repository",
258
+ key: `dl_${hmacProjectValue(deviceSalt, `${observation.commonDir}
259
+ ${input.commonDirMarker}`).slice(12)}`,
260
+ reason: "local_fallback"
261
+ };
262
+ };
263
+
264
+ // packages/koed-server/dist/project-associated-selection.js
265
+ var selectionSchema = external_exports.discriminatedUnion("state", [
266
+ external_exports.object({
267
+ state: external_exports.literal("selected"),
268
+ anchorFingerprint: external_exports.string().min(1).max(512)
269
+ }).strict(),
270
+ external_exports.object({ state: external_exports.literal("conflict") }).strict()
271
+ ]);
272
+ var responseSchema = external_exports.object({
273
+ association: external_exports.object({
274
+ groupId: external_exports.string().min(1),
275
+ associationId: external_exports.string().min(1),
276
+ selectionId: external_exports.string().min(1),
277
+ selection: selectionSchema.nullable()
278
+ }).strict().nullable()
279
+ }).strict();
280
+ var lookupAcceptedProjectSelection = async (paths, checkout, deps = {}) => {
281
+ const environment = deps.environment ?? process.env;
282
+ const repoEnv = loadRepoEnv(paths.repoRoot);
283
+ const token = resolveActiveIntegrationApiToken(paths, environment, repoEnv);
284
+ if (!token)
285
+ throw new Error("Project association lookup requires the local API credential");
286
+ const runtime = readActiveRuntimeState(paths.runtimeStatePath);
287
+ const origin = new URL(runtime?.apiUrl ?? resolveApiUrl(applyPersistedLocalPorts(paths, environment, { force: true }), repoEnv));
288
+ if (!isLoopbackHostname(origin.hostname) || !["http:", "https:"].includes(origin.protocol) || origin.username || origin.password)
289
+ throw new Error("Project association lookup requires the local Personal API");
290
+ const url = new URL("/v1/memory/repository-selection", origin);
291
+ url.search = new URLSearchParams(checkout).toString();
292
+ const { response, payload } = await fetchBoundedJsonObject(deps.fetch ?? globalThis.fetch, url, {
293
+ headers: { authorization: `Bearer ${token.token}` },
294
+ redirect: "error"
295
+ }, { timeoutMs: 1e4, maxBytes: 64 * 1024 });
296
+ if (!response.ok) {
297
+ throw new Error("Project association lookup is unavailable; retry discovery");
298
+ }
299
+ const result = responseSchema.parse(payload);
300
+ const association = result.association;
301
+ return association?.selection ? {
302
+ associationId: association.associationId,
303
+ selection: association.selection
304
+ } : void 0;
305
+ };
306
+
307
+ // packages/koed-server/dist/project-metadata.js
308
+ var depsWithDefaults = (deps = {}) => ({
309
+ existsSync: deps.existsSync ?? existsSync,
310
+ readFileSync: deps.readFileSync ?? readFileSync,
311
+ writeFileSync: deps.writeFileSync ?? writeFileSync,
312
+ renameSync: deps.renameSync ?? renameSync,
313
+ mkdirSync: deps.mkdirSync ?? mkdirSync,
314
+ statSync: deps.statSync ?? statSync2,
315
+ lookupAssociatedSelection: deps.lookupAssociatedSelection ?? lookupAcceptedProjectSelection,
316
+ execFile: deps.execFile ?? nodeExecFile,
317
+ now: deps.now ?? (() => /* @__PURE__ */ new Date()),
318
+ randomId: deps.randomId ?? randomUUID,
319
+ probeGit: deps.probeGit ?? (deps.execFile ? createGitProjectProbe({ execFile: deps.execFile }) : probeGitProject)
320
+ });
321
+ var defaultStore = (now, deps) => ({
322
+ schemaVersion: 3,
323
+ updatedAt: now,
324
+ deviceSaltId: `pms_${deps.randomId()}`,
325
+ repositoryChanges: [],
326
+ checkouts: [],
327
+ namedProjects: [],
328
+ projects: []
329
+ });
330
+ var historicalFolderRepositoryIdentity = (paths, cwd, depsInput = {}) => {
331
+ const root = normalizeRecordedProjectDirectory(cwd);
332
+ if (!root)
333
+ return null;
334
+ const deps = depsWithDefaults(depsInput);
335
+ const store = readStore(paths, deps);
336
+ return {
337
+ kind: "non_git_project",
338
+ key: `ng_${hmacProjectValue(store.deviceSaltId, JSON.stringify(["historical_folder", root])).slice(12)}`,
339
+ root,
340
+ branch: null,
341
+ reason: "non_git",
342
+ checkoutId: null,
343
+ originatingDeviceId: store.deviceSaltId,
344
+ selectedRemote: null,
345
+ anchorDisplay: null
346
+ };
347
+ };
348
+ var readStoreUnlocked = (paths, deps) => {
349
+ const now = deps.now().toISOString();
350
+ if (!deps.existsSync(paths.projectMetadataPath)) {
351
+ return defaultStore(now, deps);
352
+ }
353
+ try {
354
+ const parsed = JSON.parse(deps.readFileSync(paths.projectMetadataPath, "utf8"));
355
+ const store = {
356
+ schemaVersion: 3,
357
+ updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : now,
358
+ deviceSaltId: typeof parsed.deviceSaltId === "string" && parsed.deviceSaltId.trim() ? parsed.deviceSaltId.trim() : `pms_${deps.randomId()}`,
359
+ repositoryChanges: Array.isArray(parsed.repositoryChanges) ? parsed.repositoryChanges.map((change) => repositoryChangeInputSchema.parse(change)) : [],
360
+ checkouts: Array.isArray(parsed.checkouts) ? parsed.checkouts.filter((entry) => typeof entry.id === "string" && typeof entry.root === "string" && typeof entry.marker === "string" && (entry.selectedRemote === void 0 || typeof entry.selectedRemote === "string") && (entry.associationLookupRequired === void 0 || typeof entry.associationLookupRequired === "boolean")) : [],
361
+ projects: Array.isArray(parsed.projects) ? parsed.projects.filter(isProjectMetadata).map(normalizeProjectMetadata) : [],
362
+ namedProjects: Array.isArray(parsed.namedProjects) ? parsed.namedProjects.map((project) => {
363
+ if (!project || typeof project.id !== "string" || typeof project.name !== "string" || !project.name.trim() || project.name.length > 160 || typeof project.createdAt !== "string")
364
+ throw new Error("Invalid named Project");
365
+ const repository = repositoryIdentitySchema.parse(project.repository);
366
+ if (repository.kind !== "local_project")
367
+ throw new Error("Invalid named Project identity");
368
+ return {
369
+ id: project.id,
370
+ name: project.name,
371
+ createdAt: project.createdAt,
372
+ repository
373
+ };
374
+ }) : []
375
+ };
376
+ if (parsed.schemaVersion !== 3 || parsed.deviceSaltId !== store.deviceSaltId) {
377
+ writeStore(paths, store, deps);
378
+ }
379
+ return store;
380
+ } catch (error) {
381
+ throw new Error("Project metadata config is malformed.", { cause: error });
382
+ }
383
+ };
384
+ var updateStore = (paths, deps, mutate) => withFileLock(paths.projectMetadataPath, () => {
385
+ const store = readStoreUnlocked(paths, deps);
386
+ const result = mutate(store);
387
+ writeStore(paths, store, deps);
388
+ return result;
389
+ });
390
+ var readStore = (paths, deps) => withFileLock(paths.projectMetadataPath, () => {
391
+ const store = readStoreUnlocked(paths, deps);
392
+ if (!deps.existsSync(paths.projectMetadataPath))
393
+ writeStore(paths, store, deps);
394
+ return store;
395
+ });
396
+ var writeStore = (paths, store, deps) => {
397
+ deps.mkdirSync(dirname2(paths.projectMetadataPath), {
398
+ recursive: true,
399
+ mode: 448
400
+ });
401
+ const tmpPath = `${paths.projectMetadataPath}.${randomUUID()}.tmp`;
402
+ try {
403
+ deps.writeFileSync(tmpPath, `${JSON.stringify(store, null, 2)}
404
+ `, {
405
+ mode: 384
406
+ });
407
+ deps.renameSync(tmpPath, paths.projectMetadataPath);
408
+ } finally {
409
+ rmSync(tmpPath, { force: true });
410
+ }
411
+ };
412
+ var isProjectMetadata = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value) && value.schemaVersion === 1 && typeof value.localProjectId === "string" && typeof value.displayName === "string" && Boolean(value.path);
413
+ var isNormalizedGitRemote = (value) => {
414
+ if (!value || typeof value !== "object" || Array.isArray(value))
415
+ return false;
416
+ const remote = value;
417
+ return typeof remote.name === "string" && (remote.host === null || typeof remote.host === "string") && (remote.namespace === null || typeof remote.namespace === "string") && (remote.repo === null || typeof remote.repo === "string") && (remote.display === null || typeof remote.display === "string") && typeof remote.fingerprint === "string";
418
+ };
419
+ var withoutFields = (value, ...fields) => {
420
+ const copy = { ...value };
421
+ for (const field of fields)
422
+ delete copy[field];
423
+ return copy;
424
+ };
425
+ var normalizeProjectMetadata = (value) => {
426
+ const metadata = withoutFields(value, "sourceProjectId");
427
+ if (!metadata.git)
428
+ return metadata;
429
+ const git = withoutFields(metadata.git, "remoteSetFingerprint", "remoteAliases", "commonDirHash");
430
+ const remotes = Array.isArray(git.remotes) ? git.remotes.filter(isNormalizedGitRemote) : [];
431
+ return {
432
+ ...metadata,
433
+ git: {
434
+ ...git,
435
+ remotes
436
+ }
437
+ };
438
+ };
439
+ var readPackageName = (packageJsonPath, deps) => {
440
+ try {
441
+ const parsed = JSON.parse(deps.readFileSync(packageJsonPath, "utf8"));
442
+ return typeof parsed.name === "string" && parsed.name.trim() ? parsed.name.trim() : null;
443
+ } catch {
444
+ return null;
445
+ }
446
+ };
447
+ var discoverPackages = (projectRoot, cwd, deps) => {
448
+ const root = projectRoot ?? cwd;
449
+ const packageJsonPath = resolve2(root, "package.json");
450
+ if (!deps.existsSync(packageJsonPath)) {
451
+ return [];
452
+ }
453
+ const manager = deps.existsSync(resolve2(root, "pnpm-lock.yaml")) ? "pnpm" : deps.existsSync(resolve2(root, "package-lock.json")) ? "npm" : deps.existsSync(resolve2(root, "yarn.lock")) ? "yarn" : deps.existsSync(resolve2(root, "bun.lockb")) ? "bun" : "unknown";
454
+ return [
455
+ {
456
+ manager,
457
+ name: readPackageName(packageJsonPath, deps),
458
+ relativePath: relative(root, packageJsonPath) || "package.json"
459
+ }
460
+ ];
461
+ };
462
+ var discoverProjectMetadata = async (paths, input, depsInput = {}) => {
463
+ const deps = depsWithDefaults(depsInput);
464
+ const initial = readStore(paths, deps);
465
+ const now = deps.now().toISOString();
466
+ const cwd = resolve2(input.cwd);
467
+ const observation = await deps.probeGit({
468
+ profile: paths.projectMetadataPath,
469
+ cwd,
470
+ deviceSalt: initial.deviceSaltId
471
+ });
472
+ const gitRoot = observation.root;
473
+ const remotes = observation.remotes;
474
+ const checkoutRoot = gitRoot ?? cwd;
475
+ let checkoutMarker = null;
476
+ try {
477
+ const stat = deps.statSync(observation.gitDir ?? checkoutRoot);
478
+ checkoutMarker = JSON.stringify([stat.dev, stat.ino, stat.birthtimeMs]);
479
+ } catch {
480
+ }
481
+ const observedCheckout = updateStore(paths, deps, (store) => {
482
+ let checkout = store.checkouts.find((entry) => entry.root === checkoutRoot && entry.marker === checkoutMarker);
483
+ if (!checkout && checkoutMarker) {
484
+ checkout = {
485
+ id: `checkout_${deps.randomId()}`,
486
+ root: checkoutRoot,
487
+ marker: checkoutMarker
488
+ };
489
+ store.checkouts.push(checkout);
490
+ }
491
+ return checkout;
492
+ });
493
+ let associatedSelection = input.associatedSelection;
494
+ const lookedUp = !associatedSelection && observedCheckout?.associationLookupRequired && observedCheckout.selectedRemote === void 0;
495
+ if (lookedUp) {
496
+ associatedSelection = await deps.lookupAssociatedSelection(paths, {
497
+ originatingDeviceId: initial.deviceSaltId,
498
+ checkoutId: observedCheckout.id
499
+ });
500
+ }
501
+ return updateStore(paths, deps, (store) => {
502
+ const checkout = store.checkouts.find((entry) => entry.id === observedCheckout?.id);
503
+ if (store.deviceSaltId !== initial.deviceSaltId || observedCheckout && !checkout)
504
+ throw new Error("Checkout changed during discovery; retry discovery");
505
+ if (checkoutMarker) {
506
+ const currentStat = deps.statSync(observation.gitDir ?? checkoutRoot);
507
+ if (JSON.stringify([
508
+ currentStat.dev,
509
+ currentStat.ino,
510
+ currentStat.birthtimeMs
511
+ ]) !== checkoutMarker)
512
+ throw new Error("Checkout changed during discovery; retry discovery");
513
+ }
514
+ if (lookedUp && !checkout?.associationLookupRequired)
515
+ associatedSelection = void 0;
516
+ const repository = resolveRepositoryIdentity({
517
+ observation,
518
+ cwd,
519
+ deviceSalt: store.deviceSaltId,
520
+ checkoutId: checkout?.id ?? null,
521
+ localSelection: checkout?.selectedRemote,
522
+ associatedSelection,
523
+ commonDirMarker: (() => {
524
+ try {
525
+ const stat = deps.statSync(observation.commonDir);
526
+ return JSON.stringify([stat.dev, stat.ino, stat.birthtimeMs]);
527
+ } catch {
528
+ return null;
529
+ }
530
+ })()
531
+ });
532
+ const packages = discoverPackages(gitRoot, cwd, deps);
533
+ const localProjectId = deriveLocalProjectId({
534
+ salt: store.deviceSaltId,
535
+ projectRoot: gitRoot,
536
+ cwd
537
+ });
538
+ const previousProject = store.projects.find((entry) => entry.localProjectId === localProjectId && entry.repository?.checkoutId === repository.checkoutId);
539
+ const previous = previousProject?.repository;
540
+ if (checkout && previous && previous.checkoutId === repository.checkoutId && !(previous.kind === "unresolved" && repository.kind === "unresolved" && previous.reason === repository.reason) && !repositoryIdentityMatches(previous, repository)) {
541
+ checkout.repositoryRevision = (checkout.repositoryRevision ?? 0) + 1;
542
+ store.repositoryChanges.push(repositoryChangeInputSchema.parse({
543
+ id: randomUUID(),
544
+ kind: "anchor_change",
545
+ originatingDeviceId: repository.originatingDeviceId,
546
+ checkoutId: checkout.id,
547
+ originatingRevision: checkout.repositoryRevision,
548
+ previousIdentity: previous,
549
+ targetIdentity: repository
550
+ }));
551
+ }
552
+ const { branch, headCommit, commonDir: resolvedCommonDir, gitDir: resolvedGitDir } = observation;
553
+ const isWorktree = Boolean(resolvedCommonDir && resolvedGitDir && resolvedCommonDir !== resolvedGitDir);
554
+ const displayName = normalizeProjectDisplayName({
555
+ cwd,
556
+ projectRoot: gitRoot,
557
+ packages,
558
+ remotes
559
+ });
560
+ const project = {
561
+ schemaVersion: 1,
562
+ discoveredAt: previousProject?.discoveredAt ?? now,
563
+ lastSeenAt: now,
564
+ localProjectId,
565
+ displayName,
566
+ path: {
567
+ cwd,
568
+ projectRoot: gitRoot,
569
+ basename: path.basename(gitRoot ?? cwd),
570
+ localPathHash: hmacProjectValue(store.deviceSaltId, gitRoot ?? cwd)
571
+ },
572
+ ...gitRoot ? {
573
+ git: {
574
+ rootHash: hmacProjectValue(store.deviceSaltId, gitRoot),
575
+ remotes,
576
+ branch,
577
+ headCommit,
578
+ isWorktree,
579
+ worktreeHash: isWorktree ? hmacProjectValue(store.deviceSaltId, gitRoot) : null
580
+ }
581
+ } : {},
582
+ repository,
583
+ packages,
584
+ ...input.aiClientSource ? {
585
+ aiClient: {
586
+ cwdHash: hmacProjectValue(store.deviceSaltId, cwd),
587
+ cwdBasename: path.basename(cwd),
588
+ source: input.aiClientSource
589
+ }
590
+ } : {}
591
+ };
592
+ const projects = [
593
+ ...store.projects.filter((entry) => entry.localProjectId !== localProjectId),
594
+ project
595
+ ].sort((left, right) => left.displayName.localeCompare(right.displayName));
596
+ store.updatedAt = now;
597
+ store.projects = projects;
598
+ return {
599
+ ok: true,
600
+ state: "discovered",
601
+ message: "Project metadata discovered.",
602
+ gitProbe: {
603
+ status: observation.status,
604
+ failedCommands: observation.failedCommands
605
+ },
606
+ project
607
+ };
608
+ });
609
+ };
610
+ var listProjectMetadata = (paths, depsInput = {}) => {
611
+ const store = readStore(paths, depsWithDefaults(depsInput));
612
+ return {
613
+ ok: true,
614
+ state: "listed",
615
+ message: `Found ${store.projects.length} Project metadata record(s).`,
616
+ projects: store.projects
617
+ };
618
+ };
619
+ var listNamedProjects = (paths, depsInput = {}) => readStore(paths, depsWithDefaults(depsInput)).namedProjects;
620
+ var createNamedProject = (paths, name, depsInput = {}) => {
621
+ const trimmed = name.trim();
622
+ if (!trimmed || trimmed.length > 160)
623
+ throw new Error("Enter a Project name of 1 to 160 characters.");
624
+ const deps = depsWithDefaults(depsInput);
625
+ return updateStore(paths, deps, (store) => {
626
+ if (store.namedProjects.length >= 500)
627
+ throw new Error("The local Project catalog is full.");
628
+ const id = `project_${deps.randomId()}`;
629
+ const project = {
630
+ id,
631
+ name: trimmed,
632
+ createdAt: deps.now().toISOString(),
633
+ repository: {
634
+ kind: "local_project",
635
+ key: id,
636
+ reason: "manual",
637
+ originatingDeviceId: store.deviceSaltId,
638
+ root: null,
639
+ branch: null,
640
+ checkoutId: null,
641
+ selectedRemote: null,
642
+ anchorDisplay: null
643
+ }
644
+ };
645
+ store.updatedAt = project.createdAt;
646
+ store.namedProjects.push(project);
647
+ return project;
648
+ });
649
+ };
650
+ var getProjectMetadataForCwd = (paths, cwd, depsInput = {}) => {
651
+ const resolvedCwd = resolve2(cwd);
652
+ const store = readStore(paths, depsWithDefaults(depsInput));
653
+ const project = store.projects.find((entry) => entry.path.cwd === resolvedCwd || entry.path.projectRoot === resolvedCwd) ?? null;
654
+ if (!project) {
655
+ return {
656
+ ok: false,
657
+ state: "missing",
658
+ message: "Project metadata not found."
659
+ };
660
+ }
661
+ return {
662
+ ok: true,
663
+ state: "found",
664
+ message: "Project metadata found.",
665
+ project
666
+ };
667
+ };
668
+ var forgetProjectMetadata = (paths, localProjectId, depsInput = {}) => {
669
+ const deps = depsWithDefaults(depsInput);
670
+ return updateStore(paths, deps, (store) => {
671
+ const project = store.projects.find((entry) => entry.localProjectId === localProjectId);
672
+ if (!project) {
673
+ return {
674
+ ok: false,
675
+ state: "missing",
676
+ message: "Project metadata not found."
677
+ };
678
+ }
679
+ const now = deps.now().toISOString();
680
+ store.updatedAt = now;
681
+ store.projects = store.projects.filter((entry) => entry.localProjectId !== localProjectId);
682
+ return {
683
+ ok: true,
684
+ state: "forgotten",
685
+ message: "Project metadata forgotten.",
686
+ project
687
+ };
688
+ });
689
+ };
690
+ var setProjectRepositoryAnchor = async (paths, input, depsInput = {}) => {
691
+ if (input.remoteName !== null && (!input.remoteName.trim() || input.remoteName.length > 512 || /\s/.test(input.remoteName)))
692
+ throw new Error("Repository remote name is invalid.");
693
+ const deps = depsWithDefaults(depsInput);
694
+ const original = readStore(paths, deps).projects.find((project) => project.localProjectId === input.localProjectId);
695
+ if (!original)
696
+ throw new Error("Project metadata not found.");
697
+ const discovery = await discoverProjectMetadata(paths, { cwd: original.path.projectRoot ?? original.path.cwd }, depsInput);
698
+ if (discovery.project?.repository?.checkoutId !== input.expectedCheckoutId)
699
+ throw new Error("Checkout changed. Inspect the Project again before selecting an anchor.");
700
+ updateStore(paths, deps, (store) => {
701
+ const checkout = store.checkouts.find((entry) => entry.id === input.expectedCheckoutId);
702
+ if (!checkout)
703
+ throw new Error("Checkout provenance is unavailable.");
704
+ if (input.remoteName === null)
705
+ delete checkout.selectedRemote;
706
+ else
707
+ checkout.selectedRemote = input.remoteName;
708
+ });
709
+ return discoverProjectMetadata(paths, { cwd: original.path.projectRoot ?? original.path.cwd }, depsInput);
710
+ };
711
+ var setProjectAssociationLookup = async (paths, input, depsInput = {}) => {
712
+ const deps = depsWithDefaults(depsInput);
713
+ const original = readStore(paths, deps).projects.find((entry) => entry.localProjectId === input.localProjectId);
714
+ if (!original)
715
+ throw new Error("Local Project is unavailable");
716
+ const discovery = await discoverProjectMetadata(paths, { cwd: original.path.projectRoot ?? original.path.cwd }, depsInput);
717
+ if (discovery.project?.repository?.checkoutId !== input.expectedCheckoutId)
718
+ throw new Error("Checkout changed; inspect the Project again");
719
+ updateStore(paths, deps, (store) => {
720
+ const checkout = store.checkouts.find((entry) => entry.id === input.expectedCheckoutId);
721
+ if (!checkout)
722
+ throw new Error("Checkout provenance is unavailable");
723
+ checkout.associationLookupRequired = input.enabled;
724
+ });
725
+ };
726
+ var refreshProjectAssociations = async (paths, depsInput = {}) => {
727
+ const store = readStore(paths, depsWithDefaults(depsInput));
728
+ for (const project of store.projects) {
729
+ if (!store.checkouts.some((entry) => entry.id === project.repository?.checkoutId && entry.associationLookupRequired))
730
+ continue;
731
+ await discoverProjectMetadata(paths, { cwd: project.path.projectRoot ?? project.path.cwd }, depsInput);
732
+ }
733
+ };
734
+ var listPendingRepositoryChanges = (paths, depsInput = {}) => readStore(paths, depsWithDefaults(depsInput)).repositoryChanges;
735
+ var acknowledgeRepositoryChange = (paths, id, depsInput = {}) => {
736
+ const deps = depsWithDefaults(depsInput);
737
+ updateStore(paths, deps, (store) => {
738
+ store.repositoryChanges = store.repositoryChanges.filter((change) => change.id !== id);
739
+ });
740
+ };
741
+ export {
742
+ acknowledgeRepositoryChange,
743
+ createNamedProject,
744
+ discoverProjectMetadata,
745
+ forgetProjectMetadata,
746
+ getProjectMetadataForCwd,
747
+ historicalFolderRepositoryIdentity,
748
+ listNamedProjects,
749
+ listPendingRepositoryChanges,
750
+ listProjectMetadata,
751
+ refreshProjectAssociations,
752
+ setProjectAssociationLookup,
753
+ setProjectRepositoryAnchor
754
+ };