robisie 0.1.4 → 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 (47) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +39 -11
  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/planer-client.d.ts +45 -4
  33. package/dist/planer-client.js +120 -14
  34. package/dist/roles.d.ts +1 -1
  35. package/dist/select-fingerprint.d.ts +19 -0
  36. package/dist/select-fingerprint.js +46 -0
  37. package/dist/test-report.d.ts +9 -0
  38. package/dist/test-report.js +139 -0
  39. package/dist/tester-result-reader.d.ts +87 -0
  40. package/dist/tester-result-reader.js +122 -0
  41. package/docs/ENGINE-API.md +9 -1
  42. package/docs/README.en.md +55 -16
  43. package/docs/README.md +53 -16
  44. package/docs/RELEASE-0.1.0.md +27 -5
  45. package/helpers/ceo-client-launcher-mcp.mjs +76 -5
  46. package/package.json +6 -2
  47. package/roles/ceo-client.md +10 -8
@@ -0,0 +1,230 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { closeSync, fsyncSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { z } from "zod";
6
+ const text = z.string().trim().min(1), at = z.iso.datetime({ offset: true });
7
+ const eventSchema = z.strictObject({ id: text, at, sha: z.string().regex(/^[a-f0-9]{40}$/), ref: text, operation: text, result: text });
8
+ const digest = (v) => createHash("sha256").update(v).digest("hex");
9
+ const failure = (e) => e instanceof z.ZodError ? "Niepoprawny kontrakt JSON" : String(e);
10
+ export function relative(ref) {
11
+ if (path.isAbsolute(ref) || ref.split(/[\\/]/).some(p => p === ".." || p === "") || ref.includes("\0"))
12
+ throw new Error("Obca ścieżka dowodu");
13
+ }
14
+ export function within(root, ref) {
15
+ relative(ref);
16
+ const base = realpathSync(root), file = realpathSync(path.join(base, ref));
17
+ if (!file.startsWith(base + path.sep))
18
+ throw new Error("Dowód poza zatwierdzonym katalogiem");
19
+ return file;
20
+ }
21
+ /** The transport already bounds model output to 256 KiB; inputs use the same byte bound. */
22
+ export function bounded(file) {
23
+ return new TextDecoder("utf-8", { fatal: true }).decode(boundedBytes(file));
24
+ }
25
+ function boundedBytes(file) {
26
+ const fd = openSync(file, "r"), bytes = Buffer.alloc(256 * 1024 + 1);
27
+ try {
28
+ if (!fstatSync(fd).isFile())
29
+ throw new Error("Dowód nie jest plikiem");
30
+ let length = 0, n;
31
+ while (length < bytes.length && (n = readSync(fd, bytes, length, bytes.length - length, null)) > 0)
32
+ length += n;
33
+ if (length === bytes.length)
34
+ throw new Error("Zbyt duży dowód");
35
+ return bytes.subarray(0, length);
36
+ }
37
+ finally {
38
+ closeSync(fd);
39
+ }
40
+ }
41
+ export function readLocalUsageEvents(root, c) {
42
+ try {
43
+ const landed = c.landed, readAt = c.readAt, after = Date.parse(at.parse(landed.at));
44
+ const until = Math.min(Date.parse(c.deadline), Date.parse(at.parse(readAt)));
45
+ const source = bounded(within(root, c.source));
46
+ if (source && !source.endsWith("\n"))
47
+ throw new Error("Urwany JSONL");
48
+ const ids = new Set(), operations = new Set(), artifacts = new Set(), events = [];
49
+ for (const line of source.split("\n").slice(0, -1)) {
50
+ const e = eventSchema.parse(JSON.parse(line));
51
+ if (e.sha !== landed.sha || Date.parse(e.at) <= after || Date.parse(e.at) > until)
52
+ throw new Error("Obcy SHA/czas użycia");
53
+ const bytes = bounded(within(root, e.ref)), sha256 = digest(bytes);
54
+ if (!bytes.trim())
55
+ throw new Error("Pusty artefakt użycia");
56
+ const duplicate = ids.has(e.id) || operations.has(e.operation) || artifacts.has(sha256);
57
+ ids.add(e.id);
58
+ operations.add(e.operation);
59
+ artifacts.add(sha256);
60
+ if (!duplicate)
61
+ events.push({ ...e, bytes, sha256 });
62
+ }
63
+ if (Buffer.byteLength(JSON.stringify(events)) > 256 * 1024)
64
+ throw new Error("Zbyt duży pakiet dowodów");
65
+ return events;
66
+ }
67
+ catch (cause) {
68
+ throw new Error(`Odmowa dowodów użycia: ${failure(cause)}`);
69
+ }
70
+ }
71
+ function syncDirectory(dir) {
72
+ const fd = openSync(dir, "r");
73
+ try {
74
+ fsyncSync(fd);
75
+ }
76
+ finally {
77
+ closeSync(fd);
78
+ }
79
+ }
80
+ /** Check each existing parent before creating anything; canonicalize aliases for the source lock. */
81
+ function directory(root, ref) {
82
+ if (realpathSync(root) !== root)
83
+ throw new Error("Zmieniony katalog dowodów");
84
+ if (ref === ".")
85
+ return root;
86
+ relative(ref);
87
+ let dir = root;
88
+ for (const part of ref.split(path.sep)) {
89
+ const next = path.join(dir, part);
90
+ if (!lstatSync(next, { throwIfNoEntry: false })) {
91
+ mkdirSync(next, { mode: 0o700 });
92
+ syncDirectory(dir);
93
+ }
94
+ dir = within(root, path.relative(root, next));
95
+ }
96
+ return dir;
97
+ }
98
+ function destination(root, ref) {
99
+ relative(ref);
100
+ const file = path.join(directory(root, path.dirname(ref)), path.basename(ref));
101
+ return lstatSync(file, { throwIfNoEntry: false }) ? within(root, path.relative(root, file)) : file;
102
+ }
103
+ function owned(root, file) {
104
+ if (realpathSync(root) !== root || within(root, path.relative(root, file)) !== file)
105
+ throw new Error("Zmieniona ścieżka przebiegu");
106
+ return file;
107
+ }
108
+ /** One synchronous Node invocation; no shell, card commands, inherited credentials or control env. */
109
+ export function runLocalUsage(input) {
110
+ let stage = "wejście", published = false, lock, pending;
111
+ let root, run, worktree, attempted = false, result;
112
+ const errors = [];
113
+ // Deliberately small environment; no HOME/config, NODE_OPTIONS, GIT_* or Planner credentials from the caller.
114
+ // The host Next.js types require NODE_ENV; this Node-only child intentionally omits it.
115
+ const env = { PATH: "/usr/bin:/bin", LANG: "C.UTF-8" };
116
+ const git = (cwd, args) => {
117
+ const r = spawnSync("git", args, { cwd, env, encoding: "utf8", shell: false });
118
+ if (r.error || r.status !== 0 || r.signal)
119
+ throw new Error(`git ${args[0]}: status=${r.status}, signal=${r.signal}: ${r.stderr ?? ""}`, { cause: r.error });
120
+ return r.stdout.trim();
121
+ };
122
+ try {
123
+ eventSchema.shape.sha.parse(input.landed.sha);
124
+ at.parse(input.landed.at);
125
+ at.parse(input.deadline);
126
+ text.parse(input.operation);
127
+ z.array(z.string()).parse(input.program.args);
128
+ for (const ref of [input.source, input.program.entry, input.program.artifact])
129
+ relative(ref);
130
+ if (Date.parse(input.landed.at) >= Date.now() || Date.parse(input.deadline) < Date.now())
131
+ throw new Error("Obcy czas użycia");
132
+ stage = "katalog dowodów";
133
+ const state = realpathSync(input.stateDir);
134
+ root = directory(state, "evidence");
135
+ const source = destination(root, input.source), sourceRef = path.relative(root, source);
136
+ stage = "blokada";
137
+ const fd = openSync(`${source}.lock`, "wx", 0o600);
138
+ lock = `${source}.lock`;
139
+ closeSync(fd);
140
+ stage = "odczyt źródła";
141
+ let previous = Buffer.alloc(0);
142
+ if (lstatSync(source, { throwIfNoEntry: false })) {
143
+ readLocalUsageEvents(root, { ...input, source: sourceRef, readAt: new Date().toISOString() });
144
+ previous = boundedBytes(source);
145
+ }
146
+ stage = "worktree";
147
+ run = mkdtempSync(path.join(directory(root, ".runs"), "usage-"));
148
+ worktree = path.join(run, "wt");
149
+ attempted = true;
150
+ git(input.repo, ["worktree", "add", "--detach", "--quiet", worktree, input.landed.sha]);
151
+ const verify = () => {
152
+ if (git(worktree, ["rev-parse", "HEAD"]) !== input.landed.sha)
153
+ throw new Error("Obcy SHA użycia");
154
+ if (git(worktree, ["status", "--porcelain", "--untracked-files=no"]))
155
+ throw new Error("Zmieniony śledzony kod użycia");
156
+ };
157
+ stage = "SHA przed wykonaniem";
158
+ verify();
159
+ const entry = within(worktree, input.program.entry);
160
+ git(worktree, ["--literal-pathspecs", "ls-files", "--error-unmatch", "--", input.program.entry, path.relative(worktree, entry)]);
161
+ const artifact = destination(worktree, input.program.artifact);
162
+ if (lstatSync(artifact, { throwIfNoEntry: false }))
163
+ throw new Error("Artefakt istnieje przed użyciem");
164
+ stage = "proces";
165
+ const executed = spawnSync(process.execPath, [entry, ...input.program.args], { cwd: worktree, env, encoding: "utf8", shell: false });
166
+ const finishedAt = new Date().toISOString();
167
+ if (executed.error || executed.status !== 0 || executed.signal)
168
+ throw new Error(`Proces użycia: status=${executed.status}, signal=${executed.signal}; stdout=${executed.stdout ?? ""}; stderr=${executed.stderr ?? ""}`, { cause: executed.error });
169
+ stage = "SHA po wykonaniu";
170
+ verify();
171
+ stage = "artefakt";
172
+ const bytes = boundedBytes(within(worktree, input.program.artifact));
173
+ const id = randomUUID(), ref = `artifacts/${id}/${path.basename(input.program.artifact)}`;
174
+ const saved = destination(root, ref);
175
+ writeFileSync(saved, bytes, { flag: "wx", mode: 0o600, flush: true });
176
+ within(root, ref);
177
+ syncDirectory(path.dirname(saved));
178
+ result = eventSchema.parse({ id, at: finishedAt, sha: git(worktree, ["rev-parse", "HEAD"]), ref,
179
+ operation: input.operation, result: JSON.stringify({ exit: executed.status, stdout: executed.stdout ?? "", stderr: executed.stderr ?? "" }) });
180
+ stage = "walidacja zapisu";
181
+ // Stable key order; validate JSON before serializing so undefined never silently disappears.
182
+ const line = JSON.stringify(z.json().parse(Object.fromEntries(Object.entries(result).sort(([a], [b]) => a.localeCompare(b))))) + "\n";
183
+ const temp = `${source}.${id}.pending`;
184
+ if (destination(root, path.relative(root, temp)) !== temp)
185
+ throw new Error("Zmieniony katalog źródła");
186
+ const out = openSync(temp, "wx", 0o600);
187
+ pending = temp;
188
+ try {
189
+ writeFileSync(out, Buffer.concat([previous, Buffer.from(line)]));
190
+ fsyncSync(out);
191
+ }
192
+ finally {
193
+ closeSync(out);
194
+ }
195
+ readLocalUsageEvents(root, { ...input, source: path.relative(root, temp), readAt: new Date().toISOString() });
196
+ stage = "publikacja";
197
+ // Recheck physical parents immediately before publication, never follow a redirected source.
198
+ if (destination(root, input.source) !== source || within(root, path.relative(root, temp)) !== temp)
199
+ throw new Error("Zmieniony katalog źródła");
200
+ renameSync(temp, source);
201
+ published = true;
202
+ pending = undefined;
203
+ syncDirectory(path.dirname(source));
204
+ }
205
+ catch (cause) {
206
+ errors.push(new Error(`Użycie — ${stage}: ${failure(cause)}`, { cause }));
207
+ }
208
+ finally {
209
+ const cleanup = (label, action) => {
210
+ try {
211
+ action();
212
+ }
213
+ catch (cause) {
214
+ errors.push(new Error(`Użycie — cleanup ${label}: ${String(cause)}`, { cause }));
215
+ }
216
+ };
217
+ if (attempted && worktree)
218
+ cleanup("worktree", () => { git(input.repo, ["worktree", "remove", "--force", owned(root, worktree)]); });
219
+ if (run)
220
+ cleanup("katalog przebiegu", () => rmdirSync(owned(root, run)));
221
+ if (pending)
222
+ cleanup("plik tymczasowy", () => unlinkSync(owned(root, pending)));
223
+ if (lock)
224
+ cleanup("blokada", () => unlinkSync(owned(root, lock)));
225
+ }
226
+ if (errors.length)
227
+ throw new AggregateError(errors, errors.map(e => e.message).join("; ")
228
+ + (published ? "; wpis może już istnieć — sprawdź źródło, nie ponawiaj całego programu" : "; zdarzenie nie zostało opublikowane"));
229
+ return result;
230
+ }
@@ -22,6 +22,7 @@ export declare function clientPaths(dir: string): {
22
22
  dir: string;
23
23
  manifest: string;
24
24
  key: string;
25
+ reviewKey: string;
25
26
  backups: string;
26
27
  roles: string;
27
28
  codexRoles: string;
@@ -37,5 +38,7 @@ export declare function ensurePrivateDir(dir: string): void;
37
38
  export declare function writePrivate(dir: string, path: string, text: string): void;
38
39
  export declare function readManifest(path: string): Manifest | null;
39
40
  export declare function writeManifest(dir: string, manifest: Omit<Manifest, "packageVersion">): void;
40
- export declare function writeKey(dir: string, key: string): void;
41
- export declare function readKey(dir: string): string | null;
41
+ type KeySlot = "key" | "review-key";
42
+ export declare function writeKey(dir: string, key: string, slot?: KeySlot): void;
43
+ export declare function readKey(dir: string, slot?: KeySlot): string | null;
44
+ export {};
package/dist/manifest.js CHANGED
@@ -31,6 +31,7 @@ export function clientPaths(dir) {
31
31
  dir,
32
32
  manifest: join(dir, "manifest.json"),
33
33
  key: join(dir, "key"),
34
+ reviewKey: join(dir, "review-key"),
34
35
  backups: join(dir, "backups"),
35
36
  roles: join(dir, "roles"),
36
37
  codexRoles: join(dir, "roles", "codex"),
@@ -182,12 +183,11 @@ export function writeManifest(dir, manifest) {
182
183
  const paths = clientPaths(dir);
183
184
  writePrivate(paths.dir, paths.manifest, `${JSON.stringify({ packageVersion: PACKAGE_VERSION, ...manifest }, null, 2)}\n`);
184
185
  }
185
- export function writeKey(dir, key) {
186
- const paths = clientPaths(dir);
187
- writePrivate(paths.dir, paths.key, `${key}\n`);
186
+ export function writeKey(dir, key, slot = "key") {
187
+ writePrivate(dir, join(dir, slot), `${key}\n`);
188
188
  }
189
- export function readKey(dir) {
190
- const path = clientPaths(dir).key;
189
+ export function readKey(dir, slot = "key") {
190
+ const path = join(dir, slot);
191
191
  refuseSymlink(dir);
192
192
  refuseSymlink(path);
193
193
  try {
@@ -196,6 +196,6 @@ export function readKey(dir) {
196
196
  catch (error) {
197
197
  if (error.code === "ENOENT")
198
198
  return null;
199
- throw new RobisieError(`Nie mogę odczytać pliku ${path} (błąd IO).`, `Sprawdź prawa odczytu pliku ${path}. Jeśli nie jest zwykłym plikiem, przywróć go z poprawnej kopii tej samej instalacji, zachowując istniejący plik lub katalog i jego zawartość w osobnej kopii. Potem wczytaj ROBISIE_KEY zgodnie z instrukcją instalacji i ponów \`npx robisie doctor\`.`);
199
+ throw new RobisieError(`Nie mogę odczytać pliku ${path} (błąd IO).`, `Sprawdź prawa odczytu pliku ${path}. Jeśli nie jest zwykłym plikiem, przywróć go z poprawnej kopii tej samej instalacji, zachowując istniejący plik lub katalog i jego zawartość w osobnej kopii. Potem wczytaj ${slot === "key" ? "ROBISIE_KEY" : "ROBISIE_REVIEW_KEY"} zgodnie z instrukcją instalacji i ponów \`npx robisie doctor\`.`);
200
200
  }
201
201
  }
@@ -11,8 +11,8 @@ export type PlanerClientConfig = ({
11
11
  fetch?: typeof fetch;
12
12
  deadlineMs?: number;
13
13
  };
14
- type Operation = "connect" | "close" | "list_projects" | "list_tracks" | "list_tasks" | "get_task" | "reserve_task" | "update_task" | "append_detail" | "close_decision_matter" | "get_review_snapshot" | "accept_review" | "create_track" | "create_task";
15
- type Failure = "INVALID_CONFIG" | "INVALID_ARGUMENT" | "NOT_CONNECTED" | "CLOSED" | "CONTRACT_VERSION" | "INVALID_RESPONSE" | "DETAILS_READ_ERROR" | "TOOL_ERROR" | "UNAUTHORIZED" | "FORBIDDEN" | "RATE_LIMITED" | "HTTP_ERROR" | "RPC_ERROR" | "TRANSPORT_ERROR" | "TIMEOUT";
14
+ type Operation = "connect" | "close" | "list_projects" | "list_tracks" | "list_tasks" | "get_task" | "reserve_task" | "update_task" | "append_detail" | "close_decision_matter" | "get_review_snapshot" | "accept_review" | "create_track" | "create_task" | "move_task" | "write_decision_matter";
15
+ type Failure = "INVALID_CONFIG" | "INVALID_ARGUMENT" | "NOT_CONNECTED" | "CLOSED" | "CONTRACT_VERSION" | "UNSUPPORTED_CONTRACT" | "INVALID_RESPONSE" | "DETAILS_READ_ERROR" | "TOOL_ERROR" | "UNAUTHORIZED" | "FORBIDDEN" | "RATE_LIMITED" | "HTTP_ERROR" | "RPC_ERROR" | "TRANSPORT_ERROR" | "TIMEOUT";
16
16
  /** Fixed reason only. In particular, never attach SDK message, cause, raw body or caller arguments. */
17
17
  export declare class PlanerClientError extends Error {
18
18
  readonly code: Failure;
@@ -24,10 +24,13 @@ export declare class PlanerClientError extends Error {
24
24
  uncertain?: boolean, diagnostic?: {
25
25
  plannerCode?: string;
26
26
  requestId?: string;
27
+ plannerMeta?: Record<string, unknown>;
27
28
  });
28
29
  readonly plannerCode?: string;
29
30
  readonly requestId?: string;
31
+ readonly plannerMeta?: Record<string, unknown>;
30
32
  }
33
+ export declare const PLANNER_DOMAIN_CODES: readonly ["PROJECT_NOT_FOUND", "PROJECT_NAME_TAKEN", "PROJECT_LIMIT_REACHED", "CONCURRENCY_LIMIT_REACHED", "WEBHOOK_SUBSCRIPTION_LIMIT_REACHED", "TRACK_NOT_FOUND", "TRACK_HAS_TASKS", "TRACK_REORDER_MISMATCH", "TASK_DETAILS_MACHINE_FIELD_INVALID", "TASK_DETAILS_TOO_LARGE", "TASK_NOT_FOUND", "TASK_UPDATE_CONFLICT", "SEED_PACKAGE_DENIED", "TASK_DONE_EVIDENCE_REQUIRED", "TASK_CARD_CLASS_IMMUTABLE", "TASK_DONE_EVIDENCE_IMMUTABLE", "TASK_SELF_DEPENDENCY", "DEPENDENCY_NOT_FOUND", "TASK_INSERT_FAILED", "TASK_VANISHED", "TASK_ALREADY_CLAIMED", "TASK_NOT_RESERVABLE", "TASK_RESERVATION_RACED", "NEIGHBOR_NOT_FOUND", "NEIGHBOR_WRONG_TRACK", "NEIGHBOR_ORDER_INVALID"];
31
34
  declare const jsonObject: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
32
35
  declare const projectSchema: z.ZodObject<{
33
36
  id: z.ZodUUID;
@@ -56,6 +59,22 @@ declare const taskSchema: z.ZodObject<{
56
59
  }>;
57
60
  assignee: z.ZodNullable<z.ZodString>;
58
61
  dependsOn: z.ZodArray<z.ZodUUID>;
62
+ specRef: z.ZodNullable<z.ZodString>;
63
+ createdAt: z.ZodISODateTime;
64
+ updatedAt: z.ZodISODateTime;
65
+ position: z.ZodOptional<z.ZodNullable<z.ZodString>>;
66
+ statusEnteredAt: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
67
+ statusEnteredStatus: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
68
+ ready: "ready";
69
+ in_review: "in_review";
70
+ in_progress: "in_progress";
71
+ delivered: "delivered";
72
+ blocked: "blocked";
73
+ done: "done";
74
+ draft: "draft";
75
+ }>>>;
76
+ seedBriefDigest: z.ZodOptional<z.ZodNullable<z.ZodString>>;
77
+ seedPackageDigest: z.ZodOptional<z.ZodNullable<z.ZodString>>;
59
78
  }, z.core.$strip>;
60
79
  declare const echoSchema: z.ZodObject<{
61
80
  id: z.ZodUUID;
@@ -153,8 +172,8 @@ declare const appendSchema: z.ZodObject<{
153
172
  declare const closeSchema: z.ZodObject<{
154
173
  outcome: z.ZodEnum<{
155
174
  CLOSED: "CLOSED";
156
- ALREADY_CLOSED: "ALREADY_CLOSED";
157
175
  CONFLICT: "CONFLICT";
176
+ ALREADY_CLOSED: "ALREADY_CLOSED";
158
177
  NOT_APPLIED: "NOT_APPLIED";
159
178
  }>;
160
179
  cardId: z.ZodUUID;
@@ -182,6 +201,17 @@ export type AppendDetailResult = {
182
201
  export type CloseDecisionResult = Omit<z.infer<typeof closeSchema>, "matter"> & {
183
202
  isError: boolean;
184
203
  };
204
+ /** applied:false = server refused the guarded append (structured CONFLICT); nothing was written. */
205
+ export type AppendDetailIfResult = {
206
+ applied: true;
207
+ write: z.infer<typeof appendSchema>;
208
+ } | {
209
+ applied: false;
210
+ };
211
+ export type DecisionMatter = z.infer<typeof jsonObject>;
212
+ /** Minimum server contract for update_task expected.details/detailsPatch, guarded append_detail and
213
+ * write_decision_matter. Older 1.x servers silently strip these unknown fields, so the client refuses locally. */
214
+ export declare const PARITY_CONTRACT_MINOR = 1;
185
215
  /** Existing MCP operations only. No auto-connect, retry, CAS emulation or runtime cutover. */
186
216
  export declare class PlanerClient {
187
217
  #private;
@@ -204,10 +234,21 @@ export declare class PlanerClient {
204
234
  * Local validation fails with INVALID_ARGUMENT/uncertain=false; failures after sending are uncertain.
205
235
  * After an uncertain write, caller must explicitly getTask({id, include:['review_receipt']}) and decide. */
206
236
  acceptReview(args: unknown): Promise<z.infer<typeof echoSchema>>;
207
- /** For draft promotion, pass {status:'ready', expected:{status:'draft'}}. Server owns CAS/permissions. */
237
+ /** For draft promotion, pass {status:'ready', expected:{status:'draft'}}. Server owns CAS/permissions.
238
+ * expected.details (snapshot CAS) and detailsPatch (shallow merge) need contract >= 1.1.0 and are
239
+ * applied by the server in the same atomic write; details and detailsPatch are mutually exclusive. */
208
240
  updateTask(args: unknown): Promise<z.infer<typeof echoSchema>>;
209
241
  /** Flat server merge; null is literal. No deep merge, chunking, append guard or implicit retry. */
210
242
  appendDetail(args: unknown): Promise<AppendDetailResult>;
243
+ /** Guarded append (q.appendDetailIf/appendDetail guard): one CAS write on the server, no readback,
244
+ * no retry. Requires contract >= 1.1.0. applied:false only for a structured CONFLICT of this card. */
245
+ appendDetailIf(args: unknown): Promise<AppendDetailIfResult>;
246
+ /** q.writeDecisionMatter: open/update one decision matter; expected = exact current matter (CAS).
247
+ * Returns the persisted matter (also when the server refused the write) or null; caller compares.
248
+ * Requires contract >= 1.1.0. Server owns roles, size limits and closed-matter rules. */
249
+ writeDecisionMatter(args: unknown): Promise<DecisionMatter | null>;
250
+ /** Change track and/or order. Server computes the position; no retry. */
251
+ moveTask(args: unknown): Promise<z.infer<typeof echoSchema>>;
211
252
  /** full/owner_validator authority stays on the server. Non-CLOSED outcomes retain isError. */
212
253
  closeDecisionMatter(args: unknown): Promise<CloseDecisionResult>;
213
254
  }
@@ -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.4 \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;