@bendyline/gezel-mcp 1.0.4 → 1.0.6

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.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { BranchPrioritizedPulls, PullWithHeadRef, prioritizePullsForCurrentBranch } from '@bendyline/gezel';
2
+
1
3
  /**
2
4
  * Frozen inventory of every MCP tool the gezel-mcp server registers.
3
5
  *
@@ -362,19 +364,4 @@ declare function unavailableToolsForPlatform(platform: NodeJS.Platform, options?
362
364
  linuxSystemdAvailable?: boolean;
363
365
  }): readonly string[];
364
366
 
365
- interface PullWithHeadRef {
366
- headRef: string;
367
- }
368
- interface BranchPrioritizedPulls<T extends PullWithHeadRef> {
369
- pulls: T[];
370
- currentBranch?: string;
371
- matchingCount: number;
372
- }
373
- /**
374
- * Put open PRs for the checked-out branch first without disturbing the
375
- * provider's order inside either group. Callers can then safely treat the
376
- * first result as the default only when `matchingCount > 0`.
377
- */
378
- declare function prioritizePullsForCurrentBranch<T extends PullWithHeadRef>(pulls: readonly T[], currentBranch?: string): BranchPrioritizedPulls<T>;
379
-
380
- export { ALWAYS_REGISTERED_TOOLS, type AlwaysRegisteredToolName, BUILTIN_TOOL_NAMES, type BranchPrioritizedPulls, CANONICAL_TOOL_NAMES, CONDITIONALLY_REGISTERED_TOOLS, type CanonicalToolName, type CanonicalToolRegistryEntry, type ConditionallyRegisteredToolName, type FileContent, LEGACY_SPELLING_BY_CANONICAL, LEGACY_TOOL_NAMES, type LegacyToolName, type PullWithHeadRef, RENAMED_TOOLS, RESERVED_TOOL_NAMES, TOOL_NAME_TOMBSTONES, TOOL_REGISTRY, type ToolNameTombstone, type ToolRegistrationGate, type ValidateCheck, type ValidateResult, canUseLinuxSystemdDenyNet, canonicalToolName, formatValidateResult, normalizeToolNameSpelling, prioritizePullsForCurrentBranch, resolveToolNameSpelling, unavailableToolsForPlatform, validateFile };
367
+ export { ALWAYS_REGISTERED_TOOLS, type AlwaysRegisteredToolName, BUILTIN_TOOL_NAMES, CANONICAL_TOOL_NAMES, CONDITIONALLY_REGISTERED_TOOLS, type CanonicalToolName, type CanonicalToolRegistryEntry, type ConditionallyRegisteredToolName, type FileContent, LEGACY_SPELLING_BY_CANONICAL, LEGACY_TOOL_NAMES, type LegacyToolName, RENAMED_TOOLS, RESERVED_TOOL_NAMES, TOOL_NAME_TOMBSTONES, TOOL_REGISTRY, type ToolNameTombstone, type ToolRegistrationGate, type ValidateCheck, type ValidateResult, canUseLinuxSystemdDenyNet, canonicalToolName, formatValidateResult, normalizeToolNameSpelling, resolveToolNameSpelling, unavailableToolsForPlatform, validateFile };
package/dist/index.js CHANGED
@@ -380,7 +380,95 @@ function resolveToolNameSpelling(requested, knownNames) {
380
380
  }
381
381
 
382
382
  // src/validate.ts
383
+ import ts2 from "typescript";
384
+
385
+ // src/source-validation.ts
383
386
  import ts from "typescript";
