loopctl-mcp-server 3.46.1 → 3.47.0

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.
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `knowledge_link_create` / `knowledge_link_delete` / `knowledge_links` —
3
+ * `POST /api/v1/article_links`, `DELETE /api/v1/article_links/:id` and
4
+ * `GET /api/v1/articles/:article_id/links` (`ArticleLinkController`), loopctl #872.
5
+ *
6
+ * KEYS (article_link_controller.ex:22-28):
7
+ *
8
+ * - create is `role: :agent`, EXCEPT a `supersedes` link, which retires its target
9
+ * (published -> superseded) and is checked in the action to need `role: :user` (:122-129,
10
+ * 403 otherwise). So a `supersedes` create travels on LOOPCTL_USER_KEY verbatim when set
11
+ * (index.js `userKeyApiCall`) and every other type on the session's own key.
12
+ * - delete is `role: :user` with the hierarchy: LOOPCTL_USER_KEY.
13
+ * - the list is `role: :agent`: the session's own key. It returns outgoing and incoming links
14
+ * with the linked articles, scoped to what the key may see.
15
+ *
16
+ * Create reads `source_article_id`, `target_article_id`, `relationship_type` and `metadata`.
17
+ * `potential_conflict` is system-generated only and is 422 here like any unknown type (assert a
18
+ * conflict with knowledge_assert_conflict). 404 for a target the key cannot see; 422 for a
19
+ * duplicate link or a self-link.
20
+ *
21
+ * CHECKED HERE: a non-UUID article or link id, which would not answer the plain 404 a missing
22
+ * row does; a relationship type outside the four public ones (loopctl would 422 it anyway, but
23
+ * the key it travels on is chosen from it); a `metadata` that is not an object.
24
+ */
25
+
26
+ import { articleId } from "./article-id.js";
27
+ import { uuid } from "./delivery-loop.js";
28
+
29
+ export const LINK_RELATIONSHIP_TYPES = ["relates_to", "derived_from", "contradicts", "supersedes"];
30
+
31
+ function refuse(body) {
32
+ return { error: true, status: 0, body };
33
+ }
34
+
35
+ // ONE template literal per builder (see `test/tool-surface.js`).
36
+ export function articleLinksPath() {
37
+ return `/api/v1/article_links`;
38
+ }
39
+
40
+ export function articleLinkPath(linkId) {
41
+ return `/api/v1/article_links/${encodeURIComponent(linkId)}`;
42
+ }
43
+
44
+ export function articleLinksForArticlePath(articleIdValue) {
45
+ return `/api/v1/articles/${encodeURIComponent(articleIdValue)}/links`;
46
+ }
47
+
48
+ /**
49
+ * `deps.apiCall` is the session-key caller; `deps.userApiCall` the user-key caller, used only
50
+ * for a `supersedes` link.
51
+ */
52
+ export async function knowledgeLinkCreate(
53
+ { source_article_id, target_article_id, relationship_type, metadata } = {},
54
+ { apiCall, userApiCall } = {},
55
+ ) {
56
+ const source = uuid(source_article_id, "source_article_id");
57
+ if (source) return source;
58
+
59
+ const target = uuid(target_article_id, "target_article_id");
60
+ if (target) return target;
61
+
62
+ if (!LINK_RELATIONSHIP_TYPES.includes(relationship_type)) {
63
+ return refuse(
64
+ `\`relationship_type\` must be one of ${LINK_RELATIONSHIP_TYPES.join(", ")}. ` +
65
+ "potential_conflict is system-generated only; assert one with knowledge_assert_conflict.",
66
+ );
67
+ }
68
+
69
+ if (metadata !== undefined && (metadata === null || typeof metadata !== "object" || Array.isArray(metadata))) {
70
+ return refuse("`metadata` must be an object.");
71
+ }
72
+
73
+ const body = { source_article_id, target_article_id, relationship_type };
74
+ if (metadata !== undefined) body.metadata = metadata;
75
+
76
+ return relationship_type === "supersedes"
77
+ ? userApiCall("POST", articleLinksPath(), body)
78
+ : apiCall("POST", articleLinksPath(), body);
79
+ }
80
+
81
+ export async function knowledgeLinkDelete({ link_id } = {}, { apiCall } = {}) {
82
+ return uuid(link_id, "link_id") ?? apiCall("DELETE", articleLinkPath(link_id), null);
83
+ }
84
+
85
+ export async function knowledgeLinks({ article_id } = {}, { apiCall } = {}) {
86
+ const art = articleId(article_id);
87
+ if (art.refusal) return art.refusal;
88
+
89
+ return apiCall("GET", articleLinksForArticlePath(art.id), null);
90
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `corpus_get` — `GET /api/v1/corpora/:id` (`CorpusController.show`), loopctl #872.
3
+ *
4
+ * KEY: `role: :agent` with the hierarchy (corpus_controller.ex:121-123), the session's own key,
5
+ * like every corpus verb but delete. The segment takes a corpus id or slug; 404 for one that is
6
+ * not this tenant's.
7
+ *
8
+ * The answer is the corpus (`mode`, `dim`, slug, project) plus ONE aggregate,
9
+ * `status.has_sources`: whether anything is indexed in it yet. Per-source chunk counts and
10
+ * content hashes are corpus_status, which pages.
11
+ */
12
+
13
+ import { corpusPath } from "./http-helpers.js";
14
+
15
+ export async function corpusGet({ corpus_id } = {}, { apiCall } = {}) {
16
+ if (typeof corpus_id !== "string" || corpus_id.trim() === "") {
17
+ return { error: true, status: 0, body: "`corpus_id` is required: the corpus id or slug." };
18
+ }
19
+
20
+ return apiCall("GET", corpusPath(corpus_id), null);
21
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * `entity_list` / `entity_get` / `entity_create` / `entity_update` / `entity_delete` —
3
+ * `GET /api/v1/entities`, `GET /api/v1/entities/:id`, `POST /api/v1/entities`,
4
+ * `PATCH /api/v1/entities/:id` and `DELETE /api/v1/entities/:id`
5
+ * (`ContextRetrieverController`, Epic 30), loopctl #872.
6
+ *
7
+ * An entity definition is the SECURITY ROOT of the Context Retriever: its declared fields are
8
+ * the executor's allowlist, and every `cr_filter_*` / `cr_search_*` tool is generated from it.
9
+ *
10
+ * KEY: create, update and delete are `role: :user` with the hierarchy AND behind
11
+ * `RequireHumanAnchor` (context_retriever_controller.ex:59, :69), so an agent or orchestrator
12
+ * key is 403 insufficient_role and an agent-rooted tenant is 403 custody_tier_required. They
13
+ * travel on LOOPCTL_USER_KEY verbatim when set (index.js `userKeyApiCall`). List and show are
14
+ * `role: :agent` (:61-62): any key of the tenant, so they travel on the session's own key.
15
+ *
16
+ * The controller reads `name`, `backing_source` and `fields` and nothing else (`@entity_attr_keys`,
17
+ * :73); scope comes from the key. A superadmin key with no impersonation target is 422
18
+ * impersonation_tenant_required.
19
+ *
20
+ * CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
21
+ *
22
+ * - a non-UUID entity id, which would not answer the plain 404 a missing definition does;
23
+ * - an update naming no field: loopctl keeps every omitted field and answers 200 unchanged.
24
+ *
25
+ * Which columns a source allowlists, the field types and the per-tenant limit are loopctl's to
26
+ * judge (422 with the reason), so a malformed definition is sent.
27
+ */
28
+
29
+ import { uuid } from "./delivery-loop.js";
30
+
31
+ export const ENTITY_BACKING_SOURCES = ["projects", "stories", "epics"];
32
+
33
+ function refuse(body) {
34
+ return { error: true, status: 0, body };
35
+ }
36
+
37
+ // ONE template literal per builder (see `test/tool-surface.js`).
38
+ export function entitiesPath() {
39
+ return `/api/v1/entities`;
40
+ }
41
+
42
+ export function entityPath(entityId) {
43
+ return `/api/v1/entities/${encodeURIComponent(entityId)}`;
44
+ }
45
+
46
+ function badName(name) {
47
+ if (typeof name !== "string" || name.trim() === "") {
48
+ return refuse("`name` must be a non-empty string (lowercase snake_case, at most 100 characters).");
49
+ }
50
+ return null;
51
+ }
52
+
53
+ function badBackingSource(source) {
54
+ if (!ENTITY_BACKING_SOURCES.includes(source)) {
55
+ return refuse(`\`backing_source\` must be one of ${ENTITY_BACKING_SOURCES.join(", ")}.`);
56
+ }
57
+ return null;
58
+ }
59
+
60
+ function badFields(fields) {
61
+ if (
62
+ !Array.isArray(fields) ||
63
+ fields.length === 0 ||
64
+ fields.some((f) => f === null || typeof f !== "object" || Array.isArray(f))
65
+ ) {
66
+ return refuse(
67
+ "`fields` must be a non-empty list of objects, each `{name, type, filterable, " +
68
+ "searchable}`; loopctl answers 422 naming any column its source does not allowlist.",
69
+ );
70
+ }
71
+ return null;
72
+ }
73
+
74
+ export async function entityList(_args = {}, { apiCall } = {}) {
75
+ return apiCall("GET", entitiesPath(), null);
76
+ }
77
+
78
+ export async function entityGet({ entity_id } = {}, { apiCall } = {}) {
79
+ return uuid(entity_id, "entity_id") ?? apiCall("GET", entityPath(entity_id), null);
80
+ }
81
+
82
+ export async function entityCreate({ name, backing_source, fields } = {}, { apiCall } = {}) {
83
+ const bad = badName(name) ?? badBackingSource(backing_source) ?? badFields(fields);
84
+ if (bad) return bad;
85
+
86
+ return apiCall("POST", entitiesPath(), { name, backing_source, fields });
87
+ }
88
+
89
+ export async function entityUpdate(
90
+ { entity_id, name, backing_source, fields } = {},
91
+ { apiCall } = {},
92
+ ) {
93
+ const idBad = uuid(entity_id, "entity_id");
94
+ if (idBad) return idBad;
95
+
96
+ const body = {};
97
+
98
+ if (name !== undefined) {
99
+ const bad = badName(name);
100
+ if (bad) return bad;
101
+ body.name = name;
102
+ }
103
+
104
+ if (backing_source !== undefined) {
105
+ const bad = badBackingSource(backing_source);
106
+ if (bad) return bad;
107
+ body.backing_source = backing_source;
108
+ }
109
+
110
+ if (fields !== undefined) {
111
+ const bad = badFields(fields);
112
+ if (bad) return bad;
113
+ body.fields = fields;
114
+ }
115
+
116
+ if (Object.keys(body).length === 0) {
117
+ return refuse(
118
+ "Name at least one of `name`, `backing_source`, `fields`: loopctl would answer 200 " +
119
+ "with the definition unchanged.",
120
+ );
121
+ }
122
+
123
+ return apiCall("PATCH", entityPath(entity_id), body);
124
+ }
125
+
126
+ export async function entityDelete({ entity_id } = {}, { apiCall } = {}) {
127
+ return uuid(entity_id, "entity_id") ?? apiCall("DELETE", entityPath(entity_id), null);
128
+ }
@@ -0,0 +1,242 @@
1
+ /**
2
+ * `knowledge_project_usage`, `knowledge_pipeline` and `knowledge_export` — the knowledge-wiki
3
+ * reads an operator runs over a whole tenant or project, loopctl #872.
4
+ *
5
+ * - `knowledge_project_usage`: `GET /api/v1/knowledge/analytics/projects/:id/usage`
6
+ * (`KnowledgeAnalyticsController.project_usage`), `role: :orchestrator` with the hierarchy
7
+ * (knowledge_analytics_controller.ex:28). Reads `since_days` (clamped 1..365, default 7)
8
+ * and `limit` (clamped 1..100, default 20). The `:id` segment is NOT a `project_id` param,
9
+ * so `ResolveProjectRef` never rewrites it: a slug or repo name is cast as a UUID, fails, and
10
+ * answers 404 as if the project did not exist. Hence the UUID check here.
11
+ * - `knowledge_pipeline`: `GET /api/v1/knowledge/pipeline` (`KnowledgePipelineController.status`),
12
+ * `role: :orchestrator`; reads no parameter.
13
+ * - `knowledge_export`: `GET /api/v1/knowledge/export` and
14
+ * `GET /api/v1/projects/:project_id/knowledge/export` (`KnowledgeExportController.export`),
15
+ * `role: :user` with the hierarchy. It STREAMS a gzipped tar of published articles in
16
+ * Obsidian layout, which cannot be decoded as text without corrupting it, so the tool writes
17
+ * it to `out_file` (an absolute path that must not exist yet, created 0600 before the
18
+ * request) and returns where it went. The controller reads only `project_id` (UUID, slug or
19
+ * repo name; it is a `project_id` path param, so `ResolveProjectRef` resolves it). Too many
20
+ * concurrent exports is 429.
21
+ *
22
+ * FAIL-CLOSED, END TO END. loopctl ends a failed export WITHOUT the gzip trailer and the tar
23
+ * end-of-archive (`Loopctl.Knowledge.StreamingExport`), on a 200 it can no longer take back. So
24
+ * a saved archive is gunzipped once to the end before it is reported; one that does not
25
+ * decompress to the end, or does not end in the tar end-of-archive (two zero blocks), is
26
+ * deleted and reported as truncated, and so is a download the connection broke off. A
27
+ * truncated archive is never left where a restore would read it.
28
+ */
29
+
30
+ import { createReadStream, createWriteStream } from "node:fs";
31
+ import { isAbsolute } from "node:path";
32
+ import { Readable, Writable } from "node:stream";
33
+ import { pipeline } from "node:stream/promises";
34
+ import { createGunzip } from "node:zlib";
35
+
36
+ import { uuid } from "./delivery-loop.js";
37
+ import { stageOutFile } from "./secret-file.js";
38
+
39
+ export const PROJECT_USAGE_MAX_DAYS = 365;
40
+ export const PROJECT_USAGE_MAX_LIMIT = 100;
41
+ // A streamed export of a large wiki outlives the 30 s default request timeout.
42
+ export const EXPORT_TIMEOUT_MS = 600_000;
43
+ const TAR_END_OF_ARCHIVE = 1024;
44
+
45
+ function refuse(body) {
46
+ return { error: true, status: 0, body };
47
+ }
48
+
49
+ // ONE template literal per builder (see `test/tool-surface.js`).
50
+ export function projectUsagePath(projectId, query = "") {
51
+ return `/api/v1/knowledge/analytics/projects/${encodeURIComponent(projectId)}/usage${query}`;
52
+ }
53
+
54
+ export function knowledgePipelinePath() {
55
+ return `/api/v1/knowledge/pipeline`;
56
+ }
57
+
58
+ export function knowledgeExportPath() {
59
+ return `/api/v1/knowledge/export`;
60
+ }
61
+
62
+ export function projectKnowledgeExportPath(projectId) {
63
+ return `/api/v1/projects/${encodeURIComponent(projectId)}/knowledge/export`;
64
+ }
65
+
66
+ export async function knowledgeProjectUsage(
67
+ { project_id, since_days, limit } = {},
68
+ { apiCall } = {},
69
+ ) {
70
+ const idBad = uuid(project_id, "project_id");
71
+ if (idBad) return idBad;
72
+
73
+ if (
74
+ since_days !== undefined &&
75
+ !(Number.isInteger(since_days) && since_days >= 1 && since_days <= PROJECT_USAGE_MAX_DAYS)
76
+ ) {
77
+ return refuse(
78
+ `\`since_days\` must be an integer from 1 to ${PROJECT_USAGE_MAX_DAYS} (default 7); ` +
79
+ "loopctl would clamp any other value without saying so.",
80
+ );
81
+ }
82
+
83
+ if (
84
+ limit !== undefined &&
85
+ !(Number.isInteger(limit) && limit >= 1 && limit <= PROJECT_USAGE_MAX_LIMIT)
86
+ ) {
87
+ return refuse(
88
+ `\`limit\` must be an integer from 1 to ${PROJECT_USAGE_MAX_LIMIT} (default 20); ` +
89
+ "loopctl would clamp any other value without saying so.",
90
+ );
91
+ }
92
+
93
+ const params = new URLSearchParams();
94
+ if (since_days !== undefined) params.set("since_days", String(since_days));
95
+ if (limit !== undefined) params.set("limit", String(limit));
96
+ const qs = params.toString();
97
+
98
+ return apiCall("GET", projectUsagePath(project_id, qs === "" ? "" : `?${qs}`), null);
99
+ }
100
+
101
+ export async function knowledgePipeline(_args = {}, { apiCall } = {}) {
102
+ return apiCall("GET", knowledgePipelinePath(), null);
103
+ }
104
+
105
+ /**
106
+ * Gunzip the saved archive to the end. Resolves `{ ok: true, bytes }` when it decompresses
107
+ * completely and ends in the tar end-of-archive, else `{ ok: false, reason }`.
108
+ */
109
+ export async function verifyArchive(file) {
110
+ let total = 0;
111
+ let tail = Buffer.alloc(0);
112
+
113
+ const sink = new Writable({
114
+ write(chunk, _encoding, done) {
115
+ total += chunk.length;
116
+ tail = Buffer.concat([tail, chunk]).subarray(-TAR_END_OF_ARCHIVE);
117
+ done();
118
+ },
119
+ });
120
+
121
+ try {
122
+ await pipeline(createReadStream(file), createGunzip(), sink);
123
+ } catch (error) {
124
+ return { ok: false, reason: `it does not decompress to the end (${error.code || error.message})` };
125
+ }
126
+
127
+ if (tail.length < TAR_END_OF_ARCHIVE || tail.some((byte) => byte !== 0)) {
128
+ return { ok: false, reason: "it does not end in the tar end-of-archive" };
129
+ }
130
+
131
+ return { ok: true, bytes: total };
132
+ }
133
+
134
+ /**
135
+ * `deps.apiCall(method, path, body, opts)` is the user-key caller; it must forward
136
+ * `opts.saveBody` and `opts.timeoutMs` to the request (index.js `pinnedApiCall`).
137
+ */
138
+ export async function knowledgeExport({ project_id, out_file } = {}, { apiCall } = {}) {
139
+ if (project_id !== undefined && (typeof project_id !== "string" || project_id.trim() === "")) {
140
+ return refuse("`project_id` must be a project's UUID, slug or repo name, or left out.");
141
+ }
142
+
143
+ if (typeof out_file !== "string" || !isAbsolute(out_file)) {
144
+ return refuse(
145
+ "`out_file` must be an absolute path that does not exist yet (e.g. " +
146
+ "/tmp/knowledge-export.tar.gz). The archive is binary, so it is written there and " +
147
+ "never returned.",
148
+ );
149
+ }
150
+
151
+ // The download lands in a temp file beside out_file and is linked to out_file only after
152
+ // verifyArchive passes, so a process killed mid-stream never leaves a partial archive at
153
+ // the path a restore reads.
154
+ let staged;
155
+ try {
156
+ staged = stageOutFile(out_file);
157
+ } catch (error) {
158
+ return refuse(
159
+ `${out_file} could not be created (${error.code || error.message}); nothing was sent. ` +
160
+ "Pass a path that does not exist yet, in a directory that does.",
161
+ );
162
+ }
163
+
164
+ const saveBody = async (response) => {
165
+ if (!response.body) {
166
+ staged.closeStaged();
167
+ return { saved: true };
168
+ }
169
+
170
+ // The write stream owns the descriptor from here and closes it, error or not.
171
+ const sink = createWriteStream(staged.tmpPath, { fd: staged.fd });
172
+ staged.releaseStaged();
173
+
174
+ try {
175
+ await pipeline(Readable.fromWeb(response.body), sink);
176
+ return { saved: true };
177
+ } catch (error) {
178
+ return {
179
+ error: true,
180
+ status: 0,
181
+ body: `The archive download broke off (${error.code || error.message}).`,
182
+ };
183
+ }
184
+ };
185
+
186
+ let result;
187
+ try {
188
+ result = await apiCall(
189
+ "GET",
190
+ project_id === undefined ? knowledgeExportPath() : projectKnowledgeExportPath(project_id),
191
+ null,
192
+ { saveBody, timeoutMs: EXPORT_TIMEOUT_MS },
193
+ );
194
+ } catch (error) {
195
+ staged.discardStaged();
196
+ throw error;
197
+ }
198
+
199
+ staged.closeStaged();
200
+
201
+ if (!result || result.saved !== true) {
202
+ staged.discardStaged();
203
+ if (result && result.error) {
204
+ return { ...result, body: withNothingKept(result.body, out_file) };
205
+ }
206
+ return result;
207
+ }
208
+
209
+ const verdict = await verifyArchive(staged.tmpPath);
210
+ if (!verdict.ok) {
211
+ staged.discardStaged();
212
+ return {
213
+ error: true,
214
+ status: 0,
215
+ body:
216
+ `The export arrived truncated: ${verdict.reason}. loopctl ends a failed export that ` +
217
+ `way on purpose, and ${out_file} was deleted so no restore reads a partial archive. ` +
218
+ "Retry; a repeat failure is loopctl's to investigate.",
219
+ };
220
+ }
221
+
222
+ try {
223
+ staged.publishStaged();
224
+ } catch (error) {
225
+ return refuse(
226
+ `The archive verified but could not be placed at ${out_file} ` +
227
+ `(${error.code || error.message}); nothing was kept.`,
228
+ );
229
+ }
230
+
231
+ return {
232
+ out_file,
233
+ format: "tar.gz",
234
+ uncompressed_bytes: verdict.bytes,
235
+ extract: `tar -xzf ${out_file}`,
236
+ };
237
+ }
238
+
239
+ function withNothingKept(body, file) {
240
+ const text = typeof body === "string" ? body : JSON.stringify(body);
241
+ return `${text} Nothing was kept: ${file} was deleted.`;
242
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * `project_export` — `GET /api/v1/projects/:id/export` (`ImportExportController.export_project`),
3
+ * loopctl #872.
4
+ *
5
+ * KEY: `role: :agent` with the hierarchy (import_export_controller.ex:22) and NOT human-anchored
6
+ * (:25-26, a read-only op a KB-tier tenant may run), so it travels on the session's own key.
7
+ * 404 for a project that is not this tenant's. The action reads no parameter but the id.
8
+ *
9
+ * The answer is the project's whole work breakdown as JSON (`export_metadata`, `project`,
10
+ * `epics` with their stories, `story_dependencies`, `epic_dependencies`), the shape
11
+ * `import_stories` takes back. A large project is too big for a transcript, so `out_file`
12
+ * writes it to disk (an absolute path that must not exist yet) and the result carries counts.
13
+ *
14
+ * CHECKED HERE, because the server would answer it WRONGLY rather than refuse: a non-UUID
15
+ * project id. The segment is `:id`, not `project_id`, so `ResolveProjectRef` never resolves a
16
+ * slug or repo name there, and `ImportExport.export_project/2` answers 404 for it as if the
17
+ * project did not exist. Resolve a slug with resolve_project first.
18
+ */
19
+
20
+ import { writeSync } from "node:fs";
21
+ import { isAbsolute } from "node:path";
22
+
23
+ import { uuid } from "./delivery-loop.js";
24
+ import { stageOutFile } from "./secret-file.js";
25
+
26
+ function refuse(body) {
27
+ return { error: true, status: 0, body };
28
+ }
29
+
30
+ // ONE template literal per builder (see `test/tool-surface.js`).
31
+ export function projectExportPath(projectId) {
32
+ return `/api/v1/projects/${encodeURIComponent(projectId)}/export`;
33
+ }
34
+
35
+ function summarize(exported) {
36
+ const epics = Array.isArray(exported.epics) ? exported.epics : [];
37
+ const stories = epics.reduce(
38
+ (sum, epic) => sum + (Array.isArray(epic.stories) ? epic.stories.length : 0),
39
+ 0,
40
+ );
41
+
42
+ return {
43
+ project: exported.project,
44
+ export_metadata: exported.export_metadata,
45
+ epics: epics.length,
46
+ stories,
47
+ story_dependencies: Array.isArray(exported.story_dependencies)
48
+ ? exported.story_dependencies.length
49
+ : 0,
50
+ epic_dependencies: Array.isArray(exported.epic_dependencies)
51
+ ? exported.epic_dependencies.length
52
+ : 0,
53
+ };
54
+ }
55
+
56
+ export async function projectExport({ project_id, out_file } = {}, { apiCall } = {}) {
57
+ const idBad = uuid(project_id, "project_id");
58
+ if (idBad) return idBad;
59
+
60
+ if (out_file === undefined) {
61
+ return apiCall("GET", projectExportPath(project_id), null);
62
+ }
63
+
64
+ if (typeof out_file !== "string" || !isAbsolute(out_file)) {
65
+ return refuse("`out_file` must be an absolute path that does not exist yet, or left out.");
66
+ }
67
+
68
+ let staged;
69
+ try {
70
+ staged = stageOutFile(out_file);
71
+ } catch (error) {
72
+ return refuse(
73
+ `${out_file} could not be created (${error.code || error.message}); nothing was sent. ` +
74
+ "Pass a path that does not exist yet, in a directory that does.",
75
+ );
76
+ }
77
+
78
+ let result;
79
+ try {
80
+ result = await apiCall("GET", projectExportPath(project_id), null);
81
+ } catch (error) {
82
+ staged.discardStaged();
83
+ throw error;
84
+ }
85
+
86
+ if (!result || result.error || typeof result !== "object") {
87
+ staged.discardStaged();
88
+ return result;
89
+ }
90
+
91
+ try {
92
+ writeSync(staged.fd, JSON.stringify(result, null, 2) + "\n");
93
+ staged.publishStaged();
94
+ } catch (error) {
95
+ staged.discardStaged();
96
+ return refuse(`${out_file} could not be written (${error.code || error.message}).`);
97
+ }
98
+
99
+ return { out_file, ...summarize(result) };
100
+ }
@@ -10,7 +10,8 @@
10
10
  * bare `write(` call would be credited with the holder journal's `write` and its routes.
11
11
  */
12
12
 
13
- import { closeSync, openSync, unlinkSync, writeSync } from "node:fs";
13
+ import { randomBytes } from "node:crypto";
14
+ import { closeSync, existsSync, linkSync, openSync, unlinkSync, writeSync } from "node:fs";
14
15
 
15
16
  /**
16
17
  * Whether a request that should have produced a secret, and did not hand one over, may still
@@ -39,6 +40,64 @@ export function unknownOutcomeDetail(result) {
39
40
  : `HTTP ${status ?? "?"}; response body withheld: it may contain the secret`;
40
41
  }
41
42
 
43
+ /**
44
+ * An output file that appears at `path` only once it is complete. The bytes go to a 0600
45
+ * temp file beside it (created exclusively), and `publish()` hard-links that file to `path`,
46
+ * which fails with EEXIST rather than replace anything, then removes the temp name. A crash
47
+ * mid-write therefore leaves at most a `.partial-*` file, never a truncated `path` a reader
48
+ * could mistake for the real thing. `path` existing at the start is refused up front.
49
+ */
50
+ export function stageOutFile(path) {
51
+ if (existsSync(path)) {
52
+ const error = new Error(`${path} already exists`);
53
+ error.code = "EEXIST";
54
+ throw error;
55
+ }
56
+
57
+ const tmpPath = `${path}.partial-${process.pid}-${randomBytes(6).toString("hex")}`;
58
+ const fd = openSync(tmpPath, "wx", 0o600);
59
+ let open = true;
60
+
61
+ const close = () => {
62
+ if (open) {
63
+ open = false;
64
+ closeSync(fd);
65
+ }
66
+ };
67
+
68
+ const discard = () => {
69
+ close();
70
+ try {
71
+ unlinkSync(tmpPath);
72
+ } catch {
73
+ // already gone
74
+ }
75
+ };
76
+
77
+ return {
78
+ fd,
79
+ tmpPath,
80
+ // Hand the descriptor to a stream that closes it itself.
81
+ releaseStaged: () => {
82
+ open = false;
83
+ },
84
+ closeStaged: close,
85
+ publishStaged: () => {
86
+ close();
87
+ try {
88
+ linkSync(tmpPath, path);
89
+ } finally {
90
+ try {
91
+ unlinkSync(tmpPath);
92
+ } catch {
93
+ // already gone
94
+ }
95
+ }
96
+ },
97
+ discardStaged: discard,
98
+ };
99
+ }
100
+
42
101
  export function createSecretFile(path) {
43
102
  const fd = openSync(path, "wx", 0o600);
44
103
  let open = true;