-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdraft-cli.mjs
More file actions
executable file
·3343 lines (3175 loc) · 132 KB
/
draft-cli.mjs
File metadata and controls
executable file
·3343 lines (3175 loc) · 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// draft-cli — fill placeholders in legal-document templates.
// Part of the contract-ops suite. MIT. See LICENSE.
// Single-file Node.js CLI. Stdlib-only except `jszip` for .docx unzip.
import { readFileSync, writeFileSync, existsSync, statSync, realpathSync } from "node:fs";
import { resolve, dirname, basename, extname, join } from "node:path";
import { spawnSync } from "node:child_process";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
/**
* @typedef {"bracket"|"mustache"|"docx-highlight"|"heuristic"|"llm"|"none"} Tier
*
* @typedef {Object} DetectionHit
* A single raw detection from one of the cascade tiers.
* @property {string} match — the full matched span (e.g. "[Party A]").
* @property {string} inner — the text inside the delimiters (e.g. "Party A").
* @property {number} [index] — byte offset into the body, if known.
* @property {string} [suggested_key] — only on T5/LLM hits.
* @property {string} [color] — only on T3/docx-highlight hits.
*
* @typedef {Object} Placeholder
* An assembled placeholder — one canonical key, all its hits, schema metadata.
* @property {string} key — canonical snake_case identifier.
* @property {string} first_seen_as — the inner text of the first hit.
* @property {number} occurrences — number of hits for this key.
* @property {Tier} tier — which cascade tier produced this.
* @property {boolean} required — whether the user MUST supply a value.
* @property {string|null} default — schema-supplied fallback, or null.
* @property {string[]} aliases — phrase forms that map to this key.
* @property {DetectionHit[]} hits — every detection for this key.
*
* @typedef {Object} SchemaEntry
* @property {string[]} aliases — phrase forms accepted for this key.
* @property {boolean} required
* @property {string|null} default
*
* @typedef {Object} Schema
* @property {"short"|"long"} form
* @property {Object<string, SchemaEntry>} entries
* @property {string} [sourcePath] — file the schema was loaded from, if any.
*
* @typedef {Object} ParsedArgs
* Result of parseArgs(argv). See parseArgs() for shape.
*
* @typedef {Object} CascadeResult
* @property {Tier} tier
* @property {Placeholder[]} placeholders
* @property {string[]} warnings
* @property {Array<{phrase: string, tier: Tier}>} unmapped
* @property {boolean} [heuristicGate] — true iff tier='heuristic' and
* substitution requires explicit confirmation.
*
* @typedef {Object} ResolvedValues
* @property {Object<string, string>} resolved — key -> value.
* @property {Placeholder[]} missing — unresolved required placeholders.
* @property {Object<string, "cli"|"params"|"interactive"|"default">} sources
*
* @typedef {Object} Input
* @property {"text"|"docx"} kind
* @property {string} body — the template text (extracted for docx).
* @property {string|null} path — filesystem path, or null for stdin/vault.
* @property {string} [docxXml] — raw word/document.xml for docx inputs.
*
* @typedef {Object} LlmProvider
* @property {string} provider — "anthropic" | "openai" | custom.
* @property {string} apiKey
* @property {string|null} model
*/
/** @type {string} */
export const VERSION = "0.10.0";
// ─── EXIT CODES ─────────────────────────────────────────────────────────────
/**
* Stable exit codes. Documented in AGENTS.md and never re-numbered without
* a major-version bump.
* @type {Readonly<{OK: 0, IO: 1, VALIDATION: 2, VAULT: 3, LLM: 4}>}
*/
export const EXIT = Object.freeze({ OK: 0, IO: 1, VALIDATION: 2, VAULT: 3, LLM: 4 });
// ─── COLOR (honors NO_COLOR / FORCE_COLOR) ──────────────────────────────────
const ANSI = {
reset: "\x1b[0m", red: "\x1b[31m", green: "\x1b[32m",
yellow: "\x1b[33m", cyan: "\x1b[36m", dim: "\x1b[2m", bold: "\x1b[1m",
};
/**
* Whether ANSI color should be emitted to `stream`. Honors the no-color.org
* convention: `NO_COLOR` (any value) → off, `FORCE_COLOR` (any value) → on,
* otherwise on iff `stream.isTTY`.
*
* @param {{isTTY?: boolean} | null | undefined} stream
* @returns {boolean}
*/
export function colorEnabled(stream) {
if (process.env.NO_COLOR) return false;
if (process.env.FORCE_COLOR) return true;
return Boolean(stream && stream.isTTY);
}
/**
* Wrap `s` with an ANSI color code if {@link colorEnabled} for `stream`.
*
* @param {string} s
* @param {"red"|"green"|"yellow"|"cyan"|"dim"|"bold"} color
* @param {{isTTY?: boolean} | null | undefined} stream
* @returns {string}
*/
export function paint(s, color, stream) {
return colorEnabled(stream) ? `${ANSI[color] || ""}${s}${ANSI.reset}` : String(s);
}
// ─── BUNDLED HEURISTIC DICTIONARY ───────────────────────────────────────────
export const DEFAULT_HEURISTIC_DICT = [
"John Doe", "Jane Doe", "Jane Roe", "John Smith", "John Q. Public",
"Acme Corporation", "Acme Corp.", "Acme Corp", "Acme Inc.", "Acme Inc",
"Acme Co.", "Acme Co", "Acme LLC", "Acme, Inc.",
"Foo Corp", "Foo Corp.", "Foo Inc.", "Foo Inc", "Foo LLC",
"FooBar LLC", "FooBar, Inc.",
"Example Inc.", "Example Inc", "Example Corporation", "Example Corp",
"Sample Company", "Sample Corp", "Sample Inc.",
"Newco", "Newco Inc.", "Newco Inc",
"123 Main Street", "123 Main St.", "123 Main St",
"1 First Avenue", "1 First Ave", "1 First Ave.",
"Anytown, USA", "Anytown, US",
"example@example.com", "user@example.com", "john@example.com",
"jane@example.com", "test@test.com",
"555-555-5555", "(555) 555-5555", "+1-555-555-5555",
"555-5555", "555-1234",
"January 1, 20XX", "MM/DD/YYYY", "DD/MM/YYYY",
"YYYY-MM-DD", "20XX-XX-XX",
"TBD", "TBC", "TBA",
];
// ─── .env READER (tiny inline parser) ───────────────────────────────────────
/**
* Read a `.env` file. Tiny inline parser — handles `KEY=VALUE`, comments,
* blanks, and matched single/double quotes around values. Returns `{}` if
* the file doesn't exist.
*
* @param {string} path — usually `join(cwd, ".env")`.
* @returns {Object<string, string>}
*/
export function readDotenv(path) {
if (!existsSync(path)) return {};
const out = {};
for (const raw of readFileSync(path, "utf8").split(/\r?\n/)) {
const line = raw.trim();
if (!line || line.startsWith("#")) continue;
const eq = line.indexOf("=");
if (eq <= 0) continue;
const key = line.slice(0, eq).trim();
let val = line.slice(eq + 1).trim();
if ((val.startsWith('"') && val.endsWith('"')) ||
(val.startsWith("'") && val.endsWith("'"))) {
val = val.slice(1, -1);
}
out[key] = val;
}
return out;
}
/**
* Merge `.env` file contents with the process environment. Process env
* always wins where both define a key.
*
* @param {string} [cwd]
* @param {Object<string, string>} [processEnv]
* @returns {Object<string, string>}
*/
export function effectiveEnv(cwd = process.cwd(), processEnv = process.env) {
const fileEnv = readDotenv(join(cwd, ".env"));
return { ...fileEnv, ...processEnv };
}
/**
* Pick an LLM provider configuration from a merged env object. Order:
* explicit `DRAFT_LLM_*` triple > `ANTHROPIC_API_KEY` > `OPENAI_API_KEY`.
*
* @param {Object<string, string>} envObj
* @returns {LlmProvider | null} null if no provider is configured.
*/
export function llmProviderFromEnv(envObj) {
if (envObj.DRAFT_LLM_PROVIDER && envObj.DRAFT_LLM_API_KEY) {
return {
provider: envObj.DRAFT_LLM_PROVIDER,
apiKey: envObj.DRAFT_LLM_API_KEY,
model: envObj.DRAFT_LLM_MODEL || null,
};
}
if (envObj.ANTHROPIC_API_KEY) {
return {
provider: "anthropic",
apiKey: envObj.ANTHROPIC_API_KEY,
model: envObj.DRAFT_LLM_MODEL || "claude-sonnet-4-6",
};
}
if (envObj.OPENAI_API_KEY) {
return {
provider: "openai",
apiKey: envObj.OPENAI_API_KEY,
model: envObj.DRAFT_LLM_MODEL || "gpt-4o-mini",
};
}
return null;
}
/**
* Read the suite-shared LLM config and return a provider in the same shape as
* {@link llmProviderFromEnv}, or null. Lookup order:
* ~/.config/contract-ops/llm.json (suite-wide, preferred)
* ~/.config/draft-cli/llm.json (legacy per-CLI fallback)
* Schema: { provider, model, api_key }. base_url is not yet honored by the
* provider path, matching the env-based config.
*
* @param {string|undefined} home — base home dir (usually `envObj.HOME`)
* @returns {LlmProvider | null}
*/
export function llmProviderFromConfigFile(home) {
if (!home) return null;
for (const path of [
join(home, ".config", "contract-ops", "llm.json"),
join(home, ".config", "draft-cli", "llm.json"),
]) {
if (!existsSync(path)) continue;
let j;
try { j = JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
const apiKey = j.api_key || j.apiKey;
if (!apiKey) return null;
const provider = String(j.provider || "anthropic").toLowerCase();
return {
provider,
apiKey,
model: j.model || (provider === "anthropic" ? "claude-sonnet-4-6" : "gpt-4o-mini"),
};
}
return null;
}
/**
* Resolve an LLM provider: environment first (a shell-exported key always
* wins), then the suite-shared config file. Command handlers use this so that
* configuring `~/.config/contract-ops/llm.json` once works across the suite.
*
* @param {Object<string, string>} envObj — usually from {@link effectiveEnv}
* @param {string} [home] — defaults to `envObj.HOME`
* @returns {LlmProvider | null}
*/
export function resolveLlmProvider(envObj, home = envObj && envObj.HOME) {
return llmProviderFromEnv(envObj) ?? llmProviderFromConfigFile(home);
}
// ─── ARG PARSING ────────────────────────────────────────────────────────────
// Two-phase: known flags first, unknown --x VALUE pairs collected for later
// param resolution. Boolean flags listed in KNOWN_BOOLEAN; value flags in
// KNOWN_VALUE. Everything else --x is treated as a param flag.
const KNOWN_BOOLEAN = new Set([
"--help", "-h", "--version", "-V", "--demo",
"--validate", "--list-placeholders",
"--why", "--json", "--interactive", "-i",
"--no-heuristic", "--yes-heuristic",
"--no-llm", "--llm", "--check-llm",
"--silent", "-q",
"--diff",
"--strict-runs",
]);
const KNOWN_VALUE = new Set([
"--params", "--output", "-o", "--syntax", "--dictionary", "--completion", "--catalog", "--from-deal", "--bundle",
]);
/**
* Parse argv into a structured options object. Two-phase: known flags are
* recognized explicitly; everything else of the form `--xxx VALUE` is
* collected into `paramFlags` (canonical_key → value).
*
* @param {string[]} argv — typically `process.argv.slice(2)`.
* @returns {ParsedArgs}
* @throws {UsageError} on invalid `--syntax`, `--completion`, missing values.
*/
export function parseArgs(argv) {
const opts = {
positional: [],
params: null,
output: null,
syntax: "bracket",
dictionary: null,
interactive: false,
validate: false,
listPlaceholders: false,
why: false,
json: false,
demo: false,
completion: null,
silent: false,
checkLlm: false,
diff: false,
noHeuristic: false,
yesHeuristic: false,
noLlm: false,
forceLlm: false,
strictRuns: false,
help: false,
version: false,
paramFlags: {}, // canonical_key -> value (set from --kebab-name VALUE)
};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--help" || a === "-h") { opts.help = true; continue; }
if (a === "--version" || a === "-V") { opts.version = true; continue; }
if (a === "--demo") { opts.demo = true; continue; }
if (a === "--validate") { opts.validate = true; continue; }
if (a === "--list-placeholders") { opts.listPlaceholders = true; continue; }
if (a === "--catalog") { opts.catalog = argv[++i] || "json"; continue; }
if (a.startsWith("--catalog=")) { opts.catalog = a.slice("--catalog=".length); continue; }
if (a === "--why") { opts.why = true; continue; }
if (a === "--json") { opts.json = true; continue; }
if (a === "--interactive" || a === "-i") { opts.interactive = true; continue; }
if (a === "--no-heuristic") { opts.noHeuristic = true; continue; }
if (a === "--yes-heuristic") { opts.yesHeuristic = true; continue; }
if (a === "--no-llm") { opts.noLlm = true; continue; }
if (a === "--llm") { opts.forceLlm = true; continue; }
if (a === "--check-llm") { opts.checkLlm = true; continue; }
if (a === "--silent" || a === "-q") { opts.silent = true; continue; }
if (a === "--diff") { opts.diff = true; continue; }
if (a === "--strict-runs") { opts.strictRuns = true; continue; }
if (a === "--params") { opts.params = argv[++i]; continue; }
if (a === "--parties") { opts.parties = argv[++i]; continue; }
if (a === "--bundle") { opts.bundle = argv[++i]; continue; }
if (a === "--from-deal") { opts.fromDeal = argv[++i]; continue; }
if (a === "--output" || a === "-o") { opts.output = argv[++i]; continue; }
if (a === "--syntax") {
const v = argv[++i];
if (v !== "bracket" && v !== "mustache") {
throw new UsageError(`--syntax must be 'bracket' or 'mustache' (got '${v}')`);
}
opts.syntax = v;
continue;
}
if (a === "--dictionary") { opts.dictionary = argv[++i]; continue; }
if (a === "--completion") {
const v = argv[++i];
if (v !== "bash" && v !== "zsh") {
throw new UsageError(`--completion must be 'bash' or 'zsh' (got '${v}')`);
}
opts.completion = v;
continue;
}
if (a.startsWith("--")) {
// Unknown --x — treat as param flag with the next token as value.
const key = kebabToSnake(a.slice(2));
if (i + 1 >= argv.length || argv[i + 1].startsWith("-")) {
throw new UsageError(`flag ${a} requires a value`);
}
opts.paramFlags[key] = argv[++i];
continue;
}
opts.positional.push(a);
}
return opts;
}
export class UsageError extends Error {
constructor(msg) { super(msg); this.name = "UsageError"; }
}
// ─── KEY DERIVATION ─────────────────────────────────────────────────────────
/** @param {string} s @returns {string} kebab-case → snake_case. */
export function kebabToSnake(s) { return s.replace(/-/g, "_"); }
/**
* Derive a canonical snake_case key from arbitrary placeholder text.
* Permissive: non-alphanumerics collapse to `_`, leading-digit inputs get
* an `_` prefix, length capped at 60. Always produces a valid snake_case
* key for any non-empty input that contains at least one alphanumeric.
*
* @param {string} matchText — e.g. "Party A Name", "Today's date", "1 year(s)".
* @returns {string} e.g. "party_a_name", "today_s_date", "_1_year_s".
*/
export function canonicalKey(matchText) {
// Permissive slug: lowercase, non-alphanum runs become single "_",
// strip leading/trailing "_", prefix "_" if leading char is a digit.
let k = matchText.trim().toLowerCase()
.replace(/[^a-z0-9]+/g, "_")
.replace(/^_+|_+$/g, "");
if (/^[0-9]/.test(k)) k = "_" + k;
// Cap at 60 chars to keep CLI flags usable.
if (k.length > 60) k = k.slice(0, 60).replace(/_+$/, "");
return k;
}
const VALID_KEY_RE = /^[a-z_][a-z0-9_]*$/;
/** @param {string} key @returns {boolean} */
export function validKey(key) { return VALID_KEY_RE.test(key); }
// ─── HELP ───────────────────────────────────────────────────────────────────
export const HELP_TEXT = `\
draft — fill placeholders in a legal-document template.
USAGE
draft <template> [--params FILE] [--<PARAM> VALUE]... [options]
draft <category>/<name> (pulls via \`template-vault get\`)
draft - (template body on stdin)
draft --list-placeholders <template> [--json]
draft --validate <template> --params FILE
draft --demo (bundled demo, no file needed)
draft --completion bash (emit shell completion script)
DETECTION CASCADE (sequential-with-stop; first non-empty tier wins)
1. bracket [Title Case] deterministic, default on
2. mustache {{Title Case}} opt-in via --syntax mustache
3. docx-highlight yellow / green / cyan auto when input is .docx
4. heuristic generic-name dictionary --no-heuristic to skip;
warn-only without --yes-heuristic
5. llm last resort runs only if .env or process env
configures a provider; --no-llm
disables; --llm forces
OPTIONS
--params FILE JSON file of param values (snake_case keys).
-o, --output PATH Write result to PATH (default: stdout).
--syntax KIND 'bracket' (default) or 'mustache'.
-i, --interactive Prompt for any missing required parameters.
--validate Validate completeness; never writes output.
--list-placeholders Enumerate placeholders and exit.
--why Print a structured explanation to stderr.
--json Emit JSON to stdout (suppresses human messages).
-q, --silent Suppress all stderr output (warnings, --why, notes).
--no-heuristic Disable tier 4.
--yes-heuristic Substitute tier-4 matches without confirmation.
--no-llm Disable tier 5 even when env is configured.
--llm Assert env-configured LLM; fail-fast if not.
--check-llm One-token roundtrip to the configured provider.
--diff Show substitution table without writing output.
--strict-runs .docx only: skip placeholders that span multiple
runs (v0.2.0 behavior). Default is to merge runs
and emit a note for each merge.
--dictionary PATH Override the bundled heuristic dictionary.
--completion bash|zsh Emit a shell completion script to stdout.
--<param-name> VALUE Set a parameter directly. Kebab -> snake_case.
-h, --help Show this help.
-V, --version Show version.
--catalog json Machine-readable command + flag inventory (for agents).
EXIT CODES
0 ok 1 i/o error 2 validation 3 template-vault failure 4 llm failure
Part of the contract-ops suite. See cli.drbaher.com.
`;
/**
* Machine-readable command + flag inventory, emitted by `draft --catalog json`.
* Mirrors the suite-wide discovery contract (nda-review-cli / docx2pdf-cli /
* sign-cli / template-vault-cli all answer `--catalog json`). draft has no
* subcommands, so this is a flag inventory.
*/
export function getCatalog() {
return {
name: "draft-cli",
bin: "draft",
version: VERSION,
description: "Agent-first placeholder-filler for legal-document templates.",
usage: [
"draft <template> [--params FILE] [--<param> VALUE]... [options]",
"draft <category>/<name> (pulls via `template-vault get`)",
"draft - (template body on stdin)",
"draft <template> --list-placeholders --json",
"draft <template> --params FILE --validate",
],
flags: [
{ name: "--params", arg: "FILE", help: "JSON file of param values (snake_case keys)." },
{ name: "--output", aliases: ["-o"], arg: "PATH", help: "Write result to PATH (default: stdout)." },
{ name: "--syntax", arg: "KIND", choices: ["bracket", "mustache"], default: "bracket", help: "Placeholder syntax family." },
{ name: "--from-deal", arg: "PATH", help: "Infer param values from free-form prose via the LLM tier." },
{ name: "--bundle", arg: "PATH", help: "Fill multiple templates from one bundle definition (declares its own templates + shared params)." },
{ name: "--interactive", aliases: ["-i"], type: "boolean", help: "Prompt for any missing required parameters." },
{ name: "--validate", type: "boolean", help: "Validate completeness; never writes output." },
{ name: "--list-placeholders", type: "boolean", help: "Per-template manifest of placeholders; pairs with --json." },
{ name: "--diff", type: "boolean", help: "Show the substitution table without writing output." },
{ name: "--why", type: "boolean", help: "Print a structured explanation to stderr." },
{ name: "--json", type: "boolean", help: "Emit JSON to stdout (suppresses human messages)." },
{ name: "--silent", aliases: ["-q"], type: "boolean", help: "Suppress all stderr output." },
{ name: "--no-heuristic", type: "boolean", help: "Disable the tier-4 generic-name heuristic." },
{ name: "--yes-heuristic", type: "boolean", help: "Substitute tier-4 matches without confirmation." },
{ name: "--no-llm", type: "boolean", help: "Disable the tier-5 LLM even when configured." },
{ name: "--llm", type: "boolean", help: "Assert an env/config-configured LLM; fail fast if none." },
{ name: "--check-llm", type: "boolean", help: "One-token roundtrip to the configured provider." },
{ name: "--strict-runs", type: "boolean", help: ".docx: skip placeholders spanning multiple runs (default merges)." },
{ name: "--dictionary", arg: "PATH", help: "Override the bundled heuristic dictionary." },
{ name: "--completion", arg: "bash|zsh", help: "Emit a shell completion script." },
{ name: "--demo", type: "boolean", help: "Run the bundled zero-config demo." },
{ name: "--catalog", arg: "json", help: "Print this catalog and exit (agents call at startup)." },
{ name: "--help", aliases: ["-h"], type: "boolean", help: "Show usage and exit." },
{ name: "--version", aliases: ["-V"], type: "boolean", help: "Print version and exit." },
],
paramFlags: "Any unrecognized --<param-name> VALUE sets a template parameter directly (kebab → snake_case).",
discovery: {
catalog: "draft --catalog json",
placeholders: "draft <template> --list-placeholders --json",
validate: "draft <template> --params FILE --validate",
},
exitCodes: { "0": "ok", "1": "i/o error", "2": "validation", "3": "template-vault failure", "4": "llm failure" },
};
}
// ─── INPUT RESOLUTION ───────────────────────────────────────────────────────
// Returns { kind: "text"|"docx", body: string, docxXml?: string, path: string|null }
const VAULT_REF_RE = /^[a-z][a-z0-9-]*\/[a-z0-9-]+(?:@[A-Za-z0-9._-]+)?$/;
/**
* Resolve a positional template argument into a usable {@link Input}.
* Handles three forms: stdin (`-`), a `template-vault get` ref
* (`<category>/<name>[@version]`), or a filesystem path (text or `.docx`).
*
* @param {string} arg
* @param {{ spawner?: typeof spawnSync, stdinReader?: () => Promise<string> }} [opts]
* Injectable spawn / stdin reader for tests.
* @returns {Promise<Input>}
* @throws {Error} with `.exitCode` set to one of {@link EXIT}'s values on
* I/O failure (1), vault subprocess failure (3), or `.docx` parse failure (1).
*/
export async function resolveInput(arg, { spawner = spawnSync, stdinReader = readStdin } = {}) {
if (arg === "-") {
return { kind: "text", body: await stdinReader(), path: null };
}
if (VAULT_REF_RE.test(arg)) {
const r = spawner("template-vault", ["get", arg], { encoding: "utf8" });
if (r.error || r.status !== 0) {
const msg = (r.stderr || "").toString().trim() || (r.error && r.error.message) ||
`template-vault get ${arg} failed`;
const e = new Error(msg);
e.exitCode = EXIT.VAULT;
throw e;
}
return { kind: "text", body: (r.stdout || "").toString(), path: null };
}
if (!existsSync(arg)) {
const e = new Error(`template not found: ${arg}`);
e.exitCode = EXIT.IO;
throw e;
}
const ext = extname(arg).toLowerCase();
if (ext === ".docx") {
const { body, xml } = await extractDocxText(arg);
return { kind: "docx", body, docxXml: xml, path: arg };
}
return { kind: "text", body: readFileSync(arg, "utf8"), path: arg };
}
/**
* Read stdin to completion as a UTF-8 string.
* @returns {Promise<string>}
*/
export async function readStdin() {
return await new Promise((res, rej) => {
let s = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (d) => { s += d; });
process.stdin.on("end", () => res(s));
process.stdin.on("error", rej);
});
}
// ─── DOCX EXTRACTION (jszip + regex on word/document.xml) ───────────────────
async function loadJSZip() {
try { return (await import("jszip")).default; }
catch {
const e = new Error("the 'jszip' package is required for .docx input.\nrun: npm install -g jszip (or reinstall @drbaher/draft-cli)");
e.exitCode = EXIT.IO;
throw e;
}
}
/**
* Open a `.docx`, return its extracted plain-text body and the raw XML
* (the XML is needed for tier-3 highlight detection).
*
* @param {string} path
* @returns {Promise<{ body: string, xml: string }>}
* @throws {Error} with `.exitCode = EXIT.IO` on missing jszip, invalid
* `.docx`, or missing `word/document.xml`.
*/
export async function extractDocxText(path) {
const JSZip = await loadJSZip();
let zip;
try { zip = await JSZip.loadAsync(readFileSync(path)); }
catch (err) {
const e = new Error(`could not open .docx (${err.message})`);
e.exitCode = EXIT.IO;
throw e;
}
const docFile = zip.file("word/document.xml");
if (!docFile) {
const e = new Error("invalid .docx: missing word/document.xml");
e.exitCode = EXIT.IO;
throw e;
}
const xml = await docFile.async("string");
return { body: docxXmlToText(xml), xml };
}
/**
* Re-read the original `.docx`, swap in a new `word/document.xml`, and
* return the resulting `.docx` as a `Buffer`. All other parts of the
* package (`[Content_Types].xml`, relationships, images, headers, etc.)
* pass through unchanged.
*
* @param {string} originalPath — filesystem path to the source `.docx`.
* @param {string} newDocumentXml — replacement content for `word/document.xml`.
* @returns {Promise<Buffer>}
* @throws {Error} with `.exitCode = EXIT.IO` on missing jszip or invalid source.
*/
export async function writeDocxBuffer(originalPath, newDocumentXml) {
const JSZip = await loadJSZip();
let zip;
try { zip = await JSZip.loadAsync(readFileSync(originalPath)); }
catch (err) {
const e = new Error(`could not re-open source .docx (${err.message})`);
e.exitCode = EXIT.IO;
throw e;
}
zip.file("word/document.xml", newDocumentXml);
return await zip.generateAsync({ type: "nodebuffer" });
}
/**
* Derive the default `.docx` output filename from an input path. Appends
* `-filled` before the extension: `contract.docx` → `contract-filled.docx`.
* If the input has no extension, appends `-filled.docx`.
* @param {string} inputPath
* @returns {string}
*/
export function makeDocxOutputPath(inputPath) {
const ext = extname(inputPath);
if (!ext) return `${inputPath}-filled.docx`;
return `${inputPath.slice(0, -ext.length)}-filled${ext}`;
}
// Walk the XML in document order. For each <w:p> emit a line; concatenate
// <w:t> contents within. Decode XML entities. Used for both output body and
// T1/T2 detection on docx input.
/**
* Walk Word's document XML in paragraph order and produce plain text.
* One line per `<w:p>`; text-run contents concatenated within. XML entities
* are decoded via {@link decodeXml}.
*
* @param {string} xml
* @returns {string}
*/
export function docxXmlToText(xml) {
const paragraphs = xml.split(/<w:p[\s>]/i).slice(1);
const lines = [];
for (const p of paragraphs) {
const para = p.split(/<\/w:p>/i)[0];
const texts = [];
const re = /<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g;
let m;
while ((m = re.exec(para)) !== null) texts.push(decodeXml(m[1]));
lines.push(texts.join(""));
}
return lines.join("\n");
}
/**
* Decode the five XML entities that appear in Word's `<w:t>` runs.
* @param {string} s
* @returns {string}
*/
export function decodeXml(s) {
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
.replace(/"/g, '"').replace(/'/g, "'");
}
/**
* Inverse of {@link decodeXml}. Used when writing substituted text back into
* a Word document's `<w:t>` runs. Only encodes the three structural
* characters; double- and single-quotes don't need encoding inside element
* text content.
* @param {string} s
* @returns {string}
*/
export function encodeXml(s) {
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
const RECOGNIZED_HIGHLIGHTS = new Set(["yellow", "green", "cyan", "magenta"]);
// Scan the XML for highlighted runs. Returns an array of { text, color }.
/**
* Find every highlighted text run in a Word document's XML. Unlike
* {@link detectDocxHighlight}, does NOT dedupe — multiple occurrences of
* the same highlighted text appear multiple times.
*
* @param {string} xml
* @returns {Array<{ text: string, color: string }>}
*/
export function extractDocxHighlights(xml) {
const out = [];
const runRe = /<w:r\b[\s\S]*?<\/w:r>/g;
let m;
while ((m = runRe.exec(xml)) !== null) {
const run = m[0];
const hm = /<w:highlight\s+w:val="([^"]+)"/.exec(run);
if (!hm) continue;
const color = hm[1].toLowerCase();
if (!RECOGNIZED_HIGHLIGHTS.has(color)) continue;
const texts = [];
const tRe = /<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g;
let tm;
while ((tm = tRe.exec(run)) !== null) texts.push(decodeXml(tm[1]));
const text = texts.join("").trim();
if (text) out.push({ text, color });
}
return out;
}
// ─── TIER 1: BRACKET ────────────────────────────────────────────────────────
// Match [...] runs that are NOT immediately followed by '(' (markdown link).
const BRACKET_RE = /\[([^\[\]\n]{1,200})\](?!\()/g;
const SECTION_REF_RE = /^\d+(?:\.\d+)*$/;
const CHECKBOX_RE = /^[ xX]{1,3}$/;
/**
* The locked T1 admission rule. Rejects markdown links, checkbox markers,
* pure section refs, punctuation-only runs, and all-uppercase headings.
* Permissive otherwise — accepts sentence-shaped placeholders with full
* punctuation, as real legal templates use.
*
* @param {string} inner — bracket contents (no `[` `]`).
* @returns {boolean}
*/
export function isBracketPlaceholder(inner) {
if (!inner) return false;
if (CHECKBOX_RE.test(inner)) return false;
if (SECTION_REF_RE.test(inner)) return false;
// Must contain at least one letter so we don't catch [___] or [---].
if (!/[A-Za-z]/.test(inner)) return false;
// Reject all-caps headings ([CONFIDENTIALITY], [ARTICLE I]).
if (inner === inner.toUpperCase() && /[A-Z]/.test(inner)) return false;
return true;
}
/**
* Tier 1 detection: bracketed `[...]` placeholders.
*
* `schemaAliases` (optional) is a Set of phrase strings declared in the
* schema file; bracketed runs whose inner matches a schema alias are
* admitted even if the heuristic rule {@link isBracketPlaceholder} would
* reject them (lets a schema rescue `[COMPANY]`, `[_____________]`, etc.).
*
* @param {string} body
* @param {Set<string>} [schemaAliases]
* @returns {DetectionHit[]}
*/
export function detectBracket(body, schemaAliases = new Set()) {
const out = [];
let m;
BRACKET_RE.lastIndex = 0;
while ((m = BRACKET_RE.exec(body)) !== null) {
if (isBracketPlaceholder(m[1]) || schemaAliases.has(m[1])) {
out.push({ match: m[0], inner: m[1], index: m.index });
}
}
return out;
}
// ─── TIER 2: MUSTACHE ───────────────────────────────────────────────────────
const MUSTACHE_RE = /\{\{\s*([^{}\n]{1,80}?)\s*\}\}/g;
const SNAKE_RE = /^[a-z][a-z0-9_]{0,78}$/;
/**
* T2 admission rule. Accepts snake_case or Title-Case inner text.
* @param {string} inner
* @returns {boolean}
*/
export function isMustachePlaceholder(inner) {
if (SNAKE_RE.test(inner)) return true;
return isBracketPlaceholder(inner);
}
/**
* Tier 2 detection: `{{Title Case}}` or `{{snake_case}}` mustache placeholders.
* Only invoked when `--syntax mustache` is selected. Schema-rescue same as T1.
*
* @param {string} body
* @param {Set<string>} [schemaAliases]
* @returns {DetectionHit[]}
*/
export function detectMustache(body, schemaAliases = new Set()) {
const out = [];
let m;
MUSTACHE_RE.lastIndex = 0;
while ((m = MUSTACHE_RE.exec(body)) !== null) {
const inner = m[1].trim();
if (isMustachePlaceholder(inner) || schemaAliases.has(inner)) {
out.push({ match: m[0], inner, index: m.index });
}
}
return out;
}
/**
* Whether `body` contains both bracket and mustache placeholders.
* Triggers the mixed-convention `--why`/stderr warning.
*
* @param {string} body
* @returns {boolean}
*/
export function hasBothConventions(body) {
return detectBracket(body).length > 0 && detectMustache(body).length > 0;
}
// ─── TIER 3: DOCX HIGHLIGHT ─────────────────────────────────────────────────
/**
* Tier 3 detection: scan a Word document's XML for highlighted text runs.
* Recognizes yellow / green / cyan / magenta highlights as placeholders;
* other colors are ignored. Dedupes by exact text match.
*
* @param {string} xml — content of `word/document.xml`.
* @returns {DetectionHit[]}
*/
export function detectDocxHighlight(xml) {
if (!xml) return [];
const hits = extractDocxHighlights(xml);
const seen = new Map();
for (const { text, color } of hits) {
if (!seen.has(text)) seen.set(text, { match: text, inner: text, color });
}
return [...seen.values()];
}
// ─── TIER 4: HEURISTIC ──────────────────────────────────────────────────────
function escapeRegex(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
/**
* Tier 4 detection: scan body for known generic-placeholder phrases from a
* curated dictionary. Whole-word matching only. Returns one entry per
* phrase that appears (dedupe by phrase).
*
* Note: substitute() does a global regex replace on T4 hits, so a single
* detection may correspond to multiple substitutions in the output.
*
* @param {string} body
* @param {string[]} [dict] — phrases to look for. Defaults to {@link DEFAULT_HEURISTIC_DICT}.
* @returns {DetectionHit[]}
*/
export function detectHeuristic(body, dict = DEFAULT_HEURISTIC_DICT) {
const out = [];
const seen = new Set();
for (const phrase of dict) {
const re = new RegExp(`(?<![A-Za-z0-9])${escapeRegex(phrase)}(?![A-Za-z0-9])`, "g");
let m;
while ((m = re.exec(body)) !== null) {
if (!seen.has(phrase)) {
seen.add(phrase);
out.push({ match: phrase, inner: phrase, index: m.index });
}
break; // count once per phrase for detection; substitution replaces all
}
}
return out;
}
// ─── TIER 5: LLM ────────────────────────────────────────────────────────────
/**
* Tier 5 detection: ask an LLM to suggest placeholders in the body.
*
* Sends template text ONLY. Does not include params, schema, or env. The
* provider's response is parsed as `{ placeholders: [{text, suggested_key}] }`;
* malformed entries are dropped silently. Tests inject a `fetcher` so they
* never make real network calls.
*
* @param {string} body
* @param {LlmProvider} providerCfg
* @param {{ fetcher?: typeof fetch | null }} [opts]
* @returns {Promise<DetectionHit[]>}
* @throws {Error} with `.exitCode = EXIT.LLM` on auth, transport, or
* parse failure.
*/
export async function detectLlm(body, providerCfg, { fetcher = (typeof fetch !== "undefined" ? fetch : null) } = {}) {
if (!fetcher) {
const e = new Error("fetch is not available; Node 18+ is required for the LLM tier");
e.exitCode = EXIT.LLM;
throw e;
}
const prompt = `You are a placeholder detector for a legal-document drafting tool.
Given the document text below, identify spans that look like placeholders — names, dates, or
party-identifier text that a drafter would replace before sending. Do NOT detect cross-references
or section labels. Output JSON ONLY in this exact shape:
{"placeholders":[{"text":"<verbatim span>","suggested_key":"<snake_case_key>"}]}
If you find nothing, output {"placeholders":[]}.
DOCUMENT:
${body.slice(0, 12000)}`;
const raw = await callLlm(providerCfg, prompt, fetcher);
let parsed;
try {
const jsonMatch = raw.match(/\{[\s\S]*\}/);
parsed = JSON.parse(jsonMatch ? jsonMatch[0] : raw);
} catch {
const e = new Error(`LLM returned non-JSON response`);
e.exitCode = EXIT.LLM;
throw e;
}
const items = Array.isArray(parsed.placeholders) ? parsed.placeholders : [];
const out = [];
const seen = new Set();
for (const it of items) {
if (!it || typeof it.text !== "string" || typeof it.suggested_key !== "string") continue;
if (!validKey(it.suggested_key)) continue;
if (seen.has(it.suggested_key)) continue;
seen.add(it.suggested_key);
out.push({ match: it.text, inner: it.text, suggested_key: it.suggested_key });
}
return out;
}
/**
* v2 #4: LLM inference from a free-form deal description.
*
* Takes the prose deal description (the user's notes about parties, dates,
* amounts, etc.) and asks the configured T5 LLM provider to extract values
* for the placeholders the cascade has already detected. Returns
* `{values, extraKeys, warnings}`:
*
* - values: `{key: string}` for every placeholder key the LLM filled
* - extraKeys: any keys the LLM emitted that aren't in the placeholders list (Q4.2 → warn)
* - warnings: human-readable messages for malformed entries
*
* Throws on missing provider config, missing `fetch`, network/HTTP error, or
* non-JSON LLM response — same failure boundaries as `detectLlm`.
*
* @param {string} dealText — free-form deal description
* @param {Placeholder[]} placeholders — the post-detection placeholder list
* @param {ReturnType<llmProviderFromEnv>} providerCfg
* @param {{ fetcher?: typeof fetch | null }} [opts]
* @returns {Promise<{ values: Object<string,string>, extraKeys: string[], warnings: string[] }>}
*/
export async function inferFromDeal(dealText, placeholders, providerCfg, { fetcher = (typeof fetch !== "undefined" ? fetch : null) } = {}) {
if (!fetcher) {
const e = new Error("fetch is not available; Node 18+ is required for --from-deal");
e.exitCode = EXIT.LLM;
throw e;
}
if (!providerCfg) {
const e = new Error("--from-deal requires an LLM provider; set ANTHROPIC_API_KEY / OPENAI_API_KEY / DRAFT_LLM_* (in .env or the environment), or write ~/.config/contract-ops/llm.json");
e.exitCode = EXIT.LLM;
throw e;
}
const wantedKeys = placeholders.map((p) => ({
key: p.key,
aliases: (p.aliases || []).slice(0, 4),
first_seen_as: p.first_seen_as,
}));
if (wantedKeys.length === 0) {
return { values: {}, extraKeys: [], warnings: [] };
}
const fieldList = wantedKeys.map((w) =>
` - ${w.key} (template placeholder: "${w.first_seen_as}"${w.aliases.length > 1 ? `; aliases: ${w.aliases.join(", ")}` : ""})`
).join("\n");
const prompt = `You are filling parameters for a legal-document drafting tool.
A user has written prose describing a deal. Extract values for the following
fields from the deal description. Output JSON ONLY in this exact shape, with
no commentary:
{"values":{"<key>":"<extracted_value>",...}}
If a field can't be confidently extracted from the description, omit it (do
NOT guess). Do not invent additional fields not in the list. Match the deal's
language verbatim — don't reformat dates, currencies, or names.
FIELDS:
${fieldList}
DEAL DESCRIPTION:
${dealText.slice(0, 12000)}`;
const raw = await callLlm(providerCfg, prompt, fetcher);
let parsed;
try {
const jsonMatch = raw.match(/\{[\s\S]*\}/);
parsed = JSON.parse(jsonMatch ? jsonMatch[0] : raw);
} catch {
const e = new Error(`LLM returned non-JSON response for --from-deal`);
e.exitCode = EXIT.LLM;
throw e;
}
const rawValues = (parsed && typeof parsed.values === "object" && parsed.values) ? parsed.values : {};
const knownKeys = new Set(placeholders.map((p) => p.key));
const values = {};
const extraKeys = [];
const warnings = [];
for (const [k, v] of Object.entries(rawValues)) {
if (!knownKeys.has(k)) {
extraKeys.push(k);
continue;
}
if (v === null || v === undefined) continue;