@primitive.ai/prim 0.1.0-alpha.12 → 0.1.0-alpha.120

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 (56) hide show
  1. package/README.md +540 -38
  2. package/SKILL.md +315 -75
  3. package/assets/primitive-gameplan/SKILL.md +134 -0
  4. package/assets/primitive-gameplan/claude-hooks.json +28 -0
  5. package/assets/primitive-gameplan/scripts/activate.mjs +37 -0
  6. package/dist/chunk-2AKDX4RU.js +209 -0
  7. package/dist/chunk-4GLVJLEQ.js +55 -0
  8. package/dist/chunk-5BQ2NEMP.js +22695 -0
  9. package/dist/chunk-A6M2M5A2.js +36 -0
  10. package/dist/chunk-CCGFRNAA.js +1871 -0
  11. package/dist/chunk-D235RJNO.js +164 -0
  12. package/dist/chunk-EYBE724K.js +135 -0
  13. package/dist/chunk-EZXEWFDG.js +210 -0
  14. package/dist/chunk-GYQOZGGF.js +168 -0
  15. package/dist/chunk-HXICZG5J.js +503 -0
  16. package/dist/chunk-JSBRDJBE.js +30 -0
  17. package/dist/chunk-KZB4ABIB.js +13 -0
  18. package/dist/chunk-L52OD62C.js +1444 -0
  19. package/dist/chunk-LBCPRHNG.js +175 -0
  20. package/dist/chunk-LTTF4MBE.js +439 -0
  21. package/dist/chunk-MWNRXAEB.js +1572 -0
  22. package/dist/chunk-NQFRQ56V.js +262 -0
  23. package/dist/chunk-OYHYCK4K.js +13 -0
  24. package/dist/chunk-P2O7NLVN.js +1341 -0
  25. package/dist/chunk-R2NUH4B7.js +96 -0
  26. package/dist/chunk-SLDZJD6Q.js +157 -0
  27. package/dist/chunk-TC4FTRYO.js +253 -0
  28. package/dist/chunk-U67RBNIZ.js +844 -0
  29. package/dist/chunk-VOC4KOOP.js +258 -0
  30. package/dist/chunk-YTF6OCF3.js +459 -0
  31. package/dist/daemon/server.js +26444 -0
  32. package/dist/hook-runtime/daemon/server.js +26445 -0
  33. package/dist/hook-runtime/hooks/post-commit.js +23836 -0
  34. package/dist/hook-runtime/hooks/post-rewrite.js +23735 -0
  35. package/dist/hook-runtime/hooks/post-tool-use.js +36151 -0
  36. package/dist/hook-runtime/hooks/pre-commit.js +1737 -0
  37. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +35067 -0
  38. package/dist/hook-runtime/hooks/pre-tool-use.js +96 -0
  39. package/dist/hook-runtime/hooks/prim-hook.js +36211 -0
  40. package/dist/hook-runtime/hooks/session-end.js +1188 -0
  41. package/dist/hook-runtime/hooks/session-start.js +33950 -0
  42. package/dist/hook-runtime/index.js +71245 -0
  43. package/dist/hook-runtime/statusline-main.js +892 -0
  44. package/dist/hooks/post-commit.js +197 -0
  45. package/dist/hooks/post-rewrite.js +206 -0
  46. package/dist/hooks/post-tool-use.js +295 -0
  47. package/dist/hooks/pre-commit.js +16 -108
  48. package/dist/hooks/pre-tool-use-worker.js +238 -0
  49. package/dist/hooks/pre-tool-use.js +87 -0
  50. package/dist/hooks/prim-hook.js +245 -0
  51. package/dist/hooks/session-end.js +67 -0
  52. package/dist/hooks/session-start.js +312 -0
  53. package/dist/index.js +10998 -572
  54. package/dist/statusline-main.js +891 -0
  55. package/package.json +49 -16
  56. package/dist/chunk-3APLWTLB.js +0 -165
