fullstackgtm 0.43.0 → 0.45.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 (130) hide show
  1. package/CHANGELOG.md +378 -1
  2. package/README.md +37 -14
  3. package/dist/audit.d.ts +3 -1
  4. package/dist/audit.js +29 -2
  5. package/dist/cli/audit.d.ts +15 -0
  6. package/dist/cli/audit.js +392 -0
  7. package/dist/cli/auth.d.ts +80 -0
  8. package/dist/cli/auth.js +500 -0
  9. package/dist/cli/call.d.ts +1 -0
  10. package/dist/cli/call.js +373 -0
  11. package/dist/cli/capabilities.d.ts +30 -0
  12. package/dist/cli/capabilities.js +197 -0
  13. package/dist/cli/draft.d.ts +7 -0
  14. package/dist/cli/draft.js +87 -0
  15. package/dist/cli/enrich.d.ts +8 -0
  16. package/dist/cli/enrich.js +788 -0
  17. package/dist/cli/fix.d.ts +33 -0
  18. package/dist/cli/fix.js +344 -0
  19. package/dist/cli/help.d.ts +25 -0
  20. package/dist/cli/help.js +609 -0
  21. package/dist/cli/icp.d.ts +7 -0
  22. package/dist/cli/icp.js +229 -0
  23. package/dist/cli/init.d.ts +7 -0
  24. package/dist/cli/init.js +58 -0
  25. package/dist/cli/market.d.ts +1 -0
  26. package/dist/cli/market.js +391 -0
  27. package/dist/cli/plans.d.ts +5 -0
  28. package/dist/cli/plans.js +454 -0
  29. package/dist/cli/schedule.d.ts +8 -0
  30. package/dist/cli/schedule.js +479 -0
  31. package/dist/cli/shared.d.ts +70 -0
  32. package/dist/cli/shared.js +331 -0
  33. package/dist/cli/signals.d.ts +7 -0
  34. package/dist/cli/signals.js +412 -0
  35. package/dist/cli/suggest.d.ts +49 -0
  36. package/dist/cli/suggest.js +135 -0
  37. package/dist/cli/tam.d.ts +9 -0
  38. package/dist/cli/tam.js +387 -0
  39. package/dist/cli/ui.d.ts +121 -0
  40. package/dist/cli/ui.js +375 -0
  41. package/dist/cli.d.ts +1 -57
  42. package/dist/cli.js +104 -4556
  43. package/dist/connector.d.ts +15 -0
  44. package/dist/connector.js +35 -0
  45. package/dist/connectors/hubspot.d.ts +3 -1
  46. package/dist/connectors/hubspot.js +10 -3
  47. package/dist/connectors/outboxChannel.d.ts +64 -0
  48. package/dist/connectors/outboxChannel.js +170 -0
  49. package/dist/connectors/prospectSources.d.ts +22 -0
  50. package/dist/connectors/prospectSources.js +43 -0
  51. package/dist/connectors/salesforce.d.ts +3 -1
  52. package/dist/connectors/salesforce.js +12 -5
  53. package/dist/connectors/signalSources.d.ts +105 -0
  54. package/dist/connectors/signalSources.js +264 -0
  55. package/dist/connectors/theirstack.d.ts +84 -0
  56. package/dist/connectors/theirstack.js +125 -0
  57. package/dist/icp.d.ts +52 -4
  58. package/dist/icp.js +112 -35
  59. package/dist/index.d.ts +1 -0
  60. package/dist/index.js +1 -0
  61. package/dist/init.js +3 -0
  62. package/dist/judge.d.ts +2 -0
  63. package/dist/judge.js +6 -0
  64. package/dist/judgeEval.d.ts +7 -0
  65. package/dist/judgeEval.js +8 -1
  66. package/dist/marketClassify.d.ts +2 -0
  67. package/dist/marketClassify.js +7 -1
  68. package/dist/mcp-bin.js +2 -2
  69. package/dist/mcp.js +259 -166
  70. package/dist/runReport.d.ts +26 -0
  71. package/dist/runReport.js +15 -0
  72. package/dist/schedule.d.ts +80 -2
  73. package/dist/schedule.js +272 -5
  74. package/dist/signals.d.ts +54 -0
  75. package/dist/signals.js +64 -0
  76. package/dist/spoolFiles.d.ts +44 -0
  77. package/dist/spoolFiles.js +114 -0
  78. package/dist/tam.d.ts +225 -0
  79. package/dist/tam.js +470 -0
  80. package/dist/types.d.ts +11 -0
  81. package/docs/api.md +91 -11
  82. package/docs/outbox-format.md +92 -0
  83. package/docs/recipes.md +37 -0
  84. package/docs/roadmap-to-1.0.md +31 -1
  85. package/docs/signal-spool-format.md +175 -0
  86. package/docs/tam.md +195 -0
  87. package/llms.txt +83 -11
  88. package/package.json +1 -1
  89. package/skills/fullstackgtm/SKILL.md +4 -3
  90. package/src/audit.ts +27 -1
  91. package/src/cli/audit.ts +447 -0
  92. package/src/cli/auth.ts +549 -0
  93. package/src/cli/call.ts +398 -0
  94. package/src/cli/capabilities.ts +215 -0
  95. package/src/cli/draft.ts +101 -0
  96. package/src/cli/enrich.ts +885 -0
  97. package/src/cli/fix.ts +372 -0
  98. package/src/cli/help.ts +664 -0
  99. package/src/cli/icp.ts +265 -0
  100. package/src/cli/init.ts +65 -0
  101. package/src/cli/market.ts +423 -0
  102. package/src/cli/plans.ts +523 -0
  103. package/src/cli/schedule.ts +526 -0
  104. package/src/cli/shared.ts +375 -0
  105. package/src/cli/signals.ts +434 -0
  106. package/src/cli/suggest.ts +151 -0
  107. package/src/cli/tam.ts +435 -0
  108. package/src/cli/ui.ts +426 -0
  109. package/src/cli.ts +103 -5170
  110. package/src/connector.ts +46 -0
  111. package/src/connectors/hubspot.ts +14 -2
  112. package/src/connectors/outboxChannel.ts +202 -0
  113. package/src/connectors/prospectSources.ts +57 -0
  114. package/src/connectors/salesforce.ts +18 -2
  115. package/src/connectors/signalSources.ts +314 -0
  116. package/src/connectors/theirstack.ts +170 -0
  117. package/src/icp.ts +120 -34
  118. package/src/index.ts +32 -0
  119. package/src/init.ts +3 -0
  120. package/src/judge.ts +7 -0
  121. package/src/judgeEval.ts +8 -1
  122. package/src/marketClassify.ts +8 -1
  123. package/src/mcp-bin.ts +2 -2
  124. package/src/mcp.ts +130 -57
  125. package/src/runReport.ts +39 -0
  126. package/src/schedule.ts +330 -7
  127. package/src/signals.ts +90 -0
  128. package/src/spoolFiles.ts +116 -0
  129. package/src/tam.ts +654 -0
  130. package/src/types.ts +12 -0
