@gonovus-ai/spec-flow-cli 1.0.1 → 1.2.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.
Files changed (51) hide show
  1. package/README.md +24 -3
  2. package/dist/agent-commands.d.ts +11 -0
  3. package/dist/agent-commands.js +613 -0
  4. package/dist/agent-commands.js.map +1 -0
  5. package/dist/agent-session-commands.d.ts +3 -0
  6. package/dist/agent-session-commands.js +367 -0
  7. package/dist/agent-session-commands.js.map +1 -0
  8. package/dist/board-commands.d.ts +3 -0
  9. package/dist/board-commands.js +381 -0
  10. package/dist/board-commands.js.map +1 -0
  11. package/dist/cli.d.ts +4 -0
  12. package/dist/cli.js +117 -3
  13. package/dist/cli.js.map +1 -1
  14. package/dist/commands/work-item-output.d.ts +182 -0
  15. package/dist/commands/work-item-output.js +1 -0
  16. package/dist/commands/work-item-output.js.map +1 -1
  17. package/dist/context-agents-block.d.ts +57 -0
  18. package/dist/context-agents-block.js +331 -0
  19. package/dist/context-agents-block.js.map +1 -0
  20. package/dist/context-command-support.d.ts +186 -0
  21. package/dist/context-command-support.js +176 -0
  22. package/dist/context-command-support.js.map +1 -0
  23. package/dist/context-document-commands.d.ts +5 -0
  24. package/dist/context-document-commands.js +674 -0
  25. package/dist/context-document-commands.js.map +1 -0
  26. package/dist/index.js +42 -2
  27. package/dist/index.js.map +1 -1
  28. package/dist/program.js +1 -0
  29. package/dist/program.js.map +1 -1
  30. package/dist/resource-command-runtime.d.ts +1 -0
  31. package/dist/runtime/errors.d.ts +21 -0
  32. package/dist/runtime/errors.js +92 -1
  33. package/dist/runtime/errors.js.map +1 -1
  34. package/dist/runtime/execute.d.ts +9 -0
  35. package/dist/runtime/execute.js +18 -4
  36. package/dist/runtime/execute.js.map +1 -1
  37. package/dist/runtime/session.d.ts +1 -1
  38. package/dist/runtime/session.js +22 -11
  39. package/dist/runtime/session.js.map +1 -1
  40. package/dist/work-item-query-commands.js +48 -6
  41. package/dist/work-item-query-commands.js.map +1 -1
  42. package/dist/work-item-resource-link-commands.js +36 -0
  43. package/dist/work-item-resource-link-commands.js.map +1 -1
  44. package/dist/work-item-thread-commands.js +14 -1
  45. package/dist/work-item-thread-commands.js.map +1 -1
  46. package/guides/agent-sessions.md +110 -0
  47. package/guides/boards.md +123 -0
  48. package/guides/context-documents.md +181 -0
  49. package/guides/errors.md +15 -0
  50. package/guides/work-items.md +7 -0
  51. package/package.json +1 -1
