@cclabsnz/sf-core 0.6.0 → 0.7.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.
package/CHANGELOG.md CHANGED
@@ -12,6 +12,23 @@ CycloneDX SBOM for the build.
12
12
 
13
13
  Nothing yet.
14
14
 
15
+ ## [0.7.0] — 2026-09-22
16
+
17
+ ### Added
18
+
19
+ - **An activity engine for classifying and tracing one actor's API calls across a Salesforce
20
+ org.** Exported from the package root: `parseCsv` and `normalise` turn EventLogFile rows
21
+ (`ApiTotalUsage`, `RestApi`, `CompositeApiSubrequest`, `API`, `Login`) into a common
22
+ `ActivityEvent` shape; `classify` labels each one read, write, destructive, control or
23
+ unknown; `decomposeComposite` joins composite parents to their subrequests on `REQUEST_ID`
24
+ and marks a resolved parent with `decomposedInto` so it is never mistaken for a genuinely
25
+ unclassifiable event; `sessionise` and `segmentCycles` group events into runs and
26
+ caller-delimited cycles; `flagOutliers` and `median` find anomalies on median and MAD rather
27
+ than mean and standard deviation, so one extreme value cannot hide itself; and `discoverMotif`
28
+ recovers an actor's dominant repeating sequence from the tail of transitions that depart from
29
+ it. Pure — no filesystem, no org, no clock — and the reason: every function in `src/activity/`
30
+ is unit-tested with none of those, ahead of the `sf-trace` plugin that will consume it.
31
+
15
32
  ## [0.6.0] — 2026-09-10
16
33
 
17
34
  ### Added
