portable-agent-layer 0.116.0 → 0.117.0-canary.1

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/README.md CHANGED
@@ -238,6 +238,7 @@ PAL ships with built-in skills that extend your agent's capabilities:
238
238
  | `humanize` | Rewrite text to strip AI tells and read as human |
239
239
  | `onboarding` | Interview the user to fill empty TELOS topics and the timezone, one topic at a time |
240
240
  | `pal-analyze` | Surface rating trends, failure patterns, and graduation candidates |
241
+ | `pareto-analyze` | Find the few units that drive most of an outcome (tests, clients, costs, habits) and propose one move per top cause |
241
242
  | `playwright` | Screenshot a page for a visual check |
242
243
  | `presentation` | Build branded slide decks from outlines |
243
244
  | `projects` | Look up, resume, register, or manage tracked projects |
@@ -6,7 +6,7 @@ model: claude-sonnet-5-5
6
6
 
7
7
  You write the tests first. Each acceptance criterion in the spec gets at least one test that checks it through behaviour, not implementation details.
8
8
 
9
- Test each criterion at its widest reading. Where a criterion says any, every, each, never or always, at least one test uses the plainest input those words cover. When a criterion's code writes state (a file, an event, an attachment), add a test that runs it twice and asserts the second run adds and changes nothing. Never read plan.md for acceptance tests; they come from spec.md alone.
9
+ Test each criterion at its widest reading. Where a criterion says any, every, each, never or always, at least one test uses the plainest input those words cover. When a criterion's code writes state (a file, an event, an attachment), add a test that runs it twice and asserts the second run adds and changes nothing. Never read plan.md for acceptance tests; they come from spec.md alone. When your instructions ask for unit tests from plan.md's example tables, read plan.md: the rule above is about acceptance tests only. An example table is any table in plan.md whose rows give inputs and their expected output.
10
10
 
11
11
  Follow the repo's existing test layout, helpers and fixtures. A fake program, script or path in a test must work on every OS the repo's CI runs. Reuse the repo's existing way of faking a binary, or inject a function, and never write a POSIX shell script for it. Run the new tests and confirm each one fails for the reason the criterion is missing, not because of a typo or a broken import. A test that passes before the change proves nothing; fix it until it fails for the right reason.
12
12
 