@@ -0,0 +1,164 @@
1
+ import {
2
+ daemonRequest
3
+ } from "./chunk-SLDZJD6Q.js";
4
+ import {
5
+ getClient,
6
+ getSiteUrl,
7
+ terminalSafeLine
8
+ } from "./chunk-U67RBNIZ.js";
9
+ import {
10
+ canonicalGitRoot,
11
+ canonicalRepositoryPath,
12
+ currentBranch,
13
+ repoSyncId
14
+ } from "./chunk-P2O7NLVN.js";
15
+
16
+ // src/daemon/proxy.ts
17
+ var DAEMON_HTTP_TIMEOUT_MS = 1e4;
18
+ var DAEMON_PROBE_TIMEOUT_MS = 250;
19
+ async function daemonOrDirect(method, params, direct) {
20
+ const fromDaemon = await daemonRequest(
21
+ method,
22
+ { ...params, callerEnv: getSiteUrl() },
23
+ { timeoutMs: DAEMON_PROBE_TIMEOUT_MS }
24
+ );
25
+ if (fromDaemon !== null) {
26
+ return fromDaemon;
27
+ }
28
+ return await direct();
29
+ }
30
+ async function daemonOrDirectGet(method, path, client, timeoutMs = DAEMON_HTTP_TIMEOUT_MS) {
31
+ return await daemonOrDirect(
32
+ method,
33
+ { path },
34
+ async () => await client.get(path, {
35
+ signal: AbortSignal.timeout(timeoutMs)
36
+ })
37
+ );
38
+ }
39
+
40
+ // src/hooks/decisions-check.ts
41
+ var DECISIONS_CHECK_TIMEOUT_MS = 1e4;
42
+ var MAX_FILES_PER_REQUEST = 25;
43
+ var defaultDeps = { getClient };
44
+ function chunk(items, size) {
45
+ const out = [];
46
+ for (let i = 0; i < items.length; i += size) {
47
+ out.push(items.slice(i, i + size));
48
+ }
49
+ return out;
50
+ }
51
+ async function fetchAffecting(client, batch, repository) {
52
+ const params = new URLSearchParams();
53
+ params.set("repoSyncId", repository.repoSyncId);
54
+ if (repository.branch) params.set("branch", repository.branch);
55
+ for (const file of batch) {
56
+ params.append("files", file);
57
+ }
58
+ try {
59
+ const response = await daemonOrDirectGet(
60
+ "decisions_affecting",
61
+ `/api/cli/decisions/affecting?${params.toString()}`,
62
+ client,
63
+ DECISIONS_CHECK_TIMEOUT_MS
64
+ );
65
+ if (response.repoSyncId !== repository.repoSyncId) {
66
+ return {
67
+ decisions: [],
68
+ truncated: response.truncated === true,
69
+ unavailable: response.unavailable ?? "service did not verify repository-scoped discovery"
70
+ };
71
+ }
72
+ return response;
73
+ } catch (err) {
74
+ const detail = err instanceof Error ? err.message : String(err);
75
+ return { decisions: [], truncated: false, unavailable: `decision check failed: ${detail}` };
76
+ }
77
+ }
78
+ async function checkAffectedDecisions(filePaths, deps = defaultDeps) {
79
+ if (filePaths.length === 0) {
80
+ return { decisions: [], truncated: false };
81
+ }
82
+ const cwd = process.cwd();
83
+ const root = canonicalGitRoot(cwd);
84
+ const binding = repoSyncId(cwd);
85
+ if (!root || !binding) {
86
+ return {
87
+ decisions: [],
88
+ truncated: false,
89
+ unavailable: "this checkout has no current Primitive repository binding; run prim enable"
90
+ };
91
+ }
92
+ const canonical = filePaths.map(
93
+ (file) => canonicalRepositoryPath(file, { repoRoot: root }, root)
94
+ );
95
+ if (canonical.some((path) => !path.ok)) {
96
+ return {
97
+ decisions: [],
98
+ truncated: false,
99
+ unavailable: "files must resolve inside this repository; use repository-relative paths"
100
+ };
101
+ }
102
+ const paths = [...new Set(canonical.flatMap((path) => path.ok ? [path.file] : []))];
103
+ const repository = { repoSyncId: binding, branch: currentBranch(cwd) };
104
+ const client = deps.getClient();
105
+ const responses = await Promise.all(
106
+ chunk(paths, MAX_FILES_PER_REQUEST).map((batch) => fetchAffecting(client, batch, repository))
107
+ );
108
+ const byId = /* @__PURE__ */ new Map();
109
+ let truncated = false;
110
+ let unavailable;
111
+ for (const res of responses) {
112
+ if (res.unavailable !== void 0 && unavailable === void 0) {
113
+ unavailable = res.unavailable;
114
+ }
115
+ truncated ||= res.truncated === true;
116
+ for (const d of res.decisions) {
117
+ const existing = byId.get(d.id);
118
+ if (existing) {
119
+ existing.matchedFiles = [.../* @__PURE__ */ new Set([...existing.matchedFiles, ...d.matchedFiles])];
120
+ } else {
121
+ byId.set(d.id, { ...d, matchedFiles: [...d.matchedFiles] });
122
+ }
123
+ }
124
+ }
125
+ const result = { decisions: [...byId.values()], truncated };
126
+ if (unavailable !== void 0) {
127
+ result.unavailable = unavailable;
128
+ }
129
+ return result;
130
+ }
131
+ var FILES_PREVIEW_LIMIT = 3;
132
+ function formatDecisionsWarning(result) {
133
+ const lines = [];
134
+ if (result.unavailable !== void 0) {
135
+ lines.push(`[prim] decision check not verified \u2014 ${terminalSafeLine(result.unavailable)}`);
136
+ }
137
+ if (result.decisions.length > 0) {
138
+ lines.push(
139
+ `[prim] ${String(result.decisions.length)} active decision(s) reference staged files:`
140
+ );
141
+ for (const d of result.decisions) {
142
+ const statusMark = d.status === "under_review" ? " (under review)" : "";
143
+ const preview = d.matchedFiles.slice(0, FILES_PREVIEW_LIMIT).map(terminalSafeLine).join(", ");
144
+ const overflow = d.matchedFiles.length > FILES_PREVIEW_LIMIT ? ` (+${String(d.matchedFiles.length - FILES_PREVIEW_LIMIT)} more)` : "";
145
+ lines.push(` \xB7 ${terminalSafeLine(d.intent)}${statusMark}`);
146
+ lines.push(` files: ${preview}${overflow}`);
147
+ if (d.rationale) {
148
+ lines.push(` rationale: ${terminalSafeLine(d.rationale)}`);
149
+ }
150
+ }
151
+ }
152
+ if (result.truncated) {
153
+ lines.push(
154
+ "[prim] result truncated \u2014 a discovery scan or result limit was reached; not all decisions shown"
155
+ );
156
+ }
157
+ return lines.join("\n");
158
+ }
159
+
160
+ export {
161
+ daemonOrDirectGet,
162
+ checkAffectedDecisions,
163
+ formatDecisionsWarning
164
+ };
@@ -0,0 +1,135 @@
1
+ import {
2
+ getOrCreateWorkspaceId
3
+ } from "./chunk-EZXEWFDG.js";
4
+ import {
5
+ analyzeShellTargets,
6
+ extractFileTargets
7
+ } from "./chunk-L52OD62C.js";
8
+ import {
9
+ scrubEnvironmentPaths
10
+ } from "./chunk-NQFRQ56V.js";
11
+ import {
12
+ cachedCollectScopeAdmits
13
+ } from "./chunk-5BQ2NEMP.js";
14
+ import {
15
+ canonicalRepositoryPath,
16
+ currentBranch,
17
+ isRepoActiveForCapture,
18
+ relatedWorktreeTarget,
19
+ repoSyncId
20
+ } from "./chunk-P2O7NLVN.js";
21
+
22
+ // src/hooks/file-refs.ts
23
+ var MAX_PREFLIGHT_FILE_TARGETS = 25;
24
+ function primitiveMetadataForResolution(resolution) {
25
+ const shouldAttach = resolution.fileRefs.length > 0 || (resolution.targetCheckouts?.length ?? 0) > 0 || resolution.rejected.length > 0 || resolution.targetsIncomplete || resolution.targetsTruncated || resolution.shellMutation !== void 0;
26
+ if (!shouldAttach) return;
27
+ return {
28
+ fileRefs: [...resolution.fileRefs],
29
+ ...resolution.targetCheckouts ? { targetCheckouts: resolution.targetCheckouts } : {},
30
+ ...resolution.rejected.length > 0 || resolution.targetsIncomplete ? { fileRefsIncomplete: true } : {},
31
+ ...resolution.targetsTruncated ? { fileRefsTruncated: true } : {},
32
+ ...resolution.shellMutation !== void 0 ? { shellMutation: resolution.shellMutation } : {}
33
+ };
34
+ }
35
+ function preserveHookFileMetadata(payload, resolution) {
36
+ const primitive = primitiveMetadataForResolution(resolution);
37
+ if (!primitive || !payload || typeof payload !== "object" || Array.isArray(payload)) {
38
+ return payload;
39
+ }
40
+ return { ...payload, primitive };
41
+ }
42
+ function resolveHookFileRefs(args) {
43
+ const isShellTool = (args.agent === "claude_code" || args.agent === "codex") && args.toolName === "Bash" || args.agent === "cursor" && args.toolName === "Shell";
44
+ const command = isShellTool ? typeof args.toolInput === "string" ? args.toolInput : args.toolInput && typeof args.toolInput === "object" && typeof args.toolInput.command === "string" ? args.toolInput.command : void 0 : void 0;
45
+ const shell = command === void 0 ? void 0 : analyzeShellTargets(command, args.cwd);
46
+ const shellMutation = shell?.mutation === "none" ? "none" : shell?.coverage === "complete" ? "resolved" : shell ? "unresolved" : void 0;
47
+ const readPath = args.agent === "claude_code" && args.toolName === "Read" && args.toolInput && typeof args.toolInput === "object" && typeof args.toolInput.file_path === "string" ? [args.toolInput.file_path] : void 0;
48
+ const nativeTargets = shell ? null : readPath ? { paths: readPath, complete: true } : extractFileTargets(args.toolName, args.toolInput, args.agent);
49
+ const rawPaths = shell ? shellMutation === "unresolved" ? [] : shell.paths : nativeTargets?.paths ?? [];
50
+ const uniqueRawPaths = Array.from(new Set(rawPaths));
51
+ const targetsTruncated = uniqueRawPaths.length > MAX_PREFLIGHT_FILE_TARGETS;
52
+ const fileRefs = /* @__PURE__ */ new Set();
53
+ const rejected = [];
54
+ const targets = /* @__PURE__ */ new Map();
55
+ for (const path of uniqueRawPaths.slice(0, MAX_PREFLIGHT_FILE_TARGETS)) {
56
+ const canonical = canonicalRepositoryPath(path, args.repository, args.cwd);
57
+ if (canonical.ok) fileRefs.add(canonical.file);
58
+ else {
59
+ const target = args.captureTargets && canonical.reason === "outside_repository" ? relatedWorktreeTarget(path, args.cwd, args.repository) : null;
60
+ const resolved = target ? canonicalRepositoryPath(path, target, args.cwd) : null;
61
+ if (target && resolved?.ok && isRepoActiveForCapture(target.repoRoot) && repoSyncId(target.repoRoot) === args.repository.repoSyncId && args.repository.repoSyncId && cachedCollectScopeAdmits(target.repoRoot, {
62
+ repository: target.repoFullName,
63
+ branch: currentBranch(target.repoRoot),
64
+ agent: args.agent,
65
+ paths: [resolved.file],
66
+ pathsComplete: true
67
+ })) {
68
+ const group = targets.get(target.repoRoot) ?? { repository: target, fileRefs: [] };
69
+ group.fileRefs.push(resolved.file);
70
+ targets.set(target.repoRoot, group);
71
+ } else rejected.push({ path, reason: canonical.reason });
72
+ }
73
+ }
74
+ const targetCheckouts = [];
75
+ if (targets.size > 0) {
76
+ if (fileRefs.size > 0)
77
+ targets.set(args.repository.repoRoot, {
78
+ repository: args.repository,
79
+ fileRefs: [...fileRefs]
80
+ });
81
+ for (const { repository, fileRefs: paths } of targets.values()) {
82
+ const identity = getOrCreateWorkspaceId(repository.repoRoot);
83
+ const binding = repoSyncId(repository.repoRoot);
84
+ if (identity.status !== "ready" || !binding) {
85
+ rejected.push({ path: repository.repoRoot, reason: "invalid_path" });
86
+ continue;
87
+ }
88
+ const root = scrubEnvironmentPaths({
89
+ cwd: repository.repoRoot,
90
+ gitRoot: repository.repoRoot
91
+ }).gitRoot;
92
+ targetCheckouts.push({
93
+ gitRoot: root,
94
+ workspaceId: identity.workspaceId,
95
+ repoSyncId: binding,
96
+ fileRefs: paths
97
+ });
98
+ }
99
+ }
100
+ return {
101
+ fileRefs: [...fileRefs],
102
+ ...targetCheckouts.length > 0 ? { targetCheckouts } : {},
103
+ rejected,
104
+ targetsIncomplete: nativeTargets?.complete === false,
105
+ targetsTruncated,
106
+ ...shellMutation ? { shellMutation: targetsTruncated ? "unresolved" : shellMutation } : {}
107
+ };
108
+ }
109
+ function enrichHookPayloadWithFileRefs(args) {
110
+ const toolName = typeof args.parsed.tool_name === "string" ? args.parsed.tool_name : "";
111
+ const resolution = resolveHookFileRefs({
112
+ toolName,
113
+ toolInput: args.parsed.tool_input,
114
+ agent: args.agent,
115
+ cwd: args.cwd,
116
+ repository: args.repository,
117
+ captureTargets: true
118
+ });
119
+ const primitive = primitiveMetadataForResolution(resolution);
120
+ if (!primitive) return { parsed: args.parsed, resolution };
121
+ return {
122
+ parsed: {
123
+ ...args.parsed,
124
+ // An explicit empty list is authoritative when every exposed target was
125
+ // rejected. It prevents backend fallback to unsafe raw tool input.
126
+ primitive
127
+ },
128
+ resolution
129
+ };
130
+ }
131
+
132
+ export {
133
+ preserveHookFileMetadata,
134
+ enrichHookPayloadWithFileRefs
135
+ };
@@ -0,0 +1,210 @@
1
+ // src/lib/workspace-id.ts
2
+ import { execFileSync } from "child_process";
3
+ import { randomUUID } from "crypto";
4
+ import {
5
+ constants,
6
+ chmodSync,
7
+ closeSync,
8
+ fchmodSync,
9
+ fsyncSync,
10
+ linkSync,
11
+ lstatSync,
12
+ mkdirSync,
13
+ openSync,
14
+ readFileSync,
15
+ statSync,
16
+ unlinkSync,
17
+ writeFileSync
18
+ } from "fs";
19
+ import { dirname, isAbsolute, join, resolve } from "path";
20
+ var WORKSPACE_ID_RELATIVE_PATH = join("prim", "workspace-id");
21
+ var MAX_ANCESTORS = 64;
22
+ var MAX_GIT_FILE_BYTES = 4096;
23
+ var MAX_ID_FILE_BYTES = 128;
24
+ var GIT_FALLBACK_TIMEOUT_MS = 250;
25
+ var RACE_READ_ATTEMPTS = 5;
26
+ var RACE_READ_DELAY_MS = 5;
27
+ var CANONICAL_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
28
+ var raceDelay = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
29
+ function isCanonicalWorkspaceId(value) {
30
+ return CANONICAL_UUID.test(value);
31
+ }
32
+ function inspectWorkspaceId(cwd = process.cwd()) {
33
+ const resolved = resolveWorkspaceIdPath(cwd);
34
+ if (resolved.status !== "resolved") return resolved;
35
+ return inspectPath(resolved.path);
36
+ }
37
+ function getOrCreateWorkspaceId(cwd = process.cwd()) {
38
+ const inspection = inspectWorkspaceId(cwd);
39
+ if (inspection.status !== "missing") return inspection;
40
+ return createWorkspaceId(inspection.path);
41
+ }
42
+ function resolveWorkspaceIdPath(cwd) {
43
+ if (!process.env.GIT_DIR && !process.env.GIT_WORK_TREE) {
44
+ const fromFilesystem = resolveFromFilesystem(cwd);
45
+ if (fromFilesystem) return { status: "resolved", path: fromFilesystem };
46
+ }
47
+ try {
48
+ const output = execFileSync(
49
+ "git",
50
+ ["rev-parse", "--is-inside-work-tree", "--git-path", WORKSPACE_ID_RELATIVE_PATH],
51
+ {
52
+ cwd,
53
+ encoding: "utf8",
54
+ maxBuffer: 4096,
55
+ stdio: ["ignore", "pipe", "ignore"],
56
+ timeout: GIT_FALLBACK_TIMEOUT_MS,
57
+ windowsHide: true
58
+ }
59
+ );
60
+ const [insideWorktree, gitPath, ...extra] = output.trim().split(/\r?\n/);
61
+ if (insideWorktree !== "true" || !gitPath || extra.length > 0 || gitPath.includes("\0")) {
62
+ return { status: "not_git" };
63
+ }
64
+ return {
65
+ status: "resolved",
66
+ path: isAbsolute(gitPath) ? resolve(gitPath) : resolve(cwd, gitPath)
67
+ };
68
+ } catch (error) {
69
+ const code = errorCode(error);
70
+ if (code === "ETIMEDOUT" || code === "EACCES" || code === "EPERM") {
71
+ return { status: "unavailable", operation: "resolve", errorCode: code };
72
+ }
73
+ return { status: "not_git" };
74
+ }
75
+ }
76
+ function resolveFromFilesystem(cwd) {
77
+ let current = resolve(cwd);
78
+ for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
79
+ const dotGit = join(current, ".git");
80
+ try {
81
+ const stat = lstatSync(dotGit);
82
+ if (stat.isDirectory() && isGitDirectory(dotGit)) {
83
+ return join(dotGit, WORKSPACE_ID_RELATIVE_PATH);
84
+ }
85
+ if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
86
+ const contents = readFileSync(dotGit, "utf8");
87
+ const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
88
+ if (match?.[1]) {
89
+ const gitDirectory = isAbsolute(match[1]) ? resolve(match[1]) : resolve(current, match[1]);
90
+ if (isGitDirectory(gitDirectory)) {
91
+ return join(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
92
+ }
93
+ }
94
+ }
95
+ return null;
96
+ } catch (error) {
97
+ const code = errorCode(error);
98
+ if (code !== "ENOENT" && code !== "ENOTDIR") {
99
+ return null;
100
+ }
101
+ }
102
+ const parent = dirname(current);
103
+ if (parent === current) break;
104
+ current = parent;
105
+ }
106
+ return null;
107
+ }
108
+ function isGitDirectory(path) {
109
+ try {
110
+ return statSync(join(path, "HEAD")).isFile();
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+ function inspectPath(path) {
116
+ let stat;
117
+ try {
118
+ stat = lstatSync(path);
119
+ } catch (error) {
120
+ const code = errorCode(error);
121
+ if (code === "ENOENT" || code === "ENOTDIR") return { status: "missing", path };
122
+ return { status: "unavailable", path, operation: "read", errorCode: code };
123
+ }
124
+ if (!stat.isFile()) return { status: "corrupt", path, reason: "not_file" };
125
+ if (stat.size > MAX_ID_FILE_BYTES) {
126
+ return { status: "corrupt", path, reason: "invalid_content" };
127
+ }
128
+ try {
129
+ const contents = readFileSync(path, "utf8");
130
+ const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
131
+ if ((contents === workspaceId || contents === `${workspaceId}
132
+ `) && isCanonicalWorkspaceId(workspaceId)) {
133
+ return { status: "ready", workspaceId, path, created: false };
134
+ }
135
+ return { status: "corrupt", path, reason: "invalid_content" };
136
+ } catch (error) {
137
+ return {
138
+ status: "unavailable",
139
+ path,
140
+ operation: "read",
141
+ errorCode: errorCode(error)
142
+ };
143
+ }
144
+ }
145
+ function createWorkspaceId(path) {
146
+ const parent = dirname(path);
147
+ const workspaceId = randomUUID();
148
+ const temporaryPath = join(parent, `.workspace-id-${process.pid}-${randomUUID()}.tmp`);
149
+ let temporaryCreated = false;
150
+ let publishing = false;
151
+ try {
152
+ mkdirSync(parent, { recursive: true, mode: 448 });
153
+ chmodSync(parent, 448);
154
+ const fd = openSync(
155
+ temporaryPath,
156
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,
157
+ 384
158
+ );
159
+ temporaryCreated = true;
160
+ try {
161
+ writeFileSync(fd, `${workspaceId}
162
+ `, "utf8");
163
+ fchmodSync(fd, 384);
164
+ fsyncSync(fd);
165
+ } finally {
166
+ closeSync(fd);
167
+ }
168
+ publishing = true;
169
+ linkSync(temporaryPath, path);
170
+ return { status: "ready", workspaceId, path, created: true };
171
+ } catch (error) {
172
+ if (publishing && errorCode(error) === "EEXIST") return inspectAfterRace(path);
173
+ return {
174
+ status: "unavailable",
175
+ path,
176
+ operation: "create",
177
+ errorCode: errorCode(error)
178
+ };
179
+ } finally {
180
+ if (temporaryCreated) {
181
+ try {
182
+ unlinkSync(temporaryPath);
183
+ } catch {
184
+ }
185
+ }
186
+ }
187
+ }
188
+ function inspectAfterRace(path) {
189
+ let result = { status: "missing", path };
190
+ for (let attempt = 0; attempt < RACE_READ_ATTEMPTS; attempt += 1) {
191
+ result = inspectPath(path);
192
+ if (result.status === "ready") return result;
193
+ if (attempt + 1 < RACE_READ_ATTEMPTS) {
194
+ Atomics.wait(raceDelay, 0, 0, RACE_READ_DELAY_MS);
195
+ }
196
+ }
197
+ if (result.status === "missing") {
198
+ return { status: "unavailable", path, operation: "create", errorCode: "EEXIST" };
199
+ }
200
+ return result;
201
+ }
202
+ function errorCode(error) {
203
+ if (typeof error !== "object" || error === null || !("code" in error)) return void 0;
204
+ return typeof error.code === "string" ? error.code : void 0;
205
+ }
206
+
207
+ export {
208
+ isCanonicalWorkspaceId,
209
+ getOrCreateWorkspaceId
210
+ };
@@ -0,0 +1,168 @@
1
+ import {
2
+ boundedHealthError
3
+ } from "./chunk-5BQ2NEMP.js";
4
+ import {
5
+ stripControlChars
6
+ } from "./chunk-U67RBNIZ.js";
7
+
8
+ // src/lib/delivery-backlog.ts
9
+ var MS_PER_SECOND = 1e3;
10
+ var MS_PER_MINUTE = 60 * MS_PER_SECOND;
11
+ var MS_PER_HOUR = 60 * MS_PER_MINUTE;
12
+ var MS_PER_DAY = 24 * MS_PER_HOUR;
13
+ function isNonNegativeInteger(value) {
14
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
15
+ }
16
+ function isPositiveInteger(value) {
17
+ return isNonNegativeInteger(value) && value > 0;
18
+ }
19
+ function deliveryBacklogState(ingestion) {
20
+ if (ingestion?.healthy !== false) return void 0;
21
+ const failures = ingestion.consecutiveFailures;
22
+ const failedWithoutProgress = failures !== 0 && !(isPositiveInteger(failures) && isPositiveInteger(ingestion.lastFailedDrainAcknowledgedCount));
23
+ if (failedWithoutProgress) return "failing";
24
+ const retained = ingestion.lastRetainedBucketCount;
25
+ if (!isNonNegativeInteger(retained)) return "failing";
26
+ return retained > 0 ? "retained" : "draining";
27
+ }
28
+ function formatBacklogAge(ageMs) {
29
+ if (ageMs >= MS_PER_DAY) return `${String(Math.floor(ageMs / MS_PER_DAY))}d`;
30
+ if (ageMs >= MS_PER_HOUR) return `${String(Math.floor(ageMs / MS_PER_HOUR))}h`;
31
+ if (ageMs >= MS_PER_MINUTE) return `${String(Math.floor(ageMs / MS_PER_MINUTE))}m`;
32
+ return `${String(Math.max(0, Math.floor(ageMs / MS_PER_SECOND)))}s`;
33
+ }
34
+ function formatPendingBacklog(backlog, now = Date.now()) {
35
+ const count = backlog.pendingCount;
36
+ const moves = typeof count === "number" && count > 0 ? `${backlog.pendingSampled ? "at least " : ""}${String(count)} pending move${count === 1 ? "" : "s"}` : "an unknown number of pending moves";
37
+ const age = backlog.oldestPendingAt === void 0 ? "" : ` (oldest ${backlog.pendingSampled ? "\u2265 " : ""}${formatBacklogAge(now - backlog.oldestPendingAt)})`;
38
+ return `${moves}${age}`;
39
+ }
40
+ function deliveryBacklogSummary(ingestion, now = Date.now(), backlog = ingestion) {
41
+ const state = deliveryBacklogState(ingestion);
42
+ if (!(state && ingestion && backlog)) return void 0;
43
+ const pending = formatPendingBacklog(backlog, now);
44
+ if (state === "draining") return `draining ${pending} in the background`;
45
+ if (state === "retained") {
46
+ const buckets = ingestion.lastRetainedBucketCount ?? 0;
47
+ const reasons = boundedHealthError(ingestion.lastRetainedReasons);
48
+ return `delivery held back: ${String(buckets)} journal bucket${buckets === 1 ? "" : "s"} retained${reasons ? ` (${reasons})` : ""} \xB7 holding ${pending} \u2014 run \`prim doctor\``;
49
+ }
50
+ const failures = ingestion.consecutiveFailures;
51
+ const count = isPositiveInteger(failures) ? ` (${String(failures)} consecutive failure${failures === 1 ? "" : "s"})` : "";
52
+ const error = boundedHealthError(ingestion.lastError);
53
+ return `delivery failing${count}${error ? `: ${error}` : ""} \xB7 retrying ${pending} in the background`;
54
+ }
55
+
56
+ // src/lib/presence.ts
57
+ var DECISION_ORIGIN = "https://app.getprimitive.ai";
58
+ function validDecisionUrl(value) {
59
+ if (typeof value !== "string" || stripControlChars(value) !== value) {
60
+ return void 0;
61
+ }
62
+ try {
63
+ const url = new URL(value);
64
+ if (url.origin !== DECISION_ORIGIN || url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "" || !/^\/decisions\/[^/]+$/u.test(url.pathname)) {
65
+ return void 0;
66
+ }
67
+ return url.href;
68
+ } catch {
69
+ return void 0;
70
+ }
71
+ }
72
+ function decisionLink(label, decisionUrl, plain) {
73
+ const url = validDecisionUrl(decisionUrl);
74
+ if (plain || !url) {
75
+ return label;
76
+ }
77
+ return `\x1B]8;;${url}\x07\x1B[34;4m${label}\x1B[0m\x1B]8;;\x07`;
78
+ }
79
+ function formatLabeled(labels, cap) {
80
+ if (labels === void 0) {
81
+ return "\u2014";
82
+ }
83
+ if (labels.length === 0) {
84
+ return "just you";
85
+ }
86
+ if (labels.length <= cap) {
87
+ return labels.join(", ");
88
+ }
89
+ return `${labels.slice(0, cap).join(", ")} +${String(labels.length - cap)}`;
90
+ }
91
+ function formatTeammates(names, cap) {
92
+ return formatLabeled(names?.map(stripControlChars), cap);
93
+ }
94
+ function formatTeammatesWithArea(teammates, cap, plainLinks = false) {
95
+ return formatLabeled(
96
+ teammates?.map((t) => {
97
+ const name = stripControlChars(t.name);
98
+ const area = stripControlChars(t.area ?? "").trim();
99
+ const label = area ? `${name} - ${area}` : name;
100
+ return decisionLink(label, t.decisionUrl, plainLinks);
101
+ }),
102
+ cap
103
+ );
104
+ }
105
+
106
+ // src/lib/statusline-render.ts
107
+ function repositoryBindingDiagnosticLabel(state) {
108
+ if (state === "unbound") return "GitHub repo connection: required (run `prim github connect`)";
109
+ if (state === "invalid") return "GitHub repo connection: invalid (run `prim doctor`)";
110
+ return void 0;
111
+ }
112
+ var STATUSLINE_NAME_CAP = 3;
113
+ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {}) {
114
+ const ingestionSuffix = (status) => status === void 0 ? "" : ` \xB7 Decision ingestion ${status}`;
115
+ const ingestionStatus = snapshot === null || snapshot.healthy === false ? options.includeIngestionWhenUnavailable ? resolveIngestionStatus() : void 0 : resolveIngestionStatus();
116
+ if (snapshot?.healthy === false && snapshot.needsReauth) {
117
+ return `primitive ${version} (daemon: paused \xB7 run \`prim auth login\`${ingestionSuffix(ingestionStatus)})`;
118
+ }
119
+ const repositoryLabel = repositoryBindingDiagnosticLabel(
120
+ snapshot !== null && snapshot.healthy !== false || options.includeIngestionWhenUnavailable === true ? options.resolveRepositoryBindingState?.() : void 0
121
+ );
122
+ const repositorySuffix = repositoryLabel ? ` \xB7 ${repositoryLabel}` : "";
123
+ if (!snapshot) {
124
+ return `primitive ${version} (daemon: down${repositorySuffix}${ingestionSuffix(ingestionStatus)})`;
125
+ }
126
+ if (snapshot.healthy === false) {
127
+ if (snapshot.ingestion?.healthy === false) {
128
+ const pending = snapshot.ingestion.pendingCount;
129
+ const qualifier = snapshot.ingestion.pendingSampled ? "at least " : "";
130
+ const delivery = deliveryBacklogState(snapshot.ingestion) === "draining" && snapshot.heartbeat?.healthy === true ? "draining" : "stalled";
131
+ return `primitive ${version} (daemon: degraded \xB7 delivery: ${delivery}${typeof pending === "number" ? ` \xB7 ${qualifier}${String(pending)} pending` : ""}${repositorySuffix}${ingestionSuffix(ingestionStatus)})`;
132
+ }
133
+ if (snapshot.heartbeat?.healthy === false) {
134
+ return `primitive ${version} (daemon: degraded \xB7 presence: unavailable${repositorySuffix}${ingestionSuffix(ingestionStatus)})`;
135
+ }
136
+ return `primitive ${version} (daemon: starting${repositorySuffix}${ingestionSuffix(ingestionStatus)})`;
137
+ }
138
+ if (snapshot.envMismatch) {
139
+ return `primitive ${version} (daemon: live, Decision ingestion ${ingestionStatus}${repositorySuffix} \xB7 presence: other env)`;
140
+ }
141
+ if (snapshot.principalMismatch) {
142
+ return `primitive ${version} (daemon: live, Decision ingestion ${ingestionStatus}${repositorySuffix} \xB7 presence: other account)`;
143
+ }
144
+ if (snapshot.presenceStale) {
145
+ return `primitive ${version} (daemon: live, Decision ingestion ${ingestionStatus}${repositorySuffix} \xB7 presence: stale)`;
146
+ }
147
+ let team;
148
+ if (snapshot.onlineTeammates !== void 0) {
149
+ team = `team: ${formatTeammatesWithArea(snapshot.onlineTeammates, STATUSLINE_NAME_CAP, options.plainLinks === true)}`;
150
+ } else if (snapshot.onlineNames !== void 0) {
151
+ team = `team: ${formatTeammates(snapshot.onlineNames, STATUSLINE_NAME_CAP)}`;
152
+ } else if (typeof snapshot.onlineCount === "number") {
153
+ team = `team: ${String(snapshot.onlineCount)} online`;
154
+ } else {
155
+ team = "team: \u2014";
156
+ }
157
+ return `primitive ${version} (daemon: live, Decision ingestion ${ingestionStatus}${repositorySuffix} \xB7 ${team})`;
158
+ }
159
+
160
+ export {
161
+ MS_PER_SECOND,
162
+ deliveryBacklogState,
163
+ formatPendingBacklog,
164
+ deliveryBacklogSummary,
165
+ formatTeammates,
166
+ repositoryBindingDiagnosticLabel,
167
+ formatStatusline
168
+ };