robisie 0.1.3 → 0.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 (52) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +73 -19
  3. package/dist/agents.d.ts +1 -1
  4. package/dist/agents.js +1 -1
  5. package/dist/ci-failure-result.js +1 -1
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +45 -8
  8. package/dist/codex-env.d.ts +9 -0
  9. package/dist/codex-env.js +60 -0
  10. package/dist/commands.js +140 -16
  11. package/dist/constants.d.ts +1 -1
  12. package/dist/constants.js +1 -1
  13. package/dist/delivery-local.d.ts +124 -0
  14. package/dist/delivery-local.js +286 -0
  15. package/dist/done-evidence.d.ts +25 -1
  16. package/dist/done-evidence.js +59 -1
  17. package/dist/engine/bundle-report.json +1687 -0
  18. package/dist/engine/tick.cjs +324704 -0
  19. package/dist/engine-config.d.ts +3 -1
  20. package/dist/engine-config.js +3 -3
  21. package/dist/factory-run.d.ts +17 -0
  22. package/dist/factory-run.js +262 -0
  23. package/dist/helpers.js +1 -1
  24. package/dist/k3-codex-job.d.ts +49 -0
  25. package/dist/k3-codex-job.js +324 -0
  26. package/dist/k3-helper-cli.d.ts +5 -0
  27. package/dist/k3-helper-cli.js +167 -0
  28. package/dist/local-usage.d.ts +47 -0
  29. package/dist/local-usage.js +230 -0
  30. package/dist/manifest.d.ts +5 -2
  31. package/dist/manifest.js +6 -6
  32. package/dist/opencode-review-guard.js +7 -2
  33. package/dist/planer-client.d.ts +45 -4
  34. package/dist/planer-client.js +120 -14
  35. package/dist/roles.d.ts +1 -1
  36. package/dist/seed-package.d.ts +10 -0
  37. package/dist/seed-package.js +62 -0
  38. package/dist/select-fingerprint.d.ts +19 -0
  39. package/dist/select-fingerprint.js +46 -0
  40. package/dist/task-mktemp.d.ts +1 -0
  41. package/dist/task-mktemp.js +40 -0
  42. package/dist/test-report.d.ts +9 -0
  43. package/dist/test-report.js +139 -0
  44. package/dist/tester-result-reader.d.ts +87 -0
  45. package/dist/tester-result-reader.js +122 -0
  46. package/docs/ENGINE-API.md +9 -1
  47. package/docs/README.en.md +161 -66
  48. package/docs/README.md +159 -66
  49. package/docs/RELEASE-0.1.0.md +29 -5
  50. package/helpers/ceo-client-launcher-mcp.mjs +76 -5
  51. package/package.json +6 -2
  52. package/roles/ceo-client.md +10 -8
@@ -21,9 +21,27 @@ export class PlanerClientError extends Error {
21
21
  this.plannerCode = diagnostic.plannerCode;
22
22
  if (diagnostic?.requestId !== undefined)
23
23
  this.requestId = diagnostic.requestId;
24
+ if (diagnostic?.plannerMeta !== undefined)
25
+ this.plannerMeta = diagnostic.plannerMeta;
24
26
  }
25
27
  }
26
28
  const status = z.enum(["draft", "ready", "in_progress", "in_review", "blocked", "delivered", "done"]);
29
+ // Closed wire vocabulary. Unknown codes never prove that a write was refused.
30
+ export const PLANNER_DOMAIN_CODES = [
31
+ "PROJECT_NOT_FOUND", "PROJECT_NAME_TAKEN", "PROJECT_LIMIT_REACHED", "CONCURRENCY_LIMIT_REACHED",
32
+ "WEBHOOK_SUBSCRIPTION_LIMIT_REACHED", "TRACK_NOT_FOUND", "TRACK_HAS_TASKS", "TRACK_REORDER_MISMATCH",
33
+ "TASK_DETAILS_MACHINE_FIELD_INVALID", "TASK_DETAILS_TOO_LARGE", "TASK_NOT_FOUND", "TASK_UPDATE_CONFLICT",
34
+ "SEED_PACKAGE_DENIED", "TASK_DONE_EVIDENCE_REQUIRED", "TASK_CARD_CLASS_IMMUTABLE", "TASK_DONE_EVIDENCE_IMMUTABLE",
35
+ "TASK_SELF_DEPENDENCY", "DEPENDENCY_NOT_FOUND", "TASK_INSERT_FAILED", "TASK_VANISHED", "TASK_ALREADY_CLAIMED",
36
+ "TASK_NOT_RESERVABLE", "TASK_RESERVATION_RACED", "NEIGHBOR_NOT_FOUND", "NEIGHBOR_WRONG_TRACK", "NEIGHBOR_ORDER_INVALID",
37
+ ];
38
+ const domainFailure = z.object({ domainError: z.object({ code: z.enum(PLANNER_DOMAIN_CODES), meta: z.object({
39
+ expectedStatus: status.optional(), actualStatus: status.optional(), status: status.optional(),
40
+ missing: z.array(z.enum(["enabled_evidence", "real_use_evidence", "acceptance"])).max(3).optional(),
41
+ }) }) });
42
+ const projectionName = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/)
43
+ .refine(value => !["__proto__", "prototype", "constructor"].includes(value));
44
+ const detailsFields = z.record(z.string().refine(value => projectionName.safeParse(value.endsWith(".*") ? value.slice(0, -2) : value).success), z.array(projectionName).min(1).max(64)).refine(value => Object.keys(value).length <= 32).and(z.unknown().refine(value => typeof value !== "object" || value === null || !Object.hasOwn(value, "__proto__"))).optional();
27
45
  const uuid = z.uuid();