package/README.md CHANGED
@@ -24,6 +24,7 @@ contracts behind [`@cclabsnz/sf-audit`](https://www.npmjs.com/package/@cclabsnz/
24
24
  | **API clients** | `SoqlClient`, `ToolingClient`, `RestClient`, `MetadataClient`: read-only wrappers over a `@salesforce/core` `Connection` |
25
25
  | **Platform behaviour** | `FlowRepository`, `ApexRepository`, `isSalesforceId`, `describeSalesforceError`, `mapWithConcurrency` |
26
26
  | **Event capture** | `EventBaselineStore`, `RTE_CATALOG`, `pullEventLogs`, `pullRealtimeEvents`, `CaptureManifest`: bounded, resumable EventLogFile and Real-Time Event pulls |
27
+ | **Activity engine** | Turns captured EventLogFile rows into a classified, sessionised account of one actor's API activity. Classifies each call as a read, write, destructive, control or unknown operation — `unknown` is a real answer for undecomposed `/composite` requests, not a failure to classify — resolves them into their subrequests, groups events into runs and cycles, recovers the repeating sequence, and flags outliers on median and MAD. Pure functions; no org connection. |
27
28
  | **IR contracts** | Typed interfaces plus JSON Schemas for `coupling-graph`, `landscape-manifest` and `process-graph` |
28
29
  | **Report shell** | Branding resolution and embedded webfonts for self-contained HTML reports |
29
30
  | **Test invariants** | Static guards that fail a build on org writes or network egress |
@@ -0,0 +1,17 @@
1
+ import type { OutlierReport } from './types.js';
2
+ export declare function median(values: readonly number[]): number;
3
+ /**
4
+ * Flag outliers using median and median absolute deviation.
5
+ *
6
+ * Mean and standard deviation are deliberately not used: a single extreme value inflates a
7
+ * standard deviation enough to hide itself, which is exactly the case this exists to catch.
8
+ *
9
+ * The measure callback is the whole design. On real data, measuring raw cycle duration flagged
10
+ * 78 of 161 cycles because the unit of work varied; measuring duration per unit of work flagged
11
+ * 2, and those 2 were the incident. The engine cannot choose the normaliser, so it does not try.
12
+ */
13
+ export declare function flagOutliers<T>(items: readonly T[], measure: (t: T) => number, opts?: {
14
+ madMultiple?: number;
15
+ severeMultiple?: number;
16
+ }): OutlierReport<T>;
17
+ //# sourceMappingURL=anomaly.d.ts.map
@@ -0,0 +1,55 @@
1
+ /** Below this many items, MAD is a prompt to look rather than evidence. */
2
+ const UNDERPOWERED_BELOW = 12;
3
+ export function median(values) {
4
+ if (values.length === 0)
5
+ return 0;
6
+ const s = [...values].sort((a, b) => a - b);
7
+ const mid = Math.floor(s.length / 2);
8
+ return s.length % 2 === 1 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
9
+ }
10
+ /**
11
+ * Flag outliers using median and median absolute deviation.
12
+ *
13
+ * Mean and standard deviation are deliberately not used: a single extreme value inflates a
14
+ * standard deviation enough to hide itself, which is exactly the case this exists to catch.
15
+ *
16
+ * The measure callback is the whole design. On real data, measuring raw cycle duration flagged
17
+ * 78 of 161 cycles because the unit of work varied; measuring duration per unit of work flagged
18
+ * 2, and those 2 were the incident. The engine cannot choose the normaliser, so it does not try.
19
+ */
20
+ export function flagOutliers(items, measure, opts) {
21
+ const madMultiple = opts?.madMultiple ?? 3;
22
+ const severeMultiple = opts?.severeMultiple ?? 20;
23
+ if (items.length === 0) {
24
+ return { flags: [], median: 0, mad: 0, underpowered: true };
25
+ }
26
+ const values = items.map((item, i) => {
27
+ const v = measure(item);
28
+ if (!Number.isFinite(v)) {
29
+ // Guard here, not only in callers. A non-finite measure does not throw and does not
30
+ // flag: NaN > threshold is always false, so one bad value silently exempts itself, and
31
+ // a NaN landing at the median index poisons median and mad and silently disables
32
+ // detection for the whole batch. sessionise.ts and cycles.ts throw upstream for this
33
+ // reason; this is the function their comments name as the thing being protected.
34
+ throw new Error(`measure() returned a non-finite value (${String(v)}) for item at index ${i}`);
35
+ }
36
+ return v;
37
+ });
38
+ const med = median(values);
39
+ const mad = median(values.map((v) => Math.abs(v - med)));
40
+ // With zero spread any value above the median is an outlier; there is no scale to compare
41
+ // against, so fall back to a bare inequality rather than multiplying zero.
42
+ const slowAt = mad === 0 ? med : med + madMultiple * mad;
43
+ const hungAt = mad === 0 ? med : med + severeMultiple * mad;
44
+ const flags = items.map((item, i) => {
45
+ const value = values[i];
46
+ let severity = null;
47
+ if (value > hungAt)
48
+ severity = 'hung';
49
+ else if (value > slowAt)
50
+ severity = 'slow';
51
+ return { item, value, severity };
52
+ });
53
+ return { flags, median: med, mad, underpowered: items.length < UNDERPOWERED_BELOW };
54
+ }
55
+ //# sourceMappingURL=anomaly.js.map
@@ -0,0 +1,13 @@
1
+ import type { ActivityKind } from './types.js';
2
+ /**
3
+ * Classify one operation.
4
+ *
5
+ * Order matters for REST: the resource is consulted before the method, because the resource is
6
+ * the more specific signal and the method lies about `/query`.
7
+ */
8
+ export declare function classify(input: {
9
+ family: string;
10
+ operation: string;
11
+ resource?: string;
12
+ }): ActivityKind;
13
+ //# sourceMappingURL=classify.d.ts.map
@@ -0,0 +1,62 @@
1
+ import { isCompositeContainer, resourceSegments } from './resource.js';
2
+ const SOAP_READ = new Set([
3
+ 'query', 'queryall', 'querymore', 'retrieve', 'getupdated', 'getdeleted',
4
+ 'describesobject', 'describesobjects', 'describeglobal', 'describelayout',
5
+ ]);
6
+ const SOAP_WRITE = new Set(['create', 'update', 'upsert', 'merge', 'convertlead', 'process']);
7
+ const SOAP_DESTRUCTIVE = new Set(['delete', 'undelete', 'emptyrecyclebin']);
8
+ const SOAP_CONTROL = new Set([
9
+ 'getservertimestamp', 'login', 'logout', 'getuserinfo', 'setpassword', 'resetpassword',
10
+ ]);
11
+ const REST_READ_METHODS = new Set(['get', 'head']);
12
+ const REST_WRITE_METHODS = new Set(['post', 'patch', 'put']);
13
+ /**
14
+ * Resource path segments that are reads whatever the method says.
15
+ *
16
+ * `POST /query` is the reason this exists: the method says write and the call is a read. A
17
+ * classifier that trusts the method alone reports every paginated SOQL call as a mutation.
18
+ */
19
+ const REST_READ_RESOURCES = ['/query', '/queryall', '/search', '/parameterizedsearch', '/limits'];
20
+ /**
21
+ * Classify one operation.
22
+ *
23
+ * Order matters for REST: the resource is consulted before the method, because the resource is
24
+ * the more specific signal and the method lies about `/query`.
25
+ */
26
+ export function classify(input) {
27
+ const family = input.family.trim().toLowerCase();
28
+ const op = input.operation.trim().toLowerCase();
29
+ const resource = (input.resource ?? '').trim().toLowerCase();
30
+ if (family === 'soap') {
31
+ if (SOAP_CONTROL.has(op))
32
+ return 'control';
33
+ if (SOAP_DESTRUCTIVE.has(op))
34
+ return 'destructive';
35
+ if (SOAP_WRITE.has(op))
36
+ return 'write';
37
+ if (SOAP_READ.has(op))
38
+ return 'read';
39
+ if (op.startsWith('describe'))
40
+ return 'read';
41
+ return 'unknown';
42
+ }
43
+ if (family === 'rest') {
44
+ const seg = resourceSegments(resource)[0];
45
+ // A bare composite carries no operation of its own. Guessing here was wrong for 80% of
46
+ // one integration's traffic; decomposeComposite resolves it, and until then it is unknown.
47
+ // e.g. /composite/sobjects is not a container — its subresource names an operation.
48
+ if (seg === 'composite' && isCompositeContainer(resource))
49
+ return 'unknown';
50
+ if (REST_READ_RESOURCES.some((r) => resource.includes(r)))
51
+ return 'read';
52
+ if (REST_READ_METHODS.has(op))
53
+ return 'read';
54
+ if (op === 'delete')
55
+ return 'destructive';
56
+ if (REST_WRITE_METHODS.has(op))
57
+ return 'write';
58
+ return 'unknown';
59
+ }
60
+ return 'unknown';
61
+ }
62
+ //# sourceMappingURL=classify.js.map
@@ -0,0 +1,18 @@
1
+ import type { ActivityEvent, CompositeJoinResult } from './types.js';
2
+ /**
3
+ * Join composite parents to their subrequests on REQUEST_ID.
4
+ *
5
+ * REQUEST_ID is the only safe join key between two event log types: ApiTotalUsage and RestApi
6
+ * record different id forms for the same connected app, so joining on app id silently produces
7
+ * nothing.
8
+ *
9
+ * Parents are retained as containers. Children inherit actor and app from their parent because
10
+ * CompositeApiSubrequest records neither, and unattributed children cannot be traced to a user.
11
+ *
12
+ * A parent that resolves is emitted with `decomposedInto` set to its child count. Its `kind`
13
+ * stays `unknown` — a container has no operation of its own — but the marker lets a consumer
14
+ * exclude it from unclassified totals rather than counting it alongside genuinely unresolvable
15
+ * events.
16
+ */
17
+ export declare function decomposeComposite(parents: readonly ActivityEvent[], subrequests: readonly ActivityEvent[]): CompositeJoinResult;
18
+ //# sourceMappingURL=composite.d.ts.map
@@ -0,0 +1,88 @@
1
+ import { isCompositeContainer } from './resource.js';
2
+ import { byTime } from './time.js';
3
+ /**
4
+ * True when this event is a composite container rather than a real operation.
5
+ *
6
+ * Prefix-tolerant on purpose: ApiTotalUsage logs `/v61.0/composite` while RestApi logs
7
+ * `/services/data/v58.0/composite`. Anchoring on the version segment missed the second
8
+ * shape here exactly as it did in classify.ts, and a missed parent loses its children's
9
+ * attribution rather than failing loudly.
10
+ */
11
+ function isCompositeParent(e) {
12
+ return isCompositeContainer(e.resource ?? '');
13
+ }
14
+ /**
15
+ * Join composite parents to their subrequests on REQUEST_ID.
16
+ *
17
+ * REQUEST_ID is the only safe join key between two event log types: ApiTotalUsage and RestApi
18
+ * record different id forms for the same connected app, so joining on app id silently produces
19
+ * nothing.
20
+ *
21
+ * Parents are retained as containers. Children inherit actor and app from their parent because
22
+ * CompositeApiSubrequest records neither, and unattributed children cannot be traced to a user.
23
+ *
24
+ * A parent that resolves is emitted with `decomposedInto` set to its child count. Its `kind`
25
+ * stays `unknown` — a container has no operation of its own — but the marker lets a consumer
26
+ * exclude it from unclassified totals rather than counting it alongside genuinely unresolvable
27
+ * events.
28
+ */
29
+ export function decomposeComposite(parents, subrequests) {
30
+ const byRequest = new Map();
31
+ for (const s of subrequests) {
32
+ const id = s.requestId;
33
+ if (id === undefined)
34
+ continue;
35
+ const list = byRequest.get(id);
36
+ if (list === undefined)
37
+ byRequest.set(id, [s]);
38
+ else
39
+ list.push(s);
40
+ }
41
+ const events = [];
42
+ const claimed = new Set();
43
+ let resolved = 0;
44
+ let unresolved = 0;
45
+ let duplicates = 0;
46
+ for (const p of parents) {
47
+ if (!isCompositeParent(p)) {
48
+ events.push(p);
49
+ continue;
50
+ }
51
+ const id = p.requestId;
52
+ if (id === undefined) {
53
+ events.push(p);
54
+ unresolved += 1;
55
+ continue;
56
+ }
57
+ if (claimed.has(id)) {
58
+ events.push(p);
59
+ duplicates += 1;
60
+ continue;
61
+ }
62
+ const kids = byRequest.get(id);
63
+ if (kids === undefined) {
64
+ events.push(p);
65
+ unresolved += 1;
66
+ continue;
67
+ }
68
+ resolved += 1;
69
+ claimed.add(id);
70
+ events.push({ ...p, decomposedInto: kids.length });
71
+ for (const k of kids) {
72
+ events.push({ ...k, actor: k.actor === '' ? p.actor : k.actor, app: k.app ?? p.app });
73
+ }
74
+ }
75
+ // Children whose parent is not in the input. Retained: dropping them would understate
76
+ // activity, and the caller is told how many there were.
77
+ let orphans = 0;
78
+ for (const [id, kids] of byRequest) {
79
+ if (claimed.has(id))
80
+ continue;
81
+ orphans += kids.length;
82
+ for (const k of kids)
83
+ events.push(k);
84
+ }
85
+ events.sort(byTime);
86
+ return { events, resolved, unresolved, orphans, duplicates };
87
+ }
88
+ //# sourceMappingURL=composite.js.map
@@ -0,0 +1,9 @@
1
+ import type { CsvRecord } from './types.js';
2
+ /**
3
+ * Parse an EventLogFile log body into records keyed by its header row.
4
+ *
5
+ * Returns `[]` for an empty body and for a header-only body. A short row is padded with empty
6
+ * strings rather than shifted, because shifting silently moves a value into the wrong column.
7
+ */
8
+ export declare function parseCsv(text: string): CsvRecord[];
9
+ //# sourceMappingURL=csv.d.ts.map
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Split one CSV line-set into rows of fields, honouring quotes.
3
+ *
4
+ * Written by hand rather than taken as a dependency: sf-core ships no runtime deps for this,
5
+ * and the grammar Salesforce emits is small and fixed.
6
+ */
7
+ function splitRows(text) {
8
+ const rows = [];
9
+ let row = [];
10
+ let field = '';
11
+ let quoted = false;
12
+ let i = 0;
13
+ const endField = () => {
14
+ row.push(field);
15
+ field = '';
16
+ };
17
+ const endRow = () => {
18
+ endField();
19
+ rows.push(row);
20
+ row = [];
21
+ };
22
+ while (i < text.length) {
23
+ const c = text[i];
24
+ if (quoted) {
25
+ if (c === '"') {
26
+ if (text[i + 1] === '"') {
27
+ field += '"';
28
+ i += 2;
29
+ continue;
30
+ }
31
+ quoted = false;
32
+ i += 1;
33
+ continue;
34
+ }
35
+ field += c;
36
+ i += 1;
37
+ continue;
38
+ }
39
+ if (c === '"') {
40
+ quoted = true;
41
+ i += 1;
42
+ continue;
43
+ }
44
+ if (c === ',') {
45
+ endField();
46
+ i += 1;
47
+ continue;
48
+ }
49
+ if (c === '\r' && text[i + 1] === '\n') {
50
+ endRow();
51
+ i += 2;
52
+ continue;
53
+ }
54
+ if (c === '\n' || c === '\r') {
55
+ endRow();
56
+ i += 1;
57
+ continue;
58
+ }
59
+ field += c;
60
+ i += 1;
61
+ }
62
+ // A body with no trailing newline still has a final row to flush.
63
+ if (field !== '' || row.length > 0)
64
+ endRow();
65
+ return rows;
66
+ }
67
+ /**
68
+ * Parse an EventLogFile log body into records keyed by its header row.
69
+ *
70
+ * Returns `[]` for an empty body and for a header-only body. A short row is padded with empty
71
+ * strings rather than shifted, because shifting silently moves a value into the wrong column.
72
+ */
73
+ export function parseCsv(text) {
74
+ if (text.trim() === '')
75
+ return [];
76
+ const rows = splitRows(text);
77
+ if (rows.length === 0)
78
+ return [];
79
+ const header = rows[0];
80
+ const out = [];
81
+ for (let r = 1; r < rows.length; r += 1) {
82
+ const cells = rows[r];
83
+ // A single empty cell is a blank line — but only when the body has more than one column.
84
+ // In a single-column body an empty cell is a legitimate value, not a blank line, and
85
+ // splitRows cannot tell the two apart because it discards quoting.
86
+ if (header.length > 1 && cells.length === 1 && cells[0] === '')
87
+ continue;
88
+ const rec = {};
89
+ for (let c = 0; c < header.length; c += 1)
90
+ rec[header[c]] = cells[c] ?? '';
91
+ out.push(rec);
92
+ }
93
+ return out;
94
+ }
95
+ //# sourceMappingURL=csv.js.map
@@ -0,0 +1,14 @@
1
+ import type { ActivityEvent, Cycle } from './types.js';
2
+ /**
3
+ * Split events into cycles, each ending at the first event satisfying isDelimiter.
4
+ *
5
+ * The delimiter is supplied by the caller because the unit of work is org-specific — for one
6
+ * stock integration it is `update` on `Order`.
7
+ *
8
+ * countUnits supplies the normaliser the anomaly pass divides by. It defaults to one, which
9
+ * reproduces the naive raw-duration measure on purpose so the difference is visible in tests:
10
+ * flagging raw duration on real data flagged 78 of 161 cycles and was useless, while flagging
11
+ * duration per unit of work flagged 2 and found the incident.
12
+ */
13
+ export declare function segmentCycles(events: readonly ActivityEvent[], isDelimiter: (e: ActivityEvent) => boolean, countUnits?: (cycle: ActivityEvent[]) => number): Cycle[];
14
+ //# sourceMappingURL=cycles.d.ts.map
@@ -0,0 +1,50 @@
1
+ import { countKinds } from './sessionise.js';
2
+ import { byTime, eventMs } from './time.js';
3
+ function toCycle(group, complete, countUnits) {
4
+ const from = group[0].at;
5
+ const to = group[group.length - 1].at;
6
+ const durationMs = eventMs(to) - eventMs(from);
7
+ // Floor of one: a cycle with no countable unit still took the time it took, and dividing by
8
+ // zero would produce Infinity and poison the outlier statistics downstream.
9
+ const units = Math.max(1, Math.floor(countUnits(group)));
10
+ return {
11
+ from,
12
+ to,
13
+ count: group.length,
14
+ kinds: countKinds(group),
15
+ durationMs,
16
+ units,
17
+ msPerUnit: durationMs / units,
18
+ complete,
19
+ steps: group,
20
+ };
21
+ }
22
+ /**
23
+ * Split events into cycles, each ending at the first event satisfying isDelimiter.
24
+ *
25
+ * The delimiter is supplied by the caller because the unit of work is org-specific — for one
26
+ * stock integration it is `update` on `Order`.
27
+ *
28
+ * countUnits supplies the normaliser the anomaly pass divides by. It defaults to one, which
29
+ * reproduces the naive raw-duration measure on purpose so the difference is visible in tests:
30
+ * flagging raw duration on real data flagged 78 of 161 cycles and was useless, while flagging
31
+ * duration per unit of work flagged 2 and found the incident.
32
+ */
33
+ export function segmentCycles(events, isDelimiter, countUnits = () => 1) {
34
+ if (events.length === 0)
35
+ return [];
36
+ const sorted = [...events].sort(byTime);
37
+ const cycles = [];
38
+ let group = [];
39
+ for (const e of sorted) {
40
+ group.push(e);
41
+ if (isDelimiter(e)) {
42
+ cycles.push(toCycle(group, true, countUnits));
43
+ group = [];
44
+ }
45
+ }
46
+ if (group.length > 0)
47
+ cycles.push(toCycle(group, false, countUnits));
48
+ return cycles;
49
+ }
50
+ //# sourceMappingURL=cycles.js.map
@@ -0,0 +1,12 @@
1
+ export { parseCsv } from './csv.js';
2
+ export { classify } from './classify.js';
3
+ export { normalise, SUPPORTED_EVENT_TYPES, isSupportedEventType } from './normalise.js';
4
+ export { decomposeComposite } from './composite.js';
5
+ export { sessionise, countKinds } from './sessionise.js';
6
+ export { segmentCycles } from './cycles.js';
7
+ export { flagOutliers, median } from './anomaly.js';
8
+ export { discoverMotif, stepLabel } from './motif.js';
9
+ export { resourceSegments, isCompositeContainer } from './resource.js';
10
+ export { eventMs, byTime } from './time.js';
11
+ export type { ActivityKind, ActivityEvent, CsvRecord, KindCounts, Run, Cycle, OutlierFlag, OutlierReport, Transition, MotifReport, CompositeJoinResult, } from './types.js';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,11 @@
1
+ export { parseCsv } from './csv.js';
2
+ export { classify } from './classify.js';
3
+ export { normalise, SUPPORTED_EVENT_TYPES, isSupportedEventType } from './normalise.js';
4
+ export { decomposeComposite } from './composite.js';
5
+ export { sessionise, countKinds } from './sessionise.js';
6
+ export { segmentCycles } from './cycles.js';
7
+ export { flagOutliers, median } from './anomaly.js';
8
+ export { discoverMotif, stepLabel } from './motif.js';
9
+ export { resourceSegments, isCompositeContainer } from './resource.js';
10
+ export { eventMs, byTime } from './time.js';
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,14 @@
1
+ import type { ActivityEvent, MotifReport } from './types.js';
2
+ /** The label a transition is counted against. */
3
+ export declare function stepLabel(e: ActivityEvent): string;
4
+ /**
5
+ * Recover the repeating sequence from observed transitions.
6
+ *
7
+ * Bigram counts over operation:entity. On one real integration, 8 transitions covered 99% of
8
+ * 1,782 and recovered the job's cycle exactly, which made the remaining tail — the departures
9
+ * from its own pattern — the interesting part.
10
+ */
11
+ export declare function discoverMotif(events: readonly ActivityEvent[], opts?: {
12
+ dominantShare?: number;
13
+ }): MotifReport;
14
+ //# sourceMappingURL=motif.d.ts.map
@@ -0,0 +1,47 @@
1
+ import { byTime } from './time.js';
2
+ /** The label a transition is counted against. */
3
+ export function stepLabel(e) {
4
+ return `${e.operation}:${e.entity ?? '-'}`;
5
+ }
6
+ /**
7
+ * Recover the repeating sequence from observed transitions.
8
+ *
9
+ * Bigram counts over operation:entity. On one real integration, 8 transitions covered 99% of
10
+ * 1,782 and recovered the job's cycle exactly, which made the remaining tail — the departures
11
+ * from its own pattern — the interesting part.
12
+ */
13
+ export function discoverMotif(events, opts) {
14
+ const dominantShare = opts?.dominantShare ?? 0.95;
15
+ if (events.length < 2)
16
+ return { transitions: [], dominant: [], offPattern: [] };
17
+ const sorted = [...events].sort(byTime);
18
+ const counts = new Map();
19
+ for (let i = 1; i < sorted.length; i += 1) {
20
+ const from = stepLabel(sorted[i - 1]);
21
+ const to = stepLabel(sorted[i]);
22
+ const key = `${from}|${to}`;
23
+ const cur = counts.get(key);
24
+ if (cur === undefined)
25
+ counts.set(key, { from, to, count: 1 });
26
+ else
27
+ cur.count += 1;
28
+ }
29
+ const total = [...counts.values()].reduce((a, t) => a + t.count, 0);
30
+ const transitions = [...counts.values()]
31
+ .map((t) => ({ ...t, share: t.count / total }))
32
+ .sort((a, b) => b.count - a.count ||
33
+ (a.from < b.from ? -1 : a.from > b.from ? 1 : a.to < b.to ? -1 : a.to > b.to ? 1 : 0));
34
+ // Walk most-frequent-first until the cumulative share reaches the threshold. Everything
35
+ // after that point is the tail.
36
+ const dominant = [];
37
+ let cumulative = 0;
38
+ for (const t of transitions) {
39
+ if (cumulative >= dominantShare)
40
+ break;
41
+ dominant.push(t);
42
+ cumulative += t.share;
43
+ }
44
+ const offPattern = transitions.slice(dominant.length);
45
+ return { transitions, dominant, offPattern };
46
+ }
47
+ //# sourceMappingURL=motif.js.map
@@ -0,0 +1,12 @@
1
+ import type { ActivityEvent, CsvRecord } from './types.js';
2
+ export declare const SUPPORTED_EVENT_TYPES: readonly string[];
3
+ export declare function isSupportedEventType(eventType: string): boolean;
4
+ /**
5
+ * Turn parsed log rows into ActivityEvents.
6
+ *
7
+ * Throws on an unsupported event type. Returning [] was rejected: an empty array is
8
+ * indistinguishable from a captured-but-quiet day, and that confusion is the whole reason the
9
+ * spec's failure-mode table exists.
10
+ */
11
+ export declare function normalise(rows: readonly CsvRecord[], eventType: string): ActivityEvent[];
12
+ //# sourceMappingURL=normalise.d.ts.map
@@ -0,0 +1,176 @@
1
+ import { classify } from './classify.js';
2
+ /** Trim, and treat the empty string as absent. Logs use '' where a field does not apply. */
3
+ function opt(v) {
4
+ const t = (v ?? '').trim();
5
+ return t === '' ? undefined : t;
6
+ }
7
+ /**
8
+ * Normalise a log timestamp to ISO 8601 UTC with milliseconds.
9
+ *
10
+ * Returns undefined for anything unparseable, which causes the row to be skipped. An event with
11
+ * no time cannot be sequenced, and a fabricated time would be worse than a missing row.
12
+ */
13
+ function toIso(v) {
14
+ const raw = (v ?? '').trim();
15
+ if (raw === '')
16
+ return undefined;
17
+ const ms = Date.parse(raw);
18
+ if (Number.isNaN(ms))
19
+ return undefined;
20
+ return new Date(ms).toISOString();
21
+ }
22
+ const apiTotalUsage = (row, eventType) => {
23
+ const at = toIso(row.TIMESTAMP_DERIVED ?? row.TIMESTAMP);
24
+ if (at === undefined)
25
+ return undefined;
26
+ const family = opt(row.API_FAMILY) ?? 'REST';
27
+ // SOAP leaves HTTP_METHOD blank and puts the operation name in API_RESOURCE.
28
+ const isSoap = family.toLowerCase() === 'soap';
29
+ const resource = opt(row.API_RESOURCE);
30
+ const operation = (isSoap ? resource : opt(row.HTTP_METHOD)) ?? '';
31
+ return {
32
+ at,
33
+ actor: opt(row.USER_NAME) ?? opt(row.USER_ID) ?? '',
34
+ actorId: opt(row.USER_ID),
35
+ app: opt(row.CONNECTED_APP_NAME),
36
+ family,
37
+ operation,
38
+ entity: opt(row.ENTITY_NAME),
39
+ resource: isSoap ? undefined : resource,
40
+ kind: classify({ family, operation, resource: isSoap ? undefined : resource }),
41
+ requestId: opt(row.REQUEST_ID),
42
+ sourceIp: opt(row.CLIENT_IP),
43
+ status: opt(row.STATUS_CODE),
44
+ eventType,
45
+ raw: row,
46
+ };
47
+ };
48
+ const restApi = (row, eventType) => {
49
+ const at = toIso(row.TIMESTAMP_DERIVED ?? row.TIMESTAMP);
50
+ if (at === undefined)
51
+ return undefined;
52
+ const operation = opt(row.METHOD) ?? '';
53
+ const resource = opt(row.URI);
54
+ const actorId = opt(row.USER_ID_DERIVED) ?? opt(row.USER_ID);
55
+ return {
56
+ at,
57
+ actor: actorId ?? '',
58
+ actorId,
59
+ // Deliberately not mapped. RestApi carries CONNECTED_APP_ID, not a name, and its id space
60
+ // differs from ApiTotalUsage's for the same app — the two logs use different id prefixes —
61
+ // so writing it into `app` — documented as CONNECTED_APP_NAME — would make one app appear
62
+ // as two in any grouping. Attribution for composite children comes from the parent instead.
63
+ // See the "do not join two event types on connected-app id" rule in the design.
64
+ app: undefined,
65
+ family: 'REST',
66
+ operation,
67
+ entity: opt(row.ENTITY_NAME),
68
+ resource,
69
+ kind: classify({ family: 'REST', operation, resource }),
70
+ requestId: opt(row.REQUEST_ID),
71
+ sourceIp: opt(row.CLIENT_IP),
72
+ status: opt(row.STATUS_CODE),
73
+ eventType,
74
+ raw: row,
75
+ };
76
+ };
77
+ const compositeSubrequest = (row, eventType) => {
78
+ const at = toIso(row.TIMESTAMP_DERIVED ?? row.TIMESTAMP);
79
+ if (at === undefined)
80
+ return undefined;
81
+ const operation = opt(row.METHOD) ?? '';
82
+ const resource = opt(row.URI);
83
+ const actorId = opt(row.USER_ID) ?? opt(row.USER_ID_DERIVED);
84
+ return {
85
+ at,
86
+ actor: actorId ?? '',
87
+ actorId,
88
+ app: undefined,
89
+ family: 'REST',
90
+ operation,
91
+ entity: undefined,
92
+ resource,
93
+ kind: classify({ family: 'REST', operation, resource }),
94
+ requestId: opt(row.REQUEST_ID),
95
+ sourceIp: opt(row.CLIENT_IP),
96
+ status: opt(row.STATUS_CODE),
97
+ eventType,
98
+ raw: row,
99
+ };
100
+ };
101
+ const legacyApi = (row, eventType) => {
102
+ const at = toIso(row.TIMESTAMP_DERIVED ?? row.TIMESTAMP);
103
+ if (at === undefined)
104
+ return undefined;
105
+ const family = opt(row.API_TYPE) ?? 'SOAP';
106
+ const operation = opt(row.METHOD_NAME) ?? '';
107
+ return {
108
+ at,
109
+ actor: opt(row.USER_ID) ?? '',
110
+ actorId: opt(row.USER_ID),
111
+ app: opt(row.CLIENT_NAME),
112
+ family,
113
+ operation,
114
+ entity: opt(row.ENTITY_NAME),
115
+ resource: undefined,
116
+ kind: classify({ family, operation }),
117
+ requestId: opt(row.REQUEST_ID),
118
+ sourceIp: opt(row.CLIENT_IP),
119
+ status: undefined,
120
+ eventType,
121
+ raw: row,
122
+ };
123
+ };
124
+ const login = (row, eventType) => {
125
+ const at = toIso(row.TIMESTAMP_DERIVED ?? row.TIMESTAMP);
126
+ if (at === undefined)
127
+ return undefined;
128
+ return {
129
+ at,
130
+ actor: opt(row.USER_ID) ?? '',
131
+ actorId: opt(row.USER_ID),
132
+ app: opt(row.APP_NAME) ?? opt(row.APPLICATION),
133
+ family: 'LOGIN',
134
+ operation: 'login',
135
+ entity: undefined,
136
+ resource: undefined,
137
+ kind: 'control',
138
+ requestId: opt(row.REQUEST_ID),
139
+ sourceIp: opt(row.CLIENT_IP) ?? opt(row.SOURCE_IP),
140
+ status: opt(row.LOGIN_STATUS),
141
+ eventType,
142
+ raw: row,
143
+ };
144
+ };
145
+ const ADAPTERS = {
146
+ ApiTotalUsage: apiTotalUsage,
147
+ RestApi: restApi,
148
+ CompositeApiSubrequest: compositeSubrequest,
149
+ API: legacyApi,
150
+ Login: login,
151
+ };
152
+ export const SUPPORTED_EVENT_TYPES = Object.keys(ADAPTERS);
153
+ export function isSupportedEventType(eventType) {
154
+ return Object.prototype.hasOwnProperty.call(ADAPTERS, eventType);
155
+ }
156
+ /**
157
+ * Turn parsed log rows into ActivityEvents.
158
+ *
159
+ * Throws on an unsupported event type. Returning [] was rejected: an empty array is
160
+ * indistinguishable from a captured-but-quiet day, and that confusion is the whole reason the
161
+ * spec's failure-mode table exists.
162
+ */
163
+ export function normalise(rows, eventType) {
164
+ const adapter = ADAPTERS[eventType];
165
+ if (adapter === undefined) {
166
+ throw new Error(`No normaliser for EventLogFile type '${eventType}'. Supported: ${SUPPORTED_EVENT_TYPES.join(', ')}.`);
167
+ }
168
+ const out = [];
169
+ for (const row of rows) {
170
+ const e = adapter(row, eventType);
171
+ if (e !== undefined)
172
+ out.push(e);
173
+ }
174
+ return out;
175
+ }
176
+ //# sourceMappingURL=normalise.js.map
@@ -0,0 +1,11 @@
1
+ /** Path segments of an API resource with any version prefix removed, lowercased. */
2
+ export declare function resourceSegments(resource: string): string[];
3
+ /**
4
+ * A composite container: `composite`, optionally followed by `graph`, and nothing else.
5
+ *
6
+ * One definition, used by both classify() and decomposeComposite(). Written twice before, and
7
+ * the two copies disagreed: a substring search treated `/v58.0/sobjects/Composite` as a
8
+ * container, while the first-segment approach correctly does not.
9
+ */
10
+ export declare function isCompositeContainer(resource: string): boolean;
11
+ //# sourceMappingURL=resource.d.ts.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * True for an API version path segment: `v61`, `v61.0`. Hand-written rather than a regex.
3
+ *
4
+ * The regex this replaces, `/\/v[\d.]+\//`, was a polynomial ReDoS: `[\d.]+` can match the
5
+ * `.` and `/` that delimit it, so an input of many repeated `/v./` sequences made the engine
6
+ * retry every split point. Resource strings come straight from log rows, in volume, so the
7
+ * input is attacker-shaped in exactly the way that matters. A single pass with no alternation
8
+ * and no quantifier cannot backtrack.
9
+ */
10
+ function isVersionSegment(segment) {
11
+ if (segment.length < 2 || segment[0] !== 'v')
12
+ return false;
13
+ let dots = 0;
14
+ for (let i = 1; i < segment.length; i += 1) {
15
+ const c = segment[i];
16
+ if (c === '.') {
17
+ dots += 1;
18
+ if (dots > 1)
19
+ return false;
20
+ }
21
+ else if (c < '0' || c > '9') {
22
+ return false;
23
+ }
24
+ }
25
+ return true;
26
+ }
27
+ /** Path segments of an API resource with any version prefix removed, lowercased. */
28
+ export function resourceSegments(resource) {
29
+ const segments = resource
30
+ .trim()
31
+ .toLowerCase()
32
+ .split('?')[0]
33
+ .split('/')
34
+ .filter((s) => s !== '');
35
+ // Drop the version and everything before it, so `/services/data/v61.0/sobjects/account` and
36
+ // `/v61.0/sobjects/account` describe the same call.
37
+ const version = segments.findIndex(isVersionSegment);
38
+ return version === -1 ? segments : segments.slice(version + 1);
39
+ }
40
+ /**
41
+ * A composite container: `composite`, optionally followed by `graph`, and nothing else.
42
+ *
43
+ * One definition, used by both classify() and decomposeComposite(). Written twice before, and
44
+ * the two copies disagreed: a substring search treated `/v58.0/sobjects/Composite` as a
45
+ * container, while the first-segment approach correctly does not.
46
+ */
47
+ export function isCompositeContainer(resource) {
48
+ const s = resourceSegments(resource);
49
+ return s[0] === 'composite' && (s.length === 1 || (s.length === 2 && s[1] === 'graph'));
50
+ }
51
+ //# sourceMappingURL=resource.js.map
@@ -0,0 +1,10 @@
1
+ import type { ActivityEvent, KindCounts, Run } from './types.js';
2
+ export declare function countKinds(events: readonly ActivityEvent[]): KindCounts;
3
+ /**
4
+ * Group events into runs, splitting wherever the idle gap is exceeded.
5
+ *
6
+ * A gap exactly equal to idleGapMs stays in the same run: the threshold is the longest silence
7
+ * still considered continuous.
8
+ */
9
+ export declare function sessionise(events: readonly ActivityEvent[], idleGapMs: number): Run[];
10
+ //# sourceMappingURL=sessionise.d.ts.map
@@ -0,0 +1,52 @@
1
+ import { byTime, eventMs } from './time.js';
2
+ export function countKinds(events) {
3
+ const k = { read: 0, write: 0, destructive: 0, control: 0, unknown: 0 };
4
+ for (const e of events)
5
+ k[e.kind] += 1;
6
+ return k;
7
+ }
8
+ function toRun(group) {
9
+ const from = group[0].at;
10
+ const to = group[group.length - 1].at;
11
+ const durationMs = eventMs(to) - eventMs(from);
12
+ const seconds = durationMs / 1000;
13
+ const apps = [...new Set(group.map((e) => e.app).filter((a) => a !== undefined))];
14
+ return {
15
+ from,
16
+ to,
17
+ count: group.length,
18
+ kinds: countKinds(group),
19
+ durationMs,
20
+ // A zero-duration run has no elapsed time to divide by, so its rate is just its count:
21
+ // finite and comparable rather than Infinity. Runs with real elapsed time use it, because
22
+ // flooring a 196ms burst of 50 calls to "50/s" hides a 255/s burst from the outlier pass.
23
+ ratePerSec: durationMs === 0 ? group.length : group.length / (durationMs / 1000),
24
+ apps,
25
+ };
26
+ }
27
+ /**
28
+ * Group events into runs, splitting wherever the idle gap is exceeded.
29
+ *
30
+ * A gap exactly equal to idleGapMs stays in the same run: the threshold is the longest silence
31
+ * still considered continuous.
32
+ */
33
+ export function sessionise(events, idleGapMs) {
34
+ if (events.length === 0)
35
+ return [];
36
+ const sorted = [...events].sort(byTime);
37
+ const runs = [];
38
+ let group = [sorted[0]];
39
+ for (let i = 1; i < sorted.length; i += 1) {
40
+ const gap = eventMs(sorted[i].at) - eventMs(sorted[i - 1].at);
41
+ if (gap > idleGapMs) {
42
+ runs.push(toRun(group));
43
+ group = [sorted[i]];
44
+ }
45
+ else {
46
+ group.push(sorted[i]);
47
+ }
48
+ }
49
+ runs.push(toRun(group));
50
+ return runs;
51
+ }
52
+ //# sourceMappingURL=sessionise.js.map
@@ -0,0 +1,15 @@
1
+ /** Milliseconds for an ActivityEvent.at. Throws rather than let NaN ride. */
2
+ export declare function eventMs(iso: string): number;
3
+ /**
4
+ * Chronological comparator.
5
+ *
6
+ * Compares parsed time, not string order. A lexicographic compare on `at` is only correct while
7
+ * every producer emits Z-suffixed millisecond ISO; a non-Z offset sorts wrong and yields a `to`
8
+ * earlier than its `from`, a negative durationMs and a negative rate, silently.
9
+ */
10
+ export declare const byTime: (a: {
11
+ at: string;
12
+ }, b: {
13
+ at: string;
14
+ }) => number;
15
+ //# sourceMappingURL=time.d.ts.map
@@ -0,0 +1,17 @@
1
+ /** Milliseconds for an ActivityEvent.at. Throws rather than let NaN ride. */
2
+ export function eventMs(iso) {
3
+ const t = Date.parse(iso);
4
+ if (Number.isNaN(t)) {
5
+ throw new Error(`Unparseable ActivityEvent.at: ${JSON.stringify(iso)}`);
6
+ }
7
+ return t;
8
+ }
9
+ /**
10
+ * Chronological comparator.
11
+ *
12
+ * Compares parsed time, not string order. A lexicographic compare on `at` is only correct while
13
+ * every producer emits Z-suffixed millisecond ISO; a non-Z offset sorts wrong and yields a `to`
14
+ * earlier than its `from`, a negative durationMs and a negative rate, silently.
15
+ */
16
+ export const byTime = (a, b) => eventMs(a.at) - eventMs(b.at);
17
+ //# sourceMappingURL=time.js.map
@@ -0,0 +1,102 @@
1
+ /** What an operation did to data. `unknown` is a real answer, not a fallback. */
2
+ export type ActivityKind = 'read' | 'write' | 'destructive' | 'control' | 'unknown';
3
+ /** One parsed row of an EventLogFile log body. Not the EventLogFileRow metadata record. */
4
+ export type CsvRecord = Readonly<Record<string, string>>;
5
+ export interface ActivityEvent {
6
+ /** ISO 8601, millisecond precision, UTC. */
7
+ at: string;
8
+ /** As captured: a username from USER_NAME, or an id from USER_ID. */
9
+ actor: string;
10
+ /** Present when the source carries an id as well as, or instead of, a name. */
11
+ actorId?: string;
12
+ /** CONNECTED_APP_NAME. Absent for CLI traffic, which the logs leave blank. */
13
+ app?: string;
14
+ /** SOAP | REST | BULK, verbatim from the log. */
15
+ family: string;
16
+ /** query | create | update | GET | POST — the operation, however the log spells it. */
17
+ operation: string;
18
+ entity?: string;
19
+ /** API_RESOURCE or URI. */
20
+ resource?: string;
21
+ kind: ActivityKind;
22
+ /** The composite join key. */
23
+ requestId?: string;
24
+ sourceIp?: string;
25
+ status?: string;
26
+ /** The EventLogFile type this came from. */
27
+ eventType: string;
28
+ /** Verbatim Salesforce field names, so a row can be traced back to the org. */
29
+ raw: CsvRecord;
30
+ /** Set on a composite container whose subrequests were resolved. Its own `kind` stays
31
+ * `unknown` because a container has no operation of its own — consumers should exclude
32
+ * marked events from totals rather than counting them as unclassified. */
33
+ decomposedInto?: number;
34
+ }
35
+ export interface KindCounts {
36
+ read: number;
37
+ write: number;
38
+ destructive: number;
39
+ control: number;
40
+ unknown: number;
41
+ }
42
+ export interface Run {
43
+ from: string;
44
+ to: string;
45
+ count: number;
46
+ kinds: KindCounts;
47
+ durationMs: number;
48
+ ratePerSec: number;
49
+ /** Distinct apps seen, so a shared identity is visible rather than averaged away. */
50
+ apps: string[];
51
+ }
52
+ export interface Cycle {
53
+ from: string;
54
+ to: string;
55
+ count: number;
56
+ kinds: KindCounts;
57
+ durationMs: number;
58
+ /** Caller-counted unit of work. Never below 1. */
59
+ units: number;
60
+ msPerUnit: number;
61
+ /** False for a trailing group with no delimiter. */
62
+ complete: boolean;
63
+ steps: ActivityEvent[];
64
+ }
65
+ export interface OutlierFlag<T> {
66
+ item: T;
67
+ value: number;
68
+ severity: 'slow' | 'hung' | null;
69
+ }
70
+ export interface OutlierReport<T> {
71
+ flags: Array<OutlierFlag<T>>;
72
+ median: number;
73
+ mad: number;
74
+ /** True below 12 items: a prompt to look, not proof. */
75
+ underpowered: boolean;
76
+ }
77
+ export interface Transition {
78
+ from: string;
79
+ to: string;
80
+ count: number;
81
+ /** Fraction of all transitions, 0..1. */
82
+ share: number;
83
+ }
84
+ export interface MotifReport {
85
+ transitions: Transition[];
86
+ /** Transitions inside the dominant share, most frequent first. */
87
+ dominant: Transition[];
88
+ /** The remainder — where the actor departed from its own pattern. */
89
+ offPattern: Transition[];
90
+ }
91
+ export interface CompositeJoinResult {
92
+ events: ActivityEvent[];
93
+ /** Parents whose children were found and attached. */
94
+ resolved: number;
95
+ /** Parents left `unknown` because no children were available. */
96
+ unresolved: number;
97
+ /** Children with no parent in the input. Retained, never dropped. */
98
+ orphans: number;
99
+ /** Parents sharing a requestId already resolved. Retained as events, children not re-attached. */
100
+ duplicates: number;
101
+ }
102
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
package/lib/index.d.ts CHANGED
@@ -27,4 +27,5 @@ export { RISK_LEVELS } from './findings/RiskLevel.js';
27
27
  export * from './platform/index.js';
28
28
  export * from './schemas/index.js';
29
29
  export * from './graph/index.js';
30
+ export * from './activity/index.js';
30
31
  //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -23,4 +23,6 @@ export * from './schemas/index.js';
23
23
  // sf-orgintel can both produce fragments of one schema without either depending on the other.
24
24
  // See sf-orgviz/docs/CONVERGENCE_SPEC.md section 1.2.
25
25
  export * from './graph/index.js';
26
+ // --- Activity engine ---
27
+ export * from './activity/index.js';
26
28
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-core",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Shared platform layer for CloudCounsel Salesforce sf plugins — API clients, org context, event log pull, report shell, and versioned IR schemas.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",