open-agreements
Version:
Open-source legal template filling CLI and library
344 lines • 16.9 kB
JavaScript
import { Command } from 'commander';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { runFill } from '../commands/fill.js';
import { runValidate } from '../commands/validate.js';
import { runList } from '../commands/list.js';
import { runTemplateShow } from '../commands/template.js';
import { runFieldSelectorCommand, runFieldSelectorClean, runFieldSelectorPatch } from '../commands/field-selector.js';
import { runFieldSelectorSchema } from '../commands/field-selector-schema.js';
import { createNumberingRenderCopy } from '../core/field-selector/numbering-render-copy.js';
import { FieldSelectorMetadataSchema } from '../core/metadata.js';
import yaml from 'js-yaml';
import { runScan } from '../commands/scan.js';
import { runChecklistCreate, runChecklistList, runChecklistShow, runChecklistUpdate, runChecklistRender, runChecklistHistory, runChecklistPatchValidate, runChecklistPatchApply, } from '../commands/checklist.js';
import { loadAgreementTerms, runAgreementCreate, runAgreementList, runAgreementRender, runAgreementReview, runAgreementShow, runAgreementUpdate, } from '../commands/agreements.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pkg = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf-8'));
export function createProgram() {
const program = new Command();
program
.name('open-agreements')
.description('Open-source legal template and field-selector filling CLI')
.version(pkg.version);
// --- Fill command ---
const fillCmd = new Command('fill');
fillCmd
.description('Fill a template with provided values and render a DOCX file')
.argument('<template>', 'Template name to fill')
.option('-o, --output <path>', 'Output file path')
.option('-d, --data <json-file>', 'JSON file with field values')
.option('--values <json-file>', 'Alias for --data')
.option('--set <key=value...>', 'Set a field value (repeatable)')
.option('--memo [format]', 'Generate memo artifact(s): json, markdown, or both (default: both)')
.option('--memo-json <path>', 'Output path for memo JSON')
.option('--memo-md <path>', 'Output path for memo Markdown')
.option('--memo-jurisdiction <name>', 'Jurisdiction override used for memo warning rules')
.option('--memo-baseline <template-id>', 'Baseline template id for deterministic variance checks')
.action(async (template, opts) => {
let values = {};
const dataPath = opts.data ?? opts.values;
if (dataPath) {
values = JSON.parse(readFileSync(dataPath, 'utf-8'));
}
for (const pair of opts.set ?? []) {
const eq = pair.indexOf('=');
if (eq < 1)
throw new Error(`Invalid --set format: "${pair}" (expected key=value)`);
values[pair.slice(0, eq)] = pair.slice(eq + 1);
}
await runFill({
template,
output: opts.output,
values,
memo: buildMemoArgs(opts),
});
});
program.addCommand(fillCmd);
// --- Local persistent agreements ---
const agreementsCmd = new Command('agreements');
agreementsCmd.description('Create and manage local persistent agreements');
agreementsCmd
.command('create <template>')
.description('Create a local agreement from a template')
.option('-d, --data <json-file>', 'JSON file with initial terms')
.option('--set <key=value...>', 'Set an initial term (repeatable)')
.action(async (template, opts) => {
await runAgreementCreate({ template, terms: loadAgreementTerms(opts.data, opts.set) });
});
agreementsCmd
.command('list')
.description('List local agreements')
.option('--json', 'Output machine-readable JSON')
.action(async (opts) => {
await runAgreementList(opts);
});
agreementsCmd
.command('show <id>')
.description('Show a local agreement')
.option('--json', 'Output the full agreement record')
.action(async (id, opts) => {
await runAgreementShow({ id, json: opts.json });
});
agreementsCmd
.command('update <id>')
.description('Merge terms into a local agreement and advance its revision')
.option('-d, --data <json-file>', 'JSON file with terms to merge')
.option('--set <key=value...>', 'Set a term (repeatable)')
.option('--revision <number>', 'Require this current revision before updating', parsePositiveRevision)
.action(async (id, opts) => {
await runAgreementUpdate({
id,
terms: loadAgreementTerms(opts.data, opts.set),
revision: opts.revision,
});
});
agreementsCmd
.command('review <id>')
.description('Review local terms and template provenance, persisting warnings')
.action(async (id) => {
await runAgreementReview({ id });
});
agreementsCmd
.command('render <id>')
.description('Render the current agreement revision to DOCX')
.option('-o, --output <path>', 'Output DOCX path')
.action(async (id, opts) => {
await runAgreementRender({ id, output: opts.output });
});
program.addCommand(agreementsCmd);
// --- Validate command ---
program
.command('validate [template]')
.description('Run validation pipeline on all templates and field-selectors')
.option('--strict', 'Treat warnings (scaffolds, missing files) as errors')
.action((template, opts) => {
runValidate({ template, strict: opts.strict });
});
// --- List command ---
program
.command('list')
.description('Show all available agreements (templates, external, and field-selectors)')
.option('--json', 'Output machine-readable JSON with full field definitions')
.option('--json-strict', 'Like --json but exit non-zero if any metadata fails')
.action((opts) => {
runList({ json: opts.json, jsonStrict: opts.jsonStrict });
});
// --- Template discovery command ---
const templateCmd = new Command('template');
templateCmd.description('Inspect agreement metadata and fillable fields');
templateCmd
.command('show <template>')
.description('Show one template, external form, or field-selector')
.option('--json', 'Output the canonical machine-readable catalog item')
.action((template, opts) => {
runTemplateShow(template, { json: opts.json });
});
program.addCommand(templateCmd);
// --- Field-selector command ---
const fieldSelectorCmd = new Command('field-selector');
fieldSelectorCmd.description('Work with field-selector-based document pipelines');
fieldSelectorCmd
.command('render-copy <input>')
.description('Create a disposable numbering snapshot for PDF conversion; never replace the editable DOCX')
.requiredOption('-o, --output <path>', 'New *.render.docx path (must not exist)')
.option('--nonbreaking-hyphen-font <family>', 'Host-verified font for U+2011 glyphs in the temporary main-story render copy')
.option('--style-separator-metadata <path>', 'Opt in to source-declared spacing corrections from canonical metadata.yaml')
.option('--style-separator-source <path>', 'Unmodified pinned source DOCX required with --style-separator-metadata')
.action((input, opts) => {
if (!!opts.styleSeparatorMetadata !== !!opts.styleSeparatorSource)
throw new Error('Both style-separator metadata and source are required');
let styleSeparatorSpacing;
if (opts.styleSeparatorMetadata && opts.styleSeparatorSource) {
const metadata = FieldSelectorMetadataSchema.parse(yaml.load(readFileSync(opts.styleSeparatorMetadata, 'utf8')));
if (!metadata.rendering)
throw new Error('Metadata has no style-separator spacing declaration');
styleSeparatorSpacing = { sourcePath: opts.styleSeparatorSource, sourceSha256: metadata.source_sha256, profile: metadata.rendering.style_separator_spacing };
}
console.log(JSON.stringify(createNumberingRenderCopy(input, opts.output, { nonbreakingHyphenFont: opts.nonbreakingHyphenFont, styleSeparatorSpacing }), null, 2));
});
fieldSelectorCmd
.command('schema [field-selector-id]')
.description('Export the canonical caller-input JSON Schema for one or all field-selectors')
.option('-o, --output <path>', 'Write one schema to a file instead of stdout')
.option('--all', 'Export every field-selector schema plus a hash-pinned manifest')
.option('--output-dir <path>', 'Directory for --all schema bundle')
.option('--runtime-revision <sha>', 'Exact lowercase 40-character Git revision for --all provenance')
.action((fieldSelectorId, opts) => {
runFieldSelectorSchema({ fieldSelectorId, ...opts });
});
fieldSelectorCmd
.command('run <field-selector-id>')
.description('Run the full field-selector pipeline (clean → patch → fill → verify)')
.option('-i, --input <path>', 'Source DOCX file (auto-downloads if omitted)')
.option('-o, --output <path>', 'Output file path')
.option('-d, --data <json-file>', 'JSON file with field values')
.option('--values <json-file>', 'Alias for --data')
.option('--keep-intermediate', 'Preserve intermediate files')
.option('--computed-out <path>', 'Write computed interaction artifact JSON')
.option('--no-normalize-brackets', 'Disable post-fill bracket artifact normalization')
.action(async (fieldSelectorId, opts) => {
await runFieldSelectorCommand({
fieldSelectorId,
input: opts.input,
output: opts.output,
data: opts.data ?? opts.values,
keepIntermediate: opts.keepIntermediate,
computedOut: opts.computedOut,
normalizeBrackets: opts.normalizeBrackets,
});
});
fieldSelectorCmd
.command('clean <input>')
.description('Run only the clean stage of a field-selector')
.requiredOption('-o, --output <path>', 'Output file path')
.requiredOption('--field-selector <id>', 'Field-selector ID to use for clean config')
.option('--extract-guidance <path>', 'Extract removed content as guidance JSON to the specified path')
.action(async (input, opts) => {
await runFieldSelectorClean({ input, output: opts.output, fieldSelector: opts.fieldSelector, extractGuidance: opts.extractGuidance });
});
fieldSelectorCmd
.command('patch <input>')
.description('Run only the patch stage of a field-selector')
.requiredOption('-o, --output <path>', 'Output file path')
.requiredOption('--field-selector <id>', 'Field-selector ID to use for replacements')
.action(async (input, opts) => {
await runFieldSelectorPatch({ input, output: opts.output, fieldSelector: opts.fieldSelector });
});
program.addCommand(fieldSelectorCmd);
// --- Scan command ---
program
.command('scan <input>')
.description('Scan a DOCX file for bracketed placeholders')
.option('--output-replacements <path>', 'Write a draft replacements.json')
.action((input, opts) => {
runScan({ input, outputReplacements: opts.outputReplacements });
});
// --- Checklist command ---
const checklistCmd = new Command('checklist');
checklistCmd.description('Work with closing checklists');
checklistCmd
.command('create')
.description('Initialize a new checklist in the state directory')
.argument('<deal-name>', 'Deal name for the checklist')
.option('-d, --data <json-file>', 'JSON file with initial checklist data (brownfield)')
.option('--values <json-file>', 'Alias for --data')
.action(async (dealName, opts) => {
await runChecklistCreate({ dealName, data: opts.data ?? opts.values });
});
checklistCmd
.command('list')
.description('List all checklists')
.action(async () => {
await runChecklistList();
});
checklistCmd
.command('show')
.description('Show current checklist state')
.argument('<name-or-id>', 'Deal name or UUID')
.option('--json', 'Print full JSON state')
.action(async (nameOrId, opts) => {
await runChecklistShow({ nameOrId, json: opts.json });
});
checklistCmd
.command('update')
.description('Validate and apply a patch to a checklist (unified command)')
.argument('<name-or-id>', 'Deal name or UUID')
.requiredOption('-d, --data <json-file>', 'Patch envelope JSON file')
.action(async (nameOrId, opts) => {
await runChecklistUpdate({ nameOrId, data: opts.data });
});
checklistCmd
.command('render')
.description('Render a checklist to DOCX')
.argument('<name-or-id>', 'Deal name or UUID')
.option('-o, --output <path>', 'Output file path (default: closing-checklist.docx)')
.action(async (nameOrId, opts) => {
await runChecklistRender({ nameOrId, output: opts.output });
});
checklistCmd
.command('history')
.description('Show update history for a checklist')
.argument('<name-or-id>', 'Deal name or UUID')
.action(async (nameOrId) => {
await runChecklistHistory({ nameOrId });
});
checklistCmd
.command('patch-validate')
.description('Validate a checklist patch against state (dry run, no mutation)')
.requiredOption('--state <json-file>', 'Checklist state JSON ({ checklist_id, revision, checklist })')
.requiredOption('--patch <json-file>', 'Patch envelope JSON file')
.option('-o, --output <json-file>', 'Output JSON path for validation result')
.option('--validation-store <json-file>', 'Persist validation artifacts to this JSON file')
.action(async (opts) => {
await runChecklistPatchValidate({
state: opts.state,
patch: opts.patch,
output: opts.output,
validationStore: opts.validationStore,
});
});
checklistCmd
.command('patch-apply')
.description('Apply a previously validated checklist patch to state')
.requiredOption('--state <json-file>', 'Checklist state JSON ({ checklist_id, revision, checklist })')
.requiredOption('--request <json-file>', 'Patch apply request JSON ({ validation_id, patch })')
.option('-o, --output <json-file>', 'Output JSON path for apply result')
.option('--validation-store <json-file>', 'Validation artifact JSON store')
.option('--applied-store <json-file>', 'Applied patch JSON store')
.option('--proposed-store <json-file>', 'Proposed patch JSON store')
.action(async (opts) => {
await runChecklistPatchApply({
state: opts.state,
request: opts.request,
output: opts.output,
validationStore: opts.validationStore,
appliedStore: opts.appliedStore,
proposedStore: opts.proposedStore,
});
});
program.addCommand(checklistCmd);
return program;
}
function parsePositiveRevision(value) {
const revision = Number(value);
if (!Number.isInteger(revision) || revision < 1) {
throw new Error(`Invalid --revision: "${value}" (expected a positive integer)`);
}
return revision;
}
function buildMemoArgs(opts) {
const hasMemoRelatedFlag = Boolean(opts.memo !== undefined
|| opts.memoJson
|| opts.memoMd
|| opts.memoJurisdiction
|| opts.memoBaseline);
if (!hasMemoRelatedFlag) {
return undefined;
}
let format = 'both';
if (typeof opts.memo === 'string') {
if (opts.memo !== 'json' && opts.memo !== 'markdown' && opts.memo !== 'both') {
throw new Error(`Invalid --memo format: "${opts.memo}" (expected json, markdown, or both)`);
}
format = opts.memo;
}
return {
enabled: true,
format,
jsonOutputPath: opts.memoJson,
markdownOutputPath: opts.memoMd,
jurisdiction: opts.memoJurisdiction,
baselineTemplateId: opts.memoBaseline,
};
}
export async function runCli(argv = process.argv) {
const program = createProgram();
await program.parseAsync(argv);
}
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
await runCli(process.argv);
}
//# sourceMappingURL=index.js.map