28
46
  const keys = z.array(z.string());
29
47
  const jsonObject = z.record(z.string(), z.json());
@@ -34,7 +52,9 @@ const date = z.iso.datetime({ offset: true });
34
52
  const projectSchema = z.object({ id: uuid, name: z.string(), slug: z.string() });
35
53
  const trackSchema = z.object({ id: uuid, projectId: uuid, name: z.string(), position: z.number().int() });
36
54
  const taskSchema = z.object({ id: uuid, projectId: uuid, trackId: uuid, title: z.string(), status,
37
- assignee: z.string().nullable(), dependsOn: z.array(uuid) });
55
+ assignee: z.string().nullable(), dependsOn: z.array(uuid), specRef: z.string().nullable(), createdAt: date, updatedAt: date,
56
+ position: z.string().nullable().optional(), statusEnteredAt: date.nullable().optional(), statusEnteredStatus: status.nullable().optional(),
57
+ seedBriefDigest: z.string().nullable().optional(), seedPackageDigest: z.string().nullable().optional() });
38
58
  const echoSchema = z.object({ id: uuid, title: z.string(), status, trackId: uuid, updatedAt: date });
39
59
  const createTrackInput = z.strictObject({ projectId: uuid, name, color: z.string().max(50).optional() });
40
60
  const createTaskInput = z.strictObject({ projectId: uuid, trackId: uuid, title: name,
@@ -53,14 +73,29 @@ const acceptReviewInput = z.strictObject({ id: uuid, cardId: uuid, projectId: uu
53
73
  // reserve_task still transfers full server PlannerTask/details; only these fields leave this adapter.
54
74
  const reservationSchema = z.object({ id: uuid, status, assignee: z.string().nullable(), trackId: uuid, updatedAt: date });
55
75
  const appendSchema = echoSchema.extend({ appendedKeys: keys });
56
- const listInput = z.strictObject({ projectId: uuid, trackId: uuid.optional(), statuses: z.array(status).optional(), detailsKeys: keys });
57
- const getInput = z.strictObject({ id: uuid, include: keys });
58
- const reserveInput = z.strictObject({ id: uuid, assignee: freeText.nullable().optional() });
76
+ const listInput = z.strictObject({ projectId: uuid, trackId: uuid.optional(), statuses: z.array(status).optional(), detailsKeys: keys,
77
+ briefDigest: z.boolean().optional(), detailsFields });
78
+ const getInput = z.strictObject({ id: uuid, include: keys, briefDigest: z.boolean().optional(), detailsFields,
79
+ fullDetails: z.boolean().optional() }).refine(value => !value.fullDetails || (!value.include.length && value.detailsFields === undefined));
80
+ const reserveInput = z.strictObject({ id: uuid, assignee: freeText.nullable().optional(), domainErrors: z.boolean().optional() });
81
+ // expected.details is a whole-card snapshot (tick passes fresh.details): deliberately not size-bounded here.
59
82
  const updateInput = z.strictObject({ id: uuid, title: name.optional(), status: status.optional(),
60
- expected: z.strictObject({ status }).optional(), details: jsonObject.nullable().optional(),
83
+ domainErrors: z.boolean().optional(),
84
+ expected: z.strictObject({ status, details: jsonObject.nullable().optional() }).optional(), details: jsonObject.nullable().optional(),
85
+ detailsPatch: jsonObject.optional(),
61
86
  specRef: freeText.nullable().optional(), assignee: freeText.nullable().optional(), rob: freeText.nullable().optional(),
62
- dependsOn: z.array(uuid).max(200).optional() });
87
+ dependsOn: z.array(uuid).max(200).optional() }).refine(value => value.details === undefined || value.detailsPatch === undefined);
63
88
  const appendInput = z.strictObject({ id: uuid, patch: boundedObject });
89
+ // value omitted = guarded key absent; value null = literal JSON null (mirrors q.appendDetail guard).
90
+ const appendIfInput = z.strictObject({ id: uuid, patch: boundedObject, expected: z.strictObject({ key: z.string().min(1),
91
+ value: z.json().optional(), status: status.optional(), details: jsonObject.nullable().optional() }) });
92
+ const appendConflictSchema = z.object({ outcome: z.literal("CONFLICT"), cardId: uuid });
93
+ const matterIdSchema = z.string().regex(/^[0-9a-f]{16}$/);
94
+ const writeMatterInput = z.strictObject({ id: uuid, matterId: matterIdSchema,
95
+ patch: jsonObject.refine(value => Object.keys(value).length > 0), expected: jsonObject.optional() });
96
+ const writeMatterSchema = z.object({ cardId: uuid, matterId: matterIdSchema, matter: jsonObject.nullable() });
97
+ const moveInput = z.strictObject({ id: uuid, trackId: uuid.optional(), afterId: uuid.optional(), beforeId: uuid.optional() })
98
+ .refine(value => value.trackId !== undefined || value.afterId !== undefined || value.beforeId !== undefined);
64
99
  const closeInput = z.strictObject({ id: uuid, matterId: z.string().regex(/^[0-9a-f]{16}$/), expected: boundedObject })
65
100
  .refine(value => Object.keys(value.expected).length > 0
66
101
  && !(typeof value.expected.closedAt === "string" && value.expected.closedAt.length > 0)
@@ -74,6 +109,9 @@ const runFailure = z.object({ requestId: uuid,
74
109
  causeMessage: z.string(), code: z.string().regex(/^[0-9A-Z]{5}$/).optional(),
75
110
  severity: z.enum(["ERROR", "FATAL", "PANIC", "WARNING", "NOTICE", "DEBUG", "INFO", "LOG"]).optional(),
76
111
  message: z.string().optional() });
112
+ /** Minimum server contract for update_task expected.details/detailsPatch, guarded append_detail and
113
+ * write_decision_matter. Older 1.x servers silently strip these unknown fields, so the client refuses locally. */
114
+ export const PARITY_CONTRACT_MINOR = 1;
77
115
  function parse(schema, value, operation, code, uncertain = false) {
78
116
  // Zod/JSON may throw on cyclic values too; those exceptions must not cross the boundary.
79
117
  try {
@@ -97,7 +135,10 @@ function sdkFailure(error, operation, mutation) {
97
135
  return new PlanerClientError(error.code === ErrorCode.RequestTimeout ? "TIMEOUT" : "RPC_ERROR", operation, mutation);
98
136
  return new PlanerClientError("TRANSPORT_ERROR", operation, mutation);
99
137
  }
100
- function toolFailure(value, operation, mutation) {
138
+ function toolFailure(value, operation, mutation, domainErrors = false) {
139
+ const domain = domainErrors ? domainFailure.safeParse(value) : undefined;
140
+ if (domain?.success)
141
+ return new PlanerClientError("TOOL_ERROR", operation, false, { plannerCode: domain.data.domainError.code, plannerMeta: domain.data.domainError.meta });
101
142
  // Tool diagnostics can follow a committed write whose COMMIT acknowledgement was lost.
102
143
  const update = updateFailure.safeParse(value);
103
144
  if (update.success)
@@ -109,15 +150,16 @@ function toolFailure(value, operation, mutation) {
109
150
  return new PlanerClientError("TOOL_ERROR", operation, mutation, diagnostic.success
110
151
  ? { plannerCode: diagnostic.data.code, requestId: diagnostic.data.requestId } : undefined);
111
152
  }
112
- function taskProjection(raw, selected, operation) {
153
+ function taskProjection(raw, selected, operation, fullDetails = false) {
113
154
  const object = parse(z.record(z.string(), z.unknown()), raw, operation, "INVALID_RESPONSE");
114
155
  if (object.detailsReadError !== undefined && object.detailsReadError !== null)
115
156
  throw new PlanerClientError("DETAILS_READ_ERROR", operation);
116
157
  const task = parse(taskSchema, object, operation, "INVALID_RESPONSE");
117
- if (!selected.length)
158
+ if (!fullDetails && !selected.length)
118
159
  return task;
119
160
  const details = parse(jsonObject.nullable(), object.details, operation, "INVALID_RESPONSE");
120
- return { ...task, details: details === null ? null : Object.fromEntries(Object.entries(details).filter(([key]) => selected.includes(key))) };
161
+ return { ...task, details: fullDetails || details === null ? details
162
+ : Object.fromEntries(Object.entries(details).filter(([key]) => selected.includes(key))) };
121
163
  }
122
164
  /** Existing MCP operations only. No auto-connect, retry, CAS emulation or runtime cutover. */
123
165
  export class PlanerClient {
@@ -125,6 +167,7 @@ export class PlanerClient {
125
167
  #transport;
126
168
  #deadlineMs;
127
169
  #state = "new";
170
+ #contractMinor = -1;
128
171
  #connecting;
129
172
  constructor(config) {
130
173
  const parsed = parse(z.strictObject({ origin: z.string().optional(), endpoint: z.string().optional(),
@@ -163,7 +206,10 @@ export class PlanerClient {
163
206
  }
164
207
  if (initialize && response.ok) {
165
208
  try {
166
- assertCompatible(response.headers.get(CONTRACT_VERSION_HEADER));
209
+ const version = response.headers.get(CONTRACT_VERSION_HEADER);
210
+ assertCompatible(version);
211
+ const minor = /^\d+\.(\d+)\.\d+$/.exec(version ?? "")?.[1];
212
+ this.#contractMinor = minor === undefined ? -1 : Number(minor);
167
213
  }
168
214
  catch {
169
215
  try {
@@ -236,10 +282,17 @@ export class PlanerClient {
236
282
  }
237
283
  return { value, isError: result.isError === true };
238
284
  }
285
+ /** Local refusal, before IO, when the connected server cannot honour the requested semantics. */
286
+ #requireParity(operation, minor = PARITY_CONTRACT_MINOR) {
287
+ if (this.#state !== "connected")
288
+ throw new PlanerClientError("NOT_CONNECTED", operation);
289
+ if (this.#contractMinor < minor)
290
+ throw new PlanerClientError("UNSUPPORTED_CONTRACT", operation);
291
+ }
239
292
  async #value(operation, args, mutation = false) {
240
293
  const result = await this.#call(operation, args, mutation);
241
294
  if (result.isError)
242
- throw toolFailure(result.value, operation, mutation);
295
+ throw toolFailure(result.value, operation, mutation, args.domainErrors === true);
243
296
  return result.value;
244
297
  }
245
298
  async listProjects(args = {}) {
@@ -266,16 +319,20 @@ export class PlanerClient {
266
319
  }
267
320
  async listTasks(args) {
268
321
  const input = parse(listInput, args, "list_tasks", "INVALID_ARGUMENT");
322
+ if (input.detailsFields !== undefined)
323
+ this.#requireParity("list_tasks", 2);
269
324
  const rows = parse(z.array(z.unknown()), await this.#value("list_tasks", { ...input, full: true }), "list_tasks", "INVALID_RESPONSE");
270
325
  return rows.map(raw => ({ ...taskProjection(raw, input.detailsKeys, "list_tasks"),
271
326
  depsReady: parse(z.object({ depsReady: z.boolean() }), raw, "list_tasks", "INVALID_RESPONSE").depsReady }));
272
327
  }
273
328
  async getTask(args) {
274
329
  const input = parse(getInput, args, "get_task", "INVALID_ARGUMENT");
330
+ if (input.detailsFields !== undefined || input.fullDetails)
331
+ this.#requireParity("get_task", 2);
275
332
  const value = await this.#value("get_task", input);
276
333
  if (value === null)
277
334
  return null;
278
- const task = taskProjection(value, input.include, "get_task");
335
+ const task = taskProjection(value, input.include, "get_task", input.fullDetails);
279
336
  if (task.id !== input.id)
280
337
  throw new PlanerClientError("INVALID_RESPONSE", "get_task");
281
338
  const detailsIndex = parse(z.object({ availableDetailsKeys: keys.nullable().optional() }), value, "get_task", "INVALID_RESPONSE");
@@ -283,6 +340,8 @@ export class PlanerClient {
283
340
  }
284
341
  async reserveTask(args) {
285
342
  const input = parse(reserveInput, args, "reserve_task", "INVALID_ARGUMENT");
343
+ if (input.domainErrors)
344
+ this.#requireParity("reserve_task", 2);
286
345
  const echo = parse(reservationSchema, await this.#value("reserve_task", input, true), "reserve_task", "INVALID_RESPONSE", true);
287
346
  if (echo.id !== input.id)
288
347
  throw new PlanerClientError("INVALID_RESPONSE", "reserve_task", true);
@@ -309,9 +368,15 @@ export class PlanerClient {
309
368
  throw new PlanerClientError("INVALID_RESPONSE", "accept_review", true);
310
369
  return echo;
311
370
  }
312
- /** For draft promotion, pass {status:'ready', expected:{status:'draft'}}. Server owns CAS/permissions. */
371
+ /** For draft promotion, pass {status:'ready', expected:{status:'draft'}}. Server owns CAS/permissions.
372
+ * expected.details (snapshot CAS) and detailsPatch (shallow merge) need contract >= 1.1.0 and are
373
+ * applied by the server in the same atomic write; details and detailsPatch are mutually exclusive. */
313
374
  async updateTask(args) {
314
375
  const input = parse(updateInput, args, "update_task", "INVALID_ARGUMENT");
376
+ if (input.domainErrors)
377
+ this.#requireParity("update_task", 2);
378
+ if (input.expected?.details !== undefined || input.detailsPatch !== undefined)
379
+ this.#requireParity("update_task");
315
380
  const echo = parse(echoSchema, await this.#value("update_task", input, true), "update_task", "INVALID_RESPONSE", true);
316
381
  if (echo.id !== input.id)
317
382
  throw new PlanerClientError("INVALID_RESPONSE", "update_task", true);
@@ -332,6 +397,47 @@ export class PlanerClient {
332
397
  return { write, readback: { ok: false, error: sdkFailure(error, "get_task", false) } };
333
398
  }
334
399
  }
400
+ /** Guarded append (q.appendDetailIf/appendDetail guard): one CAS write on the server, no readback,
401
+ * no retry. Requires contract >= 1.1.0. applied:false only for a structured CONFLICT of this card. */
402
+ async appendDetailIf(args) {
403
+ const input = parse(appendIfInput, args, "append_detail", "INVALID_ARGUMENT");
404
+ this.#requireParity("append_detail");
405
+ const result = await this.#call("append_detail", input, true);
406
+ if (result.isError) {
407
+ const conflict = appendConflictSchema.safeParse(result.value);
408
+ if (!conflict.success)
409
+ throw toolFailure(result.value, "append_detail", true);
410
+ if (conflict.data.cardId !== input.id)
411
+ throw new PlanerClientError("INVALID_RESPONSE", "append_detail", true);
412
+ return { applied: false };
413
+ }
414
+ const write = parse(appendSchema, result.value, "append_detail", "INVALID_RESPONSE", true);
415
+ const included = Object.keys(input.patch);
416
+ if (write.id !== input.id || write.appendedKeys.length !== included.length || !included.every(key => write.appendedKeys.includes(key))) {
417
+ throw new PlanerClientError("INVALID_RESPONSE", "append_detail", true);
418
+ }
419
+ return { applied: true, write };
420
+ }
421
+ /** q.writeDecisionMatter: open/update one decision matter; expected = exact current matter (CAS).
422
+ * Returns the persisted matter (also when the server refused the write) or null; caller compares.
423
+ * Requires contract >= 1.1.0. Server owns roles, size limits and closed-matter rules. */
424
+ async writeDecisionMatter(args) {
425
+ const input = parse(writeMatterInput, args, "write_decision_matter", "INVALID_ARGUMENT");
426
+ this.#requireParity("write_decision_matter");
427
+ const echo = parse(writeMatterSchema, await this.#value("write_decision_matter", input, true), "write_decision_matter", "INVALID_RESPONSE", true);
428
+ if (echo.cardId !== input.id || echo.matterId !== input.matterId)
429
+ throw new PlanerClientError("INVALID_RESPONSE", "write_decision_matter", true);
430
+ return echo.matter;
431
+ }
432
+ /** Change track and/or order. Server computes the position; no retry. */
433
+ async moveTask(args) {
434
+ const input = parse(moveInput, args, "move_task", "INVALID_ARGUMENT");
435
+ const echo = parse(echoSchema, await this.#value("move_task", input, true), "move_task", "INVALID_RESPONSE", true);
436
+ if (echo.id !== input.id || (input.trackId !== undefined && echo.trackId !== input.trackId)) {
437
+ throw new PlanerClientError("INVALID_RESPONSE", "move_task", true);
438
+ }
439
+ return echo;
440
+ }
335
441
  /** full/owner_validator authority stays on the server. Non-CLOSED outcomes retain isError. */
336
442
  async closeDecisionMatter(args) {
337
443
  const input = parse(closeInput, args, "close_decision_matter", "INVALID_ARGUMENT");
package/dist/roles.d.ts CHANGED
@@ -17,7 +17,7 @@ export interface Role {
17
17
  export declare function rolesDir(): string;
18
18
  export declare function parseRole(file: Role["file"], text: string): Role;
19
19
  export declare function loadRoles(dir?: string): Role[];
20
- export declare const MANAGED_LINE = "<!-- robisie:managed 0.1.3 \u2014 plik zarz\u0105dzany przez `npx robisie`; `npx robisie uninstall` go usunie -->";
20
+ export declare const MANAGED_LINE = "<!-- robisie:managed 0.2.0 \u2014 plik zarz\u0105dzany przez `npx robisie`; `npx robisie uninstall` go usunie -->";
21
21
  export type AgentFlavor = "claude" | "codex" | "opencode";
22
22
  /** How the operator starts the Builder for one card in its own session (the card id is not a secret). */
23
23
  export declare function builderStartCommand(flavor: AgentFlavor, codexRolePath?: string): string;
@@ -0,0 +1,10 @@
1
+ export type SeedPackage = Readonly<{
2
+ scope: string;
3
+ spec: string;
4
+ brief: string;
5
+ }>;
6
+ export declare function embeddedDetails(card: Readonly<{
7
+ details: unknown;
8
+ }>, seedPackage: SeedPackage): Record<string, unknown>;
9
+ export declare function readbackMismatches(details: unknown, seedPackage: SeedPackage): string[];
10
+ export declare function parseSeedPackage(raw: string): SeedPackage;
@@ -0,0 +1,62 @@
1
+ import { createHash } from "node:crypto";
2
+ function isRecord(value) {
3
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4
+ }
5
+ function stripFence(text) {
6
+ let value = text.trim();
7
+ const opening = value.match(/^```(?:json)?\s*/i);
8
+ if (opening !== null)
9
+ value = value.slice(opening[0].length);
10
+ value = value.replace(/\s*```\s*$/, "");
11
+ return value.trim();
12
+ }
13
+ function errorText(error) {
14
+ return error instanceof Error ? error.message : String(error);
15
+ }
16
+ function sha256(content) {
17
+ return createHash("sha256").update(content, "utf8").digest("hex");
18
+ }
19
+ export function embeddedDetails(card, seedPackage) {
20
+ const original = isRecord(card.details) ? card.details : {};
21
+ return {
22
+ ...(Object.hasOwn(original, "card_class") ? {} : { card_class: "executable" }),
23
+ seed_scope: seedPackage.scope,
24
+ seed_scope_sha256: sha256(seedPackage.scope),
25
+ seed_spec: seedPackage.spec,
26
+ seed_spec_sha256: sha256(seedPackage.spec),
27
+ seed_brief: seedPackage.brief,
28
+ seed_brief_sha256: sha256(seedPackage.brief),
29
+ };
30
+ }
31
+ export function readbackMismatches(details, seedPackage) {
32
+ if (!isRecord(details))
33
+ return ["details nie są obiektem"];
34
+ const mismatches = [];
35
+ for (const field of ["scope", "spec", "brief"]) {
36
+ const contentKey = `seed_${field}`;
37
+ const hashKey = `${contentKey}_sha256`;
38
+ const content = details[contentKey];
39
+ const expected = seedPackage[field];
40
+ if (content !== expected || typeof content !== "string" || details[hashKey] !== sha256(content)) {
41
+ mismatches.push(contentKey);
42
+ }
43
+ }
44
+ return mismatches;
45
+ }
46
+ export function parseSeedPackage(raw) {
47
+ let parsed;
48
+ try {
49
+ parsed = JSON.parse(stripFence(raw));
50
+ }
51
+ catch (error) {
52
+ throw new Error(`odpowiedź modelu nie jest JSON: ${errorText(error)}`);
53
+ }
54
+ if (!isRecord(parsed))
55
+ throw new Error("odpowiedź modelu nie jest obiektem");
56
+ for (const field of ["scope", "spec", "brief"]) {
57
+ if (typeof parsed[field] !== "string" || parsed[field].trim().length === 0) {
58
+ throw new Error(`brak niepustego pola ${field}`);
59
+ }
60
+ }
61
+ return { scope: parsed.scope, spec: parsed.spec, brief: parsed.brief };
62
+ }
@@ -0,0 +1,19 @@
1
+ export declare function selectFingerprint(model: string, prompt: string): string;
2
+ export declare function readSelectFingerprint(file: string): string | null;
3
+ export declare function writeSelectFingerprint(file: string, fingerprint: string): void;
4
+ export declare function askUnlessUnchanged<T>(opts: {
5
+ model: string;
6
+ prompt: string;
7
+ file: string;
8
+ force: boolean;
9
+ ask: (prompt: string) => Promise<T>;
10
+ log: (line: string) => void;
11
+ }): Promise<{
12
+ skipped: true;
13
+ fingerprint: string;
14
+ } | {
15
+ skipped: false;
16
+ fingerprint: string;
17
+ value: T;
18
+ commit: () => void;
19
+ }>;
@@ -0,0 +1,46 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ export function selectFingerprint(model, prompt) {
4
+ return createHash("sha256").update(`${model}\n${prompt}`).digest("hex");
5
+ }
6
+ export function readSelectFingerprint(file) {
7
+ try {
8
+ return readFileSync(file, "utf8").trim();
9
+ }
10
+ catch (error) {
11
+ if (error.code === "ENOENT")
12
+ return null;
13
+ throw error;
14
+ }
15
+ }
16
+ export function writeSelectFingerprint(file, fingerprint) {
17
+ const temporary = `${file}.${process.pid}.tmp`;
18
+ try {
19
+ writeFileSync(temporary, fingerprint);
20
+ renameSync(temporary, file);
21
+ }
22
+ catch (error) {
23
+ try {
24
+ unlinkSync(temporary);
25
+ }
26
+ catch (cleanupError) {
27
+ if (cleanupError.code !== "ENOENT")
28
+ throw cleanupError;
29
+ }
30
+ throw error;
31
+ }
32
+ }
33
+ export async function askUnlessUnchanged(opts) {
34
+ const fingerprint = selectFingerprint(opts.model, opts.prompt);
35
+ if (!opts.force && readSelectFingerprint(opts.file) === fingerprint) {
36
+ opts.log(`selector: skip — input unchanged (fingerprint ${fingerprint})`);
37
+ return { skipped: true, fingerprint };
38
+ }
39
+ const value = await opts.ask(opts.prompt);
40
+ return {
41
+ skipped: false,
42
+ fingerprint,
43
+ value,
44
+ commit: () => writeSelectFingerprint(opts.file, fingerprint),
45
+ };
46
+ }
@@ -0,0 +1 @@
1
+ export declare function taskMktempEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
@@ -0,0 +1,40 @@
1
+ import { lstatSync, mkdtempSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { workerEnv } from "./worker-env.js";
4
+ // Only omitted templates need rewriting; explicit paths and unknown options belong to mktemp.
5
+ const wrapper = `#!/bin/bash
6
+ if [[ -z "$TMPDIR" || "$TMPDIR" != /* || ! -d "$TMPDIR" || ! -w "$TMPDIR" ]]; then
7
+ echo 'ACTIONABLE: brak zapisywalnego TMPDIR zadania' >&2
8
+ exit 1
9
+ fi
10
+ original=("$@")
11
+ flags=()
12
+ prefix=tmp
13
+ while getopts ':dqut:p:' flag; do
14
+ case "$flag" in
15
+ d|q|u) flags+=("-$flag") ;;
16
+ t) prefix="$OPTARG" ;;
17
+ *) exec /usr/bin/mktemp "\${original[@]}" ;;
18
+ esac
19
+ done
20
+ shift "$((OPTIND - 1))"
21
+ if (( $# > 0 )); then exec /usr/bin/mktemp "\${original[@]}"; fi
22
+ if [[ "$prefix" == */* ]]; then
23
+ echo 'mktemp: prefix must not contain a slash' >&2
24
+ exit 1
25
+ fi
26
+ exec /usr/bin/mktemp "\${flags[@]}" "$TMPDIR/$prefix.XXXXXXXX"
27
+ `;
28
+ export function taskMktempEnv(env) {
29
+ try {
30
+ const tmp = env.TMPDIR;
31
+ if (!tmp || !path.isAbsolute(tmp) || !lstatSync(tmp).isDirectory())
32
+ throw new Error("brak katalogu zadania");
33
+ const bin = mkdtempSync(path.join(tmp, "mktemp-bin-"));
34
+ writeFileSync(path.join(bin, "mktemp"), wrapper, { mode: 0o700, flag: "wx" });
35
+ return { ...workerEnv(env, tmp), PATH: `${bin}${path.delimiter}${env.PATH ?? ""}` };
36
+ }
37
+ catch (error) {
38
+ throw new Error(`ACTIONABLE: podkładka mktemp TMPDIR zadania: ${error instanceof Error ? error.message : String(error)}`);
39
+ }
40
+ }
@@ -0,0 +1,9 @@
1
+ export declare function passedVitestReport(value: unknown, evidence?: {
2
+ root: string;
3
+ paths: string[];
4
+ skipped: string[];
5
+ reason: string;
6
+ testNamePattern?: RegExp;
7
+ }): boolean;
8
+ export declare function vitestReportPath(name: unknown, root: string): string | null;
9
+ export declare function timeoutVitestFiles(value: unknown, root: string): string[] | null;
@@ -0,0 +1,139 @@
1
+ import { posix } from "node:path";
2
+ import path from "node:path";
3
+ export function passedVitestReport(value, evidence) {
4
+ const r = asRecord(value);
5
+ if (r.success !== true || !positiveInteger(r.numTotalTestSuites) || !positiveInteger(r.numTotalTests) || r.numFailedTests !== 0 || !Number.isSafeInteger(r.numPendingTests) || Number(r.numPendingTests) < 0
6
+ || r.numTodoTests !== 0 || r.numFailedTestSuites !== 0 || r.numPendingTestSuites !== 0
7
+ || !Number.isSafeInteger(r.numPassedTests) || Number(r.numPassedTests) < 0 || Number(r.numPassedTests) + Number(r.numPendingTests) !== r.numTotalTests || r.numPassedTestSuites !== r.numTotalTestSuites
8
+ || !Array.isArray(r.testResults) || !r.testResults.length)
9
+ return false;
10
+ let count = 0, filtered = 0;
11
+ const skipped = [];
12
+ const valid = r.testResults.every(v => {
13
+ const f = asRecord(v);
14
+ if (!nonempty(f.name) || f.status !== "passed" || f.message !== "" || !Array.isArray(f.assertionResults))
15
+ return false;
16
+ const name = f.name;
17
+ return f.assertionResults.every(v => {
18
+ const t = asRecord(v);
19
+ count++;
20
+ if (!Array.isArray(t.failureMessages) || t.failureMessages.length)
21
+ return false;
22
+ if (t.status === "passed")
23
+ return true;
24
+ if (t.status !== "skipped" || !nonempty(t.fullName) || !evidence?.paths.length)
25
+ return false;
26
+ const rel = posix.relative(evidence.root, path.resolve(evidence.root, name));
27
+ if (!rel || rel.startsWith("../"))
28
+ return false;
29
+ // Vitest's JSON reporter omits the final separator for an empty test title.
30
+ const fullName = t.title === "" ? `${t.fullName} ` : t.fullName;
31
+ if (evidence.testNamePattern && !evidence.testNamePattern.test(fullName)) {
32
+ filtered++;
33
+ return true;
34
+ }
35
+ const identity = JSON.stringify([rel, t.fullName]);
36
+ if (scopesOverlap([rel], evidence.paths)) {
37
+ evidence.reason = `Pominięcie w zakresie karty: ${identity}`;
38
+ return false;
39
+ }
40
+ skipped.push(identity);
41
+ return true;
42
+ });
43
+ }) && count === r.numTotalTests && skipped.length + filtered === r.numPendingTests;
44
+ if (valid && filtered > 0 && r.numPassedTests === 0 && evidence) {
45
+ evidence.reason = "Filtr nazwy nie wybrał żadnego testu";
46
+ return false;
47
+ }
48
+ if (valid)
49
+ evidence?.skipped.push(...skipped);
50
+ return valid;
51
+ }
52
+ export function vitestReportPath(name, root) {
53
+ if (!nonempty(name) || /[\r\n\0\\]/.test(name) || name.split("/").includes(".."))
54
+ return null;
55
+ const rel = path.relative(root, path.resolve(root, name));
56
+ return rel && !rel.startsWith("-") && !rel.startsWith("../") && !path.isAbsolute(rel) ? rel : null;
57
+ }
58
+ export function timeoutVitestFiles(value, root) {
59
+ const report = asRecord(value);
60
+ const counts = ["numTotalTests", "numPassedTests", "numFailedTests", "numPendingTests", "numTodoTests",
61
+ "numTotalTestSuites", "numPassedTestSuites", "numFailedTestSuites", "numPendingTestSuites"];
62
+ if (!counts.every(k => Number.isSafeInteger(report[k]) && Number(report[k]) >= 0)
63
+ || !positiveInteger(report.numTotalTests) || !positiveInteger(report.numFailedTestSuites)
64
+ || report.success !== false || report.numPendingTestSuites !== 0
65
+ || Number(report.numTotalTests) !== Number(report.numPassedTests) + Number(report.numFailedTests) + Number(report.numPendingTests) + Number(report.numTodoTests)
66
+ || Number(report.numTotalTestSuites) !== Number(report.numPassedTestSuites) + Number(report.numFailedTestSuites)
67
+ || !Array.isArray(report.testResults) || !report.testResults.length)
68
+ return null;
69
+ const timeout = (message, duration) => typeof message === "string" && (/^(?:Error: )?(?:Test|Hook) timed out in \d+ms\.(?:\s|$)/.test(message)
70
+ || message.split(/\r?\n/, 1)[0] === "Error: STACK_TRACE_ERROR"
71
+ && typeof duration === "number" && Number.isFinite(duration) && duration >= 30_000);
72
+ if (report.numRuntimeErrorTestSuites != null && report.numRuntimeErrorTestSuites !== 0
73
+ || report.unhandledErrors != null && (!Array.isArray(report.unhandledErrors) || report.unhandledErrors.length))
74
+ return null;
75
+ const paths = [];
76
+ const seen = new Set();
77
+ let failed = 0, passed = 0, pending = 0, todo = 0, total = 0, failedFiles = 0;
78
+ for (const entry of report.testResults) {
79
+ const file = asRecord(entry);
80
+ if (!nonempty(file.name) || !Array.isArray(file.assertionResults) || !["passed", "failed"].includes(String(file.status)))
81
+ return null;
82
+ const rel = vitestReportPath(file.name, root);
83
+ if (!rel || seen.has(rel) || !file.assertionResults.length)
84
+ return null;
85
+ seen.add(rel);
86
+ let red = false;
87
+ if (file.message !== "") {
88
+ if (!timeout(file.message, file.duration))
89
+ return null;
90
+ red = true;
91
+ }
92
+ for (const item of file.assertionResults) {
93
+ const test = asRecord(item);
94
+ total++;
95
+ if (!["passed", "failed", "skipped", "pending", "todo"].includes(String(test.status)))
96
+ return null;
97
+ if (test.status === "failed") {
98
+ failed++;
99
+ red = true;
100
+ if (!Array.isArray(test.failureMessages) || !test.failureMessages.length || !test.failureMessages.every(message => timeout(message, test.duration)))
101
+ return null;
102
+ }
103
+ else {
104
+ if (!Array.isArray(test.failureMessages) || test.failureMessages.length)
105
+ return null;
106
+ if (test.status === "passed")
107
+ passed++;
108
+ else if (test.status === "todo")
109
+ todo++;
110
+ else
111
+ pending++;
112
+ }
113
+ }
114
+ if ((file.status === "failed") !== red)
115
+ return null;
116
+ if (red) {
117
+ failedFiles++;
118
+ paths.push(rel);
119
+ }
120
+ }
121
+ return paths.length && total === report.numTotalTests && failed === report.numFailedTests
122
+ && passed === report.numPassedTests && pending === report.numPendingTests && todo === report.numTodoTests
123
+ && Number(report.numFailedTestSuites) >= failedFiles && Number(report.numPassedTestSuites) >= seen.size - failedFiles ? paths : null;
124
+ }
125
+ function scopesOverlap(a, b) {
126
+ return a.some(x => b.some(y => x === "." || y === "." || x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`)));
127
+ }
128
+ function record(value) {
129
+ return value !== null && typeof value === "object" && !Array.isArray(value);
130
+ }
131
+ function asRecord(value) {
132
+ return record(value) ? value : {};
133
+ }
134
+ function positiveInteger(value) {
135
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
136
+ }
137
+ function nonempty(value) {
138
+ return typeof value === "string" && value.trim().length > 0;
139
+ }