@holdyourvoice/hyv 3.4.0 → 3.4.2

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/cli.js CHANGED
@@ -199,6 +199,9 @@ function json(value) {
199
199
  console.log(JSON.stringify(value, null, 2));
200
200
  }
201
201
  function canonical(value) { process.stdout.write(`${canonicalJson(value)}\n`); }
202
+ function writeJson(path, value) {
203
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
204
+ }
202
205
  function profileArguments(args) {
203
206
  const [output, ...rest] = args;
204
207
  const samples = [];
@@ -375,351 +378,386 @@ function runAgent(args) {
375
378
  }
376
379
  throw new Error('Usage: hyv agent <list|validate|describe|emit> ...');
377
380
  }
378
- export async function runCli(args) {
379
- const [command, ...rest] = args;
380
- if (command === 'agent') {
381
- return runAgent(rest);
382
- }
383
- if (command === 'profile') {
384
- const { output, samples, avoid } = profileArguments(rest);
385
- writeFileSync(output, `${JSON.stringify(buildProfile(samples.map(input), avoid), null, 2)}\n`);
386
- return 0;
387
- }
388
- if (command === 'analyze') {
389
- const [draft, profilePath, briefPath] = rest;
390
- if (!draft || !profilePath)
391
- throw new Error('Usage: hyv analyze draft.md profile.json [writing-brief.json]');
392
- json(analyze(input(draft), readProfile(profilePath), readBrief(briefPath)));
381
+ function runProfile(args) {
382
+ const { output, samples, avoid } = profileArguments(args);
383
+ writeJson(output, buildProfile(samples.map(input), avoid));
384
+ return 0;
385
+ }
386
+ function runAnalyze(args) {
387
+ const [draft, profilePath, briefPath] = args;
388
+ if (!draft || !profilePath)
389
+ throw new Error('Usage: hyv analyze draft.md profile.json [writing-brief.json]');
390
+ json(analyze(input(draft), readProfile(profilePath), readBrief(briefPath)));
391
+ return 0;
392
+ }
393
+ function runHygiene(args) {
394
+ const { path, fix, output } = hygieneArguments(args);
395
+ if (fix && path === '-')
396
+ throw new Error('hyv hygiene --fix requires a file path so the original can be preserved.');
397
+ const text = input(path);
398
+ if (!fix) {
399
+ json(inspectHygiene(text));
393
400
  return 0;
394
401
  }
395
- if (command === 'hygiene') {
396
- const { path, fix, output } = hygieneArguments(rest);
397
- if (fix && path === '-')
398
- throw new Error('hyv hygiene --fix requires a file path so the original can be preserved.');
399
- const text = input(path);
400
- if (!fix) {
401
- json(inspectHygiene(text));
402
- return 0;
402
+ const outputPath = output ?? cleanedPath(path);
403
+ if (resolve(outputPath) === resolve(path))
404
+ throw new Error('Hygiene output must differ from the input path.');
405
+ const result = cleanHygiene(text);
406
+ writeNewFileAtomically(outputPath, result.cleaned);
407
+ json({ ...result.report, changed: result.changed, changes: result.changes, outputPath });
408
+ return 0;
409
+ }
410
+ function runInspectHiddenText(args) {
411
+ const [path, policyPath, ...extra] = args;
412
+ if (!path || extra.length)
413
+ throw new Error('Usage: hyv inspect-hidden-text draft.md [policy.json]');
414
+ json(inspectHiddenText(input(path), policyPath ? parseHiddenTextPolicy(readJson(policyPath)) : undefined));
415
+ return 0;
416
+ }
417
+ function runApplyHiddenTextPolicy(args) {
418
+ const [path, policyPath, output, ...extra] = args;
419
+ if (!path || !policyPath || !output || extra.length)
420
+ throw new Error('Usage: hyv apply-hidden-text-policy draft.md policy.json output.md');
421
+ if (path === '-' || resolve(path) === resolve(output))
422
+ throw new Error('Hidden-text output must differ from the input path.');
423
+ const result = applyHiddenTextPolicy(input(path), parseHiddenTextPolicy(readJson(policyPath)));
424
+ writeNewFileAtomically(output, result.output);
425
+ json({ ...result, outputPath: output });
426
+ return 0;
427
+ }
428
+ function runFinalCheck(args) {
429
+ const [path, ...options] = args;
430
+ if (!path || options.length)
431
+ throw new Error('Usage: hyv final-check <path|->');
432
+ const result = finalOutputCheck(input(path));
433
+ if (!result.accepted) {
434
+ console.error(JSON.stringify(result, null, 2));
435
+ return 2;
436
+ }
437
+ if (result.changed)
438
+ console.error(JSON.stringify({ changed: true, changes: result.changes }, null, 2));
439
+ process.stdout.write(result.output);
440
+ return 0;
441
+ }
442
+ function runFactLint(args) {
443
+ const [draftPath, ...options] = args;
444
+ const sources = [];
445
+ let metadata;
446
+ let strict = false;
447
+ let human = false;
448
+ if (!draftPath)
449
+ throw new Error('Usage: hyv fact-lint <draft|-> --source=id:path [--source=id:path] [--metadata=metadata.json] [--strict] [--human]');
450
+ for (const option of options) {
451
+ if (option === '--strict') {
452
+ strict = true;
453
+ continue;
403
454
  }
404
- const outputPath = output ?? cleanedPath(path);
405
- if (resolve(outputPath) === resolve(path))
406
- throw new Error('Hygiene output must differ from the input path.');
407
- const result = cleanHygiene(text);
408
- writeNewFileAtomically(outputPath, result.cleaned);
409
- json({ ...result.report, changed: result.changed, changes: result.changes, outputPath });
410
- return 0;
411
- }
412
- if (command === 'inspect-hidden-text') {
413
- const [path, policyPath, ...extra] = rest;
414
- if (!path || extra.length)
415
- throw new Error('Usage: hyv inspect-hidden-text draft.md [policy.json]');
416
- json(inspectHiddenText(input(path), policyPath ? parseHiddenTextPolicy(readJson(policyPath)) : undefined));
417
- return 0;
418
- }
419
- if (command === 'apply-hidden-text-policy') {
420
- const [path, policyPath, output, ...extra] = rest;
421
- if (!path || !policyPath || !output || extra.length)
422
- throw new Error('Usage: hyv apply-hidden-text-policy draft.md policy.json output.md');
423
- if (path === '-' || resolve(path) === resolve(output))
424
- throw new Error('Hidden-text output must differ from the input path.');
425
- const result = applyHiddenTextPolicy(input(path), parseHiddenTextPolicy(readJson(policyPath)));
426
- writeNewFileAtomically(output, result.output);
427
- json({ ...result, outputPath: output });
428
- return 0;
429
- }
430
- if (command === 'final-check') {
431
- const [path, ...options] = rest;
432
- if (!path || options.length)
433
- throw new Error('Usage: hyv final-check <path|->');
434
- const result = finalOutputCheck(input(path));
435
- if (!result.accepted) {
436
- console.error(JSON.stringify(result, null, 2));
437
- return 2;
455
+ if (option === '--human') {
456
+ human = true;
457
+ continue;
438
458
  }
439
- if (result.changed)
440
- console.error(JSON.stringify({ changed: true, changes: result.changes }, null, 2));
441
- process.stdout.write(result.output);
442
- return 0;
443
- }
444
- if (command === 'fact-lint') {
445
- const [draftPath, ...options] = rest;
446
- const sources = [];
447
- let metadata;
448
- let strict = false;
449
- let human = false;
450
- if (!draftPath)
451
- throw new Error('Usage: hyv fact-lint <draft|-> --source=id:path [--source=id:path] [--metadata=metadata.json] [--strict] [--human]');
452
- for (const option of options) {
453
- if (option === '--strict') {
454
- strict = true;
455
- continue;
456
- }
457
- if (option === '--human') {
458
- human = true;
459
- continue;
460
- }
461
- if (option.startsWith('--source=')) {
462
- const value = option.slice('--source='.length);
463
- const separator = value.indexOf(':');
464
- const id = value.slice(0, separator).trim();
465
- const path = value.slice(separator + 1);
466
- if (separator < 1 || !id || !path)
467
- throw new Error('Sources must use --source=id:path.');
468
- sources.push({ id, text: input(path) });
469
- continue;
470
- }
471
- if (option.startsWith('--metadata=')) {
472
- metadata = JSON.parse(input(option.slice('--metadata='.length)));
473
- continue;
474
- }
475
- throw new Error('Usage: hyv fact-lint <draft|-> --source=id:path [--source=id:path] [--metadata=metadata.json] [--strict] [--human]');
459
+ if (option.startsWith('--source=')) {
460
+ const value = option.slice('--source='.length);
461
+ const separator = value.indexOf(':');
462
+ const id = value.slice(0, separator).trim();
463
+ const path = value.slice(separator + 1);
464
+ if (separator < 1 || !id || !path)
465
+ throw new Error('Sources must use --source=id:path.');
466
+ sources.push({ id, text: input(path) });
467
+ continue;
476
468
  }
477
- const report = lintFacts({ sources, draft: input(draftPath), metadata });
478
- if (human)
479
- console.log(formatFactLintReport(report));
480
- else
481
- json(report);
482
- return strict && report.findings.some((item) => item.severity === 'error') ? 2 : 0;
483
- }
484
- if (command === 'logic-lint') {
485
- const [draftPath, briefPath, ...extra] = rest;
486
- if (!draftPath || extra.length)
487
- throw new Error('Usage: hyv logic-lint <draft|-> [writing-brief.json]');
488
- const report = lintLogic(input(draftPath), readBrief(briefPath));
489
- json(report);
490
- return report.passed ? 0 : 2;
491
- }
492
- if (command === 'batch-analyze') {
493
- if (rest.length < 2)
494
- throw new Error('Usage: hyv batch-analyze draft-a.md draft-b.md [draft-c.md]');
495
- json(analyzeBatch(rest.map(input)));
496
- return 0;
497
- }
498
- if (command === 'rewrite-prompt') {
499
- const [draft, profilePath, briefPath] = rest;
500
- if (!draft || !profilePath)
501
- throw new Error('Usage: hyv rewrite-prompt draft.md profile.json [writing-brief.json]');
502
- const profile = readProfile(profilePath);
503
- console.log(rewritePrompt(input(draft), profile, composeLearning(profile), readBrief(briefPath)));
504
- return 0;
505
- }
506
- if (command === 'prepare-rewrite') {
507
- const [draft, profilePath, output, ...contextPaths] = rest;
508
- if (!draft || !profilePath || !output)
509
- throw new Error('Usage: hyv prepare-rewrite draft.md profile.json task.json [copy-spec.json] [writing-brief.json]');
510
- const context = prepareContext(contextPaths);
511
- const task = prepareRewriteTask(input(draft), readProfile(profilePath), context.copySpec, context.writingBrief);
512
- writeFileSync(output, `${JSON.stringify(task, null, 2)}\n`);
513
- json({ version: task.version, fingerprint: task.fingerprint, eligibleSentenceIds: task.eligibleSentenceIds });
514
- return 0;
469
+ if (option.startsWith('--metadata=')) {
470
+ metadata = JSON.parse(input(option.slice('--metadata='.length)));
471
+ continue;
472
+ }
473
+ throw new Error('Usage: hyv fact-lint <draft|-> --source=id:path [--source=id:path] [--metadata=metadata.json] [--strict] [--human]');
515
474
  }
516
- if (command === 'apply-rewrite') {
517
- const [taskPath, responsePath, profilePath] = rest;
518
- if (!taskPath || !responsePath || !profilePath)
519
- throw new Error('Usage: hyv apply-rewrite task.json response.json profile.json');
520
- const result = evaluateRewriteResponse(parseRewriteTask(JSON.parse(input(taskPath))), input(responsePath), readProfile(profilePath));
521
- json(result);
522
- return result.status === 'accepted' ? 0 : 2;
523
- }
524
- if (command === 'prepare-judgment') {
525
- const [stage, kind, draft, profilePath, output, candidatePath] = rest;
526
- if (!stage || !kind || !draft || !profilePath || !output)
527
- throw new Error('Usage: hyv prepare-judgment pre-edit|post-candidate kind draft.md profile.json task.json [candidate.md]');
528
- if (stage === 'post-candidate' && !candidatePath)
529
- throw new Error('Usage: hyv prepare-judgment post-candidate kind draft.md profile.json task.json candidate.md');
530
- const profile = readProfile(profilePath);
531
- const task = stage === 'pre-edit'
532
- ? preparePreEditJudgment(input(draft), profile, kind)
533
- : preparePostCandidateJudgment(input(draft), input(candidatePath ?? ''), profile, kind);
534
- writeFileSync(output, `${JSON.stringify(task, null, 2)}\n`);
535
- json({ version: task.version, stage: task.stage, judgmentType: task.judgmentType, taskFingerprint: task.taskFingerprint });
475
+ const report = lintFacts({ sources, draft: input(draftPath), metadata });
476
+ if (human)
477
+ console.log(formatFactLintReport(report));
478
+ else
479
+ json(report);
480
+ return strict && report.findings.some((item) => item.severity === 'error') ? 2 : 0;
481
+ }
482
+ function runLogicLint(args) {
483
+ const [draftPath, briefPath, ...extra] = args;
484
+ if (!draftPath || extra.length)
485
+ throw new Error('Usage: hyv logic-lint <draft|-> [writing-brief.json]');
486
+ const report = lintLogic(input(draftPath), readBrief(briefPath));
487
+ json(report);
488
+ return report.passed ? 0 : 2;
489
+ }
490
+ function runBatchAnalyze(args) {
491
+ if (args.length < 2)
492
+ throw new Error('Usage: hyv batch-analyze draft-a.md draft-b.md [draft-c.md]');
493
+ json(analyzeBatch(args.map(input)));
494
+ return 0;
495
+ }
496
+ function runRewritePrompt(args) {
497
+ const [draft, profilePath, briefPath] = args;
498
+ if (!draft || !profilePath)
499
+ throw new Error('Usage: hyv rewrite-prompt draft.md profile.json [writing-brief.json]');
500
+ const profile = readProfile(profilePath);
501
+ console.log(rewritePrompt(input(draft), profile, composeLearning(profile), readBrief(briefPath)));
502
+ return 0;
503
+ }
504
+ function runPrepareRewrite(args) {
505
+ const [draft, profilePath, output, ...contextPaths] = args;
506
+ if (!draft || !profilePath || !output)
507
+ throw new Error('Usage: hyv prepare-rewrite draft.md profile.json task.json [copy-spec.json] [writing-brief.json]');
508
+ const context = prepareContext(contextPaths);
509
+ const task = prepareRewriteTask(input(draft), readProfile(profilePath), context.copySpec, context.writingBrief);
510
+ writeJson(output, task);
511
+ json({ version: task.version, fingerprint: task.fingerprint, eligibleSentenceIds: task.eligibleSentenceIds });
512
+ return 0;
513
+ }
514
+ function runApplyRewrite(args) {
515
+ const [taskPath, responsePath, profilePath] = args;
516
+ if (!taskPath || !responsePath || !profilePath)
517
+ throw new Error('Usage: hyv apply-rewrite task.json response.json profile.json');
518
+ const result = evaluateRewriteResponse(parseRewriteTask(JSON.parse(input(taskPath))), input(responsePath), readProfile(profilePath));
519
+ json(result);
520
+ return result.status === 'accepted' ? 0 : 2;
521
+ }
522
+ function runPrepareJudgment(args) {
523
+ const [stage, kind, draft, profilePath, output, candidatePath] = args;
524
+ if (!stage || !kind || !draft || !profilePath || !output)
525
+ throw new Error('Usage: hyv prepare-judgment pre-edit|post-candidate kind draft.md profile.json task.json [candidate.md]');
526
+ if (stage === 'post-candidate' && !candidatePath)
527
+ throw new Error('Usage: hyv prepare-judgment post-candidate kind draft.md profile.json task.json candidate.md');
528
+ const profile = readProfile(profilePath);
529
+ const task = stage === 'pre-edit'
530
+ ? preparePreEditJudgment(input(draft), profile, kind)
531
+ : preparePostCandidateJudgment(input(draft), input(candidatePath ?? ''), profile, kind);
532
+ writeJson(output, task);
533
+ json({ version: task.version, stage: task.stage, judgmentType: task.judgmentType, taskFingerprint: task.taskFingerprint });
534
+ return 0;
535
+ }
536
+ function runReduceJudgment(args) {
537
+ if (args.length < 3)
538
+ throw new Error('Usage: hyv reduce-judgment envelope.json envelope.json [envelope.json...]');
539
+ const envelopes = args.map((path) => parseJudgmentEnvelope(JSON.parse(input(path))));
540
+ json(envelopes[0]?.stage === 'pre-edit' ? reducePreEdit(envelopes) : reducePostCandidate(envelopes));
541
+ return 0;
542
+ }
543
+ function runPrepareRebuild(args) {
544
+ const { values, capability, recompositionPolicy } = rebuildArguments(args);
545
+ const [draft, profilePath, reductionPath, specPath, output, briefPath] = values;
546
+ if (!draft || !profilePath || !reductionPath || !specPath || !output || !capability) {
547
+ throw new Error('Usage: hyv prepare-rebuild draft.md profile.json reduction.json copy-spec.json task.json [writing-brief.json] [--recomposition-policy policy.json] (--capability-stdin|--capability-file path)');
548
+ }
549
+ const context = loadApprovalContext();
550
+ const task = prepareRebuildTask(input(draft), readProfile(profilePath), readJson(reductionPath), parseCopySpec(JSON.parse(input(specPath))), capability, context.trustStore, context.now, briefPath ? parseWritingBrief(JSON.parse(input(briefPath))) : undefined, recompositionPolicy);
551
+ writeJson(output, task);
552
+ json({ version: task.version, fingerprint: task.fingerprint, recommendationFingerprint: task.recommendationFingerprint, authorizationFingerprint: task.authorizationFingerprint, ...(task.recompositionPolicy ? { recompositionPolicy: task.recompositionPolicy } : {}) });
553
+ return 0;
554
+ }
555
+ function runApplyRebuild(args) {
556
+ const { values, capability } = capabilityArguments(args);
557
+ const [taskPath, responsePath, profilePath, ...extra] = values;
558
+ if (!taskPath || !responsePath || !profilePath || extra.length || !capability)
559
+ throw new Error('Usage: hyv apply-rebuild task.json response.json profile.json (--capability-stdin|--capability-file path)');
560
+ const context = loadApprovalContext();
561
+ const result = evaluateRebuildResponse(parseRebuildTask(JSON.parse(input(taskPath))), input(responsePath), readProfile(profilePath), capability, context.trustStore, context.now);
562
+ json(result);
563
+ return result.status === 'accepted' ? 0 : 2;
564
+ }
565
+ function runRebuildWriterRequest(args) {
566
+ const [taskPath, output, ...extra] = args;
567
+ if (!taskPath || !output || extra.length)
568
+ throw new Error('Usage: hyv rebuild-writer-request task.json writer-request.json');
569
+ const request = writerRequestForRebuild(parseRebuildTask(JSON.parse(input(taskPath))));
570
+ writeJson(output, request);
571
+ json({ version: request.version, taskFingerprint: request.taskFingerprint, copySpecFingerprint: request.copySpecFingerprint, ...(request.recompositionPolicyFingerprint ? { recompositionPolicyFingerprint: request.recompositionPolicyFingerprint } : {}) });
572
+ return 0;
573
+ }
574
+ function runVerify(args) {
575
+ const [original, candidate, profilePath, briefPath] = args;
576
+ if (!original || !candidate || !profilePath)
577
+ throw new Error('Usage: hyv verify original.md candidate.md profile.json [writing-brief.json]');
578
+ const profile = readProfile(profilePath);
579
+ const originalText = input(original);
580
+ const candidateText = input(candidate);
581
+ const result = verify(originalText, candidateText, profile, readBrief(briefPath));
582
+ json(result);
583
+ return result.passed ? 0 : 2;
584
+ }
585
+ function runVerifySpec(args) {
586
+ const [original, candidate, profilePath, specPath, briefPath] = args;
587
+ if (!original || !candidate || !profilePath || !specPath)
588
+ throw new Error('Usage: hyv verify-spec original.md candidate.md profile.json copy-spec.json [writing-brief.json]');
589
+ const profile = readProfile(profilePath);
590
+ const candidateText = input(candidate);
591
+ const result = verifyWithCopySpec(input(original), candidateText, profile, parseCopySpec(JSON.parse(input(specPath))), readBrief(briefPath));
592
+ json(result);
593
+ return result.passed ? 0 : 2;
594
+ }
595
+ function runLifecycle(args) {
596
+ const [action, ...raw] = args;
597
+ if (action === 'prepare-semantic')
598
+ return prepareSemanticLifecycle(raw);
599
+ if (action === 'submit-verdict')
600
+ return submitLifecycleVerdict(raw);
601
+ if (action === 'inspect')
602
+ return inspectLifecycleArtifact(raw);
603
+ if (action === 'validate-final-approval' || action === 'finalize')
604
+ return finishLifecycle(action, raw);
605
+ throw new Error('Usage: hyv lifecycle <prepare-semantic|submit-verdict|inspect|validate-final-approval|finalize> ...');
606
+ }
607
+ function prepareSemanticLifecycle(args) {
608
+ const [deterministicPath, bindingPath, receiptPath, policy, violationsPath, output, ...extra] = args;
609
+ if (!deterministicPath || !bindingPath || !receiptPath || !policy || !violationsPath || !output || extra.length || !['normal', 'high_assurance'].includes(policy))
610
+ throw new Error('Usage: hyv lifecycle prepare-semantic deterministic.json binding.json receipt.json <normal|high_assurance> violations.json output.json');
611
+ if (policy === 'high_assurance')
612
+ throw new Error('High-assurance semantic review requires a trusted embedding.');
613
+ const result = prepareLifecycle(readJson(deterministicPath), readJson(bindingPath), readJson(receiptPath), policy, readJson(violationsPath));
614
+ const serialized = canonicalJson(result);
615
+ writeFileSync(output, `${serialized}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
616
+ process.stdout.write(`${serialized}\n`);
617
+ return 0;
618
+ }
619
+ function submitLifecycleVerdict(args) {
620
+ const [artifactPath, taskPath, evaluatorId, verdictPath, ...extra] = args;
621
+ if (!artifactPath || !taskPath || !evaluatorId || !verdictPath || extra.length)
622
+ throw new Error('Usage: hyv lifecycle submit-verdict artifact.json task.json evaluator-id verdict.json');
623
+ const artifact = readJson(artifactPath);
624
+ const task = readJson(taskPath);
625
+ if (task.policy !== 'normal')
626
+ throw new Error('High-assurance semantic review requires a trusted embedding.');
627
+ const result = submitSemanticVerdict(artifact, task, evaluatorId, readJson(verdictPath), loadApprovalContext());
628
+ canonical(result.ok ? result.artifact : { error: result.error });
629
+ return result.ok && result.artifact.status === 'ready_for_human_review' ? 0 : 2;
630
+ }
631
+ function inspectLifecycleArtifact(args) {
632
+ const [artifactPath, ...extra] = args;
633
+ if (!artifactPath || extra.length)
634
+ throw new Error('Usage: hyv lifecycle inspect artifact.json');
635
+ canonical(inspectLifecycle(readJson(artifactPath)));
636
+ return 0;
637
+ }
638
+ function finishLifecycle(action, args) {
639
+ const { values, capability } = capabilityArguments(args);
640
+ if (action === 'validate-final-approval') {
641
+ const [artifactPath, ...extra] = values;
642
+ if (!artifactPath || extra.length || !capability)
643
+ throw new Error('Usage: hyv lifecycle validate-final-approval artifact.json (--capability-stdin|--capability-file path)');
644
+ const result = validateFinalApproval(readJson(artifactPath), capability, loadApprovalContext());
645
+ canonical(result);
646
+ return result.ok ? 0 : 2;
647
+ }
648
+ const [artifactPath, decisionPath, ...extra] = values;
649
+ if (!artifactPath || !decisionPath || extra.length)
650
+ throw new Error('Usage: hyv lifecycle finalize artifact.json decision.json [--capability-stdin|--capability-file path]');
651
+ const decision = readJson(decisionPath);
652
+ if (decision.decision === 'approve' && !capability)
653
+ throw new Error('Approval requires a capability.');
654
+ if (decision.decision === 'reject' && capability)
655
+ throw new Error('Rejection does not accept a capability.');
656
+ const result = finalizeLifecycle(readJson(artifactPath), decision, loadApprovalContext(), capability);
657
+ canonical(result.ok ? result.artifact : { error: result.error });
658
+ return result.ok && result.artifact.status === 'approved' ? 0 : 2;
659
+ }
660
+ function runLearning(args) {
661
+ const [action, ...raw] = args;
662
+ if (action === 'record-approved')
663
+ return runRecordApprovedLearning(raw);
664
+ const { values, options } = learningArguments(raw);
665
+ const [profilePath, ...operands] = values;
666
+ if (!action || !profilePath)
667
+ throw new Error('Usage: hyv learning <show|inspect|add|record|ratify|supersede|migrate|clear> profile.json [value] [options]');
668
+ const profile = readProfile(profilePath);
669
+ if (action === 'show') {
670
+ json({ profile: profileFingerprint(profile), preferences: composeLearning(profile, options) });
536
671
  return 0;
537
672
  }
538
- if (command === 'reduce-judgment') {
539
- if (rest.length < 3)
540
- throw new Error('Usage: hyv reduce-judgment envelope.json envelope.json [envelope.json...]');
541
- const envelopes = rest.map((path) => parseJudgmentEnvelope(JSON.parse(input(path))));
542
- const stage = envelopes[0]?.stage;
543
- json(stage === 'pre-edit' ? reducePreEdit(envelopes) : reducePostCandidate(envelopes));
673
+ if (action === 'inspect') {
674
+ if (Object.keys(options).length)
675
+ throw new Error('Usage: hyv learning inspect profile.json');
676
+ json(inspectLearning(profile));
544
677
  return 0;
545
678
  }
546
- if (command === 'prepare-rebuild') {
547
- const { values, capability, recompositionPolicy } = rebuildArguments(rest);
548
- const [draft, profilePath, reductionPath, specPath, output, briefPath] = values;
549
- if (!draft || !profilePath || !reductionPath || !specPath || !output || !capability) {
550
- throw new Error('Usage: hyv prepare-rebuild draft.md profile.json reduction.json copy-spec.json task.json [writing-brief.json] [--recomposition-policy policy.json] (--capability-stdin|--capability-file path)');
551
- }
552
- const context = loadApprovalContext();
553
- const task = prepareRebuildTask(input(draft), readProfile(profilePath), readJson(reductionPath), parseCopySpec(JSON.parse(input(specPath))), capability, context.trustStore, context.now, briefPath ? parseWritingBrief(JSON.parse(input(briefPath))) : undefined, recompositionPolicy);
554
- writeFileSync(output, `${JSON.stringify(task, null, 2)}\n`);
555
- json({ version: task.version, fingerprint: task.fingerprint, recommendationFingerprint: task.recommendationFingerprint, authorizationFingerprint: task.authorizationFingerprint, ...(task.recompositionPolicy ? { recompositionPolicy: task.recompositionPolicy } : {}) });
679
+ if (action === 'add' || action === 'record') {
680
+ const text = operands.join(' ').trim();
681
+ if (!text)
682
+ throw new Error('Usage: hyv learning record profile.json "instruction" [options]');
683
+ const result = recordLearningInstruction(profile, text, options);
684
+ json(action === 'add' ? { added: result.status === 'recorded' } : result);
556
685
  return 0;
557
686
  }
558
- if (command === 'apply-rebuild') {
559
- const { values, capability } = capabilityArguments(rest);
560
- const [taskPath, responsePath, profilePath, ...extra] = values;
561
- if (!taskPath || !responsePath || !profilePath || extra.length || !capability)
562
- throw new Error('Usage: hyv apply-rebuild task.json response.json profile.json (--capability-stdin|--capability-file path)');
563
- const context = loadApprovalContext();
564
- const result = evaluateRebuildResponse(parseRebuildTask(JSON.parse(input(taskPath))), input(responsePath), readProfile(profilePath), capability, context.trustStore, context.now);
565
- json(result);
566
- return result.status === 'accepted' ? 0 : 2;
567
- }
568
- if (command === 'rebuild-writer-request') {
569
- const [taskPath, output, ...extra] = rest;
570
- if (!taskPath || !output || extra.length)
571
- throw new Error('Usage: hyv rebuild-writer-request task.json writer-request.json');
572
- const request = writerRequestForRebuild(parseRebuildTask(JSON.parse(input(taskPath))));
573
- writeFileSync(output, `${JSON.stringify(request, null, 2)}\n`);
574
- json({ version: request.version, taskFingerprint: request.taskFingerprint, copySpecFingerprint: request.copySpecFingerprint, ...(request.recompositionPolicyFingerprint ? { recompositionPolicyFingerprint: request.recompositionPolicyFingerprint } : {}) });
687
+ if (action === 'ratify' || action === 'supersede') {
688
+ const [eventId, ...extra] = operands;
689
+ if (!eventId || extra.length)
690
+ throw new Error(`Usage: hyv learning ${action} profile.json event-id [options]`);
691
+ json(action === 'ratify' ? ratifyLearningEvent(requireProfileV3(profile), eventId, options) : supersedeLearningEvent(requireProfileV3(profile), eventId, options));
575
692
  return 0;
576
693
  }
577
- if (command === 'verify') {
578
- const [original, candidate, profilePath, briefPath] = rest;
579
- if (!original || !candidate || !profilePath)
580
- throw new Error('Usage: hyv verify original.md candidate.md profile.json [writing-brief.json]');
581
- const profile = readProfile(profilePath);
582
- const originalText = input(original);
583
- const candidateText = input(candidate);
584
- const result = verify(originalText, candidateText, profile, readBrief(briefPath));
585
- json(result);
586
- return result.passed ? 0 : 2;
587
- }
588
- if (command === 'verify-spec') {
589
- const [original, candidate, profilePath, specPath, briefPath] = rest;
590
- if (!original || !candidate || !profilePath || !specPath)
591
- throw new Error('Usage: hyv verify-spec original.md candidate.md profile.json copy-spec.json [writing-brief.json]');
592
- const profile = readProfile(profilePath);
593
- const candidateText = input(candidate);
594
- const result = verifyWithCopySpec(input(original), candidateText, profile, parseCopySpec(JSON.parse(input(specPath))), readBrief(briefPath));
595
- json(result);
596
- return result.passed ? 0 : 2;
597
- }
598
- if (command === 'lifecycle') {
599
- const [action, ...raw] = rest;
600
- if (action === 'prepare-semantic') {
601
- const [deterministicPath, bindingPath, receiptPath, policy, violationsPath, output, ...extra] = raw;
602
- if (!deterministicPath || !bindingPath || !receiptPath || !policy || !violationsPath || !output || extra.length || !['normal', 'high_assurance'].includes(policy))
603
- throw new Error('Usage: hyv lifecycle prepare-semantic deterministic.json binding.json receipt.json <normal|high_assurance> violations.json output.json');
604
- if (policy === 'high_assurance')
605
- throw new Error('High-assurance semantic review requires a trusted embedding.');
606
- const result = prepareLifecycle(readJson(deterministicPath), readJson(bindingPath), readJson(receiptPath), policy, readJson(violationsPath));
607
- const serialized = canonicalJson(result);
608
- writeFileSync(output, `${serialized}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
609
- process.stdout.write(`${serialized}\n`);
610
- return 0;
611
- }
612
- if (action === 'submit-verdict') {
613
- const [artifactPath, taskPath, evaluatorId, verdictPath, ...extra] = raw;
614
- if (!artifactPath || !taskPath || !evaluatorId || !verdictPath || extra.length)
615
- throw new Error('Usage: hyv lifecycle submit-verdict artifact.json task.json evaluator-id verdict.json');
616
- const artifact = readJson(artifactPath);
617
- const task = readJson(taskPath);
618
- if (task.policy !== 'normal')
619
- throw new Error('High-assurance semantic review requires a trusted embedding.');
620
- const result = submitSemanticVerdict(artifact, task, evaluatorId, readJson(verdictPath), loadApprovalContext());
621
- canonical(result.ok ? result.artifact : { error: result.error });
622
- return result.ok && result.artifact.status === 'ready_for_human_review' ? 0 : 2;
623
- }
624
- if (action === 'inspect') {
625
- const [artifactPath, ...extra] = raw;
626
- if (!artifactPath || extra.length)
627
- throw new Error('Usage: hyv lifecycle inspect artifact.json');
628
- canonical(inspectLifecycle(readJson(artifactPath)));
629
- return 0;
630
- }
631
- if (action === 'validate-final-approval' || action === 'finalize') {
632
- const { values, capability } = capabilityArguments(raw);
633
- if (action === 'validate-final-approval') {
634
- const [artifactPath, ...extra] = values;
635
- if (!artifactPath || extra.length || !capability)
636
- throw new Error('Usage: hyv lifecycle validate-final-approval artifact.json (--capability-stdin|--capability-file path)');
637
- const result = validateFinalApproval(readJson(artifactPath), capability, loadApprovalContext());
638
- canonical(result);
639
- return result.ok ? 0 : 2;
640
- }
641
- const [artifactPath, decisionPath, ...extra] = values;
642
- if (!artifactPath || !decisionPath || extra.length)
643
- throw new Error('Usage: hyv lifecycle finalize artifact.json decision.json [--capability-stdin|--capability-file path]');
644
- const decision = readJson(decisionPath);
645
- if (decision.decision === 'approve' && !capability)
646
- throw new Error('Approval requires a capability.');
647
- if (decision.decision === 'reject' && capability)
648
- throw new Error('Rejection does not accept a capability.');
649
- const result = finalizeLifecycle(readJson(artifactPath), decision, loadApprovalContext(), capability);
650
- canonical(result.ok ? result.artifact : { error: result.error });
651
- return result.ok && result.artifact.status === 'approved' ? 0 : 2;
652
- }
653
- throw new Error('Usage: hyv lifecycle <prepare-semantic|submit-verdict|inspect|validate-final-approval|finalize> ...');
654
- }
655
- if (command === 'learning') {
656
- const [action, ...raw] = rest;
657
- if (action === 'record-approved') {
658
- const { values, capability } = capabilityArguments(raw);
659
- const [readyPath, approvedPath, originalPath, candidatePath, profilePath, decisionPath, ...contextPaths] = values;
660
- if (!readyPath || !approvedPath || !originalPath || !candidatePath || !profilePath || !decisionPath || !capability)
661
- throw new Error('Usage: hyv learning record-approved ready.json approved.json original.md candidate.md profile.json decision.json [copy-spec.json] [writing-brief.json] (--capability-stdin|--capability-file path)');
662
- const context = prepareContext(contextPaths);
663
- const status = recordApprovedLearning({ ready: readJson(readyPath), approved: readJson(approvedPath), decision: readJson(decisionPath), capability, source: input(originalPath), candidate: input(candidatePath), profile: readProfile(profilePath), context: loadApprovalContext(), copySpec: context.copySpec, writingBrief: context.writingBrief });
664
- canonical({ status });
665
- return status === 'write_failed' ? 2 : 0;
666
- }
667
- const { values, options } = learningArguments(raw);
668
- const [profilePath, ...operands] = values;
669
- if (!action || !profilePath)
670
- throw new Error('Usage: hyv learning <show|inspect|add|record|ratify|supersede|migrate|clear> profile.json [value] [options]');
671
- const profile = readProfile(profilePath);
672
- if (action === 'show') {
673
- json({ profile: profileFingerprint(profile), preferences: composeLearning(profile, options) });
674
- return 0;
675
- }
676
- if (action === 'inspect') {
677
- if (Object.keys(options).length)
678
- throw new Error('Usage: hyv learning inspect profile.json');
679
- json(inspectLearning(profile));
680
- return 0;
681
- }
682
- if (action === 'add' || action === 'record') {
683
- const text = operands.join(' ').trim();
684
- if (!text)
685
- throw new Error('Usage: hyv learning record profile.json "instruction" [options]');
686
- const result = recordLearningInstruction(profile, text, options);
687
- json(action === 'add' ? { added: result.status === 'recorded' } : result);
688
- return 0;
689
- }
690
- if (action === 'ratify' || action === 'supersede') {
691
- const [eventId, ...extra] = operands;
692
- if (!eventId || extra.length)
693
- throw new Error(`Usage: hyv learning ${action} profile.json event-id [options]`);
694
- json(action === 'ratify' ? ratifyLearningEvent(requireProfileV3(profile), eventId, options) : supersedeLearningEvent(requireProfileV3(profile), eventId, options));
695
- return 0;
696
- }
697
- if (action === 'migrate') {
698
- const [targetPath, ...extra] = operands;
699
- if (!targetPath || extra.length || profile.version !== '2')
700
- throw new Error('Usage: hyv learning migrate source-v2.json target-v3.json [options]');
701
- json(migrateLearningV2ToV3(profile, requireProfileV3(readProfile(targetPath)), options));
702
- return 0;
703
- }
704
- if (action === 'clear') {
705
- if (operands.length || Object.keys(options).length)
706
- throw new Error('Usage: hyv learning clear profile.json');
707
- json({ cleared: clearLearning(profile) });
708
- return 0;
709
- }
710
- throw new Error('Usage: hyv learning <show|inspect|add|record|ratify|supersede|migrate|clear> profile.json [value] [options]');
711
- }
712
- if (command === 'patterns') {
713
- json({ version: RULESET_VERSION, rules: serializedRules() });
694
+ if (action === 'migrate') {
695
+ const [targetPath, ...extra] = operands;
696
+ if (!targetPath || extra.length || profile.version !== '2')
697
+ throw new Error('Usage: hyv learning migrate source-v2.json target-v3.json [options]');
698
+ json(migrateLearningV2ToV3(profile, requireProfileV3(readProfile(targetPath)), options));
714
699
  return 0;
715
700
  }
716
- if (command === 'mcp') {
717
- if (rest.length > 0)
718
- throw new Error('Usage: hyv mcp');
719
- await import('./mcp.js');
701
+ if (action === 'clear') {
702
+ if (operands.length || Object.keys(options).length)
703
+ throw new Error('Usage: hyv learning clear profile.json');
704
+ json({ cleared: clearLearning(profile) });
720
705
  return 0;
721
706
  }
722
- throw new Error(`${usage}.`);
707
+ throw new Error('Usage: hyv learning <show|inspect|add|record|ratify|supersede|migrate|clear> profile.json [value] [options]');
708
+ }
709
+ function runRecordApprovedLearning(args) {
710
+ const { values, capability } = capabilityArguments(args);
711
+ const [readyPath, approvedPath, originalPath, candidatePath, profilePath, decisionPath, ...contextPaths] = values;
712
+ if (!readyPath || !approvedPath || !originalPath || !candidatePath || !profilePath || !decisionPath || !capability)
713
+ throw new Error('Usage: hyv learning record-approved ready.json approved.json original.md candidate.md profile.json decision.json [copy-spec.json] [writing-brief.json] (--capability-stdin|--capability-file path)');
714
+ const context = prepareContext(contextPaths);
715
+ const status = recordApprovedLearning({ ready: readJson(readyPath), approved: readJson(approvedPath), decision: readJson(decisionPath), capability, source: input(originalPath), candidate: input(candidatePath), profile: readProfile(profilePath), context: loadApprovalContext(), copySpec: context.copySpec, writingBrief: context.writingBrief });
716
+ canonical({ status });
717
+ return status === 'write_failed' ? 2 : 0;
718
+ }
719
+ function runPatterns() {
720
+ json({ version: RULESET_VERSION, rules: serializedRules() });
721
+ return 0;
722
+ }
723
+ async function runMcp(args) {
724
+ if (args.length > 0)
725
+ throw new Error('Usage: hyv mcp');
726
+ await import('./mcp.js');
727
+ return 0;
728
+ }
729
+ const commandHandlers = {
730
+ agent: runAgent,
731
+ profile: runProfile,
732
+ analyze: runAnalyze,
733
+ hygiene: runHygiene,
734
+ 'inspect-hidden-text': runInspectHiddenText,
735
+ 'apply-hidden-text-policy': runApplyHiddenTextPolicy,
736
+ 'final-check': runFinalCheck,
737
+ 'fact-lint': runFactLint,
738
+ 'logic-lint': runLogicLint,
739
+ 'batch-analyze': runBatchAnalyze,
740
+ 'rewrite-prompt': runRewritePrompt,
741
+ 'prepare-rewrite': runPrepareRewrite,
742
+ 'apply-rewrite': runApplyRewrite,
743
+ 'prepare-judgment': runPrepareJudgment,
744
+ 'reduce-judgment': runReduceJudgment,
745
+ 'prepare-rebuild': runPrepareRebuild,
746
+ 'apply-rebuild': runApplyRebuild,
747
+ 'rebuild-writer-request': runRebuildWriterRequest,
748
+ verify: runVerify,
749
+ 'verify-spec': runVerifySpec,
750
+ lifecycle: runLifecycle,
751
+ learning: runLearning,
752
+ patterns: runPatterns,
753
+ mcp: runMcp,
754
+ };
755
+ export async function runCli(args) {
756
+ const [command, ...rest] = args;
757
+ const handler = command ? commandHandlers[command] : undefined;
758
+ if (!handler)
759
+ throw new Error(`${usage}.`);
760
+ return handler(rest);
723
761
  }
724
762
  void (async () => {
725
763
  try {