@@ -0,0 +1,139 @@
1
+ ---
2
+ name: pareto-analyze
3
+ license: MIT
4
+ description: "Finds the few units that drive most of an outcome (roughly the 20% behind 80%) in any domain, from a number per unit: the slowest tests, the costliest jobs, the clients who bring most revenue, the foods behind most excess calories, the one lever that fixes most of a problem. Ranks the units with a deterministic tool, finds the trait the top units share, and proposes one structural move per top cause, then stops for approval. Use when the user asks where to focus, what to cut or fix first, which few things matter most, for an 80/20 or Pareto analysis, or for the biggest offenders or contributors behind a total. Not for a single root-cause hunt without per-unit numbers, and not for answering a health question by itself."
5
+ argument-hint: <problem or goal, and where the numbers are>
6
+ metadata:
7
+ source: portable-agent-layer
8
+ triggers:
9
+ - "pareto-analyze"
10
+ - "pareto analyze"
11
+ - "80/20"
12
+ - "pareto principle"
13
+ - "biggest offenders"
14
+ - "find the 20 percent"
15
+ - "where to focus"
16
+ ---
17
+
18
+ Find the few units that drive most of the outcome in $ARGUMENTS, so effort goes where it pays most. The result is approximate: "about 20% of the units carry about 80%" is a shape to test for, not a law. Some problems do not have it, and saying so is a valid result.
19
+
20
+ ## Workflow
21
+
22
+ 1. **Frame the outcome and the units.** State three things in one line each:
23
+ - **Outcome**: the one number being analyzed, with its unit of measure (seconds, currency, kcal, failures).
24
+ - **Direction**: more of it (revenue, sign-ups) or less of it (time, cost, failures, calories).
25
+ - **Units**: what gets ranked. Units are one of two kinds:
26
+ - **items** carry the measure themselves: tests, jobs, clients, endpoints, invoices.
27
+ - **levers** contribute to the outcome: foods, habits, treatments, causes, channels.
28
+
29
+ When the outcome is an excess over a target or plan, the value of a unit is the part that removing it would take away, not its raw total. Units that are part of the plan are not ranked.
30
+
31
+ If the outcome or the units can be read in more than one way, ask the user once, in a single question that names your recommended default. Otherwise proceed without asking.
32
+ 2. **Run the fit check.** It flags exactly one case: levers that depend on each other so much that their contributions cannot be separated (each works only together with another, or one only matters once another is in place). In that case do not rank. Tell the user which levers are entangled, name the combination as one unit if that is meaningful, and stop or continue with the separable units only.
33
+ 3. **Measure before theorizing.** Get one number per unit before naming any cause. Label every number as one of two kinds:
34
+ - **measured**: the user's own data. A command run now, a CSV or CRM export, logs, a billing report, a food or time log. Name the source and the period it covers.
35
+ - **estimated**: an effect size from research, with the source named. For any health, medical, nutrition or exercise estimate, invoke the `scientific-research` skill and use the figures it returns; never take them from memory.
36
+
37
+ Put all values on one scale. If estimated levers cannot be put on one scale, do not compute shares: list them in order of effect with their sources and say the shares are unknown. When a measured number and an estimated one disagree about the same unit, the measured one wins. Cover every unit, not a sample of the ones that look large; if some units could not be measured, count them and report them as unmeasured.
38
+ 4. **Rank with the tool.** Write the numbers to a CSV file with one row per unit (or per observation; rows naming the same unit are summed), a value column, an `evidence` column holding `measured: <source>` or `estimated: <source>`, and no trait columns yet. Run:
39
+
40
+ ```bash
41
+ pal cli skill run pareto-analyze pareto <file> --unit <unit column> --value <value column>
42
+ ```
43
+
44
+ Take every share, cumulative share and the cut-off from its output. Do not compute or round them yourself. Read the `Shape` line:
45
+ - `concentrated`: a third of the units or fewer reach the cut-off. Continue.
46
+ - `weak`: between a third and a half of the units are needed. Continue, and tell the user the concentration is weak.
47
+ - `flat`: more than half of the units are needed. Tell the user plainly that no small set drives this outcome, show the table, and skip to step 6 with no proposed moves. With fewer than five units, treat the shape label as uninformative and say so.
48
+ 5. **Find what the top units share.** This is where the leverage is: one cause shared by the top units is worth more than the list of them. When the top set is a single unit, that unit is the cause: skip this step and say so in the report.
49
+ 1. Name two to five candidate traits. A trait is a fact that can be checked for a unit: "starts a subprocess", "came through referral", "eaten after 8 pm", "runs on the largest instance type".
50
+ 2. Check each trait for ALL units, top and tail, with the same check: a search over the code, a field in the export, a question to the user about the log. Never fill a trait from a unit's name or from what seems likely. Leave the cell blank when the check gives no answer.
51
+ 3. Add one column per trait to the file and run the tool once more, with one `--group-by` per trait:
52
+
53
+ ```bash
54
+ pal cli skill run pareto-analyze pareto <file> --unit <unit column> --value <value column> --group-by <trait> --group-by <other trait>
55
+ ```
56
+
57
+ 4. A trait is a top cause when one of its groups holds most of the units in the top set AND a share of the total close to the cut-off. A group that holds the top units but a small share, or a large share spread over many tail units, is not one. Report the `(unknown)` and `(mixed)` shares for the trait you pick: they are the part of the outcome the cause does not explain.
58
+ 5. When no trait qualifies, say that the top units share no checked trait, and treat each top unit as its own cause.
59
+ 6. **Report, then stop.** Produce the output below. Propose moves only for top causes: nothing for units or groups below the cut-off, even when a fix for them is obvious. Then stop and wait for the user's approval. Make no edit, send nothing and change nothing before it.
60
+
61
+ ## The pareto tool
62
+
63
+ ```bash
64
+ pal cli skill run pareto-analyze pareto <file.csv|file.json> [--unit <column>] [--value <column>] [--group-by <column>]... [--cutoff <percent>] [--limit <rows>]
65
+ ```
66
+
67
+ - Input: a CSV with a header row, or a JSON array of flat objects. `--unit` defaults to a column named `unit`, `--value` to one named `value`.
68
+ - Output: a table sorted by contribution with `n` (rows summed into the unit), value, share and cumulative share; a marker on the row where the cumulative share reaches the cut-off; a `Cut-off` line with how many units that took; a `Shape` line; and one table per `--group-by` with each group's units, units in the top set, value and share, followed by the unknown share.
69
+ - `--cutoff` changes the 80% target. `--limit` sets how many unit rows are printed before the rest collapse into one row (default 30, `0` prints all).
70
+ - It refuses negative values. When an outcome has gains and losses, analyze each side in its own run.
71
+
72
+ ## Output format
73
+
74
+ Return exactly these sections, in this order:
75
+
76
+ ```markdown
77
+ ## Pareto: <outcome>, <more of it | less of it>
78
+
79
+ **Units:** <items | levers>: <what a unit is>. **Period and source:** <what the numbers cover>.
80
+
81
+ ### Ranking
82
+
83
+ | unit or cause | n | value | share | cumulative share | evidence |
84
+ |---|---|---|---|---|---|
85
+ | <rows from the tool, down to the cut-off row, then one row for the rest> |
86
+
87
+ <The tool's Cut-off and Shape lines, in one sentence.>
88
+
89
+ ### What the top units share
90
+
91
+ <The trait, how it was checked for every unit, its group's row from the tool (units, units in the top set, value, share), and the unknown share. Or: "The top units share no checked trait", with the traits that were checked.>
92
+
93
+ ### Weakest assumption
94
+
95
+ <The one assumption the result leans on most, and the measurement that would prove it wrong.>
96
+
97
+ ### Proposed moves
98
+
99
+ 1. <Top cause>: <one structural fix or move>. Expected effect: up to <the cause's measured share> of <outcome>.
100
+
101
+ Nothing has been changed. Approve a move and it will be carried out.
102
+ ```
103
+
104
+ Rules for the sections:
105
+
106
+ - **Ranking**: copy numbers from the tool output. The `evidence` cell reads `measured: <source>` or `estimated: <source>`. When a shared trait was found, add the cause's group row above the unit rows.
107
+ - **Weakest assumption**: one assumption, not a list. Typical ones: the period measured is representative; the trait causes the cost instead of merely accompanying it; an estimated effect size applies to this user.
108
+ - **Proposed moves**: a numbered list with one item per top cause and no item for anything below the cut-off. A structural move removes the cause for all units that share it (a rule, a default, a change of process), as opposed to tuning units one at a time. State the expected effect as an upper bound taken from the measured share, and label it estimated when the share was estimated. With a `flat` shape, write "No move is supported by these numbers" instead of a list.
109
+ - The last line always states that nothing was changed and asks for approval.
110
+
111
+ ## Worked example
112
+
113
+ A test suite is slow. Timing every test file (measured, one full run) and ranking the files shows that a small set of files holds most of the total time. Checking each file for candidate traits, the trait "starts a subprocess" is checked by searching every file for process-spawning calls, and its group holds nearly all of the top set and most of the total; directory and file size, checked in the same way, split the time evenly. The proposed move is structural, one for the one cause: a test preload that refuses any subprocess outside files with a dedicated name suffix, plus moving the spawning tests into such files, so that a fast tier can run every non-spawning test in seconds. Tuning the slow tests one by one is not proposed, and neither is anything for the slow non-spawning files below the cut-off.
114
+
115
+ ## Verticals
116
+
117
+ Read the matching reference before step 3 when the problem falls in one of these domains. Each lists typical metrics, where the data comes from, typical shared traits and pitfalls.
118
+
119
+ - Software (test time, CI cost, flaky failures, latency, error logs): [references/software.md](references/software.md)
120
+ - Health (sleep, diet items, exercise and other levers): [references/health.md](references/health.md)
121
+ - Sales (revenue per client, acquisition channel, churn): [references/sales.md](references/sales.md)
122
+
123
+ For any other domain, follow the workflow as written.
124
+
125
+ ## When to use
126
+
127
+ - The user asks where to focus, what to cut or fix first, or which few things matter most, and the outcome can be expressed as a number per unit.
128
+ - The user asks for an 80/20 or Pareto analysis, the biggest offenders, or the top contributors to a total.
129
+ - A total is too large or too small (suite time, cloud bill, calories, churn, revenue) and the user wants the smallest change with the largest effect.
130
+
131
+ ## Do NOT use
132
+
133
+ - Finding the root cause of one failure, or decomposing a problem that has no per-unit numbers. That is the `first-principles` skill.
134
+ - Open-ended thinking, brainstorming or weighing options. That is the `think` skill.
135
+ - Diagnosing why a PAL hook, skill or automation did not fire. That is the `reflect` skill.
136
+ - Analyzing PAL's own ratings and failure patterns. That is the `pal-analyze` skill.
137
+ - Answering a health or scientific question. That is the `scientific-research` skill; this skill calls it for effect sizes and only ranks what it returns.
138
+ - Levers that cannot be separated from each other (step 2). Say so instead of ranking.
139
+ - Carrying out the fix. This skill ends at the proposal; the work starts after the user approves.
@@ -0,0 +1,45 @@
1
+ # Pareto analysis: health
2
+
3
+ Read this before step 3 of the workflow when the outcome is about the user's body or habits: weight, energy, sleep, fitness, a symptom. Units here are usually **levers** (sleep, diet items, exercise, a treatment), and their numbers are **estimated** unless the user has their own log.
4
+
5
+ ## The evidence rule
6
+
7
+ - Every effect size that does not come from the user's own log goes through the `scientific-research` skill. Invoke it with one question per lever ("how much does <lever> change <outcome>, in <unit>, in <population>?") and use the figures and sources it returns. Never fill a value from memory.
8
+ - Label each row `estimated: <source>` or `measured: <the user's log and its period>`.
9
+ - A measured row outranks an estimated one about the same lever.
10
+ - This skill ranks levers. It does not diagnose, and it does not replace a clinician: when the outcome is a symptom, a medication or a condition, say so in the report and keep the proposed move to "raise this with your clinician first" where the lever is a treatment.
11
+
12
+ ## Typical metrics
13
+
14
+ | Outcome | Direction | Unit | Value column |
15
+ |---|---|---|---|
16
+ | Excess energy intake | less | food or drink item outside the plan | kcal over the period |
17
+ | Body weight change | less or more | lever (diet item, activity, sleep) | estimated kcal per week, all levers on that one scale |
18
+ | Poor sleep | less | lever (caffeine timing, screens, alcohol, schedule) | estimated minutes of sleep lost or gained |
19
+ | Low activity | more | activity | minutes or energy spent per week |
20
+ | A recurring symptom | less | trigger | occurrences that followed the trigger, from a diary |
21
+
22
+ ## Where the data comes from
23
+
24
+ - **The user's own log** (measured): a food diary or tracking app export, a sleep or activity tracker export, a symptom diary. Ask for at least one full week, including the weekend.
25
+ - **Research** (estimated): effect sizes returned by `scientific-research`, converted to the outcome's scale. If the levers cannot be put on one scale, do not compute shares: list them in order of effect with their sources.
26
+ - When the user has no log and the question is about their own intake or habits, recommend keeping one for a week before ranking. A ranking of estimates for an average person is a weaker answer than a week of the user's own numbers.
27
+
28
+ ## Typical shared traits
29
+
30
+ Check each for every logged item, from the log or by asking the user:
31
+
32
+ - Time of day (after dinner, late evening).
33
+ - Setting (at the desk, in front of a screen, when eating out).
34
+ - Category (sweets, sugary drinks, alcohol, fried food).
35
+ - Planned or unplanned.
36
+ - What came before it (a short night, a skipped meal, a stressful day).
37
+
38
+ ## Pitfalls
39
+
40
+ - **Entangled levers.** Many health levers work through each other (sleep, appetite and exercise are the usual example). When a lever only works through another, the fit check in step 2 applies. Rank only what can be separated, and when `scientific-research` shows one lever sitting upstream of the others, name it as the one to act on first.
41
+ - **Raw totals instead of excess.** The largest item in a food log is usually a planned meal. Rank what lies outside the plan, or the amount above the target.
42
+ - **Under-reported logs.** Snacks and drinks are the entries people forget. Report it as the weakest assumption when a log shows less than the weight trend implies.
43
+ - **One week is one week.** A holiday, an illness or a celebration distorts it. Name the period.
44
+ - **Population averages.** An estimated effect is an average over a study population and may not apply to this user. Say so, and prefer a measurement.
45
+ - **Spreading the advice.** When one item carries most of the excess, name it first and alone. A list of five small changes hides the one that pays.
@@ -0,0 +1,44 @@
1
+ # Pareto analysis: sales
2
+
3
+ Read this before step 3 of the workflow when the outcome is revenue, profit, pipeline or churn. Numbers are **measured**: they come from the user's CRM, invoicing or billing system.
4
+
5
+ ## Typical metrics
6
+
7
+ | Outcome | Direction | Unit | Value column |
8
+ |---|---|---|---|
9
+ | Revenue | more | client | invoiced amount over a period |
10
+ | Profit | more | client or product | revenue minus direct cost |
11
+ | New business | more | acquisition channel, or deal | value of deals won |
12
+ | Churn | less | lost client, or churn reason | recurring revenue lost |
13
+ | Support or delivery cost | less | client | hours or cost spent |
14
+ | Late payment | less | client | overdue amount x days |
15
+
16
+ ## Where the data comes from
17
+
18
+ - **Revenue and profit**: an export from the invoicing or accounting system, one row per invoice, with the client as the unit. Use paid or invoiced amounts, not quotes.
19
+ - **New business**: the CRM's closed-won deals with their source field.
20
+ - **Churn**: the billing system's cancellations with the recurring amount each one carried, plus the cancellation reason when it was recorded.
21
+ - **Cost to serve**: time tracking or the support system, summed per client.
22
+
23
+ Ask for a full year when the business is seasonal; state the period in the report. Write one row per invoice or deal and let the tool sum rows that name the same client.
24
+
25
+ ## Typical shared traits
26
+
27
+ Check each for every client from a field in the export, or ask the user for the ones that are not recorded:
28
+
29
+ - Acquisition channel (referral, outbound, ads, events, partner).
30
+ - Who referred them, when the channel is referral.
31
+ - Size band or industry.
32
+ - Product or plan.
33
+ - Region or sales owner.
34
+ - Age of the relationship (first-year client or long-standing).
35
+ - Contract type (recurring or one-off).
36
+
37
+ ## Pitfalls
38
+
39
+ - **Revenue is not profit.** A top client by revenue can be a bottom client by margin once cost to serve is counted. Say which of the two was ranked, and rank the other when the data exists.
40
+ - **One-off deals.** A single large project inflates one period. Check whether the top set is the same over two periods.
41
+ - **Blank source fields.** Channel fields are often empty for older clients. Report the unknown share; when it is large, the trait is not established yet, and filling the field is the next measurement.
42
+ - **Concentration is also a risk.** The clients that carry the outcome are the ones whose loss would hurt most. Name that in the weakest assumption or the move instead of only proposing to do more of the same.
43
+ - **Survivorship in churn.** Ranking churn reasons only among clients who gave a reason ignores the silent ones. Report how many cancellations had no reason.
44
+ - **Small tails still cost.** Do not propose dropping the tail from a revenue ranking alone: that needs the cost-to-serve ranking too.
@@ -0,0 +1,46 @@
1
+ # Pareto analysis: software
2
+
3
+ Read this before step 3 of the workflow when the outcome is about code, builds, tests or a running service. Numbers here are almost always **measured**: the tools already record them.
4
+
5
+ ## Typical metrics
6
+
7
+ | Outcome | Direction | Unit | Value column |
8
+ |---|---|---|---|
9
+ | Test suite time | less | test file (or test case) | seconds per file |
10
+ | CI cost or duration | less | job or step | billed minutes, or seconds, summed over a period |
11
+ | Flaky failures | less | test, or failure signature | failed runs over a period |
12
+ | Latency | less | endpoint or query | total time = calls x mean duration |
13
+ | Errors | less | error signature | occurrences over a period |
14
+ | Bundle or image size | less | module, dependency or layer | bytes |
15
+
16
+ ## Where the data comes from
17
+
18
+ - **Test time**: the test runner's per-file or per-test timing report (a JUnit XML or JSON reporter). When the runner reports only a total, run each file on its own and record the wall time.
19
+ - **CI**: the CI provider's API or usage export, one row per job run. Sum over at least a week so that one unusual run does not decide the ranking.
20
+ - **Flaky failures**: CI history of runs that failed and then passed on retry with no code change, one row per failure.
21
+ - **Latency**: tracing or access logs. Rank by total time (calls x duration), not by the slowest single call: a fast endpoint called a million times can outweigh a slow one called twice.
22
+ - **Errors**: the error tracker's grouped issues, or logs reduced to a signature (message with ids and numbers removed), one row per occurrence.
23
+ - **Size**: the bundler's or image builder's size report.
24
+
25
+ Write one row per observation and let the tool sum rows that name the same unit.
26
+
27
+ ## Typical shared traits
28
+
29
+ Check each for every unit with one search or one field, never from the file name:
30
+
31
+ - Starts a subprocess, a container, a browser or a database.
32
+ - Touches the network or the real file system instead of a fake.
33
+ - Uses a shared fixture or a particular setup step.
34
+ - Sleeps or waits on a fixed timer.
35
+ - Belongs to one dependency, one owner team or one service.
36
+ - Runs on a particular runner type, operating system or region.
37
+ - Was introduced by one change or one release (for errors and flakiness).
38
+
39
+ ## Pitfalls
40
+
41
+ - **One run is noisy.** Timings vary between runs. Measure twice, or sum several runs, before trusting a ranking where the top units are close together.
42
+ - **Parallel runs hide wall time.** Summed per-file seconds are CPU-side cost; the wall time of a parallel suite is set by its slowest worker. State which of the two the outcome is.
43
+ - **Cold caches.** A first run after a dependency change measures the cache, not the tests.
44
+ - **Counting instead of weighing.** Ten occurrences of a harmless warning are not worth more than one outage. When units differ in severity, weight the value or analyze severities separately.
45
+ - **Fixing units instead of the cause.** When the top set shares a trait, tuning its members one by one leaves the cause in place for the next file. Propose the structural move.
46
+ - **Name-based traits.** A file called `integration` may start nothing, and one called `unit` may start a server. Run the check.
@@ -0,0 +1,376 @@
1
+ #!/usr/bin/env bun
2
+ import { extname } from "node:path";
3
+ import { parseArgs as parseFlags } from "node:util";
4
+
5
+ const USAGE = `Usage: pal cli skill run pareto-analyze pareto <file.csv|file.json> [flags]
6
+
7
+ --unit <column> column that names the unit (default: unit)
8
+ --value <column> column that holds the number (default: value)
9
+ --group-by <column> also print totals per value of this trait column; repeatable
10
+ --cutoff <percent> cumulative share that ends the top set (default: 80)
11
+ --limit <rows> unit rows to print before collapsing the rest; 0 prints all (default: 30)
12
+
13
+ Rows that name the same unit are summed. A column named "evidence" is carried into the table.`;
14
+
15
+ const UNKNOWN = "(unknown)";
16
+ const MIXED = "(mixed)";
17
+ const EVIDENCE_COLUMN = "evidence";
18
+ const CSV_FIELD = /("(?:[^"]|"")*"|[^",\r\n]*)(,|\r?\n|$)/g;
19
+
20
+ type Row = Record<string, string>;
21
+
22
+ export interface Options {
23
+ file: string;
24
+ unitColumn: string;
25
+ valueColumn: string;
26
+ groupBy: string[];
27
+ cutoffPercent: number;
28
+ limit: number;
29
+ }
30
+
31
+ interface Unit {
32
+ name: string;
33
+ n: number;
34
+ value: number;
35
+ share: number;
36
+ cumulative: number;
37
+ rows: Row[];
38
+ }
39
+
40
+ interface Group {
41
+ name: string;
42
+ units: number;
43
+ inCutoff: number;
44
+ value: number;
45
+ share: number;
46
+ cumulative: number;
47
+ }
48
+
49
+ class InputError extends Error {}
50
+
51
+ function numberFlag(name: string, raw: string, min: number, max: number): number {
52
+ const parsed = Number(raw);
53
+ if (raw.trim() === "" || !Number.isFinite(parsed) || parsed < min || parsed > max) {
54
+ throw new InputError(
55
+ `--${name} must be a number from ${min} to ${max}, got "${raw}"`
56
+ );
57
+ }
58
+ return parsed;
59
+ }
60
+
61
+ export function parseArgs(argv: string[]): Options {
62
+ const { values, positionals } = parseFlags({
63
+ args: argv,
64
+ allowPositionals: true,
65
+ options: {
66
+ unit: { type: "string", default: "unit" },
67
+ value: { type: "string", default: "value" },
68
+ "group-by": { type: "string", multiple: true, default: [] },
69
+ cutoff: { type: "string", default: "80" },
70
+ limit: { type: "string", default: "30" },
71
+ },
72
+ });
73
+ const [file] = positionals;
74
+ if (!file || positionals.length > 1) throw new InputError(USAGE);
75
+ const cutoffPercent = numberFlag("cutoff", values.cutoff, 0, 100);
76
+ if (cutoffPercent === 0) throw new InputError("--cutoff must be above 0");
77
+ return {
78
+ file,
79
+ unitColumn: values.unit,
80
+ valueColumn: values.value,
81
+ groupBy: values["group-by"],
82
+ cutoffPercent,
83
+ limit: Math.floor(numberFlag("limit", values.limit, 0, Number.MAX_SAFE_INTEGER)),
84
+ };
85
+ }
86
+
87
+ function unquoted(field: string): string {
88
+ if (!field.startsWith('"')) return field.trim();
89
+ return field.slice(1, -1).replaceAll('""', '"');
90
+ }
91
+
92
+ function csvRecords(text: string): string[][] {
93
+ const records: string[][] = [[]];
94
+ let consumed = 0;
95
+ for (const [whole, field = "", end] of text.matchAll(CSV_FIELD)) {
96
+ consumed += whole.length;
97
+ records.at(-1)?.push(unquoted(field));
98
+ if (end !== ",") records.push([]);
99
+ }
100
+ if (consumed !== text.length) {
101
+ throw new InputError("Malformed CSV: a quoted field is not closed or not delimited");
102
+ }
103
+ return records.filter((record) => record.some((cell) => cell !== ""));
104
+ }
105
+
106
+ function rowFromRecord(header: string[], record: string[], line: number): Row {
107
+ if (record.length !== header.length) {
108
+ throw new InputError(
109
+ `CSV record ${line} has ${record.length} cells, the header has ${header.length}`
110
+ );
111
+ }
112
+ return Object.fromEntries(header.map((column, i) => [column, record[i] ?? ""]));
113
+ }
114
+
115
+ function parseCsv(text: string): Row[] {
116
+ const [header, ...records] = csvRecords(text.replace(/^/, ""));
117
+ if (!header) return [];
118
+ return records.map((record, i) => rowFromRecord(header, record, i + 2));
119
+ }
120
+
121
+ function cellText(cell: unknown): string {
122
+ if (cell === null || cell === undefined) return "";
123
+ return typeof cell === "object" ? JSON.stringify(cell) : String(cell).trim();
124
+ }
125
+
126
+ function parseJson(text: string): Row[] {
127
+ let parsed: unknown;
128
+ try {
129
+ parsed = JSON.parse(text);
130
+ } catch (error) {
131
+ throw new InputError(`Invalid JSON: ${(error as Error).message}`);
132
+ }
133
+ if (
134
+ !Array.isArray(parsed) ||
135
+ parsed.some((item) => typeof item !== "object" || !item)
136
+ ) {
137
+ throw new InputError("JSON input must be an array of objects, one per row");
138
+ }
139
+ return parsed.map((item: Record<string, unknown>) =>
140
+ Object.fromEntries(Object.entries(item).map(([key, cell]) => [key, cellText(cell)]))
141
+ );
142
+ }
143
+
144
+ export function parseRows(fileName: string, text: string): Row[] {
145
+ const rows =
146
+ extname(fileName).toLowerCase() === ".json" ? parseJson(text) : parseCsv(text);
147
+ if (rows.length === 0) throw new InputError(`${fileName} holds no data rows`);
148
+ return rows;
149
+ }
150
+
151
+ function requireColumn(rows: Row[], column: string): void {
152
+ const columns = Object.keys(rows[0] ?? {});
153
+ if (!columns.includes(column)) {
154
+ throw new InputError(`No column "${column}". Columns: ${columns.join(", ")}`);
155
+ }
156
+ }
157
+
158
+ function numberIn(row: Row, options: Options, line: number): number {
159
+ const raw = row[options.valueColumn] ?? "";
160
+ const value = Number(raw);
161
+ if (raw.trim() === "" || !Number.isFinite(value)) {
162
+ throw new InputError(
163
+ `Row ${line}: "${raw}" in column "${options.valueColumn}" is not a number`
164
+ );
165
+ }
166
+ if (value < 0) {
167
+ throw new InputError(
168
+ `Row ${line}: negative value ${raw}. Shares need one direction: analyze gains and losses in separate runs`
169
+ );
170
+ }
171
+ return value;
172
+ }
173
+
174
+ function sumPerUnit(rows: Row[], options: Options): Unit[] {
175
+ const units = new Map<string, Unit>();
176
+ rows.forEach((row, i) => {
177
+ const name = row[options.unitColumn]?.trim() || UNKNOWN;
178
+ const unit = units.get(name) ?? {
179
+ name,
180
+ n: 0,
181
+ value: 0,
182
+ share: 0,
183
+ cumulative: 0,
184
+ rows: [],
185
+ };
186
+ unit.n += 1;
187
+ unit.value += numberIn(row, options, i + 1);
188
+ unit.rows.push(row);
189
+ units.set(name, unit);
190
+ });
191
+ return [...units.values()];
192
+ }
193
+
194
+ function byValueThenName(a: { value: number; name: string }, b: typeof a): number {
195
+ return b.value - a.value || a.name.localeCompare(b.name);
196
+ }
197
+
198
+ function withShares<T extends { value: number; share: number; cumulative: number }>(
199
+ sorted: T[],
200
+ total: number
201
+ ): T[] {
202
+ let running = 0;
203
+ for (const entry of sorted) {
204
+ running += entry.value;
205
+ entry.share = (entry.value / total) * 100;
206
+ entry.cumulative = (running / total) * 100;
207
+ }
208
+ return sorted;
209
+ }
210
+
211
+ export function rankUnits(rows: Row[], options: Options): Unit[] {
212
+ requireColumn(rows, options.unitColumn);
213
+ requireColumn(rows, options.valueColumn);
214
+ const units = sumPerUnit(rows, options).sort(byValueThenName);
215
+ const total = units.reduce((sum, unit) => sum + unit.value, 0);
216
+ if (total <= 0) throw new InputError("Every value is 0: there is nothing to rank");
217
+ return withShares(units, total);
218
+ }
219
+
220
+ export function cutoffCount(
221
+ ranked: { cumulative: number }[],
222
+ cutoffPercent: number
223
+ ): number {
224
+ const index = ranked.findIndex((entry) => entry.cumulative >= cutoffPercent - 1e-9);
225
+ return index === -1 ? ranked.length : index + 1;
226
+ }
227
+
228
+ export function shapeOf(topCount: number, unitCount: number): string {
229
+ const unitShare = topCount / unitCount;
230
+ if (unitShare <= 1 / 3) return "concentrated";
231
+ if (unitShare <= 1 / 2) return "weak";
232
+ return "flat";
233
+ }
234
+
235
+ function traitOf(unit: Unit, column: string): string {
236
+ const distinct = new Set(unit.rows.map((row) => row[column]?.trim() || UNKNOWN));
237
+ return distinct.size === 1 ? [...distinct].join("") : MIXED;
238
+ }
239
+
240
+ export function groupTotals(ranked: Unit[], column: string, topCount: number): Group[] {
241
+ const groups = new Map<string, Group>();
242
+ ranked.forEach((unit, i) => {
243
+ const name = traitOf(unit, column);
244
+ const group = groups.get(name) ?? {
245
+ name,
246
+ units: 0,
247
+ inCutoff: 0,
248
+ value: 0,
249
+ share: 0,
250
+ cumulative: 0,
251
+ };
252
+ group.units += 1;
253
+ group.inCutoff += i < topCount ? 1 : 0;
254
+ group.value += unit.value;
255
+ groups.set(name, group);
256
+ });
257
+ const total = ranked.reduce((sum, unit) => sum + unit.value, 0);
258
+ return withShares([...groups.values()].sort(byValueThenName), total);
259
+ }
260
+
261
+ function amount(value: number): string {
262
+ return String(Number(value.toFixed(2)));
263
+ }
264
+
265
+ function percent(value: number): string {
266
+ return `${value.toFixed(1)}%`;
267
+ }
268
+
269
+ function tableOf(header: string[], lines: string[][]): string {
270
+ const asLine = (cells: string[]) =>
271
+ `| ${cells.map((cell) => cell.replaceAll("|", "\\|")).join(" | ")} |`;
272
+ return [asLine(header), asLine(header.map(() => "---")), ...lines.map(asLine)].join(
273
+ "\n"
274
+ );
275
+ }
276
+
277
+ function evidenceOf(unit: Unit): string {
278
+ const distinct = new Set(unit.rows.map((row) => row[EVIDENCE_COLUMN] ?? ""));
279
+ return [...distinct].filter(Boolean).join("; ");
280
+ }
281
+
282
+ function unitTable(ranked: Unit[], options: Options, topCount: number): string {
283
+ const hasEvidence = ranked.some((unit) => EVIDENCE_COLUMN in (unit.rows[0] ?? {}));
284
+ const shown = options.limit === 0 ? ranked : ranked.slice(0, options.limit);
285
+ const lines = shown.map((unit, i) => [
286
+ String(i + 1),
287
+ unit.name,
288
+ String(unit.n),
289
+ amount(unit.value),
290
+ percent(unit.share),
291
+ percent(unit.cumulative),
292
+ i + 1 === topCount ? `<-- ${amount(options.cutoffPercent)}%` : "",
293
+ ...(hasEvidence ? [evidenceOf(unit)] : []),
294
+ ]);
295
+ const rest = ranked.slice(shown.length);
296
+ if (rest.length > 0) {
297
+ const restValue = rest.reduce((sum, unit) => sum + unit.value, 0);
298
+ const restShare = rest.reduce((sum, unit) => sum + unit.share, 0);
299
+ const restRows = rest.reduce((sum, unit) => sum + unit.n, 0);
300
+ lines.push([
301
+ "",
302
+ `(remaining ${rest.length} units)`,
303
+ String(restRows),
304
+ amount(restValue),
305
+ percent(restShare),
306
+ percent(100),
307
+ "",
308
+ ...(hasEvidence ? [""] : []),
309
+ ]);
310
+ }
311
+ const header = [
312
+ "#",
313
+ options.unitColumn,
314
+ "n",
315
+ options.valueColumn,
316
+ "share",
317
+ "cumulative",
318
+ ];
319
+ return tableOf(
320
+ [...header, "cut-off", ...(hasEvidence ? [EVIDENCE_COLUMN] : [])],
321
+ lines
322
+ );
323
+ }
324
+
325
+ function groupSection(ranked: Unit[], column: string, topCount: number): string {
326
+ const groups = groupTotals(ranked, column, topCount);
327
+ const unknownShare = groups.find((group) => group.name === UNKNOWN)?.share ?? 0;
328
+ const lines = groups.map((group) => [
329
+ group.name,
330
+ String(group.units),
331
+ String(group.inCutoff),
332
+ amount(group.value),
333
+ percent(group.share),
334
+ percent(group.cumulative),
335
+ ]);
336
+ const header = [column, "units", "units in top set", "value", "share", "cumulative"];
337
+ return [
338
+ `Grouped by \`${column}\`:`,
339
+ "",
340
+ tableOf(header, lines),
341
+ "",
342
+ `Unknown share for \`${column}\`: ${percent(unknownShare)}`,
343
+ ].join("\n");
344
+ }
345
+
346
+ export function report(rows: Row[], options: Options): string {
347
+ const ranked = rankUnits(rows, options);
348
+ options.groupBy.forEach((column) => {
349
+ requireColumn(rows, column);
350
+ });
351
+ const topCount = cutoffCount(ranked, options.cutoffPercent);
352
+ const total = ranked.reduce((sum, unit) => sum + unit.value, 0);
353
+ const last = ranked[topCount - 1];
354
+ const summary = [
355
+ `Total ${options.valueColumn}: ${amount(total)} across ${ranked.length} units (${rows.length} rows).`,
356
+ `Cut-off: ${topCount} of ${ranked.length} units (${percent((topCount / ranked.length) * 100)} of units) reach ${percent(last?.cumulative ?? 100)} of the total (target ${amount(options.cutoffPercent)}%).`,
357
+ `Shape: ${shapeOf(topCount, ranked.length)}.`,
358
+ ].join("\n");
359
+ const groupSections = options.groupBy.map((column) =>
360
+ groupSection(ranked, column, topCount)
361
+ );
362
+ return [unitTable(ranked, options, topCount), summary, ...groupSections].join("\n\n");
363
+ }
364
+
365
+ async function run(): Promise<void> {
366
+ try {
367
+ const options = parseArgs(Bun.argv.slice(2));
368
+ const text = await Bun.file(options.file).text();
369
+ console.log(report(parseRows(options.file, text), options));
370
+ } catch (error) {
371
+ console.error(error instanceof Error ? error.message : String(error));
372
+ process.exit(1);
373
+ }
374
+ }
375
+
376
+ if (import.meta.main) await run();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "portable-agent-layer",
3
- "version": "0.116.0",
3
+ "version": "0.117.0-canary.1",
4
4
  "description": "PAL — Portable Agent Layer: persistent personal context for AI coding assistants",