@@ -0,0 +1,674 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { chmod, lstat, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { z } from "zod";
7
+ import { applyContextBlock, checkContextBlocks, ContextBlockError, readContextBlockMetadata, renderContextBlock, repositoryFromRemote, unifiedDiff, } from "./context-agents-block.js";
8
+ import { collectRepository, documentSummary, draftView, invalidArgument, mapData, parseDocumentVersion, parseIdentity, parseJsonInput, parseRepository, readTextInput, reviewNotice, revisionView, uncertainWriteOptions, } from "./context-command-support.js";
9
+ const run = promisify(execFile);
10
+ const parseWorkspaceId = parseIdentity("Workspace ID");
11
+ const parseDocumentId = parseIdentity("Context Document ID");
12
+ const maximumBodyBytes = 1_000_000;
13
+ async function git(directory, args) {
14
+ try {
15
+ const { stdout } = await run("git", ["-C", directory, ...args], {
16
+ timeout: 5_000,
17
+ windowsHide: true,
18
+ });
19
+ return stdout.trim();
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ /** `owner/name` of the checkout's `origin` remote, or of its only remote. */
26
+ export async function inferRepository(directory) {
27
+ const origin = await git(directory, ["remote", "get-url", "origin"]);
28
+ if (origin)
29
+ return repositoryFromRemote(origin);
30
+ const remotes = (await git(directory, ["remote"]))?.split("\n").filter(Boolean) ?? [];
31
+ if (remotes.length !== 1 || remotes[0] === undefined)
32
+ return null;
33
+ const url = await git(directory, ["remote", "get-url", remotes[0]]);
34
+ return url ? repositoryFromRemote(url) : null;
35
+ }
36
+ async function requireRepository(repository, directory) {
37
+ const resolved = repository ?? (await inferRepository(directory));
38
+ if (resolved === null)
39
+ throw invalidArgument("Pass --repository owner/name; it could not be inferred from this checkout's Git remote");
40
+ return resolved;
41
+ }
42
+ function isMissing(error) {
43
+ return error.code === "ENOENT";
44
+ }
45
+ async function readBytes(file) {
46
+ try {
47
+ return await readFile(file);
48
+ }
49
+ catch (error) {
50
+ if (isMissing(error))
51
+ return null;
52
+ throw error;
53
+ }
54
+ }
55
+ /** Reads the agent instructions file through any symlink, refusing text that is not UTF-8. */
56
+ async function readAgentsFile(file) {
57
+ let target = file;
58
+ try {
59
+ await lstat(file);
60
+ target = await realpath(file);
61
+ }
62
+ catch (error) {
63
+ if (!isMissing(error))
64
+ throw invalidArgument("The agent instructions file could not be read");
65
+ // A symlink whose target is missing is not created behind the user's back.
66
+ const link = await lstat(file).catch(() => null);
67
+ if (link?.isSymbolicLink() === true)
68
+ throw invalidArgument("The agent instructions file is a symlink to a missing file");
69
+ }
70
+ let bytes;
71
+ let mode = null;
72
+ try {
73
+ bytes = await readBytes(target);
74
+ if (bytes !== null)
75
+ mode = (await stat(target)).mode & 0o7777;
76
+ }
77
+ catch {
78
+ throw invalidArgument("The agent instructions file could not be read");
79
+ }
80
+ let text = null;
81
+ if (bytes !== null) {
82
+ try {
83
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
84
+ }
85
+ catch {
86
+ throw invalidArgument("The agent instructions file is not valid UTF-8; convert it before syncing");
87
+ }
88
+ }
89
+ try {
90
+ checkContextBlocks(text);
91
+ }
92
+ catch (error) {
93
+ if (error instanceof ContextBlockError)
94
+ throw invalidArgument(`${error.message}; fix the markers in ${basename(file)} by hand, then sync again`);
95
+ throw error;
96
+ }
97
+ return { target, bytes, text, mode };
98
+ }
99
+ /**
100
+ * Replaces the file atomically, keeping its mode, unless it changed since it was read:
101
+ * a concurrent edit is refused rather than overwritten.
102
+ */
103
+ async function writeAgentsFile(snapshot, next) {
104
+ const temporary = join(dirname(snapshot.target), `.${basename(snapshot.target)}.${randomUUID()}.tmp`);
105
+ let created = false;
106
+ try {
107
+ await writeFile(temporary, next, {
108
+ encoding: "utf8",
109
+ flag: "wx",
110
+ ...(snapshot.mode === null ? {} : { mode: snapshot.mode }),
111
+ });
112
+ created = true;
113
+ if (snapshot.mode !== null)
114
+ await chmod(temporary, snapshot.mode);
115
+ const current = await readBytes(snapshot.target);
116
+ const unchanged = current === null || snapshot.bytes === null
117
+ ? current === snapshot.bytes
118
+ : current.equals(snapshot.bytes);
119
+ if (!unchanged) {
120
+ await rm(temporary, { force: true });
121
+ return "changed";
122
+ }
123
+ await rename(temporary, snapshot.target);
124
+ return "written";
125
+ }
126
+ catch {
127
+ // Only the temporary file this run created is removed.
128
+ if (created)
129
+ await rm(temporary, { force: true });
130
+ return "failed";
131
+ }
132
+ }
133
+ const guardrailInput = z.object({
134
+ id: z.string().optional(),
135
+ title: z.string(),
136
+ prohibitedBehavior: z.string(),
137
+ safePath: z.string(),
138
+ repositoryGlob: z.string().nullable().optional(),
139
+ pathGlob: z.string().nullable().optional(),
140
+ });
141
+ const draftInput = z.object({
142
+ title: z.string().optional(),
143
+ body: z.string().optional(),
144
+ guardrails: z.array(guardrailInput).max(1000).optional(),
145
+ });
146
+ /** The version a `draft read` result carries, used as If-Match when the file is written back. */
147
+ function draftFileVersion(value) {
148
+ const candidate = typeof value === "object" && value !== null && "document" in value
149
+ ? value.document
150
+ : value;
151
+ if (typeof candidate !== "object" || candidate === null || !("version" in candidate))
152
+ return undefined;
153
+ const version = candidate.version;
154
+ if (typeof version !== "number" && typeof version !== "string")
155
+ throw invalidArgument("The draft file's version must be the version a draft read printed");
156
+ return parseDocumentVersion(String(version));
157
+ }
158
+ /** Draft input from a file: the fields to change, or a `draft read` result edited in place. */
159
+ function parseDraftFile(value) {
160
+ const candidate = typeof value === "object" && value !== null && "document" in value
161
+ ? value.document
162
+ : value;
163
+ if (typeof candidate === "object" && candidate !== null && "boards" in candidate) {
164
+ const boards = candidate.boards;
165
+ // A `draft read` lists boards by identity only; any other board content is refused.
166
+ if (!Array.isArray(boards) ||
167
+ boards.some((board) => typeof board !== "object" ||
168
+ board === null ||
169
+ "elements" in board ||
170
+ "files" in board ||
171
+ "style" in board))
172
+ throw invalidArgument("Draft files cannot change boards; use specflow board import or specflow board edit");
173
+ }
174
+ const parsed = draftInput.safeParse(candidate);
175
+ if (!parsed.success)
176
+ throw invalidArgument("Draft file must be a JSON object with optional title, body and guardrails (title, prohibitedBehavior, safePath, repositoryGlob, pathGlob)");
177
+ return parsed.data;
178
+ }
179
+ export function registerContextDocumentCommands(program, runtime) {
180
+ const context = program
181
+ .command("context")
182
+ .description("Read the Context Index and keep a repository's AGENTS.md block current");
183
+ context
184
+ .command("index")
185
+ .description("Read the Context Index of one repository: types, documents, Guardrails")
186
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
187
+ .option("--repository <owner/name>", "GitHub repository; inferred from the Git remote")
188
+ .option("--directory <path>", "Checkout used to infer the repository", ".")
189
+ .action(async (options) => {
190
+ const repository = parseRepository(await requireRepository(options.repository, options.directory));
191
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/context-index", {
192
+ params: { path: { workspaceId: options.workspaceId }, query: { repository } },
193
+ })));
194
+ });
195
+ context
196
+ .command("guardrails")
197
+ .description("List the Guardrails in effect for one repository and, optionally, one path")
198
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
199
+ .option("--repository <owner/name>", "GitHub repository; inferred from the Git remote")
200
+ .option("--path <path>", "Repository-relative path the Guardrails must apply to")
201
+ .option("--directory <path>", "Checkout used to infer the repository", ".")
202
+ .action(async (options) => {
203
+ const repository = parseRepository(await requireRepository(options.repository, options.directory));
204
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/context-guardrails", {
205
+ params: {
206
+ path: { workspaceId: options.workspaceId },
207
+ query: {
208
+ repository,
209
+ ...(options.path === undefined ? {} : { path: options.path }),
210
+ },
211
+ },
212
+ })));
213
+ });
214
+ context
215
+ .command("sync-agents")
216
+ .description("Write (or with --check, verify) the SpecFlow block in AGENTS.md from the Context Index")
217
+ .option("--workspace-id <workspaceId>", "Workspace ID; defaults to the one the block recorded", parseWorkspaceId)
218
+ .option("--repository <owner/name>", "GitHub repository; defaults to the block's, then the Git remote")
219
+ .option("--file <path>", "Agent instructions file; defaults to AGENTS.md at the checkout root")
220
+ .option("--directory <path>", "Checkout used for the repository and default file; defaults to the file's folder, then .")
221
+ .option("--check", "Change nothing; exit 1 with a diff when the block is missing or stale")
222
+ .action(async (options) => {
223
+ const directory = options.directory ?? ".";
224
+ const root = options.file === undefined
225
+ ? ((await git(directory, ["rev-parse", "--show-toplevel"])) ?? resolve(directory))
226
+ : undefined;
227
+ const file = resolve(options.file ?? join(root ?? ".", "AGENTS.md"));
228
+ const snapshot = await readAgentsFile(file);
229
+ const existing = snapshot.text;
230
+ const recorded = readContextBlockMetadata(existing);
231
+ const workspaceId = options.workspaceId ?? recorded?.workspaceId;
232
+ if (workspaceId === undefined)
233
+ throw invalidArgument("Pass --workspace-id on the first sync; later syncs reuse the one the block records");
234
+ const repository = parseRepository(await requireRepository(options.repository ?? recorded?.repository,
235
+ // An explicit --directory names the checkout even when --file points elsewhere.
236
+ options.directory ?? dirname(file)));
237
+ const outcome = { stale: false };
238
+ const exitCode = await runtime.run(async (client) => {
239
+ const index = await client.GET("/v1/workspaces/{workspaceId}/context-index", {
240
+ params: { path: { workspaceId }, query: { repository } },
241
+ });
242
+ if (index.data === undefined)
243
+ return index;
244
+ const next = applyContextBlock(existing, renderContextBlock(index.data, workspaceId));
245
+ const summary = {
246
+ file,
247
+ repository,
248
+ fingerprint: index.data.fingerprint,
249
+ documents: index.data.documents.length,
250
+ guardrails: index.data.guardrails.length,
251
+ };
252
+ if (options.check === true) {
253
+ const stale = next !== existing;
254
+ outcome.stale = stale;
255
+ return {
256
+ response: index.response,
257
+ data: stale
258
+ ? {
259
+ ...summary,
260
+ status: existing === null ? "missing" : "stale",
261
+ diff: unifiedDiff(existing ?? "", next, basename(file)),
262
+ }
263
+ : { ...summary, status: "current" },
264
+ };
265
+ }
266
+ if (next === existing)
267
+ return { response: index.response, data: { ...summary, status: "unchanged" } };
268
+ const written = await writeAgentsFile(snapshot, next);
269
+ if (written === "changed")
270
+ return {
271
+ response: new Response(null, { status: 412 }),
272
+ error: {
273
+ code: "LOCAL_FILE_CHANGED",
274
+ message: "The agent instructions file changed while syncing; nothing was written, so run sync-agents again",
275
+ },
276
+ };
277
+ if (written === "failed")
278
+ return {
279
+ response: new Response(null, { status: 400 }),
280
+ error: {
281
+ code: "LOCAL_FILE_WRITE_FAILED",
282
+ message: "The agent instructions file could not be written",
283
+ },
284
+ };
285
+ return {
286
+ response: index.response,
287
+ data: { ...summary, status: existing === null ? "created" : "updated" },
288
+ };
289
+ });
290
+ // A stale block exits 1 only when nothing else failed first.
291
+ runtime.setExitCode(exitCode === 0 && outcome.stale ? 1 : exitCode);
292
+ });
293
+ const contextDoc = program
294
+ .command("context-doc")
295
+ .description("Read and draft Context Documents (specifications with Guardrails and boards)");
296
+ contextDoc
297
+ .command("type")
298
+ .description("Context Document Types")
299
+ .command("list")
300
+ .description("List Context Document Types with their Reading Cues")
301
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
302
+ .action(async (options) => {
303
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/context-document-types", {
304
+ params: { path: { workspaceId: options.workspaceId } },
305
+ })));
306
+ });
307
+ contextDoc
308
+ .command("list")
309
+ .description("List Context Documents with their state, version, boards and pending review")
310
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
311
+ .option("--effective-only", "Only documents currently in effect")
312
+ .option("--repository <owner/name>", "Only documents that apply to this repository")
313
+ .option("--type <typeId>", "Only documents of this type ID")
314
+ .action(async (options) => {
315
+ const repository = options.repository === undefined ? undefined : parseRepository(options.repository);
316
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.GET("/v1/workspaces/{workspaceId}/context-documents", {
317
+ params: {
318
+ path: { workspaceId: options.workspaceId },
319
+ // The server coerces any present value to true, so absent means all.
320
+ ...(options.effectiveOnly === true ? { query: { effectiveOnly: true } } : {}),
321
+ },
322
+ }), (data) => ({
323
+ types: data.types.map(({ id, name, readingCue }) => ({ id, name, readingCue })),
324
+ documents: data.documents
325
+ .filter((document) => (repository === undefined ||
326
+ // No applicable repository means the document applies to all.
327
+ document.applicableRepositories.length === 0 ||
328
+ document.applicableRepositories.some((candidate) => candidate.toLowerCase() === repository.toLowerCase())) &&
329
+ (options.type === undefined || document.typeId === options.type))
330
+ .map(documentSummary),
331
+ capabilities: data.capabilities,
332
+ })), { rejectWorkspaceReadToken: true }));
333
+ });
334
+ contextDoc
335
+ .command("search")
336
+ .description("Find Context Documents by ID, title, body or Guardrail text")
337
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
338
+ .requiredOption("--query <query>", "Words to find (case-insensitive)")
339
+ .option("--limit <limit>", "Maximum results (1–100)", parseLimit, 20)
340
+ .action(async (options) => {
341
+ const words = options.query.toLowerCase().split(/\s+/u).filter(Boolean);
342
+ if (words.length === 0)
343
+ throw invalidArgument("Search query must contain a word");
344
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.GET("/v1/workspaces/{workspaceId}/context-documents", {
345
+ params: { path: { workspaceId: options.workspaceId }, query: {} },
346
+ }), (data) => {
347
+ const results = data.documents.flatMap((document) => {
348
+ const match = searchDocument(document, words);
349
+ return match === null ? [] : [match];
350
+ });
351
+ results.sort((a, b) => b.score - a.score);
352
+ return {
353
+ query: options.query,
354
+ total: results.length,
355
+ results: results.slice(0, options.limit).map((entry) => entry.result),
356
+ };
357
+ }), { rejectWorkspaceReadToken: true }));
358
+ });
359
+ contextDoc
360
+ .command("read")
361
+ .description("Read a Context Document's published content and state; --revision reads one Revision")
362
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
363
+ .requiredOption("--document-id <documentId>", "Context Document ID", parseDocumentId)
364
+ .option("--revision <revisionId>", "A Revision ID from the changelog")
365
+ .action(async (options) => {
366
+ const path = { workspaceId: options.workspaceId, documentId: options.documentId };
367
+ if (runtime.isReadToken()) {
368
+ runtime.setExitCode(await runtime.run(async (client) => mapData(options.revision === undefined
369
+ ? await client.GET("/v1/workspaces/{workspaceId}/published/context-documents/{documentId}/current-revision", { params: { path } })
370
+ : await client.GET("/v1/workspaces/{workspaceId}/published/context-documents/{documentId}/revisions/{revisionId}", { params: { path: { ...path, revisionId: options.revision } } }), (data) => ({ revision: revisionView(data.revision) }))));
371
+ return;
372
+ }
373
+ if (options.revision !== undefined) {
374
+ const revisionId = options.revision;
375
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.GET("/v1/workspaces/{workspaceId}/context-documents/{documentId}/revisions/{revisionId}", { params: { path: { ...path, revisionId } } }), (data) => ({ revision: revisionView(data.revision) }))));
376
+ return;
377
+ }
378
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.GET("/v1/workspaces/{workspaceId}/context-documents/{documentId}", {
379
+ params: { path },
380
+ }), (data) => ({
381
+ document: documentSummary(data.document),
382
+ published: data.published === null ? null : revisionView(data.published),
383
+ capabilities: data.capabilities,
384
+ }))));
385
+ });
386
+ contextDoc
387
+ .command("create")
388
+ .description("Create a Context Document draft; an Agent's type and parent await human review on the Web")
389
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
390
+ .requiredOption("--title <title>", "Document title")
391
+ .option("--type <type>", "Context Document Type ID or name")
392
+ .option("--parent <documentId>", "Parent Context Document ID", parseDocumentId)
393
+ .option("--repository <owner/name>", "Applicable repository; repeat for several", collectRepository)
394
+ .option("--body-file <path>", "Markdown body from a file, or - for standard input")
395
+ .action(async (options) => {
396
+ if (!runtime.canWrite()) {
397
+ runtime.setExitCode(runtime.rejectWrite());
398
+ return;
399
+ }
400
+ const title = options.title.trim();
401
+ if (title.length === 0 || title.length > 500)
402
+ throw invalidArgument("Title must contain 1 to 500 characters");
403
+ const body = options.bodyFile === undefined
404
+ ? undefined
405
+ : await readTextInput(options.bodyFile, maximumBodyBytes, "Body");
406
+ const path = { workspaceId: options.workspaceId };
407
+ runtime.setExitCode(await runtime.run(async (client) => {
408
+ let typeId;
409
+ if (options.type !== undefined) {
410
+ const types = await client.GET("/v1/workspaces/{workspaceId}/context-document-types", {
411
+ params: { path },
412
+ });
413
+ if (types.data === undefined)
414
+ return types;
415
+ const wanted = options.type.trim();
416
+ const match = types.data.types.find((type) => type.id === wanted) ??
417
+ types.data.types.find((type) => type.name.toLowerCase() === wanted.toLowerCase());
418
+ if (match === undefined)
419
+ return {
420
+ response: new Response(null, { status: 400 }),
421
+ error: {
422
+ code: "CONTEXT_DOCUMENT_TYPE_NOT_FOUND",
423
+ message: `No Context Document Type has this ID or name; choose one of: ${types.data.types.map((type) => `${type.name} (${type.id})`).join(", ")}`,
424
+ },
425
+ };
426
+ typeId = match.id;
427
+ }
428
+ return mapData(await client.POST("/v1/workspaces/{workspaceId}/context-documents", {
429
+ params: { path },
430
+ body: {
431
+ title,
432
+ ...(body === undefined ? {} : { body }),
433
+ ...(typeId === undefined ? {} : { typeId }),
434
+ ...(options.parent === undefined ? {} : { parentDocumentId: options.parent }),
435
+ ...(options.repository === undefined
436
+ ? {}
437
+ : { applicableRepositories: options.repository }),
438
+ },
439
+ }), (data) => ({ document: draftView(data.document) }));
440
+ }, uncertainWriteOptions("Context Document creation")));
441
+ });
442
+ const draft = contextDoc.command("draft").description("The working draft of a Context Document");
443
+ draft
444
+ .command("read")
445
+ .description("Read the working draft: title, body, Guardrails, boards, version and review")
446
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
447
+ .requiredOption("--document-id <documentId>", "Context Document ID", parseDocumentId)
448
+ .action(async (options) => {
449
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.GET("/v1/workspaces/{workspaceId}/context-documents/{documentId}", {
450
+ params: {
451
+ path: { workspaceId: options.workspaceId, documentId: options.documentId },
452
+ },
453
+ }), (data) => ({ document: draftView(data.document), capabilities: data.capabilities })), { rejectWorkspaceReadToken: true }));
454
+ });
455
+ draft
456
+ .command("edit")
457
+ .description("Replace draft fields (title, body, Guardrails); unspecified fields keep their draft value")
458
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
459
+ .requiredOption("--document-id <documentId>", "Context Document ID", parseDocumentId)
460
+ .option("--file <path>", "JSON with title, body and/or guardrails (or an edited draft read)")
461
+ .option("--title <title>", "New title")
462
+ .option("--body-file <path>", "Markdown body from a file, or - for standard input")
463
+ .option("--expected-version <version>", "Document version from your last read (required unless --file is an edited draft read, which carries it)", parseDocumentVersion)
464
+ .action(async (options) => {
465
+ if (!runtime.canWrite()) {
466
+ runtime.setExitCode(runtime.rejectWrite());
467
+ return;
468
+ }
469
+ if (options.file === "-" && options.bodyFile === "-")
470
+ throw invalidArgument("Only one input can come from standard input");
471
+ const fileInput = options.file === undefined
472
+ ? undefined
473
+ : parseJsonInput(await readTextInput(options.file, 4 * maximumBodyBytes, "Draft file"), "Draft file");
474
+ const fromFile = fileInput === undefined ? {} : parseDraftFile(fileInput);
475
+ // A draft read edited in place carries the version it was read at.
476
+ const expectedVersion = options.expectedVersion ?? draftFileVersion(fileInput);
477
+ const body = options.bodyFile === undefined
478
+ ? fromFile.body
479
+ : await readTextInput(options.bodyFile, maximumBodyBytes, "Body");
480
+ const title = options.title ?? fromFile.title;
481
+ if (title === undefined && body === undefined && fromFile.guardrails === undefined)
482
+ throw invalidArgument("Draft edit needs --file, --title or --body-file");
483
+ // Writing at a version read just now could overwrite a person's edit made after
484
+ // the Agent's own read, so the Agent must name the version it based its edit on.
485
+ if (expectedVersion === undefined)
486
+ throw invalidArgument("Draft edit needs --expected-version with the version from your last read (or a --file edited from draft read, which carries it)");
487
+ const path = { workspaceId: options.workspaceId, documentId: options.documentId };
488
+ runtime.setExitCode(await runtime.run(async (client) => {
489
+ const current = await client.GET("/v1/workspaces/{workspaceId}/context-documents/{documentId}", { params: { path } });
490
+ if (current.data === undefined)
491
+ return current;
492
+ const document = current.data.document;
493
+ const guardrails = (fromFile.guardrails ?? document.guardrails).map((guardrail) => ({
494
+ ...(guardrail.id === undefined ? {} : { id: guardrail.id }),
495
+ title: guardrail.title,
496
+ prohibitedBehavior: guardrail.prohibitedBehavior,
497
+ safePath: guardrail.safePath,
498
+ repositoryGlob: guardrail.repositoryGlob ?? null,
499
+ pathGlob: guardrail.pathGlob ?? null,
500
+ }));
501
+ return mapData(await client.PUT("/v1/workspaces/{workspaceId}/context-documents/{documentId}/draft", {
502
+ params: {
503
+ path,
504
+ header: {
505
+ "if-match": expectedVersion,
506
+ },
507
+ },
508
+ body: {
509
+ title: title ?? document.title,
510
+ body: body ?? document.body,
511
+ guardrails,
512
+ },
513
+ }), (data) => ({ document: draftView(data.document) }));
514
+ }, uncertainWriteOptions("Draft edit")));
515
+ });
516
+ draft
517
+ .command("discard")
518
+ .description("Discard the working draft and return to the published Revision")
519
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
520
+ .requiredOption("--document-id <documentId>", "Context Document ID", parseDocumentId)
521
+ .action(async (options) => {
522
+ if (!runtime.canWrite()) {
523
+ runtime.setExitCode(runtime.rejectWrite());
524
+ return;
525
+ }
526
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.DELETE("/v1/workspaces/{workspaceId}/context-documents/{documentId}/draft", {
527
+ params: {
528
+ path: { workspaceId: options.workspaceId, documentId: options.documentId },
529
+ },
530
+ }), (data) => ({ document: documentSummary(data.document) })), uncertainWriteOptions("Draft discard")));
531
+ });
532
+ contextDoc
533
+ .command("publish")
534
+ .description("Publish the draft as a new Revision; refused while Agent changes await human review")
535
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
536
+ .requiredOption("--document-id <documentId>", "Context Document ID", parseDocumentId)
537
+ .action(async (options) => {
538
+ if (!runtime.canWrite()) {
539
+ runtime.setExitCode(runtime.rejectWrite());
540
+ return;
541
+ }
542
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.POST("/v1/workspaces/{workspaceId}/context-documents/{documentId}/publish", {
543
+ params: {
544
+ path: { workspaceId: options.workspaceId, documentId: options.documentId },
545
+ },
546
+ body: { discardDraft: false },
547
+ }), (data) => ({
548
+ document: documentSummary(data.document),
549
+ revision: revisionView(data.revision),
550
+ })), uncertainWriteOptions("Publication")));
551
+ });
552
+ contextDoc
553
+ .command("rollback")
554
+ .description("Publish an earlier Revision again as the current one")
555
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
556
+ .requiredOption("--document-id <documentId>", "Context Document ID", parseDocumentId)
557
+ .requiredOption("--revision-id <revisionId>", "Revision ID from the changelog")
558
+ .option("--discard-draft", "Discard an open draft as part of the rollback")
559
+ .action(async (options) => {
560
+ if (!runtime.canWrite()) {
561
+ runtime.setExitCode(runtime.rejectWrite());
562
+ return;
563
+ }
564
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.POST("/v1/workspaces/{workspaceId}/context-documents/{documentId}/rollback", {
565
+ params: {
566
+ path: { workspaceId: options.workspaceId, documentId: options.documentId },
567
+ },
568
+ body: {
569
+ revisionId: options.revisionId,
570
+ discardDraft: options.discardDraft === true,
571
+ },
572
+ }), (data) => ({
573
+ document: documentSummary(data.document),
574
+ revision: revisionView(data.revision),
575
+ })), uncertainWriteOptions("Rollback")));
576
+ });
577
+ contextDoc
578
+ .command("state")
579
+ .description("Mark a Context Document Superseded or Deprecated")
580
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
581
+ .requiredOption("--document-id <documentId>", "Context Document ID", parseDocumentId)
582
+ .requiredOption("--state <state>", "Superseded or Deprecated", (value) => {
583
+ if (value !== "Superseded" && value !== "Deprecated")
584
+ throw invalidArgument("State must be Superseded or Deprecated");
585
+ return value;
586
+ })
587
+ .option("--superseded-by <documentId>", "The document that replaces this one", parseDocumentId)
588
+ .option("--discard-draft", "Discard an open draft as part of the change")
589
+ .action(async (options) => {
590
+ if (!runtime.canWrite()) {
591
+ runtime.setExitCode(runtime.rejectWrite());
592
+ return;
593
+ }
594
+ if (options.state === "Deprecated" && options.supersededBy !== undefined)
595
+ throw invalidArgument("--superseded-by applies only to --state Superseded");
596
+ runtime.setExitCode(await runtime.run(async (client) => mapData(await client.POST("/v1/workspaces/{workspaceId}/context-documents/{documentId}/state", {
597
+ params: {
598
+ path: { workspaceId: options.workspaceId, documentId: options.documentId },
599
+ },
600
+ body: {
601
+ state: options.state,
602
+ ...(options.supersededBy === undefined
603
+ ? {}
604
+ : { supersededByDocumentId: options.supersededBy }),
605
+ discardDraft: options.discardDraft === true,
606
+ },
607
+ }), (data) => ({ document: documentSummary(data.document) })), uncertainWriteOptions("State change")));
608
+ });
609
+ contextDoc
610
+ .command("changelog")
611
+ .description("List a Context Document's publications, rollbacks and state changes")
612
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", parseWorkspaceId)
613
+ .requiredOption("--document-id <documentId>", "Context Document ID", parseDocumentId)
614
+ .action(async (options) => {
615
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/context-documents/{documentId}/changelog", {
616
+ params: {
617
+ path: { workspaceId: options.workspaceId, documentId: options.documentId },
618
+ },
619
+ }), { rejectWorkspaceReadToken: true }));
620
+ });
621
+ }
622
+ function parseLimit(value) {
623
+ const limit = Number(value);
624
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
625
+ throw invalidArgument("Limit must be an integer from 1 to 100");
626
+ return limit;
627
+ }
628
+ function snippet(text, word) {
629
+ const at = text.toLowerCase().indexOf(word);
630
+ const start = Math.max(0, at - 60);
631
+ const end = Math.min(text.length, at + word.length + 60);
632
+ return `${start > 0 ? "…" : ""}${text.slice(start, end).replace(/\s+/gu, " ")}${end < text.length ? "…" : ""}`;
633
+ }
634
+ function searchDocument(document, words) {
635
+ const fields = [
636
+ ["id", document.id, 8],
637
+ ["title", document.title, 5],
638
+ ...document.guardrails.map((guardrail) => [
639
+ `guardrail ${guardrail.id}`,
640
+ `${guardrail.title}\n${guardrail.prohibitedBehavior}\n${guardrail.safePath}`,
641
+ 3,
642
+ ]),
643
+ ...document.boards.map((board) => [
644
+ `board ${board.id}`,
645
+ board.title,
646
+ 2,
647
+ ]),
648
+ ["body", document.body, 1],
649
+ ];
650
+ let score = 0;
651
+ const matches = [];
652
+ for (const word of words) {
653
+ const hit = fields.find(([, text]) => text.toLowerCase().includes(word));
654
+ if (hit === undefined)
655
+ return null;
656
+ score += hit[2];
657
+ if (!matches.some((match) => match.field === hit[0]))
658
+ matches.push({ field: hit[0], snippet: snippet(hit[1], word) });
659
+ }
660
+ return {
661
+ score,
662
+ result: {
663
+ id: document.id,
664
+ title: document.title,
665
+ typeId: document.typeId,
666
+ state: document.state,
667
+ version: document.version,
668
+ reviewPendingCount: document.review.pendingCount,
669
+ reviewNotice: reviewNotice(document.review.pendingCount),
670
+ matches,
671
+ },
672
+ };
673
+ }
674
+ //# sourceMappingURL=context-document-commands.js.map