387
+ var DIAG_BLOCK_COMMENT_UNCLOSED = 1010;
388
+ var DIAG_TEMPLATE_UNTERMINATED = 1160;
389
+ var DIAG_TOKEN_EXPECTED = 1005;
390
+ function locateUnterminatedConstruct(body, scriptKind = ts.ScriptKind.JS) {
391
+ const sf = parseFor(body, scriptKind);
392
+ const first = parseDiagnosticsOf(sf)?.[0];
393
+ if (!first || first.start == null) return null;
394
+ if (first.start < body.trimEnd().length) return null;
395
+ if (first.code === DIAG_BLOCK_COMMENT_UNCLOSED) {
396
+ const start2 = locateTrailingBlockComment(body, scriptKind);
397
+ if (start2 !== null) return { start: start2, label: "block comment", closer: "*/" };
398
+ }
399
+ const closer = closerForDiagnostic(first);
400
+ if (!closer) return null;
401
+ const relatedStart = first.relatedInformation?.[0]?.start;
402
+ if (typeof relatedStart === "number") {
403
+ return { start: relatedStart, label: labelForCloser(closer), closer };
404
+ }
405
+ const start = locateNodeSpanningEnd(body, closer, scriptKind);
406
+ return start === null ? null : { start, label: labelForCloser(closer), closer };
407
+ }
408
+ function parseFor(source, scriptKind) {
409
+ const ext = scriptKind === ts.ScriptKind.TSX ? "tsx" : scriptKind === ts.ScriptKind.TS ? "ts" : scriptKind === ts.ScriptKind.JSX ? "jsx" : "js";
410
+ return ts.createSourceFile(
411
+ `unterminated-probe.${ext}`,
412
+ source,
413
+ ts.ScriptTarget.ES2022,
414
+ /*setParentNodes*/
415
+ false,
416
+ scriptKind
417
+ );
418
+ }
419
+ function parseDiagnosticsOf(sf) {
420
+ return sf.parseDiagnostics;
421
+ }
422
+ function closerForDiagnostic(diag) {
423
+ if (diag.code === DIAG_BLOCK_COMMENT_UNCLOSED) return "*/";
424
+ if (diag.code === DIAG_TEMPLATE_UNTERMINATED) return "`";
425
+ if (diag.code === DIAG_TOKEN_EXPECTED) {
426
+ const text = ts.flattenDiagnosticMessageText(diag.messageText, " ");
427
+ const quoted = /^'(.{1,2})' expected/.exec(text);
428
+ const token = quoted?.[1];
429
+ return token && ["}", ")", "]"].includes(token) ? token : null;
430
+ }
431
+ return null;
432
+ }
433
+ function labelForCloser(closer) {
434
+ switch (closer) {
435
+ case "*/":
436
+ return "block comment";
437
+ case "`":
438
+ return "template literal";
439
+ case "}":
440
+ return "{ ... } block";
441
+ case ")":
442
+ return "( ... ) group";
443
+ case "]":
444
+ return "[ ... ] list";
445
+ default:
446
+ return "construct";
447
+ }
448
+ }
449
+ function locateTrailingBlockComment(body, scriptKind) {
450
+ const repaired = `${body}*/`;
451
+ const sf = parseFor(repaired, scriptKind);
452
+ const ranges = ts.getLeadingCommentRanges(repaired, sf.endOfFileToken.pos) ?? [];
453
+ const trailing = ranges.find((r) => r.end === repaired.length);
454
+ return trailing ? trailing.pos : null;
455
+ }
456
+ function locateNodeSpanningEnd(body, closer, scriptKind) {
457
+ const repaired = `${body}${closer}`;
458
+ const sf = parseFor(repaired, scriptKind);
459
+ let best = null;
460
+ const visit = (node) => {
461
+ const start = node.getStart(sf);
462
+ if (node.end === repaired.length && start < repaired.length) {
463
+ if (best === null || start > best) best = start;
464
+ }
465
+ ts.forEachChild(node, visit);
466
+ };
467
+ ts.forEachChild(sf, visit);
468
+ return best;
469
+ }
470
+
471
+ // src/validate.ts
384
472
  function validateFile(path, content) {
385
473
  const lower = path.toLowerCase();
386
474
  if (lower.endsWith(".html") || lower.endsWith(".htm")) {
@@ -452,6 +540,20 @@ function buildExcerpt(text, targetLine, context = 2) {
452
540
  var SCRIPT_RE = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
453
541
  var SCRIPT_OPEN_RE = /<script\b[^>]*>/gi;
454
542
  var SCRIPT_CLOSE_RE = /<\/script\s*>/gi;
543
+ var INERT_WITHOUT_SCRIPT = [
544
+ { re: /<canvas\b/i, what: "<canvas> element" },
545
+ {
546
+ re: /\son(?:click|change|input|submit|keydown|keyup|keypress|mousedown|mouseup|mousemove|mouseover|mouseout|touchstart|touchend|touchmove|load|focus|blur|error|scroll|resize)\s*=/i,
547
+ what: "inline event-handler attribute"
548
+ }
549
+ ];
550
+ function inertMarkupWithoutScript(html) {
551
+ for (const { re, what } of INERT_WITHOUT_SCRIPT) {
552
+ const m = re.exec(html);
553
+ if (m) return { what, line: (html.slice(0, m.index).match(/\n/g)?.length ?? 0) + 1 };
554
+ }
555
+ return null;
556
+ }
455
557
  function validateHtml(_path, content) {
456
558
  if (!content.text) {
457
559
  return [
@@ -470,6 +572,18 @@ function validateHtml(_path, content) {
470
572
  const opens = (html.match(SCRIPT_OPEN_RE) ?? []).length;
471
573
  const closes = (html.match(SCRIPT_CLOSE_RE) ?? []).length;
472
574
  if (opens === 0) {
575
+ const inert = inertMarkupWithoutScript(html);
576
+ if (inert) {
577
+ checks.push({
578
+ ok: false,
579
+ name: "script-tag-present",
580
+ message: `page has a ${inert.what} but no <script> at all \u2014 this markup is inert, so nothing on the page can run`,
581
+ location: { line: inert.line },
582
+ excerpt: buildExcerpt(html, inert.line, 2),
583
+ fixHint: "the page is missing its JavaScript entirely \u2014 a syntax pass on markup alone is not evidence it works. Add the <script> block that drives it, then re-validate."
584
+ });
585
+ return checks;
586
+ }
473
587
  checks.push({
474
588
  ok: true,
475
589
  name: "script-tag-present",
@@ -508,8 +622,24 @@ function validateHtml(_path, content) {
508
622
  const openIdx = m.index ?? 0;
509
623
  const openLine = (html.slice(0, openIdx).match(/\n/g)?.length ?? 0) + 1;
510
624
  scripts.push({ body, attrs, openLine });
511
- const parseError = isModuleScript(attrs) ? tryParseSource(body, ts.ScriptKind.JS) : tryParseFunctionBody(body);
625
+ const parseError = isModuleScript(attrs) ? tryParseSource(body, ts2.ScriptKind.JS) : tryParseFunctionBody(body);
512
626
  if (parseError) {
627
+ const unterminated = locateUnterminatedConstruct(body);
628
+ if (unterminated) {
629
+ const before = body.slice(0, unterminated.start);
630
+ const newlines = before.match(/\n/g)?.length ?? 0;
631
+ const fileLine2 = openLine + newlines;
632
+ const col2 = newlines > 0 ? unterminated.start - before.lastIndexOf("\n") : void 0;
633
+ checks.push({
634
+ ok: false,
635
+ name: scriptIdx === 1 ? "script-body-parses" : `script-body-parses[${scriptIdx}]`,
636
+ message: `unterminated ${unterminated.label} \u2014 it swallows the rest of the script, so nothing on the page runs`,
637
+ location: { line: fileLine2, ...col2 ? { col: col2 } : {} },
638
+ excerpt: buildExcerpt(html, fileLine2, 2),
639
+ fixHint: `add the missing \`${unterminated.closer}\` where that construct should end. The defect is at line ${fileLine2}, not at the end of the script \u2014 do not edit or remove the </script> tag.`
640
+ });
641
+ return checks;
642
+ }
513
643
  const locMatch = parseError.match(/line (\d+)(?:.*?col(?:umn)?\s*(\d+))?/i);
514
644
  const scriptInternalLine = locMatch ? Number(locMatch[1]) : 1;
515
645
  const col = locMatch?.[2] ? Number(locMatch[2]) : void 0;
@@ -589,15 +719,15 @@ function validateUniqueTopLevelFunctions(scripts) {
589
719
  const seen = /* @__PURE__ */ new Map();
590
720
  let count = 0;
591
721
  for (const script of scripts) {
592
- const sf = ts.createSourceFile(
722
+ const sf = ts2.createSourceFile(
593
723
  "inline-script.js",
594
724
  script.body,
595
- ts.ScriptTarget.ES2022,
725
+ ts2.ScriptTarget.ES2022,
596
726
  true,
597
- ts.ScriptKind.JS
727
+ ts2.ScriptKind.JS
598
728
  );
599
729
  for (const statement of sf.statements) {
600
- if (!ts.isFunctionDeclaration(statement) || !statement.name) continue;
730
+ if (!ts2.isFunctionDeclaration(statement) || !statement.name) continue;
601
731
  count += 1;
602
732
  const relative = sf.getLineAndCharacterOfPosition(statement.name.getStart(sf));
603
733
  const line = script.openLine + relative.line;
@@ -622,18 +752,18 @@ function validateUniqueTopLevelFunctions(scripts) {
622
752
  };
623
753
  }
624
754
  function tryParseSource(source, scriptKind) {
625
- const fileName = scriptKind === ts.ScriptKind.TSX ? "source.tsx" : "source.js";
626
- const output = ts.transpileModule(source, {
755
+ const fileName = scriptKind === ts2.ScriptKind.TSX ? "source.tsx" : "source.js";
756
+ const output = ts2.transpileModule(source, {
627
757
  fileName,
628
758
  reportDiagnostics: true,
629
- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }
759
+ compilerOptions: { target: ts2.ScriptTarget.ES2022, module: ts2.ModuleKind.ESNext }
630
760
  });
631
761
  const diagnostics = output.diagnostics?.filter(
632
- (diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error && diagnostic.file !== void 0 && diagnostic.start !== void 0
762
+ (diagnostic) => diagnostic.category === ts2.DiagnosticCategory.Error && diagnostic.file !== void 0 && diagnostic.start !== void 0
633
763
  );
634
764
  if (!diagnostics || diagnostics.length === 0) return null;
635
765
  const first = diagnostics[0];
636
- const message = ts.flattenDiagnosticMessageText(first.messageText, "\n");
766
+ const message = ts2.flattenDiagnosticMessageText(first.messageText, "\n");
637
767
  const { line, character } = first.file.getLineAndCharacterOfPosition(first.start);
638
768
  return `${message} at line ${line + 1}, col ${character + 1}`;
639
769
  }
@@ -651,11 +781,11 @@ function validateJsTs(path, content) {
651
781
  }
652
782
  const checks = [fileNonEmptyCheck(content)];
653
783
  const lower = path.toLowerCase();
654
- const scriptKind = lower.endsWith(".tsx") ? ts.ScriptKind.TSX : lower.endsWith(".ts") ? ts.ScriptKind.TS : lower.endsWith(".jsx") ? ts.ScriptKind.JSX : ts.ScriptKind.JS;
655
- const sf = ts.createSourceFile(
784
+ const scriptKind = lower.endsWith(".tsx") ? ts2.ScriptKind.TSX : lower.endsWith(".ts") ? ts2.ScriptKind.TS : lower.endsWith(".jsx") ? ts2.ScriptKind.JSX : ts2.ScriptKind.JS;
785
+ const sf = ts2.createSourceFile(
656
786
  path,
657
787
  content.text,
658
- ts.ScriptTarget.ES2022,
788
+ ts2.ScriptTarget.ES2022,
659
789
  /*setParentNodes*/
660
790
  true,
661
791
  scriptKind
@@ -678,12 +808,12 @@ function validateJsTs(path, content) {
678
808
  checks.push({
679
809
  ok: true,
680
810
  name: "parses",
681
- detail: `${scriptKind === ts.ScriptKind.TS || scriptKind === ts.ScriptKind.TSX ? "TypeScript" : "JavaScript"} parses cleanly`
811
+ detail: `${scriptKind === ts2.ScriptKind.TS || scriptKind === ts2.ScriptKind.TSX ? "TypeScript" : "JavaScript"} parses cleanly`
682
812
  });
683
813
  return checks;
684
814
  }
685
815
  const first = diags[0];
686
- const msg = ts.flattenDiagnosticMessageText(first.messageText, "\n");
816
+ const msg = ts2.flattenDiagnosticMessageText(first.messageText, "\n");
687
817
  const { line, character } = sf.getLineAndCharacterOfPosition(first.start);
688
818
  checks.push({
689
819
  ok: false,
@@ -699,11 +829,11 @@ function findNestedStaticModuleDeclaration(sf) {
699
829
  let found = null;
700
830
  const visit = (node) => {
701
831
  if (found) return;
702
- if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node) || ts.isExportAssignment(node)) && node.parent !== sf) {
832
+ if ((ts2.isImportDeclaration(node) || ts2.isExportDeclaration(node) || ts2.isExportAssignment(node)) && node.parent !== sf) {
703
833
  found = node;
704
834
  return;
705
835
  }
706
- ts.forEachChild(node, visit);
836
+ ts2.forEachChild(node, visit);
707
837
  };
708
838
  visit(sf);
709
839
  return found;
@@ -882,21 +1012,10 @@ function unavailableToolsForPlatform(platform, options = {}) {
882
1012
  return DENY_NET_TOOLS;
883
1013
  }
884
1014
 
885
- // src/github-pr-selection.ts
886
- function prioritizePullsForCurrentBranch(pulls, currentBranch) {
887
- const branch = currentBranch?.trim();
888
- if (!branch) return { pulls: [...pulls], matchingCount: 0 };
889
- const matching = [];
890
- const others = [];
891
- for (const pull of pulls) {
892
- (pull.headRef === branch ? matching : others).push(pull);
893
- }
894
- return {
895
- pulls: [...matching, ...others],
896
- currentBranch: branch,
897
- matchingCount: matching.length
898
- };
899
- }
1015
+ // src/index.ts
1016
+ import {
1017
+ prioritizePullsForCurrentBranch
1018
+ } from "@bendyline/gezel";
900
1019
  export {
901
1020
  ALWAYS_REGISTERED_TOOLS,
902
1021
  BUILTIN_TOOL_NAMES,
package/dist/server.js CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  isReservedShadowArtifactPath,
29
29
  isTrustedConstrainedToolset,
30
30
  pickRandomNameWithGender,
31
+ prioritizePullsForCurrentBranch,
31
32
  removeStepAndCleanEdges,
32
33
  reorderStepsArray,
33
34
  resolveRoleId,
@@ -364,22 +365,6 @@ function quantizeImageSize(size) {
364
365
  return Math.max(SIZE_MULTIPLE, Math.min(AGENT_IMAGE_MAX_SIDE_PX, rounded));
365
366
  }
366
367
 
367
- // src/github-pr-selection.ts
368
- function prioritizePullsForCurrentBranch(pulls, currentBranch) {
369
- const branch = currentBranch?.trim();
370
- if (!branch) return { pulls: [...pulls], matchingCount: 0 };
371
- const matching = [];
372
- const others = [];
373
- for (const pull of pulls) {
374
- (pull.headRef === branch ? matching : others).push(pull);
375
- }
376
- return {
377
- pulls: [...matching, ...others],
378
- currentBranch: branch,
379
- matchingCount: matching.length
380
- };
381
- }
382
-
383
368
  // src/near-miss.ts
384
369
  function closestFileNames(target, names, limit = 3) {
385
370
  const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
@@ -484,6 +469,75 @@ function isContinuableBlock(trimmed) {
484
469
  return false;
485
470
  }
486
471
 
472
+ // src/partial-edits.ts
473
+ var CAP = 12;
474
+ var GATED_TOOLS = /* @__PURE__ */ new Set(["advance_task_step", "verify_outcome"]);
475
+ var PartialEditRegistry = class {
476
+ drafts = /* @__PURE__ */ new Map();
477
+ /**
478
+ * Record a provisional edit. `priorContent` is only kept the first
479
+ * time — it is the last state the file was in before the sequence
480
+ * started, not the previous provisional step.
481
+ */
482
+ record(path, priorContent) {
483
+ const existing = this.drafts.get(path);
484
+ if (existing) {
485
+ existing.edits += 1;
486
+ return existing;
487
+ }
488
+ const created = { path, edits: 1, snapshot: priorContent };
489
+ this.drafts.set(path, created);
490
+ return created;
491
+ }
492
+ get(path) {
493
+ return this.drafts.get(path);
494
+ }
495
+ isOpen(path) {
496
+ return this.drafts.has(path);
497
+ }
498
+ /** Called when a path validates cleanly again, by any write path. */
499
+ close(path) {
500
+ const draft = this.drafts.get(path);
501
+ if (draft) this.drafts.delete(path);
502
+ return draft;
503
+ }
504
+ openPaths() {
505
+ return [...this.drafts.keys()].sort();
506
+ }
507
+ /**
508
+ * Why `toolName` may not run, or null. Mirrors the unresolved-tool
509
+ * failure ledger: narrow set of gated tools, and `set_task_status`
510
+ * stays open so a stuck gezel keeps an honest exit.
511
+ */
512
+ blockReason(toolName) {
513
+ if (!GATED_TOOLS.has(toolName)) return null;
514
+ const open = this.openPaths();
515
+ if (open.length === 0) return null;
516
+ const list = open.map((p) => `\`${p}\``).join(", ");
517
+ return [
518
+ `${toolName} is blocked: ${open.length === 1 ? "a file is" : "files are"} still in a provisional edit sequence (${list}).`,
519
+ "Those edits were accepted without the syntax gate because you passed `partial: true`, so the file is not known to parse.",
520
+ "Finish the sequence with a final edit that omits `partial`, or re-emit the whole file with `write_file`.",
521
+ `Then re-run \`validate\` and call ${toolName} again.`
522
+ ].join(" ");
523
+ }
524
+ /** Model-facing note appended to a provisional edit's result. */
525
+ noticeFor(draft) {
526
+ const left = CAP - draft.edits;
527
+ const parts = [
528
+ `[Provisional edit ${draft.edits} of at most ${CAP}] \`${draft.path}\` is a draft and was NOT syntax-checked.`,
529
+ "Nothing that declares work finished will run until it parses again.",
530
+ `Close the sequence with a final edit that omits \`partial\`, then call \`validate({ path: "${draft.path}" })\`.`
531
+ ];
532
+ if (left <= 3) {
533
+ parts.push(`Only ${left} provisional edit(s) remain before the sequence is reverted.`);
534
+ }
535
+ return `
536
+
537
+ ${parts.join(" ")}`;
538
+ }
539
+ };
540
+
487
541
  // src/platform-tool-availability.ts
488
542
  import { spawnSync } from "child_process";
489
543
  var DENY_NET_TOOLS = ["run_nodejs_script", "derive_file"];
@@ -1523,8 +1577,10 @@ ${res.callsSummary.map((c) => ` - ${c.kind} (${c.durationMs}ms)${c.error ? ` \u
1523
1577
  const outputBlock = res.output === void 0 ? "" : `
1524
1578
  output:
1525
1579
  ${JSON.stringify(res.output, null, 2)}`;
1580
+ if (res.status === "error") {
1581
+ return errorResult(`${res.error ?? "Script failed."}${outputBlock}${callsSummary}`);
1582
+ }
1526
1583
  const text = `${header}${outputBlock}${callsSummary}`;
1527
- if (res.status === "error") return errorResult(text);
1528
1584
  return okResult(
1529
1585
  ExecutionToolOutputSchema,
1530
1586
  {
@@ -1652,6 +1708,15 @@ function validateHtmlInlineScripts(path, html) {
1652
1708
  if (isModuleScript(s.attrs)) continue;
1653
1709
  const parseError = tryParseFunctionBody(s.body);
1654
1710
  if (parseError) {
1711
+ const unterminated = locateUnterminatedConstruct(s.body);
1712
+ if (unterminated) {
1713
+ const at = lineColAt(html, s.bodyStart + unterminated.start);
1714
+ return {
1715
+ ok: false,
1716
+ message: `${path}: inline <script> #${i + 1} opens a ${unterminated.label} at line ${at.line}, col ${at.col} and never closes it, so the rest of the script is swallowed and nothing runs. Add the missing \`${unterminated.closer}\` where that construct should end. The defect is at line ${at.line} \u2014 do not edit the last line of the script or the </script> tag, which are correct.`,
1717
+ recoverablePartialWrite: "invalid-html"
1718
+ };
1719
+ }
1655
1720
  const loc = locateInlineScriptError(html, s.bodyStart, s.body);
1656
1721
  const where = loc ? `at line ${loc.line}, col ${loc.col}` : `(opens near line ${s.openLine})`;
1657
1722
  return {
@@ -1694,6 +1759,89 @@ function tryParseFunctionBody(body) {
1694
1759
  return err instanceof Error ? err.message : String(err);
1695
1760
  }
1696
1761
  }
1762
+ var DIAG_BLOCK_COMMENT_UNCLOSED = 1010;
1763
+ var DIAG_TEMPLATE_UNTERMINATED = 1160;
1764
+ var DIAG_TOKEN_EXPECTED = 1005;
1765
+ function locateUnterminatedConstruct(body, scriptKind = ts.ScriptKind.JS) {
1766
+ const sf = parseFor(body, scriptKind);
1767
+ const first = parseDiagnosticsOf(sf)?.[0];
1768
+ if (!first || first.start == null) return null;
1769
+ if (first.start < body.trimEnd().length) return null;
1770
+ if (first.code === DIAG_BLOCK_COMMENT_UNCLOSED) {
1771
+ const start2 = locateTrailingBlockComment(body, scriptKind);
1772
+ if (start2 !== null) return { start: start2, label: "block comment", closer: "*/" };
1773
+ }
1774
+ const closer = closerForDiagnostic(first);
1775
+ if (!closer) return null;
1776
+ const relatedStart = first.relatedInformation?.[0]?.start;
1777
+ if (typeof relatedStart === "number") {
1778
+ return { start: relatedStart, label: labelForCloser(closer), closer };
1779
+ }
1780
+ const start = locateNodeSpanningEnd(body, closer, scriptKind);
1781
+ return start === null ? null : { start, label: labelForCloser(closer), closer };
1782
+ }
1783
+ function parseFor(source, scriptKind) {
1784
+ const ext = scriptKind === ts.ScriptKind.TSX ? "tsx" : scriptKind === ts.ScriptKind.TS ? "ts" : scriptKind === ts.ScriptKind.JSX ? "jsx" : "js";
1785
+ return ts.createSourceFile(
1786
+ `unterminated-probe.${ext}`,
1787
+ source,
1788
+ ts.ScriptTarget.ES2022,
1789
+ /*setParentNodes*/
1790
+ false,
1791
+ scriptKind
1792
+ );
1793
+ }
1794
+ function parseDiagnosticsOf(sf) {
1795
+ return sf.parseDiagnostics;
1796
+ }
1797
+ function closerForDiagnostic(diag) {
1798
+ if (diag.code === DIAG_BLOCK_COMMENT_UNCLOSED) return "*/";
1799
+ if (diag.code === DIAG_TEMPLATE_UNTERMINATED) return "`";
1800
+ if (diag.code === DIAG_TOKEN_EXPECTED) {
1801
+ const text = ts.flattenDiagnosticMessageText(diag.messageText, " ");
1802
+ const quoted = /^'(.{1,2})' expected/.exec(text);
1803
+ const token2 = quoted?.[1];
1804
+ return token2 && ["}", ")", "]"].includes(token2) ? token2 : null;
1805
+ }
1806
+ return null;
1807
+ }
1808
+ function labelForCloser(closer) {
1809
+ switch (closer) {
1810
+ case "*/":
1811
+ return "block comment";
1812
+ case "`":
1813
+ return "template literal";
1814
+ case "}":
1815
+ return "{ ... } block";
1816
+ case ")":
1817
+ return "( ... ) group";
1818
+ case "]":
1819
+ return "[ ... ] list";
1820
+ default:
1821
+ return "construct";
1822
+ }
1823
+ }
1824
+ function locateTrailingBlockComment(body, scriptKind) {
1825
+ const repaired = `${body}*/`;
1826
+ const sf = parseFor(repaired, scriptKind);
1827
+ const ranges = ts.getLeadingCommentRanges(repaired, sf.endOfFileToken.pos) ?? [];
1828
+ const trailing = ranges.find((r) => r.end === repaired.length);
1829
+ return trailing ? trailing.pos : null;
1830
+ }
1831
+ function locateNodeSpanningEnd(body, closer, scriptKind) {
1832
+ const repaired = `${body}${closer}`;
1833
+ const sf = parseFor(repaired, scriptKind);
1834
+ let best = null;
1835
+ const visit = (node) => {
1836
+ const start = node.getStart(sf);
1837
+ if (node.end === repaired.length && start < repaired.length) {
1838
+ if (best === null || start > best) best = start;
1839
+ }
1840
+ ts.forEachChild(node, visit);
1841
+ };
1842
+ ts.forEachChild(sf, visit);
1843
+ return best;
1844
+ }
1697
1845
  function locateInlineScriptError(html, bodyStart, body) {
1698
1846
  const sf = ts.createSourceFile(
1699
1847
  "inline-script.js",
@@ -1735,6 +1883,14 @@ function validateJsTsSource(path, source) {
1735
1883
  );
1736
1884
  const diags = sf.parseDiagnostics;
1737
1885
  if (diags && diags.length > 0) {
1886
+ const unterminated = locateUnterminatedConstruct(source, scriptKind);
1887
+ if (unterminated) {
1888
+ const { line, character } = sf.getLineAndCharacterOfPosition(unterminated.start);
1889
+ return {
1890
+ ok: false,
1891
+ message: `${path}: opens a ${unterminated.label} at line ${line + 1}, col ${character + 1} and never closes it, so everything after it is swallowed. Add the missing \`${unterminated.closer}\` where that construct should end. The defect is at line ${line + 1}, not at the end of the file.${atomicSourceWriteRejectionRecovery(path)}`
1892
+ };
1893
+ }
1738
1894
  return formatSourceDiagnostic(path, sf, diags[0]);
1739
1895
  }
1740
1896
  const nestedModuleSyntax = findNestedStaticModuleDeclaration(sf);
@@ -1963,6 +2119,20 @@ function buildExcerpt(text, targetLine, context = 2) {
1963
2119
  var SCRIPT_RE2 = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
1964
2120
  var SCRIPT_OPEN_RE2 = /<script\b[^>]*>/gi;
1965
2121
  var SCRIPT_CLOSE_RE2 = /<\/script\s*>/gi;
2122
+ var INERT_WITHOUT_SCRIPT = [
2123
+ { re: /<canvas\b/i, what: "<canvas> element" },
2124
+ {
2125
+ re: /\son(?:click|change|input|submit|keydown|keyup|keypress|mousedown|mouseup|mousemove|mouseover|mouseout|touchstart|touchend|touchmove|load|focus|blur|error|scroll|resize)\s*=/i,
2126
+ what: "inline event-handler attribute"
2127
+ }
2128
+ ];
2129
+ function inertMarkupWithoutScript(html) {
2130
+ for (const { re, what } of INERT_WITHOUT_SCRIPT) {
2131
+ const m = re.exec(html);
2132
+ if (m) return { what, line: (html.slice(0, m.index).match(/\n/g)?.length ?? 0) + 1 };
2133
+ }
2134
+ return null;
2135
+ }
1966
2136
  function validateHtml(_path, content) {
1967
2137
  if (!content.text) {
1968
2138
  return [
@@ -1981,6 +2151,18 @@ function validateHtml(_path, content) {
1981
2151
  const opens = (html.match(SCRIPT_OPEN_RE2) ?? []).length;
1982
2152
  const closes = (html.match(SCRIPT_CLOSE_RE2) ?? []).length;
1983
2153
  if (opens === 0) {
2154
+ const inert = inertMarkupWithoutScript(html);
2155
+ if (inert) {
2156
+ checks.push({
2157
+ ok: false,
2158
+ name: "script-tag-present",
2159
+ message: `page has a ${inert.what} but no <script> at all \u2014 this markup is inert, so nothing on the page can run`,
2160
+ location: { line: inert.line },
2161
+ excerpt: buildExcerpt(html, inert.line, 2),
2162
+ fixHint: "the page is missing its JavaScript entirely \u2014 a syntax pass on markup alone is not evidence it works. Add the <script> block that drives it, then re-validate."
2163
+ });
2164
+ return checks;
2165
+ }
1984
2166
  checks.push({
1985
2167
  ok: true,
1986
2168
  name: "script-tag-present",
@@ -2021,6 +2203,22 @@ function validateHtml(_path, content) {
2021
2203
  scripts.push({ body, attrs, openLine });
2022
2204
  const parseError = isModuleScript2(attrs) ? tryParseSource(body, ts2.ScriptKind.JS) : tryParseFunctionBody2(body);
2023
2205
  if (parseError) {
2206
+ const unterminated = locateUnterminatedConstruct(body);
2207
+ if (unterminated) {
2208
+ const before = body.slice(0, unterminated.start);
2209
+ const newlines = before.match(/\n/g)?.length ?? 0;
2210
+ const fileLine2 = openLine + newlines;
2211
+ const col2 = newlines > 0 ? unterminated.start - before.lastIndexOf("\n") : void 0;
2212
+ checks.push({
2213
+ ok: false,
2214
+ name: scriptIdx === 1 ? "script-body-parses" : `script-body-parses[${scriptIdx}]`,
2215
+ message: `unterminated ${unterminated.label} \u2014 it swallows the rest of the script, so nothing on the page runs`,
2216
+ location: { line: fileLine2, ...col2 ? { col: col2 } : {} },
2217
+ excerpt: buildExcerpt(html, fileLine2, 2),
2218
+ fixHint: `add the missing \`${unterminated.closer}\` where that construct should end. The defect is at line ${fileLine2}, not at the end of the script \u2014 do not edit or remove the </script> tag.`
2219
+ });
2220
+ return checks;
2221
+ }
2024
2222
  const locMatch = parseError.match(/line (\d+)(?:.*?col(?:umn)?\s*(\d+))?/i);
2025
2223
  const scriptInternalLine = locMatch ? Number(locMatch[1]) : 1;
2026
2224
  const col = locMatch?.[2] ? Number(locMatch[2]) : void 0;
@@ -2758,6 +2956,10 @@ var sessionCraftbookId = process.env.GEZEL_CRAFTBOOK_ID ?? "";
2758
2956
  var certPath = process.env.GEZEL_CERT_PATH;
2759
2957
  var fetchImpl = certPath ? createTrustingFetch({ cert: readFileSync(certPath, "utf8") }) : createPatientFetch();
2760
2958
  var api = new GezelClient({ baseUrl, token, fetch: fetchImpl });
2959
+ var partialEdits = new PartialEditRegistry();
2960
+ var PartialEditArg = z5.boolean().optional().describe(
2961
+ "Set true ONLY when this edit is one step of a planned multi-edit sequence that leaves the file temporarily unparseable \u2014 for example landing a large script in several pieces. It skips the whole-file syntax gate for this call and marks the file as a draft. You must close the sequence with a final edit that omits this flag (or a full `write_file`); until the file parses again, `advance_task_step` and `verify_outcome` are blocked. Leave it unset for an ordinary self-contained edit \u2014 an unset flag is what protects the last working version of the file."
2962
+ );
2761
2963
  var ExpectedDeliverableArgSchema = coerceJsonObject(
2762
2964
  ExpectedDeliverableSchema.pick({ kind: true, filePath: true })
2763
2965
  );
@@ -2900,7 +3102,7 @@ server.tool(
2900
3102
  {
2901
3103
  text: z5.string().describe("The memory to save \u2014 a concise fact or observation"),
2902
3104
  scope: z5.enum(["gezel", "project"]).describe(
2903
- 'Where to save: "agent" for personal memories, "project" for project-specific context'
3105
+ 'Where to save: "gezel" for your own personal memories, "project" for project-shared context'
2904
3106
  ),
2905
3107
  kind: z5.enum(["fact", "decision", "pref", "status"]).optional().describe(
2906
3108
  'What kind of memory: "fact" (durable fact \u2014 the default), "decision" (a choice made), "pref" (a preference or working style), "status" (a temporary condition true right now)'
@@ -3576,8 +3778,22 @@ ${message}` }],
3576
3778
  }
3577
3779
  }
3578
3780
  const failed = result.checks.some((c) => c.ok === false);
3781
+ let draftNote = "";
3782
+ if (drawer === "workspace" && partialEdits.isOpen(filePath)) {
3783
+ if (failed) {
3784
+ const draft = partialEdits.get(filePath);
3785
+ draftNote = `
3786
+
3787
+ \`${filePath}\` is still an open provisional edit sequence (${draft.edits} of at most ${CAP} edits). Fix the failures above, then close it with an edit that omits \`partial\`.`;
3788
+ } else {
3789
+ partialEdits.close(filePath);
3790
+ draftNote = `
3791
+
3792
+ Provisional edit sequence on \`${filePath}\` is now closed \u2014 the file parses again.`;
3793
+ }
3794
+ }
3579
3795
  return {
3580
- content: [{ type: "text", text: formatValidateResult(result) }],
3796
+ content: [{ type: "text", text: formatValidateResult(result) + draftNote }],
3581
3797
  ...failed ? { isError: true } : {}
3582
3798
  };
3583
3799
  }
@@ -4067,6 +4283,7 @@ Flawed first draft ${path} was saved anyway so you can continue with read_file({
4067
4283
  ...gezelId ? { gezelId } : {},
4068
4284
  ...sessionId ? { sessionId } : {}
4069
4285
  });
4286
+ partialEdits.close(path);
4070
4287
  return {
4071
4288
  content: [
4072
4289
  { type: "text", text: `Wrote ${path}${await htmlRuntimeCheckSuffix(path)}` }
@@ -4154,6 +4371,7 @@ server.tool(
4154
4371
  ...gezelId ? { gezelId } : {},
4155
4372
  ...sessionId ? { sessionId } : {}
4156
4373
  });
4374
+ partialEdits.close(path);
4157
4375
  return {
4158
4376
  content: [
4159
4377
  {
@@ -4179,9 +4397,10 @@ server.tool(
4179
4397
  replace: z5.string().describe("New content for the matched region. May be empty to delete."),
4180
4398
  occurrence: z5.union([z5.number().int().positive(), z5.literal("all")]).optional().describe(
4181
4399
  "Default: exactly one match required. Pass a 1-based index for the Nth match, or 'all' to replace every occurrence."
4182
- )
4400
+ ),
4401
+ partial: PartialEditArg
4183
4402
  },
4184
- async ({ path, find, replace, occurrence }) => {
4403
+ async ({ path, find, replace, occurrence, partial }) => {
4185
4404
  try {
4186
4405
  const before = await api.readProjectWorkspaceFile(projectId, path);
4187
4406
  const result = await api.replaceInProjectWorkspaceFile(projectId, {
@@ -4195,7 +4414,8 @@ server.tool(
4195
4414
  const validationError = await rejectInvalidWorkspaceEdit(
4196
4415
  path,
4197
4416
  before.content,
4198
- "replace_in_file"
4417
+ "replace_in_file",
4418
+ partial
4199
4419
  );
4200
4420
  if (validationError) {
4201
4421
  return {
@@ -4207,7 +4427,7 @@ server.tool(
4207
4427
  content: [
4208
4428
  {
4209
4429
  type: "text",
4210
- text: `Edited ${path} (+${result.addedLines} \u2212${result.removedLines}).${await htmlRuntimeCheckSuffix(path)}`
4430
+ text: `Edited ${path} (+${result.addedLines} \u2212${result.removedLines}).${await editResultSuffix(path, partial)}`
4211
4431
  }
4212
4432
  ],
4213
4433
  structuredContent: {
@@ -4234,9 +4454,10 @@ server.tool(
4234
4454
  endLine: z5.number().int().positive().describe(
4235
4455
  "1-based last line to replace (inclusive). Equal to startLine to replace one line."
4236
4456
  ),
4237
- content: z5.string().describe("Replacement text for the range. Empty deletes the lines. No `N\u2192` gutter.")
4457
+ content: z5.string().describe("Replacement text for the range. Empty deletes the lines. No `N\u2192` gutter."),
4458
+ partial: PartialEditArg
4238
4459
  },
4239
- async ({ path, startLine, endLine, content }) => {
4460
+ async ({ path, startLine, endLine, content, partial }) => {
4240
4461
  try {
4241
4462
  const before = await api.readProjectWorkspaceFile(projectId, path);
4242
4463
  const result = await api.replaceLinesInProjectWorkspaceFile(projectId, {
@@ -4250,7 +4471,8 @@ server.tool(
4250
4471
  const validationError = await rejectInvalidWorkspaceEdit(
4251
4472
  path,
4252
4473
  before.content,
4253
- "replace_lines"
4474
+ "replace_lines",
4475
+ partial
4254
4476
  );
4255
4477
  if (validationError) {
4256
4478
  return {
@@ -4269,7 +4491,7 @@ server.tool(
4269
4491
  content: [
4270
4492
  {
4271
4493
  type: "text",
4272
- text: `Edited ${path} (+${result.addedLines} \u2212${result.removedLines}).${await htmlRuntimeCheckSuffix(path)}${reanchor}`
4494
+ text: `Edited ${path} (+${result.addedLines} \u2212${result.removedLines}).${await editResultSuffix(path, partial)}${reanchor}`
4273
4495
  }
4274
4496
  ],
4275
4497
  structuredContent: {
@@ -4294,9 +4516,10 @@ server.tool(
4294
4516
  path: z5.string().describe("File path relative to the project root."),
4295
4517
  diff: z5.string().min(1).describe(
4296
4518
  "Unified-diff body. Include at least one @@ -L,N +L,N @@ hunk. Do NOT include the file headers (--- a/, +++ b/) \u2014 they are inferred from `path`."
4297
- )
4519
+ ),
4520
+ partial: PartialEditArg
4298
4521
  },
4299
- async ({ path, diff }) => {
4522
+ async ({ path, diff, partial }) => {
4300
4523
  try {
4301
4524
  const before = await api.readProjectWorkspaceFile(projectId, path);
4302
4525
  const result = await api.applyPatchToProjectWorkspaceFile(projectId, {
@@ -4305,7 +4528,12 @@ server.tool(
4305
4528
  ...gezelId ? { gezelId } : {},
4306
4529
  ...sessionId ? { sessionId } : {}
4307
4530
  });
4308
- const validationError = await rejectInvalidWorkspaceEdit(path, before.content, "apply_patch");
4531
+ const validationError = await rejectInvalidWorkspaceEdit(
4532
+ path,
4533
+ before.content,
4534
+ "apply_patch",
4535
+ partial
4536
+ );
4309
4537
  if (validationError) {
4310
4538
  return {
4311
4539
  content: [{ type: "text", text: validationError }],
@@ -4316,7 +4544,7 @@ server.tool(
4316
4544
  content: [
4317
4545
  {
4318
4546
  type: "text",
4319
- text: `Applied patch to ${path} (+${result.addedLines} \u2212${result.removedLines}).${await htmlRuntimeCheckSuffix(path)}`
4547
+ text: `Applied patch to ${path} (+${result.addedLines} \u2212${result.removedLines}).${await editResultSuffix(path, partial)}`
4320
4548
  }
4321
4549
  ],
4322
4550
  structuredContent: {
@@ -4341,9 +4569,10 @@ server.tool(
4341
4569
  path: z5.string().describe("File path relative to the project root."),
4342
4570
  marker: z5.string().min(1).describe("Literal substring that must appear exactly once in the file."),
4343
4571
  content: z5.string().describe("Content to insert before or after the marker."),
4344
- where: z5.enum(["before", "after"]).optional().describe("Where to land the content relative to the marker. Defaults to 'after'.")
4572
+ where: z5.enum(["before", "after"]).optional().describe("Where to land the content relative to the marker. Defaults to 'after'."),
4573
+ partial: PartialEditArg
4345
4574
  },
4346
- async ({ path, marker, content, where }) => {
4575
+ async ({ path, marker, content, where, partial }) => {
4347
4576
  try {
4348
4577
  const before = await api.readProjectWorkspaceFile(projectId, path);
4349
4578
  const result = await api.insertAtMarkerInProjectWorkspaceFile(projectId, {
@@ -4357,7 +4586,8 @@ server.tool(
4357
4586
  const validationError = await rejectInvalidWorkspaceEdit(
4358
4587
  path,
4359
4588
  before.content,
4360
- "insert_at_marker"
4589
+ "insert_at_marker",
4590
+ partial
4361
4591
  );
4362
4592
  if (validationError) {
4363
4593
  return {
@@ -4369,7 +4599,7 @@ server.tool(
4369
4599
  content: [
4370
4600
  {
4371
4601
  type: "text",
4372
- text: `Inserted ${content.length} chars ${where ?? "after"} marker in ${path} (+${result.addedLines} \u2212${result.removedLines}).${await htmlRuntimeCheckSuffix(path)}`
4602
+ text: `Inserted ${content.length} chars ${where ?? "after"} marker in ${path} (+${result.addedLines} \u2212${result.removedLines}).${await editResultSuffix(path, partial)}`
4373
4603
  }
4374
4604
  ],
4375
4605
  structuredContent: {
@@ -4464,7 +4694,7 @@ server.tool(
4464
4694
  z5.object({
4465
4695
  package: NpmPackageNameSchema.describe('Package name (e.g. "zod", "@types/node").'),
4466
4696
  version: NpmRegistryVersionSchema.optional().describe(
4467
- 'Semver range or exact version (e.g. "^3", "3.22.4"). Defaults to "latest".'
4697
+ 'Semver range or exact version (e.g. "^3", "3.22.4"). A known pre-vetted package defaults to its vetted range; other packages default to "latest".'
4468
4698
  )
4469
4699
  })
4470
4700
  ).min(1).describe(
@@ -4779,7 +5009,38 @@ function explainWriteFailure(err) {
4779
5009
  }
4780
5010
  return detailsMessage ? message : `Write failed: ${message}`;
4781
5011
  }
4782
- async function rejectInvalidWorkspaceEdit(path, priorContent, toolName) {
5012
+ async function editResultSuffix(path, partial) {
5013
+ if (!partial) return htmlRuntimeCheckSuffix(path);
5014
+ const draft = partialEdits.get(path);
5015
+ return draft ? partialEdits.noticeFor(draft) : "";
5016
+ }
5017
+ async function restoreWorkspaceFile(path, content) {
5018
+ try {
5019
+ await api.writeProjectWorkspaceFile(projectId, {
5020
+ path,
5021
+ content,
5022
+ ...gezelId ? { gezelId } : {},
5023
+ ...sessionId ? { sessionId } : {}
5024
+ });
5025
+ return "The previous file content was restored.";
5026
+ } catch (err) {
5027
+ return `Automatic restore failed: ${unwrapApiError(err)}. Re-read the file before continuing.`;
5028
+ }
5029
+ }
5030
+ async function rejectInvalidWorkspaceEdit(path, priorContent, toolName, partial = false) {
5031
+ if (partial) {
5032
+ const draft2 = partialEdits.record(path, priorContent);
5033
+ if (draft2.edits > CAP) {
5034
+ partialEdits.close(path);
5035
+ const restoreMessage2 = await restoreWorkspaceFile(path, draft2.snapshot);
5036
+ return [
5037
+ `${toolName} ended the provisional edit sequence on \`${path}\`: it exceeded ${CAP} edits without the file ever parsing again.`,
5038
+ restoreMessage2,
5039
+ "Stop editing in pieces. Call `write_file` once with the complete, correct file."
5040
+ ].join(" ");
5041
+ }
5042
+ return null;
5043
+ }
4783
5044
  let after;
4784
5045
  try {
4785
5046
  after = await api.readProjectWorkspaceFile(projectId, path);
@@ -4789,18 +5050,12 @@ async function rejectInvalidWorkspaceEdit(path, priorContent, toolName) {
4789
5050
  const syntax = validateSourceContent(path, after.content);
4790
5051
  const sourceValidationMessage = syntax && !syntax.ok ? syntax.message : null;
4791
5052
  const htmlQualityRejection = sourceValidationMessage ? null : rejectHtmlWithScriptOutsideScriptTag(path, after.content);
4792
- if (!sourceValidationMessage && !htmlQualityRejection) return null;
4793
- let restoreMessage = "The previous file content was restored.";
4794
- try {
4795
- await api.writeProjectWorkspaceFile(projectId, {
4796
- path,
4797
- content: priorContent,
4798
- ...gezelId ? { gezelId } : {},
4799
- ...sessionId ? { sessionId } : {}
4800
- });
4801
- } catch (err) {
4802
- restoreMessage = `Automatic restore failed: ${unwrapApiError(err)}. Re-read the file before continuing.`;
5053
+ if (!sourceValidationMessage && !htmlQualityRejection) {
5054
+ partialEdits.close(path);
5055
+ return null;
4803
5056
  }
5057
+ const draft = partialEdits.get(path);
5058
+ const restoreMessage = draft ? `\`${path}\` is still an open provisional edit sequence (${draft.edits} edit(s)); the file was left as-is so you can repair it rather than starting over.` : await restoreWorkspaceFile(path, priorContent);
4804
5059
  if (htmlQualityRejection) {
4805
5060
  return [
4806
5061
  `${toolName} was rejected because the resulting \`${path}\` failed HTML quality validation: ${htmlQualityRejection}`,
@@ -4812,8 +5067,15 @@ async function rejectInvalidWorkspaceEdit(path, priorContent, toolName) {
4812
5067
  `${toolName} was rejected because the resulting \`${path}\` failed source validation: ${sourceValidationMessage}`,
4813
5068
  restoreMessage,
4814
5069
  "Use `write_file` to re-emit one clean complete file, or re-read the file and make a smaller edit that leaves the whole file parseable.",
4815
- "Do not append or insert duplicate top-level declarations, classes, or functions while repairing parse errors."
4816
- ].join(" ");
5070
+ "Do not append or insert duplicate top-level declarations, classes, or functions while repairing parse errors.",
5071
+ // Discovery point for the opt-out. The flag is nearly useless if a
5072
+ // model only meets it in a schema it reads once: the moment it
5073
+ // matters is the moment an intentional mid-build edit gets refused.
5074
+ // Worded conditionally on purpose — this gate usually means a
5075
+ // mistake, not a build in progress, and `partial` must not read as
5076
+ // "retry to make the error go away".
5077
+ draft ? "" : "If you are deliberately building this file across several edits and it is NOT meant to parse yet, pass `partial: true` on the intermediate edits \u2014 but only if you will finish it, because nothing that declares work done runs until the file parses."
5078
+ ].filter(Boolean).join(" ");
4817
5079
  }
4818
5080
  function extractApiErrorMessage(err) {
4819
5081
  if (!err || typeof err !== "object") return void 0;
@@ -5038,10 +5300,10 @@ async function listWorkspaceDeliverableFiles(projectId2) {
5038
5300
  }
5039
5301
  server.tool(
5040
5302
  "list_artifacts",
5041
- 'List every file in the project artifacts folder, recursively across all subdirectories. Use this when handing work off between gezels \u2014 anything a teammate produced will show up here regardless of how deeply they nested it. Pass `recursive: false` for a one-level listing of a specific subdirectory. Paths are scoped to the artifacts root \u2014 do NOT prefix with "artifacts/".',
5303
+ 'List files in the project artifacts folder, recursively across all subdirectories. Use this when handing work off between gezels \u2014 anything a teammate produced will show up here regardless of how deeply they nested it. Pass `path` to walk one subtree only (large drawers are capped, so scoping is how you see every file in a corpus); pass `recursive: false` for a one-level listing. Returned paths are relative to the artifacts root and can be read as-is \u2014 do NOT prefix with "artifacts/".',
5042
5304
  {
5043
5305
  path: z5.string().optional().describe(
5044
- 'Subdirectory path within the artifacts root (default: root). Do not include "artifacts/" \u2014 the call is already scoped there.'
5306
+ 'Subdirectory to walk (default: the whole artifacts root). Scopes recursive listings too. Do not include "artifacts/" \u2014 the call is already scoped there.'
5045
5307
  ),
5046
5308
  recursive: z5.boolean().optional().describe(
5047
5309
  "Walk all subdirectories (default: true). Set to false for a single-level listing."
@@ -5050,10 +5312,11 @@ server.tool(
5050
5312
  async ({ path, recursive }) => {
5051
5313
  const subpath = normalizeArtifactPath(path ?? "");
5052
5314
  const wantRecursive = recursive !== false;
5053
- const res = wantRecursive ? await api.listProjectArtifacts(projectId, void 0, true) : await api.listProjectArtifacts(projectId, subpath, false);
5315
+ const res = await api.listProjectArtifacts(projectId, subpath || void 0, wantRecursive);
5054
5316
  const listing = res.files.map((f) => `${f.isDirectory ? "\u{1F4C1}" : "\u{1F4C4}"} ${f.path}`).join("\n");
5055
- const summary = res.files.length ? `Listed ${res.files.length} ${res.files.length === 1 ? "artifact entry" : "artifact entries"}.` : "No artifacts yet.";
5056
- const truncation = res.truncated ? "\nResults were truncated; narrow `path` or use `recursive: false`." : "";
5317
+ const summary = res.files.length ? `Listed ${res.files.length} ${res.files.length === 1 ? "artifact entry" : "artifact entries"}${subpath ? ` under ${subpath}/` : ""}.` : subpath ? `No artifacts under ${subpath}/.` : "No artifacts yet.";
5318
+ const truncation = res.truncated ? `
5319
+ Results were truncated; ${subpath ? "narrow `path` further" : "pass `path` to scope the walk"} or use \`recursive: false\`.` : "";
5057
5320
  return okResult(
5058
5321
  ListToolOutputSchema,
5059
5322
  {
@@ -5554,14 +5817,14 @@ ${listing}` : summary }
5554
5817
  );
5555
5818
  server.tool(
5556
5819
  "list_documents",
5557
- "List files in the shared documents library. This library holds cross-cutting guides like mission statements, coding guidelines, and style guides that apply across all projects.",
5820
+ "List files in the shared documents library \u2014 cross-project guides every gezel can read (guidelines, mission statements, style guides, policies). Pass { recursive: true } to see inside folders. To find content rather than names, use search_documents.",
5558
5821
  {
5559
5822
  path: z5.string().optional().describe("Subdirectory path to list (default: root)"),
5560
5823
  recursive: z5.boolean().optional().describe("List all descendants (default: false)")
5561
5824
  },
5562
5825
  async ({ path, recursive }) => {
5563
5826
  const res = await api.listDocuments(path ?? "", recursive ?? false);
5564
- const listing = res.files.map((f) => `${f.isDirectory ? "\u{1F4C1}" : "\u{1F4C4}"} ${f.path}`).join("\n");
5827
+ const listing = res.files.map((f) => `${f.isDirectory ? "dir " : "file"} ${f.path}`).join("\n");
5565
5828
  const summary = res.files.length ? `Listed ${res.files.length} ${res.files.length === 1 ? "document entry" : "document entries"}.` : "No documents found.";
5566
5829
  return okResult(
5567
5830
  ListToolOutputSchema,
@@ -5573,18 +5836,18 @@ ${listing}` : summary }
5573
5836
  );
5574
5837
  server.tool(
5575
5838
  "read_document",
5576
- "Read a document from the shared documents library. Use this to consult mission statements, coding guidelines, style guides, etc.",
5839
+ "Read one document from the shared library by path. Office documents (.docx, .pdf, .pptx, .xlsx) come back converted to markdown. Get paths from the library listing, list_documents, or a search_documents match.",
5577
5840
  {
5578
5841
  path: z5.string().describe('File path relative to the documents root (e.g. "guidelines/coding.md")')
5579
5842
  },
5580
5843
  async ({ path }) => {
5581
- const res = await api.readDocument(path);
5844
+ const res = await api.readDocument(path, { as: "markdown" });
5582
5845
  return { content: [{ type: "text", text: res.content }] };
5583
5846
  }
5584
5847
  );
5585
5848
  server.tool(
5586
5849
  "write_document",
5587
- "Create or update a document in the shared documents library. Use this to capture durable, cross-project knowledge like guidelines or policies.",
5850
+ 'Create or update a document in the shared documents library (markdown preferred). Use for durable cross-project knowledge \u2014 guidelines, policies, style rules. For knowledge specific to one project, use a folder named after that project (e.g. "acme-site/decisions.md"). Deliverables for the current job belong in the workspace or artifacts, not here.',
5588
5851
  {
5589
5852
  path: z5.string().describe('File path relative to the documents root (e.g. "guidelines/coding.md")'),
5590
5853
  content: z5.string().describe("File content to write (markdown recommended)")
@@ -5596,24 +5859,24 @@ server.tool(
5596
5859
  "write_document"
5597
5860
  );
5598
5861
  if (redirected) return redirected;
5599
- await api.writeDocument(path, normalizeMarkdown(content));
5862
+ await api.writeDocument(path, normalizeMarkdown(content), { gezelId });
5600
5863
  return { content: [{ type: "text", text: `Wrote document ${path}` }] };
5601
5864
  }
5602
5865
  );
5603
5866
  server.tool(
5604
5867
  "delete_document",
5605
- "Delete a document or folder from the shared documents library.",
5868
+ "Delete a document \u2014 or a folder and its entire contents \u2014 from the shared documents library. Folder deletes are recursive and cannot be undone; prefer exact file paths.",
5606
5869
  {
5607
5870
  path: z5.string().describe("File or folder path to delete")
5608
5871
  },
5609
5872
  async ({ path }) => {
5610
- await api.deleteDocument(path);
5873
+ await api.deleteDocument(path, { gezelId });
5611
5874
  return { content: [{ type: "text", text: `Deleted ${path}` }] };
5612
5875
  }
5613
5876
  );
5614
5877
  server.tool(
5615
5878
  "search_documents",
5616
- "Keyword-search the CONTENT of the shared documents library (not just names). Returns path + line + snippet; follow up with read_document to read a match.",
5879
+ "Search the CONTENT of every document in the shared library, including converted office documents. Returns path + line + snippet; call this first for any question the library might answer \u2014 team policy, guidelines, conventions \u2014 then read_document the best match.",
5617
5880
  {
5618
5881
  q: z5.string().min(1).describe("Full-text query against document content"),
5619
5882
  limit: z5.number().optional().describe("Max results (default 10)")
@@ -8962,6 +9225,8 @@ server.tool(
8962
9225
  evidence: z5.string().optional().describe("Artifact path or note proving it \u2014 required when met is true.")
8963
9226
  },
8964
9227
  async ({ ref, id, met, evidence }) => {
9228
+ const draftBlock = partialEdits.blockReason("verify_outcome");
9229
+ if (draftBlock) return errorResult(draftBlock);
8965
9230
  const parsed = parseRef(ref);
8966
9231
  const t = await api.getTask(parsed.projectId, parsed.num);
8967
9232
  const existing = t.outcomes ?? [];
@@ -9357,6 +9622,8 @@ server.tool(
9357
9622
  )
9358
9623
  },
9359
9624
  async ({ ref, stepId, next }) => {
9625
+ const draftBlock = partialEdits.blockReason("advance_task_step");
9626
+ if (draftBlock) return errorResult(draftBlock);
9360
9627
  const parsed = parseRef(ref);
9361
9628
  const { task, gate } = await api.completeTaskStep(
9362
9629
  parsed.projectId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/gezel-mcp",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "Gezel MCP server — gives agents access to memory, workspace, artifacts, and tools.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -55,8 +55,8 @@
55
55
  "!dist/**/*.map"
56
56
  ],
57
57
  "dependencies": {
58
- "@bendyline/gezel": "1.0.4",
59
- "@bendyline/gezel-client": "1.0.4",
58
+ "@bendyline/gezel": "1.0.6",
59
+ "@bendyline/gezel-client": "1.0.6",
60
60
  "@modelcontextprotocol/sdk": "^1.29.0",
61
61
  "typescript": "^6.0.3",
62
62
  "zod": "^4.4.3"