5
5
  "type": "module",
6
6
  "bin": {
@@ -80,7 +80,8 @@
80
80
  "eval:correction-kind": "bun eval/correction-kind/build-prompt.ts && bun eval/run.ts correction-kind",
81
81
  "eval:correction-kind:test": "bun eval/correction-kind/test-set.ts",
82
82
  "eval:rule-drafter": "bun eval/rule-drafter/build-prompt.ts && bun eval/run.ts rule-drafter",
83
- "eval:rule-drafter:test": "bun eval/rule-drafter/test-set.ts"
83
+ "eval:rule-drafter:test": "bun eval/rule-drafter/test-set.ts",
84
+ "eval:pareto-analyze": "bun eval/pareto-analyze/build-prompt.ts && bun eval/run.ts pareto-analyze"
84
85
  },
85
86
  "lint-staged": {
86
87
  "*.ts": [
@@ -20,7 +20,11 @@ import { palHome } from "./paths";
20
20
  const EXPORT_DIRS = ["telos", "memory", "skills", "agents"];
21
21
 
22
22
  /** Subdirectories/files to skip during export. */
23
- const SKIP_PATTERNS = ["memory/downloads", "memory/content"];
23
+ const SKIP_PATTERNS = [
24
+ "memory/downloads",
25
+ "memory/content",
26
+ "memory/state/transcript-handoff",
27
+ ];
24
28
 
25
29
  function shouldSkip(relPath: string): boolean {
26
30
  const normalized = relPath.replaceAll("\\", "/");