@telpin-sistemas/orqen 0.1.13 → 0.1.14

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.
@@ -97,7 +97,15 @@ export async function runWorkflow(cmd, rest) {
97
97
  dry?.finish();
98
98
  } // what it would have done, and the temporary copy is deleted
99
99
  }
100
+ /** Options the workflow commands take. One that is not here is a typo, and ignoring it can do the wrong thing (`--chnges` approves; `--isue` creates a new issue). */
101
+ const KNOWN_OPTIONS = new Set(["agent", "all", "analyst", "apply", "changes", "comment", "dir", "dry-run", "force", "issue", "json", "loop", "person", "reason", "report", "since", "step", "title", "verdict"]);
100
102
  async function runCommand(cmd, rest, onDryRun) {
103
+ const unknown = rest.filter((a) => /^--[A-Za-z]/.test(a) && !KNOWN_OPTIONS.has(a.slice(2).split("=")[0]));
104
+ if (unknown.length) {
105
+ console.error(`✘ Unknown option${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}. Nothing was run. Valid options: ${[...KNOWN_OPTIONS].map((o) => `--${o}`).join(", ")}.`);
106
+ process.exitCode = 1;
107
+ return;
108
+ }
101
109
  const cfg = loadConfig();
102
110
  warnLegacy(cfg);
103
111
  const connectors = buildConnectors(cfg.connectors);
@@ -35,14 +35,25 @@ export class AsanaTracker {
35
35
  gid = (key) => idOf(this.s.prefix, key);
36
36
  needProject() { if (!this.s.project)
37
37
  throw new Error("Asana connector without project (conectores.*.proyecto: project gid)"); return this.s.project; }
38
+ /** Every task of a listing: Asana pages them (100 at most) and a request past the first page would never be seen. */
39
+ async allPages(path) {
40
+ const out = [];
41
+ let offset;
42
+ do {
43
+ const page = await this.requestPage("GET", offset ? `${path}&offset=${encodeURIComponent(offset)}` : path);
44
+ out.push(...(page.data ?? []));
45
+ offset = page.next_page?.offset;
46
+ } while (offset);
47
+ return out;
48
+ }
38
49
  async pending() {
39
- const tasks = await this.req("GET", `/projects/${this.needProject()}/tasks?completed_since=now&limit=100&opt_fields=tags.name`);
50
+ const tasks = await this.allPages(`/projects/${this.needProject()}/tasks?completed_since=now&limit=100&opt_fields=tags.name`);
40
51
  const tag = this.s.tag.toLowerCase();
41
52
  return tasks.filter((t) => (t.tags ?? []).some((g) => g.name?.toLowerCase() === tag)).map((t) => keyOf(this.s.prefix, t.gid));
42
53
  }
43
54
  /** Text search inside the project (name and notes). */
44
55
  async search(query) {
45
- const tasks = await this.req("GET", `/projects/${this.needProject()}/tasks?limit=100&opt_fields=name,notes`);
56
+ const tasks = await this.allPages(`/projects/${this.needProject()}/tasks?limit=100&opt_fields=name,notes`);
46
57
  const q = query.toLowerCase();
47
58
  return tasks.filter((t) => `${t.name} ${t.notes ?? ""}`.toLowerCase().includes(q)).map((t) => keyOf(this.s.prefix, t.gid));
48
59
  }
@@ -227,9 +227,18 @@ export class GithubTracker {
227
227
  }
228
228
  async create(t) {
229
229
  const i = await this.req("POST", "/repos/{repo}/issues", { title: t.title.slice(0, 250), body: toMarkdown(t.description), labels: [...this.s.labels, ...(t.labels ?? [])] });
230
- if (this.s.project)
231
- await this.addToProject(i.node_id);
232
- return keyOf(this.s.prefix, i.number);
230
+ const key = keyOf(this.s.prefix, i.number);
231
+ if (this.s.project) {
232
+ // the issue exists already: losing its key here would leave it orphaned and the next attempt would create a second one. The
233
+ // project column is set again by the first transition (transition() adds the issue to the project if it is not there).
234
+ try {
235
+ await this.addToProject(i.node_id);
236
+ }
237
+ catch (e) {
238
+ console.error(`[orqen] warning: ${key} was created but could not be added to the GitHub project (${e.message.split("\n")[0]}); it is added at its next move`);
239
+ }
240
+ }
241
+ return key;
233
242
  }
234
243
  /** Without a project: "closed"/"open" close or reopen the issue. With a project: moves it to that option of the field (Status). */
235
244
  async transition(key, name) {
@@ -54,8 +54,23 @@ export class JiraTracker {
54
54
  labelled(label) { return this.search(`${this.s.project ? `project = "${this.s.project}" AND ` : ""}labels = "${label}" AND statusCategory != Done`); }
55
55
  async search(jql) {
56
56
  const path = this.s.deployment === "cloud" ? "/rest/api/3/search/jql" : "/rest/api/2/search";
57
- const r = await this.req("GET", path, undefined, { jql, fields: "key", maxResults: 100 });
58
- return (r.issues ?? []).map((i) => this.alias(i.key));
57
+ // every page: with more than 100 results the rest would never be seen (a request past the first 100 would wait forever)
58
+ const keys = [];
59
+ const cloud = this.s.deployment === "cloud";
60
+ let token;
61
+ for (let page = 0; page < 100; page++) {
62
+ const r = await this.req("GET", path, undefined, {
63
+ jql, fields: "key", maxResults: 100,
64
+ ...(cloud ? (token ? { nextPageToken: token } : {}) : { startAt: keys.length }),
65
+ });
66
+ const issues = r.issues ?? [];
67
+ keys.push(...issues.map((i) => this.alias(i.key)));
68
+ token = r.nextPageToken;
69
+ const more = cloud ? !!token && r.isLast !== true : issues.length > 0 && keys.length < (r.total ?? 0);
70
+ if (!more)
71
+ break;
72
+ }
73
+ return keys;
59
74
  }
60
75
  async ticket(key) {
61
76
  const r = await this.req("GET", `/rest/api/2/issue/${this.native(key)}`, undefined, {
@@ -41,6 +41,7 @@ export class DryRun {
41
41
  state;
42
42
  worqs;
43
43
  fakeTickets = new Map();
44
+ fakeReviews = [];
44
45
  constructor(cfg, connectors, ws, os, realStore, key) {
45
46
  this.cfg = cfg;
46
47
  this.state = join(this.dir, "state");
@@ -99,9 +100,14 @@ export class DryRun {
99
100
  workspace(ws) {
100
101
  const git = (text) => this.plan.push({ kind: "git", text });
101
102
  const pr = (text) => this.plan.push({ kind: "pr", text });
102
- return guard(ws, ["currentBranch", "remoteBranchExists", "prState", "prChecks", "prReviews", "snapshotOf"], {
103
+ const g = guard(ws, ["currentBranch", "remoteBranchExists", "prState", "prChecks", "prReviews", "snapshotOf"], {
103
104
  prepareBranch: (k) => branchFor(k), commit: () => true, push: () => { }, openPr: (v) => `https://dry-run.invalid/pr/${v.key}`,
104
- closePr: () => { }, reviewPr: () => { }, runTests: () => ({ ok: true, output: "(dry run)" }), startEnvironment: async () => ({ ok: true, detail: "dry run" }), stopEnvironment: () => { },
105
+ closePr: () => { },
106
+ // the review that would be posted: the gate reads the PR's reviews right after posting, so it has to find this one there
107
+ reviewPr: (_url, action, body) => {
108
+ this.fakeReviews.push({ id: `dry-${this.fakeReviews.length + 1}`, author: this.cfg.githubReviewers[0] ?? "dry-run", state: action === "approve" ? "APPROVED" : "CHANGES_REQUESTED", commit: "", body });
109
+ },
110
+ runTests: () => ({ ok: true, output: "(dry run)" }), startEnvironment: async () => ({ ok: true, detail: "dry run" }), stopEnvironment: () => { },
105
111
  }, (n, a) => {
106
112
  switch (n) {
107
113
  case "commit": return git(`commit "${oneLine(String(a[1]), 100)}" (if there is something to commit)`);
@@ -112,6 +118,17 @@ export class DryRun {
112
118
  default: return undefined; // prepareBranch, runTests, environment: nothing to report
113
119
  }
114
120
  });
121
+ // the PR's reviews are the real ones plus the one this run would post, on the PR's current head
122
+ return new Proxy(g, {
123
+ get: (t, prop) => {
124
+ if (prop === "prReviews" && ws.prReviews)
125
+ return (url) => {
126
+ const snap = ws.prReviews(url);
127
+ return { head: snap.head, reviews: [...snap.reviews, ...this.fakeReviews.map((r) => ({ ...r, commit: snap.head }))] };
128
+ };
129
+ return t[prop];
130
+ },
131
+ });
115
132
  }
116
133
  openspec(os) {
117
134
  return guard(os, ["exists", "dir", "validate", "planningComplete", "tasks", "scenarios"], {
@@ -19,7 +19,10 @@ export class OpenSpecCli {
19
19
  run(args) {
20
20
  const win = process.platform === "win32"; // with a shell (cmd) arguments containing spaces must be quoted
21
21
  const a = win ? args.map((x) => (/[\s"]/.test(x) ? `"${x.replace(/"/g, '\\"')}"` : x)) : args;
22
- const p = spawnSync(this.cmd, a, { cwd: this.repoPath, encoding: "utf8", shell: win });
22
+ // the same for the program: a path like C:\Program Files\nodejs\openspec.cmd breaks at its first space in cmd
23
+ // (only when it is a path that exists: OPENSPEC_CMD may also be a command with arguments, like `npx openspec`)
24
+ const cmd = win && /\s/.test(this.cmd) && existsSync(this.cmd) ? `"${this.cmd}"` : this.cmd;
25
+ const p = spawnSync(cmd, a, { cwd: this.repoPath, encoding: "utf8", shell: win });
23
26
  if (p.error)
24
27
  throw new Error(`Could not run "${this.cmd}": ${p.error.message}. Is OpenSpec installed? (npm i -g @fission-ai/openspec)`);
25
28
  try {
@@ -192,7 +192,12 @@ export class Process {
192
192
  // ================================================================ review
193
193
  async review() {
194
194
  const pending = [];
195
- for (const key of await this.requests.pending()) {
195
+ await this.resync();
196
+ // The queue of the requests system is a filter (a JQL, a tag): a request whose ticket leaves it (someone moves it to another column
197
+ // while it waits for the decision) would wait forever. The ones this machine has waiting on a decision are looked at anyway.
198
+ const queue = await this.requests.pending();
199
+ const waiting = this.store.all().filter((i) => !queue.includes(i.key) && (isGate(i.state) || i.state === "BLOCKED" || i.state === "DELIVERY")).map((i) => i.key);
200
+ for (const key of [...queue, ...waiting]) {
196
201
  try {
197
202
  const item = await this.known(key);
198
203
  if (item.recovered)
@@ -219,6 +224,11 @@ export class Process {
219
224
  console.error(`[orqen] warning: ${key} was not reviewed (temporary error, the next run tries again): ${e.message.split("\n")[0]}`);
220
225
  continue;
221
226
  }
227
+ // not in the queue: it is here only because this machine has it waiting; if its ticket cannot be read it is reported, not blocked
228
+ if (waiting.includes(key)) {
229
+ console.error(`[orqen] warning: ${key} was not reviewed: ${e.message.split("\n")[0]}`);
230
+ continue;
231
+ }
222
232
  await this.block(key, `Error reviewing the request: ${e.message}`, "process");
223
233
  }
224
234
  }
@@ -325,7 +335,7 @@ export class Process {
325
335
  if (!this.ws.reviewPr)
326
336
  throw new Error("This workspace cannot review PRs; use CODE_REVIEW_GATE=ticket.");
327
337
  this.ws.reviewPr(url, action === "approve" ? "approve" : "request-changes", body.trim() || `Approved by ${person} with orqen.`);
328
- await this.reviewCodeOnPr(item);
338
+ await this.reviewCodeOnPr(item, force);
329
339
  const after = this.item(key);
330
340
  if (after.state === "CODE_REVIEW")
331
341
  throw new Error(`The review was posted on ${url} but did not count${this.cfg.githubReviewers.length ? ` (GITHUB_REVIEWERS: ${this.cfg.githubReviewers.join(", ")})` : ""}. Check it on GitHub.`);
@@ -343,13 +353,27 @@ export class Process {
343
353
  }
344
354
  return { state: item.state, url, onGitHub: false, warning };
345
355
  }
356
+ /**
357
+ * Where `support` and `analyze` start from: this machine's record; for a request it has no record of, a new one, unless its ticket's
358
+ * label says it already went on (it is being worked on from another machine): starting from NEW would restart the work, and the
359
+ * first comment and label would overwrite what the other machine did.
360
+ */
361
+ async startable(key) {
362
+ const local = this.item(key);
363
+ if (local)
364
+ return local;
365
+ const known = await this.known(key);
366
+ if (known.recovered)
367
+ throw new Error(`${key} is already in ${known.state} according to its ticket's label, and this machine has no record of it: starting it here would restart the work. ${this.recoveredHint(key).text}`);
368
+ return known;
369
+ }
346
370
  // ================================================================ support
347
371
  /**
348
372
  * Opens (or resumes) the first-line handling of a request (available even with SUPPORT_STAGE=off: that variable only decides whether new requests are routed here). The support person drives it; the agent helps them
349
373
  * find an answer. The stage ends resolved (the client confirms in ACCEPTANCE) or escalated to the analyst.
350
374
  */
351
375
  async support(key, agent = "agent", person = agent) {
352
- const item = this.item(key) ?? newWorkItem(key);
376
+ const item = await this.startable(key);
353
377
  if (item.state !== "NEW" && item.state !== "SUPPORT")
354
378
  throw new Error(`${key} is not waiting for support (state: ${item.state}).${item.state === "ANALYSIS" ? " It was escalated to the analyst: use `orqen analyze`." : ""}`);
355
379
  this.assertClaimable(item, agent);
@@ -365,7 +389,7 @@ export class Process {
365
389
  // ================================================================ analyze
366
390
  /** Opens (or resumes) the analysis of a request. An analyst drives it; the agent does the grilling with them. */
367
391
  async analyze(key, agent = "agent", analyst = agent) {
368
- const item = this.item(key) ?? newWorkItem(key);
392
+ const item = await this.startable(key);
369
393
  if (item.state === "WAITING_CLIENT")
370
394
  throw new Error(`${key} is waiting for client answers on the ticket. When they reply it goes back to ANALYSIS (\`orqen list requests\`).`);
371
395
  if (item.state !== "NEW" && item.state !== "SUPPORT" && item.state !== "ANALYSIS")
@@ -409,6 +433,25 @@ export class Process {
409
433
  }
410
434
  // ================================================================ take
411
435
  async take(key, agent = "agent", fromAnalyze = false) {
436
+ const before = this.item(key)?.lock;
437
+ try {
438
+ return await this.takeWork(key, agent, fromAnalyze);
439
+ }
440
+ catch (e) {
441
+ // a failure after the lock was set (switching branches, reading the ticket...) must not leave the request held by an agent
442
+ // that never started: nobody else could take it until the lock expires
443
+ const item = this.item(key);
444
+ if (item?.lock && item.lock.agent === agent && JSON.stringify(item.lock) !== JSON.stringify(before)) {
445
+ if (before)
446
+ item.lock = before;
447
+ else
448
+ delete item.lock;
449
+ this.store.save(item);
450
+ }
451
+ throw e;
452
+ }
453
+ }
454
+ async takeWork(key, agent, fromAnalyze) {
412
455
  const item = this.item(key);
413
456
  if (!item)
414
457
  throw new Error(`${key} has no work for an agent (state: unknown). Run \`orqen list requests\`. ${this.fetchHint(key)}`);
@@ -561,6 +604,10 @@ export class Process {
561
604
  throw new Error(`The PR was not opened. Output: ${out || "(none)"}`);
562
605
  item.artifacts.devel_pr = url;
563
606
  this.store.save(item);
607
+ // the snapshot on the branch is what another machine recovers the worq from: without this it would not know the PR exists
608
+ this.fac.record(item, item.state, item.state, `PR to ${info.base}: ${url}`, agent);
609
+ this.attempt(() => this.ws.commit(key, `PR url ${url}`, { path: join(this.cfg.factoryDir, key), branch: item.branch }));
610
+ this.attempt(() => this.ws.push(item.branch));
564
611
  await this.commentBoth(item, `PR to *${info.base}* opened from branch \`${item.branch}\`: ${url}`);
565
612
  this.store.log(key, { ts: new Date().toISOString(), from: item.state, to: item.state, detail: `PR to ${info.base}: ${url}`, agent });
566
613
  return { url, created: true, base: info.base };
@@ -671,6 +718,18 @@ export class Process {
671
718
  const errors = this.validateAgainstOpenSpec(item, state, s);
672
719
  if (errors.length)
673
720
  return { ok: false, errors };
721
+ // the development is committed on the active branch: it has to be the request's (`orqen pr` checks the same)
722
+ if (state === "DEVELOPMENT" && s.completed && item.branch) {
723
+ let current;
724
+ try {
725
+ current = this.ws.currentBranch();
726
+ }
727
+ catch {
728
+ current = undefined;
729
+ }
730
+ if (current !== undefined && current !== item.branch)
731
+ return { ok: false, errors: [`The repo is on "${current}", not on the request branch "${item.branch}": the commit of this development would go to the wrong branch. Switch to it (git checkout ${item.branch}) and complete again.`] };
732
+ }
674
733
  // --- counters and decision
675
734
  if (state === "ANALYSIS") {
676
735
  item.route = s.route;
@@ -902,7 +961,7 @@ export class Process {
902
961
  * "dismiss stale approvals"), each review is handled once, and with GITHUB_REVIEWERS set only those GitHub logins count.
903
962
  * Changes requested win over approvals. If GitHub cannot be read, the request keeps waiting (it is not blocked).
904
963
  */
905
- async reviewCodeOnPr(item) {
964
+ async reviewCodeOnPr(item, force = false) {
906
965
  const url = item.artifacts.devel_pr;
907
966
  if (!url)
908
967
  return this.store.save(item); // no PR yet: nothing to decide on (`/orqen:pr` opens it)
@@ -922,17 +981,31 @@ export class Process {
922
981
  const authorized = this.cfg.githubReviewers;
923
982
  const latest = new Map(); // last decisive review per author, on the current head
924
983
  for (const r of snap.reviews) {
925
- if (!["APPROVED", "CHANGES_REQUESTED"].includes(r.state) || r.commit !== snap.head || handled.has(r.id))
984
+ if (!["APPROVED", "CHANGES_REQUESTED"].includes(r.state) || r.commit !== snap.head)
926
985
  continue;
927
986
  if (authorized.length && !authorized.includes(r.author))
928
987
  continue;
929
988
  latest.set(r.author, r);
930
989
  }
931
- const decisive = [...latest.values()];
990
+ // the handled ones go out only after taking each author's last review: an approval that came before a rejection already
991
+ // handled is not their opinion any more, and must not come back as a new decision
992
+ const decisive = [...latest.values()].filter((r) => !handled.has(r.id));
932
993
  const rejected = decisive.filter((r) => r.state === "CHANGES_REQUESTED");
933
994
  const approved = decisive.filter((r) => r.state === "APPROVED");
934
995
  if (!rejected.length && !approved.length)
935
996
  return this.store.save(item);
997
+ // an approval is held, like `orqen approve` does, while the PR is red, still running its CI or has conflicts (it is not marked as
998
+ // handled: the next run looks again). Unknown (no gh...) never holds it.
999
+ if (!rejected.length && !force) {
1000
+ const h = this.prHealth(url);
1001
+ const problem = h.conflicts ? `it has conflicts with ${this.cfg.develBranch}`
1002
+ : h.ci === "failing" ? `its CI is failing${h.detail ? ` (${h.detail})` : ""}`
1003
+ : h.ci === "pending" ? `its CI is still running${h.detail ? ` (${h.detail})` : ""}` : "";
1004
+ if (problem) {
1005
+ console.error(`[orqen] warning: ${item.key}: the PR ${url} is approved on GitHub but ${problem}; it stays in CODE_REVIEW and is looked at again on the next run (orqen approve ${workKey(item)} --force overrides this).`);
1006
+ return this.store.save(item);
1007
+ }
1008
+ }
936
1009
  const used = rejected.length ? rejected : approved;
937
1010
  item.artifacts.handled_reviews = [...handled, ...used.map((r) => r.id)];
938
1011
  if (rejected.length) {
@@ -1121,7 +1194,17 @@ export class Process {
1121
1194
  }
1122
1195
  const item = { ...newWorkItem(key), state: "ANALYSIS", origin: "internal", title: t, analyst: person, lock: { agent: "internal", since: new Date().toISOString() } };
1123
1196
  this.store.save(item);
1124
- const r = await this.complete(key, analysis, "internal");
1197
+ let r;
1198
+ try {
1199
+ r = await this.complete(key, analysis, "internal");
1200
+ }
1201
+ catch (e) {
1202
+ // an error of the connector halfway (the comment, the label...) leaves the same: the issue exists and the worq did not start, so
1203
+ // `--issue` has to be able to take it. Once it moved on it is a worq, and the error is shown as it is.
1204
+ if (this.store.get(key)?.state !== "ANALYSIS")
1205
+ throw e;
1206
+ r = { ok: false, errors: [e.message.split("\n")[0]] };
1207
+ }
1125
1208
  if (!r.ok) {
1126
1209
  this.store.remove(key);
1127
1210
  rmSync(this.fac.dirOf(key), { recursive: true, force: true });
@@ -1287,14 +1370,25 @@ export class Process {
1287
1370
  item.state = to;
1288
1371
  delete item.lock;
1289
1372
  if (isGate(to) || to === "BLOCKED") { // when entering a gate, ignore earlier comments
1373
+ // up to orqen's own last comment (the one that asks for the answer), not up to the last comment there is: a client who answers
1374
+ // between that comment and this read would otherwise have their answer taken as already seen, and the request would wait forever
1290
1375
  const cs = await this.requests.comments(item.key);
1291
- item.lastSeenComment = cs.at(-1)?.id ?? "";
1376
+ const ours = [...cs].reverse().find((c) => isBotComment(c.body));
1377
+ item.lastSeenComment = (ours ?? cs.at(-1))?.id ?? "";
1292
1378
  }
1293
1379
  this.store.save(item);
1294
1380
  this.store.log(item.key, { ts: new Date().toISOString(), from, to, detail, agent });
1295
1381
  this.fac.record(item, from, to, detail, agent);
1296
1382
  if (item.branch)
1297
1383
  this.attempt(() => this.ws.commit(item.key, `registro ${from} → ${to}`, { path: join(this.cfg.factoryDir, item.key), branch: item.branch }));
1384
+ await this.syncRemote(item, to);
1385
+ }
1386
+ /**
1387
+ * The state on the tickets: the label, the column or transition and, for a finished request, closing them. Everything here is
1388
+ * idempotent. When it fails the local state has already moved, so the worq is marked (`sync_pending`) and every run of
1389
+ * `orqen list` tries again until the tickets say the same as orqen (a cancelled request must not stay open there).
1390
+ */
1391
+ async syncRemote(item, to) {
1298
1392
  try {
1299
1393
  await this.requests.setStateLabel(item.key, to);
1300
1394
  // CANCELLED falls back to the CLOSED destination when the connector has no own "CANCELLED" transition
@@ -1314,9 +1408,30 @@ export class Process {
1314
1408
  if (item.issue)
1315
1409
  await this.issues?.finish?.(item.issue, reason);
1316
1410
  }
1411
+ if (item.artifacts.sync_pending) {
1412
+ delete item.artifacts.sync_pending;
1413
+ this.store.save(item);
1414
+ }
1415
+ return true;
1317
1416
  }
1318
1417
  catch (e) {
1319
- console.error(`[orqen] could not update the state on ${this.requests.label}: ${e.message}`);
1418
+ console.error(`[orqen] could not update the state on ${this.requests.label}: ${e.message}${isFinal(to) ? " (orqen tries again on the next `orqen list`)" : ""}`);
1419
+ if (item.artifacts.sync_pending !== to) {
1420
+ item.artifacts.sync_pending = to;
1421
+ this.store.save(item);
1422
+ }
1423
+ return false;
1424
+ }
1425
+ }
1426
+ /** Finishes what a failed update of the tickets left behind (see syncRemote). Runs at the start of every review. */
1427
+ async resync() {
1428
+ for (const item of this.store.all()) {
1429
+ if (item.artifacts.sync_pending === item.state)
1430
+ await this.syncRemote(item, item.state);
1431
+ else if (item.artifacts.sync_pending) {
1432
+ delete item.artifacts.sync_pending;
1433
+ this.store.save(item);
1434
+ } // it moved on since: the later move wrote the tickets
1320
1435
  }
1321
1436
  }
1322
1437
  }
@@ -12,8 +12,26 @@ export class Store {
12
12
  mkdirSync(dir, { recursive: true });
13
13
  }
14
14
  path = (key) => join(this.dir, `${key}.json`);
15
+ /**
16
+ * The saved record, or nothing when there is none. A file that is not valid JSON (a crash while writing it, an editor, a bad
17
+ * merge) is set aside as <KEY>.json.corrupt and treated as missing, so orqen recovers the request from its snapshot or its
18
+ * ticket instead of failing every command that lists requests.
19
+ */
15
20
  get(key) {
16
- return existsSync(this.path(key)) ? migrate(JSON.parse(readFileSync(this.path(key), "utf8"))) : undefined;
21
+ const file = this.path(key);
22
+ if (!existsSync(file))
23
+ return undefined;
24
+ try {
25
+ return migrate(JSON.parse(readFileSync(file, "utf8")));
26
+ }
27
+ catch (e) {
28
+ console.error(`[orqen] warning: the record of ${key} is not valid JSON (${e.message.split("\n")[0]}): kept as ${key}.json.corrupt and recovered from its snapshot or its ticket if possible`);
29
+ try {
30
+ renameSync(file, file + ".corrupt");
31
+ }
32
+ catch { /* read-only folder: it is ignored anyway */ }
33
+ return undefined;
34
+ }
17
35
  }
18
36
  save(rec) {
19
37
  const tmp = this.path(rec.key) + ".tmp";
@@ -26,7 +44,15 @@ export class Store {
26
44
  log(key, ev) { appendFileSync(join(this.dir, `${key}.log.jsonl`), JSON.stringify(ev) + "\n"); }
27
45
  events(key) {
28
46
  const f = join(this.dir, `${key}.log.jsonl`);
29
- return existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
47
+ if (!existsSync(f))
48
+ return [];
49
+ // a line cut by a crash must not hide the rest of the history
50
+ return readFileSync(f, "utf8").trim().split("\n").filter(Boolean).flatMap((l) => { try {
51
+ return [JSON.parse(l)];
52
+ }
53
+ catch {
54
+ return [];
55
+ } });
30
56
  }
31
57
  all() {
32
58
  // only request records: other tools (the desktop app) may keep their own files in this folder
@@ -66,6 +66,10 @@ export class GitWorkspace {
66
66
  catch { /* no remote */ }
67
67
  if (this.git("branch", "--list", branch))
68
68
  this.git("checkout", branch);
69
+ else if (this.git("branch", "-r", "--list", `origin/${branch}`)) {
70
+ // someone started this request on another machine (or this clone is new): continue from their branch, not from the base
71
+ this.git("checkout", "-b", branch, "--track", `origin/${branch}`);
72
+ }
69
73
  else if (this.linkedWorktree()) {
70
74
  // the base branch is usually checked out in the main worktree, where git does not let us check it out again
71
75
  const base = this.git("branch", "-r", "--list", `origin/${this.cfg.baseBranch}`) ? `origin/${this.cfg.baseBranch}` : this.cfg.baseBranch;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telpin-sistemas/orqen",
3
- "version": "0.1.13",
3
+ "version": "0.1.14",
4
4
  "description": "orqen multi-agent orchestration on OpenSpec, from customer request to production.",
5
5
  "type": "module",
6
6
  "bin": {