@causyne/agent 1.10.21 → 1.12.0

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.
Files changed (82) hide show
  1. package/docs/THIRD_PARTY_NOTICES.md +12 -0
  2. package/native-skills/media/professional-document-publishing/SKILL.md +44 -0
  3. package/native-skills/media/screenplay-and-shotlist-forge/SKILL.md +42 -0
  4. package/package.json +1 -1
  5. package/src/acp/client.js +235 -0
  6. package/src/acp/client.ts +282 -0
  7. package/src/acp/peerProfiles.js +122 -0
  8. package/src/acp/peerProfiles.ts +128 -0
  9. package/src/acp/protocol.js +55 -0
  10. package/src/acp/protocol.ts +456 -0
  11. package/src/acp/server.js +746 -0
  12. package/src/acp/server.ts +822 -0
  13. package/src/agentLoop.d.ts +64 -0
  14. package/src/agentLoop.js +156 -12
  15. package/src/approvalGrants.js +33 -0
  16. package/src/approvalGrants.ts +50 -0
  17. package/src/commands.js +203 -0
  18. package/src/compiledSkills.js +10 -0
  19. package/src/decisionPolicy.js +2 -0
  20. package/src/decisionPolicy.ts +1 -0
  21. package/src/documentEngine/antiSlopAuditor.js +156 -0
  22. package/src/documentEngine/antiSlopAuditor.ts +221 -0
  23. package/src/documentEngine/documentForge.js +443 -0
  24. package/src/documentEngine/documentForge.ts +519 -0
  25. package/src/documentEngine/screenplayFormatter.js +336 -0
  26. package/src/documentEngine/screenplayFormatter.ts +407 -0
  27. package/src/engines/cad.js +113 -0
  28. package/src/engines/cad.ts +128 -0
  29. package/src/engines/film.js +108 -0
  30. package/src/engines/film.ts +104 -0
  31. package/src/engines/installer.js +226 -0
  32. package/src/engines/installer.ts +248 -0
  33. package/src/engines/photo.js +126 -0
  34. package/src/engines/photo.ts +137 -0
  35. package/src/engines/registry.js +186 -0
  36. package/src/engines/registry.ts +185 -0
  37. package/src/engines/sound.js +117 -0
  38. package/src/engines/sound.ts +130 -0
  39. package/src/engines/types.js +1 -0
  40. package/src/engines/types.ts +73 -0
  41. package/src/entrypoint.js +13 -0
  42. package/src/execSafe.js +10 -13
  43. package/src/execSafe.ts +25 -0
  44. package/src/memoryManager.js +9 -3
  45. package/src/modelRouter.js +56 -123
  46. package/src/modelRouter.ts +134 -0
  47. package/src/observer/advisory.js +164 -0
  48. package/src/observer/advisory.ts +171 -0
  49. package/src/observer/coldObserver.js +462 -0
  50. package/src/observer/coldObserver.ts +540 -0
  51. package/src/observer/evidence.js +435 -0
  52. package/src/observer/evidence.ts +499 -0
  53. package/src/perception.js +303 -118
  54. package/src/perception.ts +387 -0
  55. package/src/procSignal.js +15 -16
  56. package/src/procSignal.ts +31 -0
  57. package/src/promptMentions.js +170 -0
  58. package/src/promptMentions.ts +212 -0
  59. package/src/sandbox.js +9 -1
  60. package/src/sessionJournal.js +12 -2
  61. package/src/sessionJournal.ts +12 -2
  62. package/src/textDiff.js +117 -109
  63. package/src/textDiff.ts +169 -0
  64. package/src/toolPacks.js +19 -8
  65. package/src/tools/documentForge.js +215 -0
  66. package/src/tools/documentForge.ts +265 -0
  67. package/src/tools/generateMediaViaApi.js +1 -1
  68. package/src/tools/nativeEngine.js +464 -0
  69. package/src/tools/nativeEngine.ts +433 -0
  70. package/src/tools/openSourceToolProvisioner.js +510 -0
  71. package/src/tools/openSourceToolProvisioner.ts +590 -0
  72. package/src/tools/peerAgent.js +102 -0
  73. package/src/tools/peerAgent.ts +116 -0
  74. package/src/tools/registry.js +6 -1
  75. package/src/tui/completion.js +98 -42
  76. package/src/tui/prompt.js +17 -17
  77. package/src/uncertainty.js +93 -205
  78. package/src/uncertainty.ts +255 -0
  79. package/src/utils/paths.js +15 -18
  80. package/src/utils/paths.ts +36 -0
  81. package/src/vfeTracker.js +122 -181
  82. package/src/vfeTracker.ts +242 -0
package/src/commands.js CHANGED
@@ -83,6 +83,56 @@ export const COMMANDS = [
83
83
  }
84
84
  },
85
85
 