package/src/schedule.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { mkdirSync, readdirSync, readFileSync } from "node:fs";
2
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import { credentialsDir, ensureSecureHomeDir, writeSecureFile } from "./credentials.ts";
5
6
 
@@ -49,9 +50,11 @@ export type ScheduleRunRecord = {
49
50
  * recorded for visibility but nothing ran. Reasons: "plan_not_approved"
50
51
  * (scheduled apply against a plan that is not approved — there is no flag
51
52
  * that relaxes this), "not_schedulable" (the stored argv no longer passes
52
- * the allowlist, e.g. after a hand edit of schedules.json).
53
+ * the allowlist, e.g. after a hand edit of schedules.json),
54
+ * "duplicate_firing" (a cron-triggered run already recorded in this minute
55
+ * — launchd can double-trigger the Vixie dom+dow OR corner).
53
56
  */
54
- noopReason?: "plan_not_approved" | "not_schedulable";
57
+ noopReason?: "plan_not_approved" | "not_schedulable" | "duplicate_firing";
55
58
  };
56
59
 
57
60
  // Mirrors stableHash in rules.ts (FNV-1a); duplicated to keep schedule.ts
@@ -84,7 +87,13 @@ const SCHEDULABLE: Record<string, string[] | null> = {
84
87
  suggest: null,
85
88
  report: null,
86
89
  doctor: null,
87
- enrich: ["append", "refresh"],
90
+ // `enrich append|refresh` fill blanks; `enrich acquire` creates net-new
91
+ // leads — but ONLY as a needs_approval `create_record` plan (`--save`,
92
+ // required below), never a write. This is what lets `tam populate` chip away
93
+ // at a TAM unattended: each firing queues a fresh lead plan, the meter is
94
+ // charged only at apply, and apply stays `apply --plan-id` (re-checked
95
+ // approved). So scheduled acquire accumulates proposals, never surprise leads.
96
+ enrich: ["append", "refresh", "acquire"],
88
97
  market: ["capture", "refresh"],
89
98
  // The GTM brain. `signals fetch` is read-only re: CRM (--save persists only
90
99
  // the local signal ledger). `icp judge`/`icp eval` are read-only/grade-only
@@ -98,9 +107,9 @@ const SCHEDULABLE: Record<string, string[] | null> = {
98
107
  };
99
108
 
100
109
  const ALLOWLIST_SUMMARY =
101
- "audit, snapshot, enrich append|refresh, market capture|refresh, signals fetch, " +
102
- "icp judge|eval, draft (stages a plan), suggest, report, doctor — " +
103
- "plus apply --plan-id <id> (re-checked approved at every firing)";
110
+ "audit, snapshot, enrich append|refresh, enrich acquire --save (stages a lead plan), " +
111
+ "market capture|refresh, signals fetch, icp judge|eval, draft (stages a plan), " +
112
+ "suggest, report, doctor — plus apply --plan-id <id> (re-checked approved at every firing)";
104
113
 
105
114
  /**
106
115
  * Validate that an argv resolves to a schedulable fullstackgtm command.
@@ -158,6 +167,16 @@ export function validateSchedulableArgv(argv: string[]): void {
158
167
  .join(", ")}.`,
159
168
  );
160
169
  }
170
+ // `enrich acquire` is schedulable ONLY in its plan-producing form: without
171
+ // --save it's a dry-run that writes nothing AND queues nothing, so an
172
+ // unattended firing would silently no-op. Require --save so a scheduled
173
+ // acquire always leaves a needs_approval plan behind (apply stays gated).
174
+ if (head === "enrich" && sub === "acquire" && !argv.includes("--save")) {
175
+ throw new Error(
176
+ "Scheduled `enrich acquire` must include --save so each firing queues a needs_approval lead plan " +
177
+ "(without it the run produces nothing). Apply stays a separate human gate (`apply --plan-id <id>`).",
178
+ );
179
+ }
161
180
  }
162
181
  }
163
182
 
@@ -713,3 +732,307 @@ export function replaceManagedBlock(existing: string, profile: string, block: st
713
732
  if (merged.length === 0) return "";
714
733
  return `${merged.join("\n")}\n`;
715
734
  }
735
+
736
+ // ---------------------------------------------------------------------------
737
+ // Local provider: launchd LaunchAgents (macOS)
738
+ //
739
+ // On macOS `crontab -` writes to the TCC-protected /var/at/tabs, which
740
+ // requires granting Full Disk Access to the *terminal app* — a permission no
741
+ // program can request and a huge over-grant for one timer line. Per-user
742
+ // LaunchAgents need no permission at all: one plist per enabled entry in
743
+ // ~/Library/LaunchAgents, loaded with `launchctl bootstrap gui/<uid>`. Bonus
744
+ // over cron: launchd coalesces firings missed while asleep into one run on
745
+ // wake, where cron silently skips. Same audit story as the crontab block —
746
+ // every plist's ProgramArguments is `... schedule run <id>` and nothing else,
747
+ // and install replaces the com.fullstackgtm.<profile>.* fleet wholesale.
748
+
749
+ /**
750
+ * One launchd StartCalendarInterval dict: every present key must match (AND),
751
+ * a missing key is a wildcard, and an array of dicts fires when ANY dict
752
+ * matches. Weekday 0 is Sunday, as in cron.
753
+ */
754
+ export type LaunchdCalendarInterval = {
755
+ Minute?: number;
756
+ Hour?: number;
757
+ Day?: number;
758
+ Weekday?: number;
759
+ Month?: number;
760
+ };
761
+
762
+ /**
763
+ * Compile a cron expression to StartCalendarInterval dicts. Full-range fields
764
+ * (`*`, but also spellings like `0-59`) are omitted (launchd wildcard); the
765
+ * rest cross-product, capped so a dense expression cannot render a megabyte
766
+ * plist. Vixie day semantics: when day-of-month AND day-of-week are both
767
+ * restricted, either may match — launchd ANDs keys within one dict, so that
768
+ * becomes the union of a Day dict set and a Weekday dict set. A date matching
769
+ * both sets makes launchd trigger twice in the same minute; the run entry
770
+ * point drops the second via isDuplicateCronFiring.
771
+ */
772
+ export function cronToCalendarIntervals(cron: CronExpression, cap = 512): LaunchdCalendarInterval[] {
773
+ const full = (values: number[], min: number, max: number) => values.length === max - min + 1;
774
+ const minutes: Array<number | undefined> = full(cron.minute, 0, 59) ? [undefined] : cron.minute;
775
+ const hours: Array<number | undefined> = full(cron.hour, 0, 23) ? [undefined] : cron.hour;
776
+ const months: Array<number | undefined> = full(cron.month, 1, 12) ? [undefined] : cron.month;
777
+ const domRestricted = cron.dayOfMonthRestricted && !full(cron.dayOfMonth, 1, 31);
778
+ const dowRestricted = cron.dayOfWeekRestricted && !full(cron.dayOfWeek, 0, 6);
779
+ const daySlots: Array<Pick<LaunchdCalendarInterval, "Day" | "Weekday">> = [];
780
+ if (domRestricted) for (const day of cron.dayOfMonth) daySlots.push({ Day: day });
781
+ if (dowRestricted) for (const weekday of cron.dayOfWeek) daySlots.push({ Weekday: weekday });
782
+ if (daySlots.length === 0) daySlots.push({});
783
+ const count = minutes.length * hours.length * daySlots.length * months.length;
784
+ if (count > cap) {
785
+ throw new Error(
786
+ `Cron expression "${cron.source}" expands to ${count} launchd calendar intervals (cap ${cap}). ` +
787
+ "Simplify the expression or split it into separate schedules.",
788
+ );
789
+ }
790
+ const intervals: LaunchdCalendarInterval[] = [];
791
+ for (const month of months) {
792
+ for (const daySlot of daySlots) {
793
+ for (const hour of hours) {
794
+ for (const minute of minutes) {
795
+ const dict: LaunchdCalendarInterval = {};
796
+ if (minute !== undefined) dict.Minute = minute;
797
+ if (hour !== undefined) dict.Hour = hour;
798
+ if (daySlot.Day !== undefined) dict.Day = daySlot.Day;
799
+ if (daySlot.Weekday !== undefined) dict.Weekday = daySlot.Weekday;
800
+ if (month !== undefined) dict.Month = month;
801
+ intervals.push(dict);
802
+ }
803
+ }
804
+ }
805
+ }
806
+ return intervals;
807
+ }
808
+
809
+ /**
810
+ * True when a cron-triggered run was already recorded in `firedAt`'s minute.
811
+ * The `schedule run` entry point checks this for trigger:cron so a launchd
812
+ * double-trigger (dom+dow OR corner above) records a duplicate_firing no-op
813
+ * instead of running the command twice. Manual runs are never deduplicated.
814
+ */
815
+ export function isDuplicateCronFiring(runs: ScheduleRunRecord[], firedAt: string): boolean {
816
+ const minute = new Date(firedAt);
817
+ minute.setSeconds(0, 0);
818
+ return runs.some((run) => {
819
+ if (run.trigger !== "cron") return false;
820
+ const fired = new Date(run.firedAt);
821
+ fired.setSeconds(0, 0);
822
+ return fired.getTime() === minute.getTime();
823
+ });
824
+ }
825
+
826
+ /** Reverse-DNS namespace for one profile's agents; install/uninstall own this prefix wholesale. */
827
+ export function launchdAgentPrefix(profile: string): string {
828
+ if (!/^[A-Za-z0-9._-]+$/.test(profile)) {
829
+ throw new Error(
830
+ `Cannot build a launchd label from profile "${profile}" — profile names in LaunchAgent labels ` +
831
+ "must be alphanumeric with dot/dash/underscore.",
832
+ );
833
+ }
834
+ return `com.fullstackgtm.${profile}.`;
835
+ }
836
+
837
+ export function launchdLabel(profile: string, scheduleEntryId: string): string {
838
+ if (!/^[A-Za-z0-9._-]+$/.test(scheduleEntryId)) {
839
+ throw new Error(`Cannot build a launchd label from schedule id "${scheduleEntryId}".`);
840
+ }
841
+ return `${launchdAgentPrefix(profile)}${scheduleEntryId}`;
842
+ }
843
+
844
+ function xmlEscape(value: string): string {
845
+ return value.replace(/[&<>"']/g, (char) => {
846
+ switch (char) {
847
+ case "&":
848
+ return "&amp;";
849
+ case "<":
850
+ return "&lt;";
851
+ case ">":
852
+ return "&gt;";
853
+ case '"':
854
+ return "&quot;";
855
+ default:
856
+ return "&apos;";
857
+ }
858
+ });
859
+ }
860
+
861
+ /**
862
+ * Render one LaunchAgent plist. ProgramArguments is an argv array — launchd
863
+ * execs it directly, no shell, so there is no quoting/injection surface at
864
+ * all (values are XML-escaped for the document, nothing more).
865
+ */
866
+ export function renderLaunchdPlist(options: {
867
+ label: string;
868
+ programArguments: string[];
869
+ calendarIntervals: LaunchdCalendarInterval[];
870
+ environment?: Record<string, string>;
871
+ standardOutPath?: string;
872
+ standardErrorPath?: string;
873
+ }): string {
874
+ const lines = [
875
+ '<?xml version="1.0" encoding="UTF-8"?>',
876
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
877
+ '<plist version="1.0">',
878
+ "<dict>",
879
+ "\t<key>Label</key>",
880
+ `\t<string>${xmlEscape(options.label)}</string>`,
881
+ "\t<key>ProgramArguments</key>",
882
+ "\t<array>",
883
+ ...options.programArguments.map((arg) => `\t\t<string>${xmlEscape(arg)}</string>`),
884
+ "\t</array>",
885
+ "\t<key>StartCalendarInterval</key>",
886
+ "\t<array>",
887
+ ];
888
+ const keyOrder = ["Minute", "Hour", "Day", "Weekday", "Month"] as const;
889
+ for (const interval of options.calendarIntervals) {
890
+ lines.push("\t\t<dict>");
891
+ for (const key of keyOrder) {
892
+ const value = interval[key];
893
+ if (value === undefined) continue;
894
+ lines.push(`\t\t\t<key>${key}</key>`, `\t\t\t<integer>${value}</integer>`);
895
+ }
896
+ lines.push("\t\t</dict>");
897
+ }
898
+ lines.push("\t</array>");
899
+ if (options.environment && Object.keys(options.environment).length > 0) {
900
+ lines.push("\t<key>EnvironmentVariables</key>", "\t<dict>");
901
+ for (const [name, value] of Object.entries(options.environment)) {
902
+ lines.push(`\t\t<key>${xmlEscape(name)}</key>`, `\t\t<string>${xmlEscape(value)}</string>`);
903
+ }
904
+ lines.push("\t</dict>");
905
+ }
906
+ if (options.standardOutPath) {
907
+ lines.push("\t<key>StandardOutPath</key>", `\t<string>${xmlEscape(options.standardOutPath)}</string>`);
908
+ }
909
+ if (options.standardErrorPath) {
910
+ lines.push("\t<key>StandardErrorPath</key>", `\t<string>${xmlEscape(options.standardErrorPath)}</string>`);
911
+ }
912
+ lines.push("</dict>", "</plist>");
913
+ return `${lines.join("\n")}\n`;
914
+ }
915
+
916
+ export type LaunchdIo = {
917
+ /** Plist file names currently in the agents directory. */
918
+ list(): string[];
919
+ write(fileName: string, content: string): void;
920
+ remove(fileName: string): void;
921
+ /** Load one agent plist into the user's gui domain; throws on failure. */
922
+ bootstrap(fileName: string): void;
923
+ /** Best-effort unload by label; a label that is not loaded is not an error. */
924
+ bootout(label: string): void;
925
+ };
926
+
927
+ /**
928
+ * The real ~/Library/LaunchAgents + launchctl. Everything above takes a
929
+ * LaunchdIo so tests inject fakes and never touch the user's agents.
930
+ */
931
+ export function systemLaunchdIo(agentsDirOverride?: string): LaunchdIo {
932
+ const agentsDir = agentsDirOverride ?? join(homedir(), "Library", "LaunchAgents");
933
+ const domain = () => {
934
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
935
+ if (uid === null) throw new Error("launchd scheduling requires a POSIX user id (macOS only).");
936
+ return `gui/${uid}`;
937
+ };
938
+ const launchctl = (args: string[]) => {
939
+ const result = spawnSync("launchctl", args, { encoding: "utf8" });
940
+ if (result.error) throw new Error(`Cannot run \`launchctl\`: ${result.error.message}`);
941
+ return result;
942
+ };
943
+ return {
944
+ list() {
945
+ try {
946
+ return readdirSync(agentsDir).filter((name) => name.endsWith(".plist"));
947
+ } catch {
948
+ return [];
949
+ }
950
+ },
951
+ write(fileName, content) {
952
+ mkdirSync(agentsDir, { recursive: true });
953
+ // 0644 like every LaunchAgent: launchd refuses group/world-WRITABLE
954
+ // plists, and this file holds a dispatch line, not a secret.
955
+ writeFileSync(join(agentsDir, fileName), content, { mode: 0o644 });
956
+ },
957
+ remove(fileName) {
958
+ rmSync(join(agentsDir, fileName), { force: true });
959
+ },
960
+ bootstrap(fileName) {
961
+ const result = launchctl(["bootstrap", domain(), join(agentsDir, fileName)]);
962
+ if (result.status !== 0) {
963
+ throw new Error(
964
+ `\`launchctl bootstrap\` failed for ${fileName}: ${(result.stderr ?? "").trim() || `exit ${result.status}`}`,
965
+ );
966
+ }
967
+ },
968
+ bootout(label) {
969
+ launchctl(["bootout", `${domain()}/${label}`]);
970
+ },
971
+ };
972
+ }
973
+
974
+ /**
975
+ * Materialize enabled entries as one LaunchAgent each, replacing the
976
+ * profile's com.fullstackgtm.<profile>.* fleet wholesale (stale agents are
977
+ * booted out and deleted; plists outside the prefix are never touched).
978
+ * `cliArgv` is the argv-array analog of the crontab invocation line.
979
+ */
980
+ export function installLaunchdAgents(
981
+ profile: string,
982
+ entries: ScheduleEntry[],
983
+ cliArgv: string[],
984
+ io: LaunchdIo,
985
+ options: { environment?: Record<string, string>; logDir?: string } = {},
986
+ ): { installed: string[]; removed: string[] } {
987
+ for (const token of cliArgv) {
988
+ if (hasControlChar(token)) {
989
+ throw new Error(
990
+ "Refusing to render LaunchAgents: the resolved CLI invocation (node path or script path) " +
991
+ "contains a newline or control character.",
992
+ );
993
+ }
994
+ }
995
+ const removed = uninstallLaunchdAgents(profile, io);
996
+ const installed: string[] = [];
997
+ for (const entry of entries) {
998
+ assertRenderableEntry(profile, entry);
999
+ let intervals: LaunchdCalendarInterval[];
1000
+ try {
1001
+ intervals = cronToCalendarIntervals(parseCron(entry.cron));
1002
+ } catch (error) {
1003
+ throw new Error(
1004
+ `Schedule ${entry.id} ("${entry.label}") cannot materialize as a LaunchAgent: ` +
1005
+ `${error instanceof Error ? error.message : String(error)}`,
1006
+ );
1007
+ }
1008
+ const label = launchdLabel(profile, entry.id);
1009
+ const logPath = options.logDir ? join(options.logDir, `${label}.log`) : undefined;
1010
+ const plist = renderLaunchdPlist({
1011
+ label,
1012
+ programArguments: [...cliArgv, "schedule", "run", entry.id, "--profile", profile, "--trigger", "cron"],
1013
+ calendarIntervals: intervals,
1014
+ environment: options.environment,
1015
+ standardOutPath: logPath,
1016
+ standardErrorPath: logPath,
1017
+ });
1018
+ const fileName = `${label}.plist`;
1019
+ io.write(fileName, plist);
1020
+ io.bootstrap(fileName);
1021
+ installed.push(label);
1022
+ }
1023
+ return { installed, removed };
1024
+ }
1025
+
1026
+ /** Boot out and delete every agent in the profile's prefix; returns the removed labels. */
1027
+ export function uninstallLaunchdAgents(profile: string, io: LaunchdIo): string[] {
1028
+ const prefix = launchdAgentPrefix(profile);
1029
+ const removed: string[] = [];
1030
+ for (const name of io.list()) {
1031
+ if (!name.startsWith(prefix)) continue;
1032
+ const label = name.slice(0, -".plist".length);
1033
+ io.bootout(label);
1034
+ io.remove(name);
1035
+ removed.push(label);
1036
+ }
1037
+ return removed;
1038
+ }
package/src/signals.ts CHANGED
@@ -416,6 +416,71 @@ function withinWindow(iso: string, now: Date, windowDays: number): boolean {
416
416
  return now.getTime() - t <= windowDays * DAY_MS;
417
417
  }
418
418
 
419
+ // ---------------------------------------------------------------------------
420
+ // Staged rows -> signals (shared by `--from` ingest and source connectors)
421
+
422
+ /**
423
+ * One staged signal row: the platform-agnostic intake shape every NON-job source
424
+ * produces (a source connector's output, or a `--from` JSON row). It carries the
425
+ * evidence anchor (`quote`) but none of the derived fields (`id`, `weight`,
426
+ * `source`) — `stagedRowToSignal` fills those so there is ONE place that gates
427
+ * evidence and stamps identity, whether the row came from a file or an API.
428
+ */
429
+ export type StagedSignalRow = {
430
+ bucket: SignalBucket;
431
+ accountDomain: string;
432
+ trigger: string;
433
+ /** VERBATIM evidence — required, non-empty. */
434
+ quote: string;
435
+ sourceUrl?: string;
436
+ /** ISO 8601; defaults to run time when absent. */
437
+ firstSeen?: string;
438
+ /** Optional explicit weight; defaults to the bucket's configured weight. */
439
+ weight?: number;
440
+ };
441
+
442
+ /**
443
+ * Validate one loosely-typed staged row and turn it into a `Signal`, applying
444
+ * the verbatim-evidence gate (a row with no quote is rejected, never faked) and
445
+ * the same id/normalization logic the ATS path uses. `errorLabel` lets the
446
+ * caller produce a precise message ("--from f.json: row 3", "serpapi-news row 0")
447
+ * since both the `--from` ingest and the source-connector registry funnel here.
448
+ *
449
+ * Throws on a malformed row; returns the canonical `Signal` on success. Bucket
450
+ * FILTERING (skip rows outside a `--bucket` selection) stays with the caller —
451
+ * this function is per-row validation only.
452
+ */
453
+ export function stagedRowToSignal(
454
+ entry: Record<string, unknown>,
455
+ opts: { now: Date; source: string; errorLabel: string },
456
+ ): Signal {
457
+ const { now, source, errorLabel } = opts;
458
+ const bucket = String(entry.bucket ?? "");
459
+ if (!SIGNAL_BUCKETS.includes(bucket as SignalBucket)) {
460
+ throw new Error(`${errorLabel} has unknown bucket "${bucket}" (one of ${SIGNAL_BUCKETS.join(", ")}).`);
461
+ }
462
+ const accountDomain = normalizeAccountDomain(String(entry.accountDomain ?? entry.domain ?? ""));
463
+ if (!accountDomain) throw new Error(`${errorLabel} is missing accountDomain.`);
464
+ const trigger = String(entry.trigger ?? "").trim();
465
+ if (!trigger) throw new Error(`${errorLabel} is missing trigger.`);
466
+ const quote = String(entry.quote ?? "").trim();
467
+ if (!quote) throw new Error(`${errorLabel} is missing the verbatim quote (the evidence anchor).`);
468
+ const base = { accountDomain, bucket: bucket as SignalBucket, trigger };
469
+ const firstSeen = typeof entry.firstSeen === "string" && entry.firstSeen ? entry.firstSeen : now.toISOString();
470
+ return {
471
+ id: signalId(base),
472
+ accountDomain,
473
+ bucket: bucket as SignalBucket,
474
+ trigger,
475
+ quote,
476
+ sourceUrl: String(entry.sourceUrl ?? ""),
477
+ firstSeen,
478
+ weight: typeof entry.weight === "number" ? entry.weight : DEFAULT_SIGNALS_CONFIG.buckets[bucket as SignalBucket].weight,
479
+ source,
480
+ judgedBy: null,
481
+ };
482
+ }
483
+
419
484
  // ---------------------------------------------------------------------------
420
485
  // Dedup
421
486
 
@@ -533,6 +598,31 @@ export function signalsDir(baseDir?: string): string {
533
598
  return join(baseDir ?? credentialsDir(), "signals");
534
599
  }
535
600
 
601
+ /**
602
+ * Conventional webhook landing zone: `<signals>/spool`, profile-scoped. A
603
+ * webhook receiver (hosted, or the operator's own glue) appends one JSONL row
604
+ * per event to a `*.jsonl` file here; `signals fetch --connector file` reads the
605
+ * whole directory when given no explicit path. The CLI never writes here — the
606
+ * receiver does — so this is just the agreed-upon location, not a managed store.
607
+ * Per-source files (`rb2b.jsonl`, `hubspot.jsonl`, …) coexist. See
608
+ * docs/signal-spool-format.md.
609
+ */
610
+ export function signalsSpoolDir(baseDir?: string): string {
611
+ return join(signalsDir(baseDir), "spool");
612
+ }
613
+
614
+ /**
615
+ * Conventional outbox: `<signals>/outbox`, profile-scoped — the SEND-side mirror
616
+ * of the spool. `apply --channel outbox` renders each APPROVED drafted opener to
617
+ * a `<channel>.jsonl` file here (one row per touch); a downstream sender (hosted,
618
+ * or the operator's own) drains it. The CLI WRITES governed, approved send
619
+ * intents here but TRANSMITS NOTHING — the "drafts everything, transmits nothing"
620
+ * invariant holds. See docs/outbox-format.md.
621
+ */
622
+ export function signalsOutboxDir(baseDir?: string): string {
623
+ return join(signalsDir(baseDir), "outbox");
624
+ }
625
+
536
626
  export type SignalRun = {
537
627
  id: string;
538
628
  runLabel: string;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Shared reader for the spool container convention (docs/signal-spool-format.md):
3
+ * newline-delimited JSON — one object per line, append-only — with a JSON array
4
+ * accepted in a `.json` file for hand-staged convenience, and a DIRECTORY
5
+ * meaning "every `*.jsonl` / `*.json` file in it, name-sorted" so multiple
6
+ * receivers can each append their own file.
7
+ *
8
+ * The container is the convention; the row SCHEMA stays with each caller:
9
+ * `signals fetch --from` validates staged signal rows, `enrich ingest` stages
10
+ * enrichment rows, `market observe --from` validates observation-set envelopes.
11
+ * This module only parses objects out of files — it never interprets them.
12
+ *
13
+ * Extracted from the `file` signal-source connector (the Phase-2 webhook
14
+ * landing-zone reader), which now delegates here; error-message text is
15
+ * parameterized by `label` so existing connector errors are unchanged.
16
+ */
17
+
18
+ import { readFileSync, readdirSync, statSync } from "node:fs";
19
+ import { join } from "node:path";
20
+
21
+ /** Spool files in a landing-zone directory: `*.jsonl` / `*.json`, name-sorted. */
22
+ export function spoolFilesIn(dir: string): string[] {
23
+ let names: string[];
24
+ try {
25
+ names = readdirSync(dir);
26
+ } catch {
27
+ return [];
28
+ }
29
+ return names
30
+ .filter((name) => name.endsWith(".jsonl") || name.endsWith(".json"))
31
+ .sort()
32
+ .map((name) => join(dir, name));
33
+ }
34
+
35
+ /** Parse a JSON-array spool file into rows. `label` prefixes error messages. */
36
+ export function parseSpoolArray(raw: string, path: string, label: string): Record<string, unknown>[] {
37
+ let parsed: unknown;
38
+ try {
39
+ parsed = JSON.parse(raw);
40
+ } catch (error) {
41
+ throw new Error(`${label} ${path}: not valid JSON (${error instanceof Error ? error.message : String(error)}).`);
42
+ }
43
+ if (!Array.isArray(parsed)) throw new Error(`${label} ${path}: expected a JSON array of staged signal rows.`);
44
+ return parsed.map((entry, index) => {
45
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
46
+ throw new Error(`${label} ${path}: row ${index} is not an object.`);
47
+ }
48
+ return entry as Record<string, unknown>;
49
+ });
50
+ }
51
+
52
+ /** Parse a JSONL spool file into rows. `label` prefixes error messages. */
53
+ export function parseSpoolJsonl(raw: string, path: string, label: string): Record<string, unknown>[] {
54
+ const out: Record<string, unknown>[] = [];
55
+ const lines = raw.split("\n");
56
+ lines.forEach((line, index) => {
57
+ const t = line.trim();
58
+ if (!t) return;
59
+ let parsed: unknown;
60
+ try {
61
+ parsed = JSON.parse(t);
62
+ } catch (error) {
63
+ throw new Error(`${label} ${path}: line ${index} is not valid JSON (${error instanceof Error ? error.message : String(error)}).`);
64
+ }
65
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
66
+ throw new Error(`${label} ${path}: line ${index} is not a JSON object.`);
67
+ }
68
+ out.push(parsed as Record<string, unknown>);
69
+ });
70
+ return out;
71
+ }
72
+
73
+ /** Parse one spool file's text — JSON array if it opens with `[`, else JSONL. */
74
+ export function parseSpoolText(raw: string, path: string, label: string): Record<string, unknown>[] {
75
+ const trimmed = raw.trim();
76
+ if (!trimmed) return [];
77
+ return trimmed.startsWith("[") ? parseSpoolArray(trimmed, path, label) : parseSpoolJsonl(trimmed, path, label);
78
+ }
79
+
80
+ /**
81
+ * Should an explicitly named intake path be read with spool semantics?
82
+ * True for a directory (a landing zone) or a `*.jsonl` file. Plain `.json` /
83
+ * `.csv` files keep each verb's original single-file handling, so existing
84
+ * invocations parse exactly as before.
85
+ */
86
+ export function isSpoolPath(absPath: string): boolean {
87
+ try {
88
+ if (statSync(absPath).isDirectory()) return true;
89
+ } catch {
90
+ return false;
91
+ }
92
+ return absPath.endsWith(".jsonl");
93
+ }
94
+
95
+ /** A parsed spool row plus where it came from (for error labels). */
96
+ export type SpoolRow = { file: string; index: number; row: Record<string, unknown> };
97
+
98
+ /**
99
+ * Read an explicitly named spool path — a `.jsonl` file or a directory of
100
+ * `*.jsonl` / `*.json` files. Unlike the webhook `file` connector (where a
101
+ * missing spool is an empty source), the user named this path: a missing or
102
+ * unreadable file is an error, and a malformed row throws with file + line.
103
+ */
104
+ export function readSpoolPath(absPath: string, label: string): SpoolRow[] {
105
+ const isDir = statSync(absPath).isDirectory();
106
+ const files = isDir ? spoolFilesIn(absPath) : [absPath];
107
+ if (isDir && files.length === 0) {
108
+ throw new Error(`${label} ${absPath}: directory contains no *.jsonl / *.json spool files.`);
109
+ }
110
+ const rows: SpoolRow[] = [];
111
+ for (const file of files) {
112
+ const raw = readFileSync(file, "utf8");
113
+ parseSpoolText(raw, file, label).forEach((row, index) => rows.push({ file, index, row }));
114
+ }
115
+ return rows;
116
+ }