86
+ {
87
+ name: 'cd',
88
+ aliases: ['cwd', 'workspace'],
89
+ scope: 'local',
90
+ usage: '/cd [directory]',
91
+ description: 'View or change active working directory and project focus',
92
+ complete: () => {
93
+ try {
94
+ const entries = fs.readdirSync(process.cwd(), { withFileTypes: true });
95
+ return entries
96
+ .filter(e => e.isDirectory() && !e.name.startsWith('.'))
97
+ .map(e => ({
98
+ value: e.name.includes(' ') ? `"${e.name}"` : e.name,
99
+ label: e.name + '/',
100
+ description: 'directory'
101
+ }));
102
+ } catch (e) {
103
+ return [];
104
+ }
105
+ },
106
+ run: async (argv, ctx) => {
107
+ const target = argv.join(' ').trim().replace(/^["']|["']$/g, '');
108
+ if (!target) {
109
+ return ok(`Current working directory: ${process.cwd()}`);
110
+ }
111
+ const resolved = path.resolve(process.cwd(), target.replace(/^~\//, os.homedir() + '/'));
112
+ if (!fs.existsSync(resolved)) {
113
+ return fail(`Directory not found: ${resolved}`);
114
+ }
115
+ const stat = fs.statSync(resolved);
116
+ if (!stat.isDirectory()) {
117
+ return fail(`Not a directory: ${resolved}`);
118
+ }
119
+ try {
120
+ process.chdir(resolved);
121
+ } catch (err) {
122
+ return fail(`Cannot switch to ${resolved}: ${err.message}`);
123
+ }
124
+ if (ctx.prompt && typeof ctx.prompt.setWorkingRoot === 'function') {
125
+ ctx.prompt.setWorkingRoot(resolved);
126
+ }
127
+ if (ctx.loop && ctx.loop.perception) {
128
+ try {
129
+ ctx.loop.workspaceContext = await ctx.loop.perception.buildContext(resolved);
130
+ } catch (e) {}
131
+ }
132
+ return ok(`Working directory changed to: ${resolved}`);
133
+ }
134
+ },
135
+
86
136
  {
87
137
  name: 'skill',
88
138
  scope: 'local',
@@ -878,6 +928,159 @@ export const COMMANDS = [
878
928
  run: (argv, ctx) => ok(buildStatusText({ loop: ctx.loop || null }))
879
929
  },
880
930
 
931
+ {
932
+ name: 'observer',
933
+ scope: 'local',
934
+ usage: '/observer [status|toggle|mode <deterministic|advisory>|endpoint <url|none>|model <name>|strictness <relaxed|standard|strict>|test|audit|reset]',
935
+ description: 'Inspect or configure the Cold Observer',
936
+ dialogTitle: 'Cold Observer',
937
+ run: async (argv) => {
938
+ const { coldObserver } = await import('./observer/coldObserver.js');
939
+ const sub = (argv[0] || 'status').toLowerCase();
940
+
941
+ if (sub === 'toggle') {
942
+ const current = coldObserver.getConfig();
943
+ coldObserver.updateConfig({ enabled: !current.enabled });
944
+ return ok(`Cold Observer is now ${!current.enabled ? 'ENABLED' : 'DISABLED'}.`);
945
+ }
946
+
947
+ if (sub === 'mode') {
948
+ const targetMode = String(argv[1] || '').toLowerCase();
949
+ if (!['deterministic', 'advisory', 'local', 'hybrid'].includes(targetMode)) {
950
+ return fail('Invalid mode. Choose: deterministic or advisory.');
951
+ }
952
+ coldObserver.updateConfig({ mode: targetMode });
953
+ return ok(`Cold Observer mode set to "${coldObserver.getConfig().mode}".`);
954
+ }
955
+
956
+ if (sub === 'endpoint') {
957
+ const target = String(argv[1] || '').trim();
958
+ try {
959
+ coldObserver.updateConfig({ endpoint: target === 'none' ? '' : target });
960
+ } catch (error) {
961
+ return fail(error instanceof Error ? error.message : 'Invalid endpoint.');
962
+ }
963
+ const endpoint = coldObserver.getConfig().endpoint;
964
+ return ok(endpoint ? `Advisory endpoint set to ${endpoint}.` : 'Advisory endpoint cleared.');
965
+ }
966
+
967
+ if (sub === 'model') {
968
+ const target = String(argv[1] || '').trim();
969
+ coldObserver.updateConfig({ model: target === 'none' ? '' : target });
970
+ const model = coldObserver.getConfig().model;
971
+ return ok(model ? `Advisory model set to ${model}.` : 'Advisory model cleared.');
972
+ }
973
+
974
+ if (sub === 'strictness') {
975
+ const target = String(argv[1] || '').toLowerCase();
976
+ if (!['relaxed', 'standard', 'strict', 'moderate', 'paranoid'].includes(target)) {
977
+ return fail('Invalid strictness. Choose: relaxed, standard, or strict.');
978
+ }
979
+ coldObserver.updateConfig({ strictness: target });
980
+ return ok(`Cold Observer strictness set to "${coldObserver.getConfig().strictness}".`);
981
+ }
982
+
983
+ if (sub === 'test') {
984
+ const health = await coldObserver.healthCheck();
985
+ if (!health.endpoint) {
986
+ return ok('No advisory endpoint configured. The deterministic observer needs no endpoint and remains active.');
987
+ }
988
+ return ok([
989
+ `Endpoint: ${health.endpoint}`,
990
+ `Model: ${health.model || '(unset)'}`,
991
+ `Healthy: ${health.healthy ? 'yes' : 'no'} (${health.latencyMs}ms)`,
992
+ `Detail: ${health.detail}`
993
+ ].join('\n'));
994
+ }
995
+
996
+ if (sub === 'reset') {
997
+ coldObserver.updateConfig({
998
+ enabled: true,
999
+ mode: 'deterministic',
1000
+ endpoint: '',
1001
+ model: '',
1002
+ timeoutMs: 800,
1003
+ strictness: 'standard'
1004
+ });
1005
+ return ok('Cold Observer configuration reset to defaults.');
1006
+ }
1007
+
1008
+ if (sub === 'audit') {
1009
+ const audits = coldObserver.getAuditHistory();
1010
+ if (audits.length === 0) {
1011
+ return ok('No Cold Observer audit records yet.');
1012
+ }
1013
+ const lines = audits.slice(-10).map((a) => {
1014
+ const time = new Date(a.timestamp).toLocaleTimeString();
1015
+ const tag = a.type === 'mutation' ? `[mutation ${a.tool || ''}]` : '[verification]';
1016
+ const score = typeof a.riskScore === 'number' ? `(risk ${(a.riskScore * 100).toFixed(0)}%)` : '';
1017
+ const veto = a.veto ? 'VETO' : 'pass';
1018
+ return `${time} ${tag} ${veto} ${score} ${a.details}`;
1019
+ });
1020
+ return ok(`Recent Cold Observer audits (last 10):\n\n${lines.join('\n')}`);
1021
+ }
1022
+
1023
+ const cfg = coldObserver.getConfig();
1024
+ const audits = coldObserver.getAuditHistory();
1025
+ const vetoes = audits.filter((a) => a.veto).length;
1026
+ return ok([
1027
+ 'Cold Observer',
1028
+ '──────────────────────────────────────────────',
1029
+ `Status: ${cfg.enabled ? 'Active (mutations and completion claims)' : 'Disabled'}`,
1030
+ `Mode: ${cfg.mode.toUpperCase()}`,
1031
+ `Strictness: ${cfg.strictness}`,
1032
+ `Advisory: ${cfg.endpoint ? `${cfg.model || '(model unset)'} at ${cfg.endpoint}` : 'not configured (deterministic only)'}`,
1033
+ `Audit events: ${audits.length} recorded (${vetoes} vetoes enforced)`,
1034
+ '',
1035
+ 'Subcommands:',
1036
+ ' /observer toggle Enable or disable protection',
1037
+ ' /observer mode <deterministic|advisory> Choose the review mode',
1038
+ ' /observer endpoint <url|none> Set a loopback advisory endpoint',
1039
+ ' /observer model <name> Set the advisory model name',
1040
+ ' /observer strictness <relaxed|standard|strict>',
1041
+ ' /observer test Probe the advisory endpoint',
1042
+ ' /observer audit Inspect recent audits',
1043
+ ' /observer reset Restore defaults'
1044
+ ].join('\n'));
1045
+ }
1046
+ },
1047
+
1048
+ {
1049
+ name: 'acp',
1050
+ scope: 'local',
1051
+ usage: '/acp [status|peers]',
1052
+ description: 'Agent Client Protocol (ACP) server and peer delegation status',
1053
+ dialogTitle: 'Agent Client Protocol',
1054
+ run: async (argv) => {
1055
+ const sub = (argv[0] || 'status').toLowerCase();
1056
+ if (sub === 'peer' || sub === 'peers') {
1057
+ const { loadPeerProfiles, peerProfilesPath } = await import('./acp/peerProfiles.js');
1058
+ const profiles = loadPeerProfiles();
1059
+ return ok([
1060
+ 'Peer delegation (ACP)',
1061
+ '──────────────────────────────────────────────',
1062
+ `Profiles file: ${peerProfilesPath()}`,
1063
+ `Configured: ${profiles.length === 0 ? 'none' : profiles.map((p) => `${p.id} (${p.policy})`).join(', ')}`,
1064
+ '',
1065
+ 'The model selects a profile id and writes a prompt. Executable, arguments,',
1066
+ 'working directory, and environment always come from the profile file.'
1067
+ ].join('\n'));
1068
+ }
1069
+ return ok([
1070
+ 'Agent Client Protocol (ACP) - Causyne Agent',
1071
+ '──────────────────────────────────────────────',
1072
+ 'Version: ACP v1 (JSON-RPC 2.0 over stdio)',
1073
+ 'Server command: causyne acp',
1074
+ 'Wire: newline-delimited JSON-RPC',
1075
+ 'Sessions: session/new, session/prompt, session/cancel, session/update',
1076
+ 'Optional: session/list, session/close, session/set_mode',
1077
+ 'Workspace: one workspace per server process',
1078
+ '',
1079
+ 'Run "causyne acp" to connect this agent to any ACP client.'
1080
+ ].join('\n'));
1081
+ }
1082
+ },
1083
+
881
1084
  {
882
1085
  name: 'exit',
883
1086
  aliases: ['quit'],
@@ -329,6 +329,16 @@ export const COMPILED_SKILLS = {
329
329
  "description": "Automate photo editing, graphic composition, text typography, and image format exports using native Photo Studio automation. Use when a task requires batch image edits, graphic layout creation, resizing, color adjustment, or PSD/PNG/JPG/WEBP asset generation.",
330
330
  "content": "---\nname: photo-studio-automation\ndescription: Automate photo editing, graphic composition, text typography, and image format exports using native Photo Studio automation. Use when a task requires batch image edits, graphic layout creation, resizing, color adjustment, or PSD/PNG/JPG/WEBP asset generation.\n---\n\n# Photo Studio Automation\n\nDirect script execution beats screenshot clicking every time: it is exact, sub-second, costs zero vision tokens, and never misclicks because a window moved. Use the native Creative Studio bridge via `creative_apps` with `action: \"studio_edit\"` and `host: \"photo-studio\"`.\n\n## Workflow\n\n1. Verify environment and inspect installed creative hosts.\n - Run `creative_apps` with `action: \"status\"`.\n - Confirm Photo Studio availability before assembling jobs.\n - **Done when:** host availability is confirmed.\n\n2. Establish workspace paths.\n - All inputs and outputs must reside strictly within the active workspace.\n - The output file must not already exist (the runtime enforces collision prevention).\n - Supported output extensions: `.psd`, `.png`, `.jpg`, `.jpeg`, `.webp`.\n - **Done when:** source asset and clean target output paths are defined.\n\n3. Plan layer hierarchy and typography before applying edits.\n - If starting from scratch, omit `input` to let the engine create a canvas (1920x1080 standard).\n - If transforming existing art, provide `input` path.\n - Layer modifications should specify explicit `name`, `opacity`, `visible`, and `blendMode`.\n - Typography actions should define `text`, `x`, `y`, `size`, and font family.\n - **Done when:** sequence of edit actions is organized logically from background to foreground.\n\n4. Apply color adjustments and canvas sizing.\n - Use `resize` or `crop` early in the action pipeline to establish composition geometry.\n - Use `adjust_color` with `brightness` (-100..100) and `contrast` (-100..100) on target layers for grading.\n - If delivering flat web assets (e.g., PNG or WEBP), include `flatten` at the end of the action chain.\n - **Done when:** geometric and tonal parameters match design requirements.\n\n5. Execute batch and verify output.\n - Invoke `creative_apps` with `action: \"studio_edit\"`, `host: \"photo-studio\"`, `output`, and `actions`.\n - The runtime verifies execution receipt and confirms nonempty file generation.\n - **Done when:** output file exists, has nonzero byte count, and matches requested specifications.\n\n## Failure Modes Worth Naming\n\n- **Overwriting existing file:** The engine halts if output exists. Specify a distinct or versioned filename.\n- **Outside workspace:** All paths must resolve inside the workspace root. Do not reference temporary directories or home root.\n- **Missing host:** If the host is not installed, the tool gracefully reports installation status. Propose alternative image processing or check system paths.\n- **Out-of-range layer index:** Layer indices start at 0. Ensure index matches existing layer count.\n\n## Verification\n\n- `action: \"studio_edit\"` returns `success: true`.\n- Output file exists on disk within workspace.\n- File size is non-zero.\n- Format matches target extension (.psd, .png, .jpg, or .webp).\n"
331
331
  },
332
+ "professional-document-publishing": {
333
+ "name": "professional-document-publishing",
334
+ "description": "Generate publication-grade PDF documents, grant proposals, financial sheets, and technical reports using HTML/CSS Paged Media and Headless Chrome. Enforces visual quality inspection, under 2MB compliance, and mathematical integrity.",
335
+ "content": "---\nname: professional-document-publishing\ndescription: Generate publication-grade PDF documents, grant proposals, financial sheets, and technical reports using HTML/CSS Paged Media and Headless Chrome. Enforces visual quality inspection, under 2MB compliance, and mathematical integrity.\n---\n\n# Professional Document Publishing & Harness\n\nFrontier LLMs and efficient models produce equally stunning, publication-ready documents when guided by this harness methodology.\n\nNever assemble print layouts through raw Python scripts. Always author in semantic HTML5 plus CSS Paged Media, compile via Headless Chrome, and visually inspect the rendered output.\n\n## Workflow\n\n1. Prepare structured data and schemas.\n - Keep numeric budget and scheduling data in structured JSON format.\n - Run math validation with `document_forge` (`action: \"audit_budget\"`).\n - **Done when:** all numbers are validated against the single source of truth.\n\n2. Compile document markup and styles.\n - Author page layouts in HTML using standard CSS `@page` rules (`size: A4 portrait; margin: 20mm 18mm 18mm 18mm;`).\n - Use `@page cover { margin: 0; }` for full-bleed cover banners without white borders.\n - Force `-webkit-print-color-adjust: exact; print-color-adjust: exact;` so backgrounds and gradients render faithfully.\n - Prevent mid-table row cuts with `tr { page-break-inside: avoid; }`.\n - Prevent orphan headers with `h1, h2, h3 { page-break-after: avoid; }`.\n - Compile via `document_forge` (`action: \"compile_document\"`).\n - **Done when:** HTML markup and CSS paged styles are written to disk.\n\n3. Render to vector PDF via Headless Chrome.\n - Invoke `document_forge` (`action: \"render_pdf\"`, `sourceHtmlPath`, `outputPdfPath`).\n - **Done when:** vector PDF file exists on disk with non-zero size.\n\n4. Inspect pages visually and audit compliance.\n - Extract page images via `document_forge` (`action: \"inspect_pages\"`).\n - Verify page fill density: flag and repair any pages with less than 25% text coverage.\n - Confirm PDF file size is below 2,048 KB for portal compliance.\n - Audit text content for long em-dashes and AI clichés with `document_forge` (`action: \"audit_text\"`).\n - **Done when:** all pages pass visual density check and size constraints.\n\n## Verification\n\n- `document_forge` returns `success: true`.\n- Output PDF file size is non-zero and under 2,048 KB.\n- Extracted page images show no clipped text or orphaned headers.\n- Mathematical totals match across all sections.\n"
336
+ },
337
+ "screenplay-and-shotlist-forge": {
338
+ "name": "screenplay-and-shotlist-forge",
339
+ "description": "Format professional Hollywood screenplays in Courier 12pt, create director production shot lists, and build voiceover timing cue sheets with Words-Per-Minute pacing analysis. Use for movie scripts, video storytelling, documentary shotlists, and audio dubbing timelines.",
340
+ "content": "---\nname: screenplay-and-shotlist-forge\ndescription: Format professional Hollywood screenplays in Courier 12pt, create director production shot lists, and build voiceover timing cue sheets with Words-Per-Minute pacing analysis. Use for movie scripts, video storytelling, documentary shotlists, and audio dubbing timelines.\n---\n\n# Screenplay & Production Shot List Forge\n\nHigh-end cinematic storytelling and video production require standardized industry formatting so that directors, cinematographers, and editors can immediately execute on set and in the edit suite.\n\n## Specifications\n\n- **Screenplay Typography:** Courier 12pt monospaced font, exactly 6 lines per inch vertical rhythm.\n- **Screenplay Margins:** Left margin 1.5 inches; right, top, and bottom margins 1.0 inch.\n- **Pacing Standard:** Voiceover narration moves at 130 to 155 Words-Per-Minute for natural documentary cadence.\n\n## Workflow\n\n1. Format screenplay elements and layout.\n - Author scenes using `document_forge` (`action: \"format_screenplay\"`, `screenplaySpec`).\n - Format scene headings in uppercase, character cues indented 2.2 inches, and dialogue width constrained to 3.5 inches.\n - **Done when:** script HTML and CSS with Courier 12pt specifications are generated.\n\n2. Build director's production shot list.\n - Generate production shot lists with `document_forge` (`action: \"format_shotlist\"`, `shotList`).\n - Assign camera framing (EWS, WS, MS, CU, ECU), lenses, movement, and audio cues.\n - **Done when:** structured shot list grid is compiled with cumulative duration estimates.\n\n3. Analyze voiceover timing and narration pacing.\n - Audit narration pacing with `document_forge` (`action: \"analyze_vo\"`, `voBlocks`).\n - Ensure word density stays within 130 to 155 WPM for optimal documentary pacing.\n - **Done when:** pacing status is confirmed as optimal across all audio blocks.\n\n4. Render and verify publication files.\n - Render scripts or shot lists to vector PDF via `document_forge` (`action: \"render_pdf\"`).\n - **Done when:** output PDF files exist and are verified visually.\n\n## Verification\n\n- `document_forge` returns `success: true`.\n- Screenplay HTML contains Courier 12pt typography and 1.5-inch left margin.\n- Shot list table summarizes total shots and total runtime.\n- Voiceover analysis confirms pacing within target WPM limits.\n"
341
+ },
332
342
  "video-timeline-assembly": {
333
343
  "name": "video-timeline-assembly",
334
344
  "description": "Assemble video timelines, import media clips to sequences, place markers, make precision edits, and export project files using native Video Studio automation. Use when a task requires automated video sequence building, cutting, multicam timeline layout, or PRPROJ/XML project generation.",
@@ -53,6 +53,8 @@ export function requiresImplementationPlan(prompt, archetype = '', confidence =
53
53
  export function isMutatingToolCall(toolName, args = {}) {
54
54
  if (toolName === 'creative_apps')
55
55
  return args.action !== 'status';
56
+ if (toolName === 'native_engine')
57
+ return !['status', 'catalog', 'describe', 'inspect', 'probe'].includes(String(args.action ?? ''));
56
58
  if (MUTATING_TOOLS.has(toolName)) {
57
59
  if (toolName === 'sysRun' || toolName === 'sysRunBg') {
58
60
  const command = String(args.command ?? '');
@@ -91,6 +91,7 @@ export function requiresImplementationPlan(prompt: string, archetype = '', confi
91
91
 
92
92
  export function isMutatingToolCall(toolName: string, args: Record<string, unknown> = {}): boolean {
93
93
  if (toolName === 'creative_apps') return args.action !== 'status';
94
+ if (toolName === 'native_engine') return !['status', 'catalog', 'describe', 'inspect', 'probe'].includes(String(args.action ?? ''));
94
95
  if (MUTATING_TOOLS.has(toolName)) {
95
96
  if (toolName === 'sysRun' || toolName === 'sysRunBg') {
96
97
  const command = String(args.command ?? '');
@@ -0,0 +1,156 @@
1
+ /*
2
+ * Copyright (c) 2026 Causyne.
3
+ * SPDX-License-Identifier: BUSL-1.1
4
+ *
5
+ * Anti-AI Slop & Humanization Compliance Auditor.
6
+ * Enforces authentic human cadence, strict hyphenation rules, and zero ungrounded placeholders.
7
+ */
8
+ const BANNED_LONG_DASHES = /[—–]/g;
9
+ const AI_SLOP_CLICHES_ID = [
10
+ /\bsangatlah\b/i,
11
+ /\btak terbantahkan\b/i,
12
+ /\brevolusioner\b/i,
13
+ /\bgame[- ]?changer\b/i,
14
+ /\bdi era yang serba\b/i,
15
+ /\bmari kita\b/i,
16
+ /\btidak dapat dipungkiri\b/i,
17
+ /\bperlu diingat bahwa\b/i,
18
+ /\bdalam lanskap modern\b/i,
19
+ /\bmerupakan sebuah bukti nyata\b/i
20
+ ];
21
+ const AI_SLOP_CLICHES_EN = [
22
+ /\bdelve(?:s|d|ing)?\b/i,
23
+ /\bcrucial(?:ly)?\b/i,
24
+ /\btestament\b/i,
25
+ /\btapestry\b/i,
26
+ /\bgame[- ]?changer\b/i,
27
+ /\brevolutionize(?:d|s|ing)?\b/i,
28
+ /\bin conclusion\b/i,
29
+ /\bit is important to remember\b/i,
30
+ /\bbeacon\b/i,
31
+ /\bfoster(?:s|ing)?\b/i,
32
+ /\bunderscore(?:s|d|ing)?\b/i,
33
+ /\bspearhead(?:ed|ing)?\b/i,
34
+ /\brealm\b/i,
35
+ /\bparamount\b/i,
36
+ /\bholistic approach\b/i
37
+ ];
38
+ const PLACEHOLDER_BRACKETS = [
39
+ /\[(?:insert|masukkan|isi|tbd|todo|placeholder|nama|tanggal|lokasi)[^\]]*\]/i,
40
+ /<(?:insert|masukkan|isi|tbd|todo|placeholder)[^>]*>/i
41
+ ];
42
+ /**
43
+ * Scan raw text or HTML content for AI slop, long em-dashes, and placeholder tokens.
44
+ */
45
+ export function auditTextContent(content, options = {}) {
46
+ const findings = [];
47
+ const lines = (content || '').split(/\r?\n/);
48
+ const lang = options.language || 'both';
49
+ const strictDashes = options.strictDashes !== false;
50
+ lines.forEach((line, idx) => {
51
+ const lineNum = idx + 1;
52
+ // 1. Long em-dash check (enforce short hyphen -)
53
+ if (strictDashes) {
54
+ const dashMatches = line.match(BANNED_LONG_DASHES);
55
+ if (dashMatches) {
56
+ findings.push({
57
+ rule: 'no_long_em_dash',
58
+ severity: 'error',
59
+ match: dashMatches[0] || '—',
60
+ line: lineNum,
61
+ message: 'Found long em-dash (—/–). Use standard short hyphen (-) to preserve natural human typing rhythm.'
62
+ });
63
+ }
64
+ }
65
+ // 2. Placeholder checks
66
+ for (const pat of PLACEHOLDER_BRACKETS) {
67
+ const m = line.match(pat);
68
+ if (m) {
69
+ findings.push({
70
+ rule: 'no_ungrounded_placeholders',
71
+ severity: 'error',
72
+ match: m[0],
73
+ line: lineNum,
74
+ message: `Found ungrounded template placeholder "${m[0]}". Must be replaced with verified real data.`
75
+ });
76
+ }
77
+ }
78
+ // 3. AI Slop Cliches (ID)
79
+ if (lang === 'id' || lang === 'both') {
80
+ for (const pat of AI_SLOP_CLICHES_ID) {
81
+ const m = line.match(pat);
82
+ if (m) {
83
+ findings.push({
84
+ rule: 'anti_ai_slop_phrase_id',
85
+ severity: 'warning',
86
+ match: m[0],
87
+ line: lineNum,
88
+ message: `Found formulaic AI phrase "${m[0]}". Rewrite in authentic, direct human voice.`
89
+ });
90
+ }
91
+ }
92
+ }
93
+ // 4. AI Slop Cliches (EN)
94
+ if (lang === 'en' || lang === 'both') {
95
+ for (const pat of AI_SLOP_CLICHES_EN) {
96
+ const m = line.match(pat);
97
+ if (m) {
98
+ findings.push({
99
+ rule: 'anti_ai_slop_phrase_en',
100
+ severity: 'warning',
101
+ match: m[0],
102
+ line: lineNum,
103
+ message: `Found generic AI trope "${m[0]}". Replace with concrete, factual language.`
104
+ });
105
+ }
106
+ }
107
+ }
108
+ });
109
+ return {
110
+ clean: findings.filter((f) => f.severity === 'error').length === 0,
111
+ findings
112
+ };
113
+ }
114
+ /**
115
+ * Audit arithmetic integrity across line items, category subtotals, and gross-up taxes.
116
+ */
117
+ export function auditBudgetArithmetic(spec) {
118
+ const itemErrors = [];
119
+ const categoryErrors = [];
120
+ let grandTotal = 0;
121
+ for (const cat of spec.categories) {
122
+ let catComputedSubtotal = 0;
123
+ for (const item of cat.items) {
124
+ const expectedItemTotal = item.volume * item.frequency * item.unitPrice;
125
+ if (Math.round(expectedItemTotal) !== Math.round(item.total)) {
126
+ itemErrors.push(`Item "${item.name}" math mismatch: ${item.volume} * ${item.frequency} * ${item.unitPrice} = ${expectedItemTotal}, but recorded total is ${item.total}`);
127
+ }
128
+ catComputedSubtotal += item.total;
129
+ }
130
+ if (cat.subtotal !== undefined && Math.round(cat.subtotal) !== Math.round(catComputedSubtotal)) {
131
+ categoryErrors.push(`Category "${cat.name}" subtotal mismatch: items sum to ${catComputedSubtotal}, but recorded subtotal is ${cat.subtotal}`);
132
+ }
133
+ grandTotal += catComputedSubtotal;
134
+ }
135
+ let grossCalculated;
136
+ let taxCalculated;
137
+ let differenceFromTarget;
138
+ if (spec.grossUpTaxRate !== undefined) {
139
+ const divisor = 1 - spec.grossUpTaxRate;
140
+ grossCalculated = Math.round(grandTotal / divisor);
141
+ taxCalculated = grossCalculated - grandTotal;
142
+ if (spec.targetGross !== undefined) {
143
+ differenceFromTarget = grossCalculated - spec.targetGross;
144
+ }
145
+ }
146
+ const valid = itemErrors.length === 0 && categoryErrors.length === 0 && (differenceFromTarget === undefined || differenceFromTarget === 0);
147
+ return {
148
+ valid,
149
+ itemErrors,
150
+ categoryErrors,
151
+ totalCalculated: grandTotal,
152
+ grossCalculated,
153
+ taxCalculated,
154
+ differenceFromTarget
155
+ };
156
+ }
@@ -0,0 +1,221 @@
1
+ /*
2
+ * Copyright (c) 2026 Causyne.
3
+ * SPDX-License-Identifier: BUSL-1.1
4
+ *
5
+ * Anti-AI Slop & Humanization Compliance Auditor.
6
+ * Enforces authentic human cadence, strict hyphenation rules, and zero ungrounded placeholders.
7
+ */
8
+
9
+ export interface SlopAuditFinding {
10
+ rule: string;
11
+ severity: 'error' | 'warning';
12
+ match: string;
13
+ line?: number;
14
+ message: string;
15
+ }
16
+
17
+ export interface ArithmeticItem {
18
+ name: string;
19
+ volume: number;
20
+ frequency: number;
21
+ unitPrice: number;
22
+ total: number;
23
+ }
24
+
25
+ export interface ArithmeticCategory {
26
+ code: string;
27
+ name: string;
28
+ items: ArithmeticItem[];
29
+ subtotal?: number;
30
+ }
31
+
32
+ export interface ArithmeticBudgetSpec {
33
+ categories: ArithmeticCategory[];
34
+ grossUpTaxRate?: number; // e.g. 0.025 for 2.5% PPh 21
35
+ targetGross?: number;
36
+ }
37
+
38
+ const BANNED_LONG_DASHES = /[—–]/g;
39
+
40
+ const AI_SLOP_CLICHES_ID = [
41
+ /\bsangatlah\b/i,
42
+ /\btak terbantahkan\b/i,
43
+ /\brevolusioner\b/i,
44
+ /\bgame[- ]?changer\b/i,
45
+ /\bdi era yang serba\b/i,
46
+ /\bmari kita\b/i,
47
+ /\btidak dapat dipungkiri\b/i,
48
+ /\bperlu diingat bahwa\b/i,
49
+ /\bdalam lanskap modern\b/i,
50
+ /\bmerupakan sebuah bukti nyata\b/i
51
+ ];
52
+
53
+ const AI_SLOP_CLICHES_EN = [
54
+ /\bdelve(?:s|d|ing)?\b/i,
55
+ /\bcrucial(?:ly)?\b/i,
56
+ /\btestament\b/i,
57
+ /\btapestry\b/i,
58
+ /\bgame[- ]?changer\b/i,
59
+ /\brevolutionize(?:d|s|ing)?\b/i,
60
+ /\bin conclusion\b/i,
61
+ /\bit is important to remember\b/i,
62
+ /\bbeacon\b/i,
63
+ /\bfoster(?:s|ing)?\b/i,
64
+ /\bunderscore(?:s|d|ing)?\b/i,
65
+ /\bspearhead(?:ed|ing)?\b/i,
66
+ /\brealm\b/i,
67
+ /\bparamount\b/i,
68
+ /\bholistic approach\b/i
69
+ ];
70
+
71
+ const PLACEHOLDER_BRACKETS = [
72
+ /\[(?:insert|masukkan|isi|tbd|todo|placeholder|nama|tanggal|lokasi)[^\]]*\]/i,
73
+ /<(?:insert|masukkan|isi|tbd|todo|placeholder)[^>]*>/i
74
+ ];
75
+
76
+ /**
77
+ * Scan raw text or HTML content for AI slop, long em-dashes, and placeholder tokens.
78
+ */
79
+ export function auditTextContent(content: string, options: { language?: 'id' | 'en' | 'both'; strictDashes?: boolean } = {}): {
80
+ clean: boolean;
81
+ findings: SlopAuditFinding[];
82
+ } {
83
+ const findings: SlopAuditFinding[] = [];
84
+ const lines = (content || '').split(/\r?\n/);
85
+ const lang = options.language || 'both';
86
+ const strictDashes = options.strictDashes !== false;
87
+
88
+ lines.forEach((line, idx) => {
89
+ const lineNum = idx + 1;
90
+
91
+ // 1. Long em-dash check (enforce short hyphen -)
92
+ if (strictDashes) {
93
+ const dashMatches = line.match(BANNED_LONG_DASHES);
94
+ if (dashMatches) {
95
+ findings.push({
96
+ rule: 'no_long_em_dash',
97
+ severity: 'error',
98
+ match: dashMatches[0] || '—',
99
+ line: lineNum,
100
+ message: 'Found long em-dash (—/–). Use standard short hyphen (-) to preserve natural human typing rhythm.'
101
+ });
102
+ }
103
+ }
104
+
105
+ // 2. Placeholder checks
106
+ for (const pat of PLACEHOLDER_BRACKETS) {
107
+ const m = line.match(pat);
108
+ if (m) {
109
+ findings.push({
110
+ rule: 'no_ungrounded_placeholders',
111
+ severity: 'error',
112
+ match: m[0],
113
+ line: lineNum,
114
+ message: `Found ungrounded template placeholder "${m[0]}". Must be replaced with verified real data.`
115
+ });
116
+ }
117
+ }
118
+
119
+ // 3. AI Slop Cliches (ID)
120
+ if (lang === 'id' || lang === 'both') {
121
+ for (const pat of AI_SLOP_CLICHES_ID) {
122
+ const m = line.match(pat);
123
+ if (m) {
124
+ findings.push({
125
+ rule: 'anti_ai_slop_phrase_id',
126
+ severity: 'warning',
127
+ match: m[0],
128
+ line: lineNum,
129
+ message: `Found formulaic AI phrase "${m[0]}". Rewrite in authentic, direct human voice.`
130
+ });
131
+ }
132
+ }
133
+ }
134
+
135
+ // 4. AI Slop Cliches (EN)
136
+ if (lang === 'en' || lang === 'both') {
137
+ for (const pat of AI_SLOP_CLICHES_EN) {
138
+ const m = line.match(pat);
139
+ if (m) {
140
+ findings.push({
141
+ rule: 'anti_ai_slop_phrase_en',
142
+ severity: 'warning',
143
+ match: m[0],
144
+ line: lineNum,
145
+ message: `Found generic AI trope "${m[0]}". Replace with concrete, factual language.`
146
+ });
147
+ }
148
+ }
149
+ }
150
+ });
151
+
152
+ return {
153
+ clean: findings.filter((f) => f.severity === 'error').length === 0,
154
+ findings
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Audit arithmetic integrity across line items, category subtotals, and gross-up taxes.
160
+ */
161
+ export function auditBudgetArithmetic(spec: ArithmeticBudgetSpec): {
162
+ valid: boolean;
163
+ itemErrors: string[];
164
+ categoryErrors: string[];
165
+ totalCalculated: number;
166
+ grossCalculated?: number | undefined;
167
+ taxCalculated?: number | undefined;
168
+ differenceFromTarget?: number | undefined;
169
+ } {
170
+ const itemErrors: string[] = [];
171
+ const categoryErrors: string[] = [];
172
+ let grandTotal = 0;
173
+
174
+ for (const cat of spec.categories) {
175
+ let catComputedSubtotal = 0;
176
+
177
+ for (const item of cat.items) {
178
+ const expectedItemTotal = item.volume * item.frequency * item.unitPrice;
179
+ if (Math.round(expectedItemTotal) !== Math.round(item.total)) {
180
+ itemErrors.push(
181
+ `Item "${item.name}" math mismatch: ${item.volume} * ${item.frequency} * ${item.unitPrice} = ${expectedItemTotal}, but recorded total is ${item.total}`
182
+ );
183
+ }
184
+ catComputedSubtotal += item.total;
185
+ }
186
+
187
+ if (cat.subtotal !== undefined && Math.round(cat.subtotal) !== Math.round(catComputedSubtotal)) {
188
+ categoryErrors.push(
189
+ `Category "${cat.name}" subtotal mismatch: items sum to ${catComputedSubtotal}, but recorded subtotal is ${cat.subtotal}`
190
+ );
191
+ }
192
+
193
+ grandTotal += catComputedSubtotal;
194
+ }
195
+
196
+ let grossCalculated: number | undefined;
197
+ let taxCalculated: number | undefined;
198
+ let differenceFromTarget: number | undefined;
199
+
200
+ if (spec.grossUpTaxRate !== undefined) {
201
+ const divisor = 1 - spec.grossUpTaxRate;
202
+ grossCalculated = Math.round(grandTotal / divisor);
203
+ taxCalculated = grossCalculated - grandTotal;
204
+
205
+ if (spec.targetGross !== undefined) {
206
+ differenceFromTarget = grossCalculated - spec.targetGross;
207
+ }
208
+ }
209
+
210
+ const valid = itemErrors.length === 0 && categoryErrors.length === 0 && (differenceFromTarget === undefined || differenceFromTarget === 0);
211
+
212
+ return {
213
+ valid,
214
+ itemErrors,
215
+ categoryErrors,
216
+ totalCalculated: grandTotal,
217
+ grossCalculated,
218
+ taxCalculated,
219
+ differenceFromTarget
220
+ };
221
+ }