loopengine 0.3.66 → 0.3.68

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.
@@ -1,5 +1,5 @@
1
1
  import type { ModelCall } from '#core/run-agent.js';
2
- import { type GoalFocus } from './goal-playbooks.js';
2
+ import { type Focus, type GoalFocus, type Lever } from './goal-playbooks.js';
3
3
  /** What LoopEngine knows about the person: the workspace, the website,
4
4
  * what they said. `kind` uses the playbook's vocabulary of needs (email,
5
5
  * messaging, web-search, orders-or-crm…). */
@@ -19,6 +19,27 @@ export interface GoalContext {
19
19
  weeklyHours?: number;
20
20
  }
21
21
  export type GoalScope = 'in' | 'partial' | 'out';
22
+ export interface GoalProfile {
23
+ /** The number it moves, and which way: up, down, reach a milestone, or keep it steady. */
24
+ metric: string;
25
+ direction: 'up' | 'down' | 'reach' | 'keep';
26
+ /** Limits that rule approaches out: budget, time, diet, an injury, a region… */
27
+ constraints: string[];
28
+ timeframe: string;
29
+ /** Where they start: first try, tried before, what's already in place. */
30
+ startingPoint: string;
31
+ /** What's most likely to stop this goal, and why. */
32
+ bottleneck: string;
33
+ bottleneckWhy: string;
34
+ }
35
+ /** How the plan chose its levers: every lever it looked at, chosen or
36
+ * ruled out, and why. */
37
+ export interface LeverChoice {
38
+ leverId?: string;
39
+ lever: string;
40
+ decision: 'chosen' | 'ruled_out';
41
+ reason: string;
42
+ }
22
43
  export interface GoalBrief {
23
44
  /** Whether agents can work on it: fully, only the information work
24
45
  * around it, or not at all. */
@@ -27,6 +48,9 @@ export interface GoalBrief {
27
48
  /** How the goal was read, e.g. "literal" or "a stretch goal for the business". */
28
49
  reading: string;
29
50
  focus: GoalFocus | 'other';
51
+ /** When no focus in the playbook fits: the one the planner named
52
+ * (generic words; saved in the workspace's own playbook). */
53
+ newFocus?: Focus;
30
54
  measure: string;
31
55
  /** Where the measure's number comes from (a system, or "none"), and
32
56
  * whether that's connected: when it isn't, the plan says how the
@@ -36,6 +60,9 @@ export interface GoalBrief {
36
60
  /** What the goal singles out beyond its main outcome (a segment, a
37
61
  * topic, a season…): each must be covered by a workflow. */
38
62
  qualifiers: string[];
63
+ /** What makes this goal different from others with the same focus, and
64
+ * what's most likely to stop it: levers are chosen against this. */
65
+ profile?: GoalProfile;
39
66
  audience: string;
40
67
  weeklyHours: number;
41
68
  approvals: string;
@@ -101,6 +128,12 @@ export interface GoalPlan {
101
128
  };
102
129
  /** The playbook version the plan was made with. */
103
130
  playbookVersion: number;
131
+ /** Every lever the plan looked at, chosen or ruled out, and why. */
132
+ considered?: LeverChoice[];
133
+ /** Levers the planner wrote because the playbook had none that fit
134
+ * (generic, like the playbook's own; saved in the workspace's own
135
+ * playbook, and the jobs made from them refer to them). */
136
+ newLevers?: Lever[];
104
137
  }
105
138
  export interface GoalPipelineInput {
106
139
  goal: string;
@@ -109,9 +142,30 @@ export interface GoalPipelineInput {
109
142
  /** The focus the person chose, instead of the one the brief reads. */
110
143
  focus?: GoalFocus | 'other';
111
144
  }
112
- export declare const GOAL_BRIEF_PROMPT = "You read a goal someone gives LoopEngine, a platform of AI agents that work with information and software: they search, read, write, draft, track, and act in connected apps (email, chat, stores, CRMs, payments, code hosts). They can't do physical work or run large real-world projects on their own.\n\nCall save_brief once:\n- scope: \"in\" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all \"in\"); \"partial\" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; \"out\" when there is nothing useful an agent could do. scopeReason: one sentence.\n- reading: how you read it. When the wording could be a metaphor (\"land on the moon\", \"climb Everest\" said of a business), prefer the reading the context supports and say which.\n- focus: the one stage of the goal to plan for. Growth of users means \"new-signups\" unless the goal speaks of using, keeping or activating people. Answering customers sooner is \"faster-support\". Use \"other\" only when none fits.\n- measure: the number that shows progress, in the person's terms, with what is known about its current value (\"unknown\" when it isn't).\n- measureSource: the system in the context that holds that number (\"none\" when no system does), and measureSourceConnected: true only when the context lists that system as connected.\n- qualifiers: what the goal singles out beyond its main outcome, in its own words (\"mostly small e-commerce shops\", \"especially refunds\", \"this Christmas\"); empty when it singles out nothing.\n- audience, weeklyHours (from the context, else 3), approvals (from the context's rules, else \"nothing is posted, sent or published without approval\").";
113
- export declare const GOAL_PLAN_PROMPT = "You plan workflows for a confirmed goal brief in LoopEngine. Each workflow is one recurring job for one AI agent; a person reviews what it drafts.\n\nRules:\n1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own new idea when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.\n2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.\n3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: \"list in app marketplaces\", not \"list Wick & Ember on Shopify\"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.\n4. Three to five workflows for an \"in\" goal, ordered by impact against effort, quickest useful one first; startsAfter when one depends on another. Their humanMinutesPerWeek together stay within three quarters of the brief's weeklyHours, so the plan survives a busy week.\n4b. Each one is a job: kind \"recurring\" when it runs again and again (a weekly scan, a reply to each signup), kind \"once\" for work on a finite list or done one time (submitting to a set of directories, a one-time audit, researching a list of communities). A once job is done by an agent once, in Chat; never make it a weekly job that runs out of things to do.\n4c. measure: the job's own number, in the person's terms, that shows it's working (\"replies per week\", \"signups tagged ref=directories\"); for a once job, what done looks like (\"done when: listed in 15 directories\"). A playbook lever says the kind and measure it usually has: start from those, and change them only when the context calls for it.\n5. Specific to this context: name the person's own communities, systems, products and channels in each request. A request anyone could use unchanged is wrong.\n6. needs: what each workflow uses, each with a kind from the playbook's vocabulary and connected true only when the context lists that kind as connected.\n7. Every request that posts, sends or publishes says nothing goes out without the person's approval.\n8. The measure must be readable. When measureSourceConnected is false, setup says how the number will be read: connecting that source (name it, e.g. \"connect Clerk's user.created webhook so signups and their ref are recorded\"), or, when it can't be connected, a light manual record the person updates weekly (kept with the Records ability). Always record a baseline: the number today. Tag what workflows produce (ref=<channel>) so each one's effect can be told apart.\n8b. Every qualifier in the brief is covered by at least one workflow that addresses it directly; list it in that workflow's covers.\n9. \"partial\" scope: at most three workflows, only ones that help the person pursue the goal, and say so in the message (\"helps you pursue\", never \"achieves\"). \"out\" scope: no workflows; the message says plainly why, and offers a smaller or related goal.\n10. agent: an existing agent's exact name when its work fits. When none fits, or there are no agents yet, suggest a new one: agent and newAgent.name the same short lowercase name with hyphens (e.g. \"community-agent\"), and newAgent.instructions two or three sentences on what it does and how it behaves. Group workflows that belong together in one agent rather than one agent each.\n\nCall save_plan once.";
114
- export declare const GOAL_CRITIQUE_PROMPT = "You check a goal plan against its rules before a person sees it. List every issue (be strict, quote the workflow):\n- a workflow that doesn't serve the brief's focus or move its measure;\n- two workflows on the same lever, or one repeating a lever already saved;\n- a request generic enough to fit any business;\n- a need marked connected that the context doesn't list as connected;\n- a request that posts, sends or publishes without saying it waits for approval;\n- review time over three quarters of the weekly budget;\n- a measure whose source isn't connected, with no setup step that connects it or a manual record, or no baseline;\n- a qualifier from the brief no workflow addresses;\n- a recurring job on a finite list that will run out (it should be kind \"once\");\n- a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.\nCall save_review once: passed true only when there are no issues.";
145
+ export declare const GOAL_BRIEF_PROMPT = "You read a goal someone gives LoopEngine, a platform of AI agents that work with information and software: they search, read, write, draft, track, and act in connected apps (email, chat, stores, CRMs, payments, code hosts). They can't do physical work or run large real-world projects on their own.\n\nCall save_brief once:\n- scope: \"in\" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all \"in\"); \"partial\" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; \"out\" when there is nothing useful an agent could do. scopeReason: one sentence.\n- reading: how you read it. When the wording could be a metaphor (\"land on the moon\", \"climb Everest\" said of a business), prefer the reading the context supports and say which.\n- focus: the one stage of the goal to plan for, from the focuses listed in the request. Growth of users means \"new-signups\" unless the goal speaks of using, keeping or activating people. Answering customers sooner is \"faster-support\". When none fits, focus \"other\" and newFocus: name the stage in a few generic words (label, e.g. \"Hiring\", \"Closing sales deals\", \"Personal health habits\") with a one-sentence hint of what goals with this focus are about. No names of the business, its products, people or places.\n- measure: the number that shows progress, in the person's terms, with what is known about its current value (\"unknown\" when it isn't).\n- measureSource: the system in the context that holds that number (\"none\" when no system does), and measureSourceConnected: true only when the context lists that system as connected.\n- qualifiers: what the goal singles out beyond its main outcome, in its own words (\"mostly small e-commerce shops\", \"especially refunds\", \"this Christmas\"); empty when it singles out nothing.\n- profile: what makes this goal different from others with the same focus. metric: the number it moves; direction: \"up\", \"down\", \"reach\" (a milestone) or \"keep\"; constraints: limits that rule approaches out (no budget, night shifts, vegetarian, an injury, only one market), from the goal and the context, empty when none; timeframe (\"by March\", \"unknown\"); startingPoint (first try, tried before, what's already in place, or \"unknown\"); bottleneck: what's most likely to stop this particular goal (for most weight goals it's sticking with it; for a new product it may be that nobody knows it exists), and bottleneckWhy in a sentence.\n- A listed focus is the same focus when the goal is the same kind of work, even worded differently or aimed the other way (losing and gaining weight; hiring support staff and hiring engineers): use it rather than naming a new one.\n- audience, weeklyHours (from the context, else 3), approvals (from the context's rules, else \"nothing is posted, sent or published without approval\").";
146
+ export declare const GOAL_PLAN_PROMPT = "You plan workflows for a confirmed goal brief in LoopEngine. Each workflow is one recurring job for one AI agent; a person reviews what it drafts.\n\nRules:\n1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.\n1b. When the request lists no playbook levers for this focus (none yet, or every one already under this goal), write the levers you need first, in newLevers (two to five), then make each workflow from one of them (its leverId is the lever's key). When levers are listed but one this goal clearly needs is missing, you may add up to two. A new lever is like the playbook's: one distinct approach (one reason it works), in generic words that fit many goals of this focus (no names of this business, its products, people, places or sites; no direction, target or amount when the approach works either way: \"a weekly meal routine toward the target\", not \"eat less\"), with when it fits and doesn't, what it needs, review time, how its effect shows up, guardrails (approval before anything is sent, posted or published), and a generic template with {placeholders}. The workflow's request is where this business's specifics go.\n2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.\n3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: \"list in app marketplaces\", not \"list Wick & Ember on Shopify\"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.\n3b. Choose levers for this goal, not for the focus in general. Look at every lever listed: rule out one whose \"not when\", needs or the profile's constraints don't fit; prefer the ones that address the profile's bottleneck; pick ones that work in different ways (not three kinds of tracking). In considered, list every lever you looked at with chosen or ruled_out and a short reason tied to this goal (\"addresses sticking with it\", \"no gym: ruled out\"). Reuse a listed lever whenever its approach fits, even if it was written for a goal aimed the other way: put what's specific to this goal (the direction, the target, the details) in the workflow's request. Write a new lever only for what no listed lever covers.\n4. Three to five workflows for an \"in\" goal, ordered by impact against effort, quickest useful one first; startsAfter when one depends on another. Their humanMinutesPerWeek together stay within three quarters of the brief's weeklyHours, so the plan survives a busy week.\n4b. Each one is a job: kind \"recurring\" when it runs again and again (a weekly scan, a reply to each signup), kind \"once\" for work on a finite list or done one time (submitting to a set of directories, a one-time audit, researching a list of communities). A once job is done by an agent once, in Chat; never make it a weekly job that runs out of things to do.\n4c. measure: the job's own number, in the person's terms, that shows it's working (\"replies per week\", \"signups tagged ref=directories\"); for a once job, what done looks like (\"done when: listed in 15 directories\"). A playbook lever says the kind and measure it usually has: start from those, and change them only when the context calls for it.\n5. Specific to this context: name the person's own communities, systems, products and channels in each request. A request anyone could use unchanged is wrong.\n6. needs: what each workflow uses, each with a kind from the playbook's vocabulary and connected true only when the context lists that kind as connected.\n7. Every request that posts, sends or publishes says nothing goes out without the person's approval.\n8. The measure must be readable. When measureSourceConnected is false, setup says how the number will be read: connecting that source (name it, e.g. \"connect Clerk's user.created webhook so signups and their ref are recorded\"), or, when it can't be connected, a light manual record the person updates weekly (kept with the Records ability). Always record a baseline: the number today. Tag what workflows produce (ref=<channel>) so each one's effect can be told apart.\n8b. Every qualifier in the brief is covered by at least one workflow that addresses it directly; list it in that workflow's covers.\n9. \"partial\" scope: at most three workflows, only ones that help the person pursue the goal, and say so in the message (\"helps you pursue\", never \"achieves\"). \"out\" scope: no workflows; the message says plainly why, and offers a smaller or related goal.\n10. agent: an existing agent's exact name when its work fits. When none fits, or there are no agents yet, suggest a new one: agent and newAgent.name the same short lowercase name with hyphens (e.g. \"community-agent\"), and newAgent.instructions two or three sentences on what it does and how it behaves. Group workflows that belong together in one agent rather than one agent each.\n\nCall save_plan once.";
147
+ export declare const GOAL_CRITIQUE_PROMPT = "You check a goal plan against its rules before a person sees it. List every issue (be strict, quote the workflow):\n- a workflow that doesn't serve the brief's focus or move its measure;\n- two workflows on the same lever, or one repeating a lever already saved;\n- a request generic enough to fit any business;\n- a need marked connected that the context doesn't list as connected;\n- a request that posts, sends or publishes without saying it waits for approval;\n- review time over three quarters of the weekly budget;\n- a measure whose source isn't connected, with no setup step that connects it or a manual record, or no baseline;\n- a qualifier from the brief no workflow addresses;\n- a recurring job on a finite list that will run out (it should be kind \"once\");\n- a lever in newLevers that names this business, its products, people, places or sites, mixes several approaches, or has no way to see its effect;\n- a workflow made from no lever when the request listed none for this focus (it should come from one of newLevers);\n- a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.\nCall save_review once: passed true only when there are no issues.";
148
+ /** A job a person added in their own words, shaped like a planned one. */
149
+ export declare const GOAL_ADD_JOB_PROMPT = "A person adds a job of their own to a goal in LoopEngine, in their own words. Shape it into one job like a planner's, and judge it honestly; it's their business, so advise, don't lecture.\n\nShape it:\n- title, kind (\"recurring\" when it repeats, \"once\" for finite work), measure (its own number, or for a once job what done looks like), why it moves the goal (mechanism), the agent (an existing agent's exact name when its work fits, else newAgent with a short name and two or three sentences of instructions), needs (connected only when the context lists it), humanMinutesPerWeek, and a request specific to this business that the agent can act on. Anything that posts, sends or publishes says nothing goes out without the person's approval.\n- lever: when it's one of the playbook levers listed, its id in leverId. When none fits, write one generic lever in newLever (one approach, no names of this business, its products, people, places or sites; when it fits and doesn't; what it needs; how its effect shows up; guardrails; a generic template) and put its key in leverId.\n\nJudge it, in verdict:\n- \"added\": it fits the goal and is safe.\n- \"changed\": a sound idea with risky details you changed (an approval added, volume limited, a platform's rules respected); say what you changed in note.\n- \"warned\": it's safe but unlikely to move the goal's measure, repeats a job already under the goal, or is unlikely to work; say why in note and give a better-aimed alternative.\n- \"refused\": it's deceptive, illegal or against a platform's rules (fake reviews or accounts, spam, buying followers, harvesting private data, impersonation, misleading claims) or could harm people. Don't shape it; say why in note, plainly and briefly, and give a legitimate alternative.\n\nCall save_job once.";
150
+ export interface ShapedJob {
151
+ verdict: 'added' | 'changed' | 'warned' | 'refused';
152
+ note: string;
153
+ alternative: string;
154
+ /** Missing when refused, or when the answer had no usable job. */
155
+ job?: PlannedGoalWorkflow;
156
+ /** The lever the planner wrote for it, when none fit. */
157
+ newLever?: Lever;
158
+ }
159
+ /** Shapes a job a person typed, under a goal already planned: its kind,
160
+ * measure, agent, request and lever (an existing one, or a new generic
161
+ * one), and judges it: added, changed, warned or refused. */
162
+ export declare function shapeJob(modelCall: ModelCall, input: {
163
+ goal: string;
164
+ brief: GoalBrief;
165
+ context: GoalContext;
166
+ saved?: SavedGoalWorkflow[];
167
+ idea: string;
168
+ }): Promise<ShapedJob>;
115
169
  export declare function contextText(context: GoalContext): string;
116
170
  /** A suggested agent's name as a folder name: lowercase, hyphens. */
117
171
  export declare function agentName(raw: string): string;
@@ -1,4 +1,4 @@
1
- import { GOAL_FOCUSES, activePlaybook, leversFor } from './goal-playbooks.js';
1
+ import { activePlaybook, leversFor } from './goal-playbooks.js';
2
2
  // The prompt lists at most this many of a focus's levers, so a growing
3
3
  // playbook never makes a long prompt. (Later: the best-ranked first.)
4
4
  const MAX_LEVERS_IN_PROMPT = 10;
@@ -8,17 +8,21 @@ export const GOAL_BRIEF_PROMPT = `You read a goal someone gives LoopEngine, a pl
8
8
  Call save_brief once:
9
9
  - scope: "in" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all "in"); "partial" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; "out" when there is nothing useful an agent could do. scopeReason: one sentence.
10
10
  - reading: how you read it. When the wording could be a metaphor ("land on the moon", "climb Everest" said of a business), prefer the reading the context supports and say which.
11
- - focus: the one stage of the goal to plan for. Growth of users means "new-signups" unless the goal speaks of using, keeping or activating people. Answering customers sooner is "faster-support". Use "other" only when none fits.
11
+ - focus: the one stage of the goal to plan for, from the focuses listed in the request. Growth of users means "new-signups" unless the goal speaks of using, keeping or activating people. Answering customers sooner is "faster-support". When none fits, focus "other" and newFocus: name the stage in a few generic words (label, e.g. "Hiring", "Closing sales deals", "Personal health habits") with a one-sentence hint of what goals with this focus are about. No names of the business, its products, people or places.
12
12
  - measure: the number that shows progress, in the person's terms, with what is known about its current value ("unknown" when it isn't).
13
13
  - measureSource: the system in the context that holds that number ("none" when no system does), and measureSourceConnected: true only when the context lists that system as connected.
14
14
  - qualifiers: what the goal singles out beyond its main outcome, in its own words ("mostly small e-commerce shops", "especially refunds", "this Christmas"); empty when it singles out nothing.
15
+ - profile: what makes this goal different from others with the same focus. metric: the number it moves; direction: "up", "down", "reach" (a milestone) or "keep"; constraints: limits that rule approaches out (no budget, night shifts, vegetarian, an injury, only one market), from the goal and the context, empty when none; timeframe ("by March", "unknown"); startingPoint (first try, tried before, what's already in place, or "unknown"); bottleneck: what's most likely to stop this particular goal (for most weight goals it's sticking with it; for a new product it may be that nobody knows it exists), and bottleneckWhy in a sentence.
16
+ - A listed focus is the same focus when the goal is the same kind of work, even worded differently or aimed the other way (losing and gaining weight; hiring support staff and hiring engineers): use it rather than naming a new one.
15
17
  - audience, weeklyHours (from the context, else 3), approvals (from the context's rules, else "nothing is posted, sent or published without approval").`;
16
18
  export const GOAL_PLAN_PROMPT = `You plan workflows for a confirmed goal brief in LoopEngine. Each workflow is one recurring job for one AI agent; a person reviews what it drafts.
17
19
 
18
20
  Rules:
19
- 1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own new idea when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.
21
+ 1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.
22
+ 1b. When the request lists no playbook levers for this focus (none yet, or every one already under this goal), write the levers you need first, in newLevers (two to five), then make each workflow from one of them (its leverId is the lever's key). When levers are listed but one this goal clearly needs is missing, you may add up to two. A new lever is like the playbook's: one distinct approach (one reason it works), in generic words that fit many goals of this focus (no names of this business, its products, people, places or sites; no direction, target or amount when the approach works either way: "a weekly meal routine toward the target", not "eat less"), with when it fits and doesn't, what it needs, review time, how its effect shows up, guardrails (approval before anything is sent, posted or published), and a generic template with {placeholders}. The workflow's request is where this business's specifics go.
20
23
  2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.
21
24
  3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: "list in app marketplaces", not "list Wick & Ember on Shopify"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.
25
+ 3b. Choose levers for this goal, not for the focus in general. Look at every lever listed: rule out one whose "not when", needs or the profile's constraints don't fit; prefer the ones that address the profile's bottleneck; pick ones that work in different ways (not three kinds of tracking). In considered, list every lever you looked at with chosen or ruled_out and a short reason tied to this goal ("addresses sticking with it", "no gym: ruled out"). Reuse a listed lever whenever its approach fits, even if it was written for a goal aimed the other way: put what's specific to this goal (the direction, the target, the details) in the workflow's request. Write a new lever only for what no listed lever covers.
22
26
  4. Three to five workflows for an "in" goal, ordered by impact against effort, quickest useful one first; startsAfter when one depends on another. Their humanMinutesPerWeek together stay within three quarters of the brief's weeklyHours, so the plan survives a busy week.
23
27
  4b. Each one is a job: kind "recurring" when it runs again and again (a weekly scan, a reply to each signup), kind "once" for work on a finite list or done one time (submitting to a set of directories, a one-time audit, researching a list of communities). A once job is done by an agent once, in Chat; never make it a weekly job that runs out of things to do.
24
28
  4c. measure: the job's own number, in the person's terms, that shows it's working ("replies per week", "signups tagged ref=directories"); for a once job, what done looks like ("done when: listed in 15 directories"). A playbook lever says the kind and measure it usually has: start from those, and change them only when the context calls for it.
@@ -41,11 +45,14 @@ export const GOAL_CRITIQUE_PROMPT = `You check a goal plan against its rules bef
41
45
  - a measure whose source isn't connected, with no setup step that connects it or a manual record, or no baseline;
42
46
  - a qualifier from the brief no workflow addresses;
43
47
  - a recurring job on a finite list that will run out (it should be kind "once");
48
+ - a lever in newLevers that names this business, its products, people, places or sites, mixes several approaches, or has no way to see its effect;
49
+ - a workflow made from no lever when the request listed none for this focus (it should come from one of newLevers);
44
50
  - a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.
45
51
  Call save_review once: passed true only when there are no issues.`;
46
52
  // ---------- tools ----------
47
- const focusEnum = [...GOAL_FOCUSES, 'other'];
48
- const BRIEF_TOOL = {
53
+ /** The focus ids the planner may pick: the playbook in use's, and "other". */
54
+ const focusEnum = () => [...activePlaybook().focuses.map((f) => f.id), 'other'];
55
+ const briefTool = () => ({
49
56
  name: 'save_brief',
50
57
  description: 'Save how the goal was read.',
51
58
  input_schema: {
@@ -54,7 +61,16 @@ const BRIEF_TOOL = {
54
61
  scope: { type: 'string', enum: ['in', 'partial', 'out'] },
55
62
  scopeReason: { type: 'string' },
56
63
  reading: { type: 'string' },
57
- focus: { type: 'string', enum: focusEnum },
64
+ focus: { type: 'string', enum: focusEnum() },
65
+ newFocus: { type: 'object', properties: { label: { type: 'string' }, hint: { type: 'string' } }, required: ['label', 'hint'], description: 'only when focus is "other": the stage, named in generic words' },
66
+ profile: {
67
+ type: 'object',
68
+ properties: {
69
+ metric: { type: 'string' }, direction: { type: 'string', enum: ['up', 'down', 'reach', 'keep'] }, constraints: { type: 'array', items: { type: 'string' } },
70
+ timeframe: { type: 'string' }, startingPoint: { type: 'string' }, bottleneck: { type: 'string' }, bottleneckWhy: { type: 'string' },
71
+ },
72
+ required: ['metric', 'direction', 'constraints', 'timeframe', 'startingPoint', 'bottleneck', 'bottleneckWhy'],
73
+ },
58
74
  measure: { type: 'string' },
59
75
  measureSource: { type: 'string' },
60
76
  measureSourceConnected: { type: 'boolean' },
@@ -65,8 +81,27 @@ const BRIEF_TOOL = {
65
81
  },
66
82
  required: ['scope', 'scopeReason', 'reading', 'focus', 'measure', 'measureSource', 'measureSourceConnected', 'qualifiers', 'audience', 'weeklyHours', 'approvals'],
67
83
  },
84
+ });
85
+ const NEW_LEVER_SCHEMA = {
86
+ type: 'object',
87
+ description: 'a lever the playbook lacks, in generic words (no names of the business, its products, people, places or sites)',
88
+ properties: {
89
+ key: { type: 'string', description: 'a short lowercase-hyphenated key; workflows made from it put this key in leverId' },
90
+ name: { type: 'string', description: 'the approach in a few words' },
91
+ kind: { type: 'string', enum: ['recurring', 'once'] },
92
+ mechanism: { type: 'string', description: 'why it tends to move the measure, one sentence' },
93
+ fitsWhen: { type: 'array', items: { type: 'string' } },
94
+ notWhen: { type: 'array', items: { type: 'string' } },
95
+ needs: { type: 'array', items: { type: 'string' }, description: 'kinds of app or ability it uses (email, messaging, web-search, records, …)' },
96
+ humanMinutesPerWeek: { type: 'number' },
97
+ firstResultDays: { type: 'number' },
98
+ measureLink: { type: 'string', description: 'how its effect shows up, generically' },
99
+ guardrails: { type: 'array', items: { type: 'string' } },
100
+ template: { type: 'string', description: 'the request it starts from, generic, with {placeholders}' },
101
+ },
102
+ required: ['key', 'name', 'kind', 'mechanism', 'fitsWhen', 'notWhen', 'needs', 'humanMinutesPerWeek', 'firstResultDays', 'measureLink', 'guardrails', 'template'],
68
103
  };
69
- const PLAN_TOOL = {
104
+ const planTool = () => ({
70
105
  name: 'save_plan',
71
106
  description: 'Save the plan.',
72
107
  input_schema: {
@@ -81,9 +116,9 @@ const PLAN_TOOL = {
81
116
  title: { type: 'string' },
82
117
  kind: { type: 'string', enum: ['recurring', 'once'] },
83
118
  measure: { type: 'string', description: "the job's own number, or for a once job what done looks like" },
84
- leverId: { type: 'string', description: "the playbook lever's id; empty for a new idea" },
119
+ leverId: { type: 'string', description: "the playbook lever's id, or the key of one of your newLevers" },
85
120
  lever: { type: 'string', description: 'the lever in a few generic words, with no names of the business, its products, people, places or sites' },
86
- focus: { type: 'string', enum: focusEnum },
121
+ focus: { type: 'string' },
87
122
  mechanism: { type: 'string', description: 'why it moves the measure, one sentence' },
88
123
  request: { type: 'string', description: 'the workflow request, specific to this context' },
89
124
  agent: { type: 'string' },
@@ -97,13 +132,75 @@ const PLAN_TOOL = {
97
132
  required: ['title', 'lever', 'focus', 'mechanism', 'request', 'agent', 'needs', 'humanMinutesPerWeek', 'measureLink'],
98
133
  },
99
134
  },
135
+ newLevers: { type: 'array', items: NEW_LEVER_SCHEMA, description: 'levers the playbook lacks; required when the request lists none for this focus' },
136
+ considered: {
137
+ type: 'array',
138
+ description: 'every lever you looked at (listed ones, and any you wrote), chosen or ruled out, with a short reason tied to this goal',
139
+ items: { type: 'object', properties: { lever: { type: 'string', description: 'its id, or for one you wrote its key' }, decision: { type: 'string', enum: ['chosen', 'ruled_out'] }, reason: { type: 'string' } }, required: ['lever', 'decision', 'reason'] },
140
+ },
100
141
  leftOut: { type: 'array', items: { type: 'string' } },
101
142
  assumptions: { type: 'array', items: { type: 'string' } },
102
143
  message: { type: 'string' },
103
144
  },
104
145
  required: ['setup', 'workflows', 'leftOut', 'assumptions', 'message'],
105
146
  },
147
+ });
148
+ /** A job a person added in their own words, shaped like a planned one. */
149
+ export const GOAL_ADD_JOB_PROMPT = `A person adds a job of their own to a goal in LoopEngine, in their own words. Shape it into one job like a planner's, and judge it honestly; it's their business, so advise, don't lecture.
150
+
151
+ Shape it:
152
+ - title, kind ("recurring" when it repeats, "once" for finite work), measure (its own number, or for a once job what done looks like), why it moves the goal (mechanism), the agent (an existing agent's exact name when its work fits, else newAgent with a short name and two or three sentences of instructions), needs (connected only when the context lists it), humanMinutesPerWeek, and a request specific to this business that the agent can act on. Anything that posts, sends or publishes says nothing goes out without the person's approval.
153
+ - lever: when it's one of the playbook levers listed, its id in leverId. When none fits, write one generic lever in newLever (one approach, no names of this business, its products, people, places or sites; when it fits and doesn't; what it needs; how its effect shows up; guardrails; a generic template) and put its key in leverId.
154
+
155
+ Judge it, in verdict:
156
+ - "added": it fits the goal and is safe.
157
+ - "changed": a sound idea with risky details you changed (an approval added, volume limited, a platform's rules respected); say what you changed in note.
158
+ - "warned": it's safe but unlikely to move the goal's measure, repeats a job already under the goal, or is unlikely to work; say why in note and give a better-aimed alternative.
159
+ - "refused": it's deceptive, illegal or against a platform's rules (fake reviews or accounts, spam, buying followers, harvesting private data, impersonation, misleading claims) or could harm people. Don't shape it; say why in note, plainly and briefly, and give a legitimate alternative.
160
+
161
+ Call save_job once.`;
162
+ const addJobTool = () => {
163
+ const plan = planTool().input_schema;
164
+ return {
165
+ name: 'save_job',
166
+ description: 'Save the shaped job and your verdict.',
167
+ input_schema: {
168
+ type: 'object',
169
+ properties: {
170
+ verdict: { type: 'string', enum: ['added', 'changed', 'warned', 'refused'] },
171
+ note: { type: 'string', description: 'for changed, warned or refused: one or two sentences for the person' },
172
+ alternative: { type: 'string', description: 'for warned or refused: a better-aimed or legitimate job, in a sentence' },
173
+ job: plan.properties.workflows.items,
174
+ newLever: NEW_LEVER_SCHEMA,
175
+ },
176
+ required: ['verdict'],
177
+ },
178
+ };
106
179
  };
180
+ /** Shapes a job a person typed, under a goal already planned: its kind,
181
+ * measure, agent, request and lever (an existing one, or a new generic
182
+ * one), and judges it: added, changed, warned or refused. */
183
+ export async function shapeJob(modelCall, input) {
184
+ const focus = input.brief.focus;
185
+ const levers = focus === 'other' ? [] : leversFor(focus);
186
+ const user = [
187
+ contextText(input.context),
188
+ briefText(input.brief),
189
+ levers.length ? `Playbook levers for this focus:\n${levers.slice(0, MAX_LEVERS_IN_PROMPT * 2).map((l) => `- ${l.id}: ${l.name}. ${l.mechanism} Usually ${l.kind === 'once' ? 'a once job' : 'a recurring job'}; its measure: ${l.measureLink}.`).join('\n')}` : 'Playbook levers: none for this focus yet.',
190
+ savedText(input.saved),
191
+ `The goal:\n${input.goal}`,
192
+ `The job the person wants to add, in their words:\n${input.idea}`,
193
+ ].join('\n\n');
194
+ const raw = await callTool(modelCall, GOAL_ADD_JOB_PROMPT, user, addJobTool());
195
+ const verdict = raw.verdict === 'changed' || raw.verdict === 'warned' || raw.verdict === 'refused' ? raw.verdict : 'added';
196
+ const note = str(raw.note).slice(0, 600);
197
+ const alternative = str(raw.alternative).slice(0, 400);
198
+ if (verdict === 'refused')
199
+ return { verdict, note, alternative };
200
+ const shaped = parsePlan({ workflows: raw.job ? [raw.job] : [], newLevers: raw.newLever ? [raw.newLever] : [] }, focus);
201
+ const job = shaped.workflows[0];
202
+ return { verdict, note, alternative, ...(job ? { job } : {}), ...(job && shaped.newLevers?.[0] ? { newLever: shaped.newLevers[0] } : {}) };
203
+ }
107
204
  const REVIEW_TOOL = {
108
205
  name: 'save_review',
109
206
  description: 'Save the check.',
@@ -160,10 +257,18 @@ export function contextText(context) {
160
257
  context.weeklyHours ? `Time to review drafts: about ${context.weeklyHours} hours a week` : '',
161
258
  ].filter(Boolean).join('\n');
162
259
  }
163
- function leversText(focus) {
164
- if (focus === 'other')
165
- return 'Playbook levers: none for this focus; use your own ideas, each marked as a new idea.';
166
- return 'Playbook levers for this focus (id: name; why; fits when; not when; needs; minutes a week):\n' + leversFor(focus).slice(0, MAX_LEVERS_IN_PROMPT).map((l) => `- ${l.id}: ${l.name}. ${l.mechanism} Fits when: ${l.fitsWhen.join('; ')}. Not when: ${l.notWhen.join('; ')}. Needs: ${[...(l.needs.anyOf?.length ? [`one of ${l.needs.anyOf.join('/')}`] : []), ...(l.needs.plus ?? [])].join(' + ')}. About ${l.humanMinutesPerWeek} min/week. Usually ${l.kind === 'once' ? 'a once job' : 'a recurring job'}; its measure: ${l.measureLink}. Template: ${l.template}`).join('\n');
260
+ /** The focus's levers the plan may still use (none already under the
261
+ * goal). With none left, the planner writes new ones, as for a new focus,
262
+ * so Generate more keeps finding approaches. */
263
+ function leversText(focus, saved = []) {
264
+ const used = new Set(saved.flatMap((s) => (s.leverId ? [s.leverId] : [])));
265
+ const all = focus === 'other' ? [] : leversFor(focus);
266
+ const levers = all.filter((l) => !used.has(l.id));
267
+ if (!levers.length)
268
+ return all.length
269
+ ? 'Playbook levers: every one for this focus is already under this goal. Write new levers in newLevers (rule 1b: two to five, each a different approach from those already saved), and make each workflow from one of them.'
270
+ : 'Playbook levers: none for this focus yet. Write the levers this goal needs in newLevers (rule 1b), and make each workflow from one of them.';
271
+ return 'Playbook levers for this focus (id: name; why; fits when; not when; needs; minutes a week):\n' + levers.slice(0, MAX_LEVERS_IN_PROMPT).map((l) => `- ${l.id}: ${l.name}. ${l.mechanism} Fits when: ${l.fitsWhen.join('; ')}. Not when: ${l.notWhen.join('; ')}. Needs: ${[...(l.needs.anyOf?.length ? [`one of ${l.needs.anyOf.join('/')}`] : []), ...(l.needs.plus ?? [])].join(' + ')}. About ${l.humanMinutesPerWeek} min/week. Usually ${l.kind === 'once' ? 'a once job' : 'a recurring job'}; its measure: ${l.measureLink}. Template: ${l.template}`).join('\n');
167
272
  }
168
273
  function savedText(saved) {
169
274
  if (!saved?.length)
@@ -176,30 +281,109 @@ export function agentName(raw) {
176
281
  }
177
282
  const str = (v, fallback = '') => (typeof v === 'string' ? v.trim() : fallback);
178
283
  const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.trim().length > 0).map((x) => x.trim()) : []);
179
- const focusOf = (v) => (typeof v === 'string' && focusEnum.includes(v) ? v : 'other');
284
+ const focusOf = (v) => (typeof v === 'string' && focusEnum().includes(v) ? v : 'other');
285
+ function profileFrom(raw) {
286
+ const p = raw && typeof raw === 'object' ? raw : undefined;
287
+ if (!p || !str(p.bottleneck))
288
+ return undefined;
289
+ const direction = p.direction === 'down' || p.direction === 'reach' || p.direction === 'keep' ? p.direction : 'up';
290
+ return {
291
+ metric: str(p.metric).slice(0, 200), direction, constraints: strings(p.constraints).slice(0, 8), timeframe: str(p.timeframe, 'unknown').slice(0, 100),
292
+ startingPoint: str(p.startingPoint, 'unknown').slice(0, 300), bottleneck: str(p.bottleneck).slice(0, 200), bottleneckWhy: str(p.bottleneckWhy).slice(0, 400),
293
+ };
294
+ }
295
+ const slug = (v) => v.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '');
296
+ /** Text that shouldn't leave the workspace in a lever: links, addresses,
297
+ * handles, long numbers. */
298
+ const UNSAFE_LEVER_TEXT = /https?:|www\.|@|\.(com|co|io|app|net|org|ai)\b|\d{4,}/i;
299
+ /** The focus the brief named, as a workspace's own focus ("x-..."). */
300
+ function newFocusFrom(raw) {
301
+ const f = raw && typeof raw === 'object' ? raw : {};
302
+ const label = str(f.label).slice(0, 60);
303
+ const hint = str(f.hint).slice(0, 300);
304
+ const id = `x-${slug(label)}`;
305
+ if (!label || !hint || id === 'x-' || UNSAFE_LEVER_TEXT.test(`${label} ${hint}`))
306
+ return undefined;
307
+ return { id, label, hint };
308
+ }
309
+ /** The levers a plan wrote, as a workspace's own levers under the focus
310
+ * (ids "<focus>.x-<key>"), keyed by the key its workflows use. One with
311
+ * unsafe text or a missing part is dropped. */
312
+ function newLeversFrom(raw, focus) {
313
+ const out = new Map();
314
+ if (!Array.isArray(raw) || focus === 'other')
315
+ return out;
316
+ for (const item of raw.slice(0, 5)) {
317
+ const x = item && typeof item === 'object' ? item : {};
318
+ const key = slug(str(x.key) || str(x.name));
319
+ const lever = {
320
+ id: `${focus}.x-${key}`,
321
+ focus,
322
+ name: str(x.name).slice(0, 80),
323
+ kind: x.kind === 'once' ? 'once' : 'recurring',
324
+ mechanism: str(x.mechanism).slice(0, 400),
325
+ fitsWhen: strings(x.fitsWhen).slice(0, 5),
326
+ notWhen: strings(x.notWhen).slice(0, 5),
327
+ needs: { ...(strings(x.needs).length ? { anyOf: strings(x.needs).map((n) => n.toLowerCase()).slice(0, 5) } : {}) },
328
+ humanMinutesPerWeek: typeof x.humanMinutesPerWeek === 'number' && x.humanMinutesPerWeek >= 0 ? Math.round(x.humanMinutesPerWeek) : 20,
329
+ firstResultDays: typeof x.firstResultDays === 'number' && x.firstResultDays >= 0 ? Math.round(x.firstResultDays) : 7,
330
+ measureLink: str(x.measureLink).slice(0, 200),
331
+ guardrails: strings(x.guardrails).slice(0, 5),
332
+ template: str(x.template).slice(0, 800),
333
+ };
334
+ const text = [lever.name, lever.mechanism, ...lever.fitsWhen, ...lever.notWhen, lever.measureLink, ...lever.guardrails, lever.template].join(' ');
335
+ if (!key || !lever.name || !lever.mechanism || !lever.measureLink || !lever.template || !lever.fitsWhen.length || UNSAFE_LEVER_TEXT.test(text))
336
+ continue;
337
+ if (!lever.guardrails.length)
338
+ lever.guardrails = ['Nothing is posted, sent or published without the person\u2019s approval.'];
339
+ out.set(key, lever);
340
+ }
341
+ return out;
342
+ }
180
343
  export async function readGoalBrief(modelCall, goal, context) {
181
- const raw = await callTool(modelCall, GOAL_BRIEF_PROMPT, `${contextText(context)}\n\nThe goal, as the person said it:\n${goal}`, BRIEF_TOOL);
344
+ const focuses = activePlaybook().focuses.map((f) => `- ${f.id}: ${f.label} (${f.hint})`).join('\n');
345
+ const raw = await callTool(modelCall, GOAL_BRIEF_PROMPT, `${contextText(context)}\n\nFocuses in the playbook:\n${focuses}\n\nThe goal, as the person said it:\n${goal}`, briefTool());
182
346
  const scope = raw.scope === 'partial' || raw.scope === 'out' ? raw.scope : 'in';
347
+ // A focus the planner named becomes the workspace's own, unless one by
348
+ // that name is already in use.
349
+ let focus = focusOf(raw.focus);
350
+ const named = focus === 'other' ? newFocusFrom(raw.newFocus) : undefined;
351
+ const existing = named && activePlaybook().focuses.find((f) => f.id === named.id || f.label.toLowerCase() === named.label.toLowerCase());
352
+ if (existing)
353
+ focus = existing.id;
354
+ else if (named)
355
+ focus = named.id;
183
356
  return {
184
357
  scope,
185
358
  scopeReason: str(raw.scopeReason),
186
359
  reading: str(raw.reading),
187
- focus: focusOf(raw.focus),
360
+ focus,
361
+ ...(named && !existing ? { newFocus: named } : {}),
188
362
  measure: str(raw.measure, 'unknown'),
189
363
  measureSource: str(raw.measureSource, 'none'),
190
364
  measureSourceConnected: raw.measureSourceConnected === true,
191
365
  qualifiers: strings(raw.qualifiers),
366
+ ...(profileFrom(raw.profile) ? { profile: profileFrom(raw.profile) } : {}),
192
367
  audience: str(raw.audience, context.audience ?? ''),
193
368
  weeklyHours: typeof raw.weeklyHours === 'number' && raw.weeklyHours > 0 ? raw.weeklyHours : context.weeklyHours ?? 3,
194
369
  approvals: str(raw.approvals, 'nothing is posted, sent or published without approval'),
195
370
  };
196
371
  }
372
+ function profileText(p) {
373
+ if (!p)
374
+ return '';
375
+ return `\n- profile: ${p.metric}, ${p.direction}; constraints: ${p.constraints.join('; ') || 'none'}; timeframe: ${p.timeframe}; starting point: ${p.startingPoint}\n- bottleneck: ${p.bottleneck} (${p.bottleneckWhy})`;
376
+ }
197
377
  function briefText(brief) {
198
- return `Confirmed brief:\n- scope: ${brief.scope} (${brief.scopeReason})\n- reading: ${brief.reading}\n- focus: ${brief.focus}\n- measure: ${brief.measure}\n- measure source: ${brief.measureSource} (${brief.measureSourceConnected ? 'connected' : 'not connected'})\n- qualifiers: ${brief.qualifiers.join('; ') || 'none'}\n- audience: ${brief.audience}\n- weekly review time: ${brief.weeklyHours} hours\n- approvals: ${brief.approvals}`;
378
+ return profileText(brief.profile).length ? `${briefTextCore(brief)}${profileText(brief.profile)}` : briefTextCore(brief);
379
+ }
380
+ function briefTextCore(brief) {
381
+ return `Confirmed brief:\n- scope: ${brief.scope} (${brief.scopeReason})\n- reading: ${brief.reading}\n- focus: ${brief.focus}${brief.newFocus ? ` (${brief.newFocus.label}: ${brief.newFocus.hint}; new, not in the playbook yet)` : ''}\n- measure: ${brief.measure}\n- measure source: ${brief.measureSource} (${brief.measureSourceConnected ? 'connected' : 'not connected'})\n- qualifiers: ${brief.qualifiers.join('; ') || 'none'}\n- audience: ${brief.audience}\n- weekly review time: ${brief.weeklyHours} hours\n- approvals: ${brief.approvals}`;
199
382
  }
200
- function parsePlan(raw) {
383
+ function parsePlan(raw, focus) {
201
384
  const { levers } = activePlaybook();
202
385
  const KNOWN_LEVER_IDS = new Set(levers.map((l) => l.id));
386
+ const written = newLeversFrom(raw.newLevers, focus);
203
387
  const workflows = (Array.isArray(raw.workflows) ? raw.workflows : []).flatMap((w) => {
204
388
  if (!w || typeof w !== 'object')
205
389
  return [];
@@ -208,8 +392,10 @@ function parsePlan(raw) {
208
392
  const request = str(x.request);
209
393
  if (!title || !request)
210
394
  return [];
211
- // Some models put the playbook id in lever and leave leverId empty.
212
- const leverId = str(x.leverId) || (KNOWN_LEVER_IDS.has(str(x.lever)) ? str(x.lever) : '');
395
+ // Some models put the playbook id in lever and leave leverId empty. A
396
+ // key of one of the plan's own levers means that lever.
397
+ const own = written.get(slug(str(x.leverId))) ?? written.get(slug(str(x.lever)));
398
+ const leverId = own?.id || str(x.leverId) && KNOWN_LEVER_IDS.has(str(x.leverId)) && str(x.leverId) || (KNOWN_LEVER_IDS.has(str(x.lever)) ? str(x.lever) : '');
213
399
  const na = x.newAgent && typeof x.newAgent === 'object' ? x.newAgent : undefined;
214
400
  const newAgentName = na ? agentName(str(na.name) || str(x.agent)) : '';
215
401
  const needs = (Array.isArray(x.needs) ? x.needs : []).flatMap((n) => {
@@ -238,18 +424,31 @@ function parsePlan(raw) {
238
424
  newIdea: !leverId,
239
425
  }];
240
426
  });
241
- return { setup: strings(raw.setup), workflows, leftOut: strings(raw.leftOut), assumptions: strings(raw.assumptions), message: str(raw.message) };
427
+ // The plan's own levers that a workflow is made from: the ones to keep.
428
+ const used = [...written.values()].filter((l) => workflows.some((w) => w.leverId === l.id));
429
+ // How it chose: each lever it looked at, named for people.
430
+ const considered = (Array.isArray(raw.considered) ? raw.considered : []).flatMap((c) => {
431
+ const x = c && typeof c === 'object' ? c : {};
432
+ const ref = str(x.lever);
433
+ const own = written.get(slug(ref));
434
+ const known = levers.find((l) => l.id === ref);
435
+ const name = own?.name ?? known?.name ?? ref;
436
+ if (!name || !str(x.reason))
437
+ return [];
438
+ return [{ ...(own || known ? { leverId: (own ?? known).id } : {}), lever: name, decision: x.decision === 'ruled_out' ? 'ruled_out' : 'chosen', reason: str(x.reason).slice(0, 300) }];
439
+ }).slice(0, 20);
440
+ return { setup: strings(raw.setup), workflows, leftOut: strings(raw.leftOut), assumptions: strings(raw.assumptions), message: str(raw.message), ...(used.length ? { newLevers: used } : {}), ...(considered.length ? { considered } : {}) };
242
441
  }
243
442
  export async function draftGoalPlan(modelCall, input, brief, issues = []) {
244
443
  const user = [
245
444
  contextText(input.context),
246
445
  briefText(brief),
247
- leversText(brief.focus),
446
+ leversText(brief.focus, input.saved),
248
447
  savedText(input.saved),
249
448
  `The goal, as the person said it:\n${input.goal}`,
250
449
  issues.length ? `A check found these issues in your last plan; fix every one:\n${issues.map((i) => `- ${i}`).join('\n')}` : '',
251
450
  ].filter(Boolean).join('\n\n');
252
- return parsePlan(await callTool(modelCall, GOAL_PLAN_PROMPT, user, PLAN_TOOL));
451
+ return parsePlan(await callTool(modelCall, GOAL_PLAN_PROMPT, user, planTool()), brief.focus);
253
452
  }
254
453
  export async function critiqueGoalPlan(modelCall, input, brief, plan) {
255
454
  const user = [contextText(input.context), briefText(brief), savedText(input.saved), `The plan:\n${JSON.stringify(plan, null, 2)}`].join('\n\n');
@@ -1,5 +1,17 @@
1
- export type GoalFocus = 'new-signups' | 'activation' | 'retention' | 'faster-support' | 'revenue-recovery' | 'ops-hygiene';
2
- export declare const GOAL_FOCUSES: readonly GoalFocus[];
1
+ /** A focus id: a shared one (below), or a workspace's own ("x-..."). */
2
+ export type GoalFocus = string;
3
+ /** The shared playbook's focuses, as bundled. */
4
+ export declare const GOAL_FOCUSES: readonly string[];
5
+ export interface Focus {
6
+ /** lowercase-hyphenated; a workspace's own starts with "x-". */
7
+ id: string;
8
+ /** What people read: "Getting new signups or customers". */
9
+ label: string;
10
+ /** What the planner reads: what goals with this focus are about. */
11
+ hint: string;
12
+ }
13
+ /** Whether an id is a workspace's own focus or lever (never shared as is). */
14
+ export declare const isLocalId: (id: string) => boolean;
3
15
  export interface Lever {
4
16
  /** `<focus>.<name>`, stable. */
5
17
  id: string;
@@ -28,26 +40,52 @@ export interface Lever {
28
40
  guardrails: string[];
29
41
  /** The request it starts from, with {placeholders} filled from context. */
30
42
  template: string;
43
+ /** A workspace's own lever written from a job the person typed, which
44
+ * they didn't agree to share: it, and every job made from it, stays in
45
+ * the workspace. */
46
+ private?: true;
31
47
  }
32
- /** Checks the playbook's shape, naming the lever at fault. */
33
- export declare function parsePlaybook(raw: unknown): {
48
+ /** Checks the playbook's shape, naming the lever at fault. A lever's
49
+ * focus must be one the playbook lists, or one of `knownFocuses`. */
50
+ export declare function parsePlaybook(raw: unknown, knownFocuses?: readonly string[]): {
34
51
  version: number;
52
+ focuses: Focus[];
35
53
  levers: Lever[];
36
54
  };
37
55
  /** The playbook bundled with this package. */
38
56
  export declare const PLAYBOOK_VERSION: number;
39
57
  export declare const LEVERS: readonly Lever[];
58
+ export declare const FOCUSES: readonly Focus[];
40
59
  /** Where the fetched playbook is cached: the project folder. */
41
60
  export declare function setPlaybookProjectDir(dir: string | undefined): void;
42
61
  export declare function mergePlaybooks(bundled: readonly Lever[], fetched: {
43
62
  levers: Lever[];
44
63
  retired?: string[];
45
64
  } | undefined): Lever[];
46
- /** The levers in use, and the version they come from (the fetched one's
47
- * when there is one, else the bundled one's). */
65
+ /** The workspace's own focuses and levers (empty when there are none, or
66
+ * the file doesn't pass the checks). */
67
+ export declare function readLocalPlaybook(dir?: string | undefined): {
68
+ focuses: Focus[];
69
+ levers: Lever[];
70
+ };
71
+ /** Adds focuses and levers to the workspace's own playbook (by id: a new
72
+ * one is added, one with an id already there replaces it). Only local
73
+ * ids ("x-...") are kept. */
74
+ export declare function addToLocalPlaybook(dir: string, add: {
75
+ focuses?: Focus[];
76
+ levers?: Lever[];
77
+ }): {
78
+ focuses: Focus[];
79
+ levers: Lever[];
80
+ };
81
+ /** The playbook in use: the bundled one, the fetched one over it, and the
82
+ * workspace's own focuses and levers; the version is the shared one's. */
48
83
  export declare function activePlaybook(): {
49
84
  version: number;
85
+ focuses: readonly Focus[];
50
86
  levers: readonly Lever[];
51
87
  };
88
+ /** A focus's label for people: its playbook label, else its id. */
89
+ export declare function focusLabel(id: string): string;
52
90
  /** The levers in use for a focus. */
53
91
  export declare function leversFor(focus: GoalFocus): Lever[];
@@ -12,15 +12,50 @@
12
12
  //
13
13
  // A lever describes a mechanism, never a promised result: why it tends
14
14
  // to move the measure, and how to see whether it does.
15
- import { readFileSync, statSync } from 'node:fs';
15
+ //
16
+ // Focuses are data too: the playbook lists them (an id, a label people
17
+ // read, and a hint the planner reads), and its levers belong to them.
18
+ //
19
+ // Each workspace also has its own playbook, .loopengine/playbook-local.json:
20
+ // focuses and levers the goal planner wrote when nothing in the shared
21
+ // playbook fit (a goal about hiring, a lever the playbook lacks). Their
22
+ // ids carry "x-" (focus "x-hiring", lever "x-hiring.x-screen-applicants",
23
+ // or "new-signups.x-..." for a new lever under a shared focus), so they
24
+ // never clash with shared ones. They're used like shared ones, in this
25
+ // workspace only.
26
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
16
27
  import { join } from 'node:path';
28
+ /** The shared playbook's focuses, as bundled. */
17
29
  export const GOAL_FOCUSES = ['new-signups', 'activation', 'retention', 'faster-support', 'revenue-recovery', 'ops-hygiene'];
30
+ /** Whether an id is a workspace's own focus or lever (never shared as is). */
31
+ export const isLocalId = (id) => /(^|\.)x-/.test(id);
32
+ const FOCUS_ID = /^[a-z][a-z0-9-]{1,48}$/;
18
33
  const PLAYBOOK_FILE = new URL('./playbook.json', import.meta.url);
19
- /** Checks the playbook's shape, naming the lever at fault. */
20
- export function parsePlaybook(raw) {
34
+ function parseFocuses(raw, where) {
35
+ if (raw === undefined)
36
+ return [];
37
+ if (!Array.isArray(raw))
38
+ throw new Error(`${where}: "focuses" must be a list`);
39
+ return raw.map((item, i) => {
40
+ const f = (item ?? {});
41
+ const at = `${where} focus ${typeof f.id === 'string' ? f.id : `#${i + 1}`}`;
42
+ if (typeof f.id !== 'string' || !FOCUS_ID.test(f.id))
43
+ throw new Error(`${at}: id must be lowercase words with hyphens`);
44
+ if (typeof f.label !== 'string' || !f.label.trim())
45
+ throw new Error(`${at}: "label" must be non-empty text`);
46
+ if (typeof f.hint !== 'string' || !f.hint.trim())
47
+ throw new Error(`${at}: "hint" must be non-empty text`);
48
+ return { id: f.id, label: f.label.trim(), hint: f.hint.trim() };
49
+ });
50
+ }
51
+ /** Checks the playbook's shape, naming the lever at fault. A lever's
52
+ * focus must be one the playbook lists, or one of `knownFocuses`. */
53
+ export function parsePlaybook(raw, knownFocuses = GOAL_FOCUSES) {
21
54
  if (!raw || typeof raw !== 'object' || !Array.isArray(raw.levers))
22
55
  throw new Error('playbook.json: expected { "levers": [...] }');
23
56
  const version = typeof raw.version === 'number' ? raw.version : 0;
57
+ const focuses = parseFocuses(raw.focuses, 'playbook.json');
58
+ const allowed = new Set([...knownFocuses, ...focuses.map((f) => f.id)]);
24
59
  const seen = new Set();
25
60
  const levers = (raw.levers).map((item, i) => {
26
61
  const l = (item ?? {});
@@ -32,8 +67,8 @@ export function parsePlaybook(raw) {
32
67
  const num = (k) => { if (typeof l[k] !== 'number' || l[k] < 0)
33
68
  throw new Error(`${where}: "${k}" must be a number`); return l[k]; };
34
69
  const focus = text('focus');
35
- if (!GOAL_FOCUSES.includes(focus))
36
- throw new Error(`${where}: focus must be one of ${GOAL_FOCUSES.join(', ')}`);
70
+ if (!allowed.has(focus))
71
+ throw new Error(`${where}: focus must be one of ${[...allowed].join(', ')}`);
37
72
  const id = text('id');
38
73
  if (!id.startsWith(`${focus}.`))
39
74
  throw new Error(`${where}: its id must start with "${focus}."`);
@@ -53,14 +88,16 @@ export function parsePlaybook(raw) {
53
88
  needs: { ...(anyOf ? { anyOf } : {}), ...(plus ? { plus } : {}) },
54
89
  humanMinutesPerWeek: num('humanMinutesPerWeek'), firstResultDays: num('firstResultDays'), measureLink: text('measureLink'),
55
90
  guardrails: list('guardrails'), template: text('template'),
91
+ ...(l.private === true ? { private: true } : {}),
56
92
  };
57
93
  });
58
- return { version, levers };
94
+ return { version, focuses, levers };
59
95
  }
60
96
  const playbook = parsePlaybook(JSON.parse(readFileSync(PLAYBOOK_FILE, 'utf8')));
61
97
  /** The playbook bundled with this package. */
62
98
  export const PLAYBOOK_VERSION = playbook.version;
63
99
  export const LEVERS = playbook.levers;
100
+ export const FOCUSES = playbook.focuses;
64
101
  // ---- The playbook in use: the bundled one, merged with the latest one a
65
102
  // Cloud workspace fetched (core/playbook-sync.ts keeps it in the project,
66
103
  // .loopengine/playbook-cache.json). By lever id: a fetched lever replaces
@@ -82,31 +119,87 @@ export function mergePlaybooks(bundled, fetched) {
82
119
  byId.set(l.id, l);
83
120
  return [...byId.values()].filter((l) => !retired.has(l.id));
84
121
  }
85
- /** The levers in use, and the version they come from (the fetched one's
86
- * when there is one, else the bundled one's). */
122
+ const localFile = (dir) => join(dir, '.loopengine', 'playbook-local.json');
123
+ const mtime = (file) => {
124
+ try {
125
+ return String(statSync(file).mtimeMs);
126
+ }
127
+ catch {
128
+ return 'none';
129
+ }
130
+ };
131
+ /** The workspace's own focuses and levers (empty when there are none, or
132
+ * the file doesn't pass the checks). */
133
+ export function readLocalPlaybook(dir = cacheDir) {
134
+ if (!dir || !existsSync(localFile(dir)))
135
+ return { focuses: [], levers: [] };
136
+ try {
137
+ const raw = JSON.parse(readFileSync(localFile(dir), 'utf8'));
138
+ const parsed = parsePlaybook({ levers: raw.levers ?? [], focuses: raw.focuses ?? [] }, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
139
+ return { focuses: parsed.focuses.filter((f) => isLocalId(f.id)), levers: parsed.levers.filter((l) => isLocalId(l.id)) };
140
+ }
141
+ catch {
142
+ return { focuses: [], levers: [] };
143
+ }
144
+ }
145
+ /** Adds focuses and levers to the workspace's own playbook (by id: a new
146
+ * one is added, one with an id already there replaces it). Only local
147
+ * ids ("x-...") are kept. */
148
+ export function addToLocalPlaybook(dir, add) {
149
+ const current = readLocalPlaybook(dir);
150
+ const focuses = new Map(current.focuses.map((f) => [f.id, f]));
151
+ for (const f of add.focuses ?? [])
152
+ if (isLocalId(f.id))
153
+ focuses.set(f.id, f);
154
+ const levers = new Map(current.levers.map((l) => [l.id, l]));
155
+ for (const l of add.levers ?? [])
156
+ if (isLocalId(l.id))
157
+ levers.set(l.id, l);
158
+ const next = { focuses: [...focuses.values()], levers: [...levers.values()] };
159
+ // Checked as a whole before it's written: a bad lever fails here.
160
+ parsePlaybook(next, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
161
+ mkdirSync(join(dir, '.loopengine'), { recursive: true });
162
+ const file = localFile(dir);
163
+ const temp = `${file}.${process.pid}.tmp`;
164
+ writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`);
165
+ renameSync(temp, file);
166
+ if (dir === cacheDir)
167
+ memo = undefined;
168
+ return next;
169
+ }
170
+ /** The playbook in use: the bundled one, the fetched one over it, and the
171
+ * workspace's own focuses and levers; the version is the shared one's. */
87
172
  export function activePlaybook() {
88
173
  if (!cacheDir)
89
- return { version: PLAYBOOK_VERSION, levers: LEVERS };
174
+ return { version: PLAYBOOK_VERSION, focuses: FOCUSES, levers: LEVERS };
90
175
  const file = join(cacheDir, '.loopengine', 'playbook-cache.json');
91
- let key = 'none';
92
- try {
93
- key = String(statSync(file).mtimeMs);
94
- }
95
- catch { }
176
+ const key = `${mtime(file)}|${mtime(localFile(cacheDir))}`;
96
177
  if (memo?.key === key)
97
178
  return memo;
98
179
  let fetched;
99
- if (key !== 'none') {
180
+ if (!key.startsWith('none|')) {
100
181
  try {
101
182
  const raw = JSON.parse(readFileSync(file, 'utf8'));
102
- const parsed = parsePlaybook(raw);
103
- fetched = { version: parsed.version, levers: parsed.levers, retired: Array.isArray(raw.retired) ? raw.retired.filter((x) => typeof x === 'string') : [] };
183
+ const parsed = parsePlaybook(raw, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
184
+ fetched = { ...parsed, retired: Array.isArray(raw.retired) ? raw.retired.filter((x) => typeof x === 'string') : [] };
104
185
  }
105
186
  catch { }
106
187
  }
107
- memo = { key, levers: mergePlaybooks(LEVERS, fetched), version: fetched?.version ?? PLAYBOOK_VERSION };
188
+ const local = readLocalPlaybook(cacheDir);
189
+ const focusById = new Map(FOCUSES.map((f) => [f.id, f]));
190
+ for (const f of fetched?.focuses ?? [])
191
+ focusById.set(f.id, f);
192
+ for (const f of local.focuses)
193
+ focusById.set(f.id, f);
194
+ memo = { key, focuses: [...focusById.values()], levers: [...mergePlaybooks(LEVERS, fetched), ...local.levers], version: fetched?.version ?? PLAYBOOK_VERSION };
108
195
  return memo;
109
196
  }
197
+ /** A focus's label for people: its playbook label, else its id. */
198
+ export function focusLabel(id) {
199
+ if (id === 'other')
200
+ return 'Something else';
201
+ return activePlaybook().focuses.find((f) => f.id === id)?.label ?? id;
202
+ }
110
203
  /** The levers in use for a focus. */
111
204
  export function leversFor(focus) {
112
205
  return activePlaybook().levers.filter((l) => l.focus === focus);
@@ -1,6 +1,38 @@
1
1
  {
2
+ "version": 3,
3
+ "focuses": [
4
+ {
5
+ "id": "new-signups",
6
+ "label": "Getting new signups or customers",
7
+ "hint": "more people signing up, buying or getting in touch for the first time"
8
+ },
9
+ {
10
+ "id": "activation",
11
+ "label": "Getting new users started",
12
+ "hint": "new users reaching their first real use: setup finished, first key step taken"
13
+ },
14
+ {
15
+ "id": "retention",
16
+ "label": "Keeping users",
17
+ "hint": "people who use it continuing to, renewing, or coming back"
18
+ },
19
+ {
20
+ "id": "faster-support",
21
+ "label": "Faster support",
22
+ "hint": "answering customers sooner and better"
23
+ },
24
+ {
25
+ "id": "revenue-recovery",
26
+ "label": "Recovering revenue",
27
+ "hint": "failed payments, abandoned checkouts and lapsed customers won back"
28
+ },
29
+ {
30
+ "id": "ops-hygiene",
31
+ "label": "Smoother operations",
32
+ "hint": "exceptions, stuck items and deadlines caught before they cost anything"
33
+ }
34
+ ],
2
35
  "$comment": "Playbook v1 for the goal planner (core/system-agents/goal-planner.ts). A lever is one proven way to move a kind of goal. Ids are stable: saved workflows, discards and eval expectations refer to them, so change wording freely but never an id. Loaded and checked by core/system-agents/goal-playbooks.ts.",
3
- "version": 2,
4
36
  "levers": [
5
37
  {
6
38
  "id": "new-signups.answer-intent-posts",
package/dist/index.d.ts CHANGED
@@ -127,8 +127,8 @@ export { createTrackedApprover, listApprovals, decideApproval, findApproval } fr
127
127
  export { scaffoldAgent, scaffoldSubagent, AgentNameError, AgentExistsError, AgentNotFoundError, AgentModelError } from './bin/cli.js';
128
128
  export type { AgentTemplateOptions } from './bin/cli.js';
129
129
  export { goalsPageHtml } from './web/goals-page.js';
130
- export { GoalError, acceptJob, assignJob, assignmentMessage, chainedRuns, chainConditionMet, checkChain, editJob, MAX_CHAIN_DEPTH, type ChainStep, goalView, type AssignmentView, checkBuiltWorkflows, createGoal, deleteGoal, editAmount, generateMore, getGoal, goalContextFrom, listGoals, markBuilt, prepareBuild, readAbout, readGoalSettings, readLeverEvents, setWorkflowState, writeAbout, writeGoalSettings, type Goal, type GoalJob, type GoalJobState, type JobDoer, type GoalWorkflow, type GoalsDeps, type LeverEvent, migrateGoal, migrateGoalFiles } from './web/goals-admin.js';
130
+ export { GoalError, acceptJob, addJob, assignJob, assignmentMessage, chainedRuns, chainConditionMet, checkChain, editJob, MAX_CHAIN_DEPTH, type ChainStep, goalView, type AssignmentView, checkBuiltWorkflows, createGoal, deleteGoal, editAmount, generateMore, getGoal, goalContextFrom, listGoals, markBuilt, prepareBuild, readAbout, readGoalSettings, readLeverEvents, setWorkflowState, writeAbout, writeGoalSettings, type Goal, type GoalJob, type GoalJobState, type JobDoer, type GoalWorkflow, type GoalsDeps, type LeverEvent, migrateGoal, migrateGoalFiles } from './web/goals-admin.js';
131
131
  export { sendLeverEvents, sharesLeverStats, startLeverEventsSync } from './web/lever-events-sync.js';
132
- export { runGoalPipeline, type GoalPlan, type GoalContext } from './core/system-agents/goal-planner.js';
132
+ export { runGoalPipeline, shapeJob, type GoalPlan, type GoalContext, type ShapedJob } from './core/system-agents/goal-planner.js';
133
133
  export { LEVERS, PLAYBOOK_VERSION, activePlaybook, setPlaybookProjectDir, type Lever } from './core/system-agents/goal-playbooks.js';
134
134
  export { startPlaybookSync, syncPlaybook, playbookSyncConfig } from './core/playbook-sync.js';
package/dist/index.js CHANGED
@@ -118,8 +118,8 @@ export { scaffoldAgent, scaffoldSubagent, AgentNameError, AgentExistsError, Agen
118
118
  // playbook, kept current on Cloud by core/playbook-sync.ts: a project's
119
119
  // own adapters/http.ts imports these.
120
120
  export { goalsPageHtml } from './web/goals-page.js';
121
- export { GoalError, acceptJob, assignJob, assignmentMessage, chainedRuns, chainConditionMet, checkChain, editJob, MAX_CHAIN_DEPTH, goalView, checkBuiltWorkflows, createGoal, deleteGoal, editAmount, generateMore, getGoal, goalContextFrom, listGoals, markBuilt, prepareBuild, readAbout, readGoalSettings, readLeverEvents, setWorkflowState, writeAbout, writeGoalSettings, migrateGoal, migrateGoalFiles } from './web/goals-admin.js';
121
+ export { GoalError, acceptJob, addJob, assignJob, assignmentMessage, chainedRuns, chainConditionMet, checkChain, editJob, MAX_CHAIN_DEPTH, goalView, checkBuiltWorkflows, createGoal, deleteGoal, editAmount, generateMore, getGoal, goalContextFrom, listGoals, markBuilt, prepareBuild, readAbout, readGoalSettings, readLeverEvents, setWorkflowState, writeAbout, writeGoalSettings, migrateGoal, migrateGoalFiles } from './web/goals-admin.js';
122
122
  export { sendLeverEvents, sharesLeverStats, startLeverEventsSync } from './web/lever-events-sync.js';
123
- export { runGoalPipeline } from './core/system-agents/goal-planner.js';
123
+ export { runGoalPipeline, shapeJob } from './core/system-agents/goal-planner.js';
124
124
  export { LEVERS, PLAYBOOK_VERSION, activePlaybook, setPlaybookProjectDir } from './core/system-agents/goal-playbooks.js';
125
125
  export { startPlaybookSync, syncPlaybook, playbookSyncConfig } from './core/playbook-sync.js';
@@ -1,5 +1,5 @@
1
1
  import type { ModelCall } from '../core/run-agent.js';
2
- import { type GoalBrief, type GoalContext, type GoalNeed } from '../core/system-agents/goal-planner.js';
2
+ import { type GoalBrief, type GoalContext, type GoalNeed, type LeverChoice } from '../core/system-agents/goal-planner.js';
3
3
  import { type GoalFocus } from '../core/system-agents/goal-playbooks.js';
4
4
  export type GoalJobState = 'suggested' | 'saved' | 'active' | 'done' | 'discarded';
5
5
  /** What does a job: a workflow on an agent, or, for a once job, each try
@@ -88,6 +88,20 @@ export interface GoalJob {
88
88
  result?: string;
89
89
  /** For a recurring job done by several workflows: what runs after what. */
90
90
  chain?: ChainStep[];
91
+ /** A job the person added themselves: their own words, and how the
92
+ * planner judged it ("changed" or "warned", with its note). */
93
+ added?: {
94
+ idea: string;
95
+ verdict: 'added' | 'changed' | 'warned';
96
+ note?: string;
97
+ alternative?: string;
98
+ };
99
+ /** This job's approach stays in the workspace: its lever events are
100
+ * never sent, and its lever is never offered as a candidate for the
101
+ * shared playbook. A job the person typed is kept this way unless they
102
+ * agreed to share its approach; a planner's job, when it's made from a
103
+ * lever written from such a job. */
104
+ keepPrivate?: true;
91
105
  /** How much the person changed the suggested request before building it
92
106
  * (edits to the built workflow's instructions later don't count). */
93
107
  edited?: EditAmount;
@@ -120,6 +134,13 @@ export interface Goal {
120
134
  /** The playbook version the latest suggestions came from. */
121
135
  playbookVersion?: number;
122
136
  rounds: number;
137
+ /** How each round of suggestions chose its levers (the latest five):
138
+ * every lever looked at, chosen or ruled out, and why. */
139
+ choices?: {
140
+ round: number;
141
+ at: string;
142
+ considered: LeverChoice[];
143
+ }[];
123
144
  jobs: GoalJob[];
124
145
  createdAt: string;
125
146
  updatedAt: string;
@@ -232,6 +253,16 @@ export declare function markBuilt(deps: GoalsDeps, id: string, workflowId: strin
232
253
  title?: unknown;
233
254
  description?: unknown;
234
255
  }): Goal;
256
+ export declare function addJob(deps: GoalsDeps, id: string, input: {
257
+ idea?: unknown;
258
+ share?: unknown;
259
+ }): Promise<{
260
+ goal: Goal;
261
+ verdict: 'added' | 'changed' | 'warned' | 'refused';
262
+ note: string;
263
+ alternative: string;
264
+ jobId?: string;
265
+ }>;
235
266
  /** Checks a chain against the job's workflows: each step joins two of
236
267
  * them, its condition and inputs make sense, every required input of the
237
268
  * next run is filled, and nothing loops. Returns it tidied, with ids. */
@@ -291,11 +322,12 @@ export declare function goalView(deps: GoalsDeps, goal: Goal): Promise<Goal & {
291
322
  /** none (same words), light (mostly the same: names, a schedule, tone)
292
323
  * or heavy (a different request), by how many words the two share. */
293
324
  export declare function editAmount(before: string, after: string): EditAmount;
294
- /** What happened to a lever's job: suggested, saved, discarded (with a
325
+ /** What happened to a lever's job: suggested (by the planner) or added
326
+ * (by the person, in their own words), saved, discarded (with a
295
327
  * reason), restored; built (a workflow does it) or done (a once job
296
328
  * finished); edited (its request, at Build); then, from its workflow,
297
329
  * kept_14d, used (weekly) and removed. */
298
- export type LeverEventType = 'suggested' | 'saved' | 'discarded' | 'discard_reason' | 'restored' | 'built' | 'done' | 'edited' | 'kept_14d' | 'used' | 'removed';
330
+ export type LeverEventType = 'suggested' | 'added' | 'saved' | 'discarded' | 'discard_reason' | 'restored' | 'built' | 'done' | 'edited' | 'kept_14d' | 'used' | 'removed';
299
331
  export interface LeverEvent {
300
332
  id: string;
301
333
  type: LeverEventType;
@@ -303,6 +335,8 @@ export interface LeverEvent {
303
335
  goal: string;
304
336
  /** The job (its id under the goal). */
305
337
  job: string;
338
+ /** From a job kept to the workspace: never sent. */
339
+ private?: true;
306
340
  leverId?: string;
307
341
  /** The lever's label (for a new idea, the planner's own, generic). */
308
342
  lever: string;
@@ -36,8 +36,8 @@
36
36
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
37
37
  import { randomBytes } from 'node:crypto';
38
38
  import { join } from 'node:path';
39
- import { agentName, runGoalPipeline } from '../core/system-agents/goal-planner.js';
40
- import { GOAL_FOCUSES, activePlaybook } from '../core/system-agents/goal-playbooks.js';
39
+ import { agentName, runGoalPipeline, shapeJob } from '../core/system-agents/goal-planner.js';
40
+ import { activePlaybook, addToLocalPlaybook } from '../core/system-agents/goal-playbooks.js';
41
41
  /** Runs a chain may start one after another, after the first. */
42
42
  export const MAX_CHAIN_DEPTH = 5;
43
43
  export class GoalError extends Error {
@@ -188,7 +188,10 @@ const sameLever = (a, b) => Boolean((a.leverId && a.leverId === b.leverId) || a.
188
188
  function toJob(w, round, deps) {
189
189
  const name = agentName(w.newAgent?.name || w.agent) || 'goal-agent';
190
190
  const exists = deps.agentExists(name);
191
+ // Made from a lever written from a person's job they kept private.
192
+ const fromPrivate = Boolean(w.leverId && activePlaybook().levers.find((l) => l.id === w.leverId)?.private);
191
193
  return {
194
+ ...(fromPrivate ? { keepPrivate: true } : {}),
192
195
  id: newId('w'),
193
196
  title: w.title,
194
197
  kind: w.kind,
@@ -225,6 +228,16 @@ function startPlanning(deps, goal) {
225
228
  saved: planning.jobs.map((w) => ({ title: w.title, lever: w.lever, ...(w.leverId ? { leverId: w.leverId } : {}), state: w.state })),
226
229
  ...(planning.focus ? { focus: planning.focus } : {}),
227
230
  });
231
+ // A focus or levers the planner wrote, because the playbook had none
232
+ // that fit, go in the workspace's own playbook for next time.
233
+ if (plan.brief.newFocus || plan.newLevers?.length) {
234
+ try {
235
+ addToLocalPlaybook(deps.projectDir(), { ...(plan.brief.newFocus ? { focuses: [plan.brief.newFocus] } : {}), levers: plan.newLevers ?? [] });
236
+ }
237
+ catch (err) {
238
+ console.error('[loopengine] couldn\'t add the planner\'s focus and levers to the playbook:', err instanceof Error ? err.message : err);
239
+ }
240
+ }
228
241
  const latest = getGoal(deps, planning.id);
229
242
  // The planner is told what's there; anything it repeats anyway is dropped.
230
243
  const fresh = plan.workflows.map((w) => toJob(w, round, deps)).filter((w, i, all) => !latest.jobs.some((old) => sameLever(old, w)) && all.findIndex((x) => sameLever(x, w)) === i);
@@ -237,6 +250,7 @@ function startPlanning(deps, goal) {
237
250
  status: 'ready',
238
251
  error: undefined,
239
252
  rounds: round,
253
+ ...(plan.considered?.length ? { choices: [...(latest.choices ?? []), { round, at: now(), considered: plan.considered }].slice(-5) } : {}),
240
254
  jobs: [...latest.jobs, ...fresh],
241
255
  updatedAt: now(),
242
256
  };
@@ -269,7 +283,7 @@ export function createGoal(deps, input) {
269
283
  export function generateMore(deps, id, input = {}) {
270
284
  const goal = getGoal(deps, id);
271
285
  const text = typeof input.goal === 'string' && input.goal.trim() ? input.goal.trim().slice(0, MAX_GOAL_CHARS) : goal.goal;
272
- const focus = typeof input.focus === 'string' && [...GOAL_FOCUSES, 'other'].includes(input.focus) ? input.focus : goal.focus;
286
+ const focus = typeof input.focus === 'string' && [...activePlaybook().focuses.map((f) => f.id), 'other'].includes(input.focus) ? input.focus : goal.focus;
273
287
  return startPlanning(deps, { ...goal, goal: text, ...(focus ? { focus } : {}) });
274
288
  }
275
289
  // ---- What the person does with a job (/goals/<id>/jobs/<jobId>).
@@ -377,6 +391,55 @@ export function markBuilt(deps, id, workflowId, input) {
377
391
  recordLeverEvent(deps, goal, w, 'edited', { amount: edited });
378
392
  return updateWorkflow(deps, goal, workflowId, (x) => ({ ...x, state: 'active', doers: [...x.doers.filter((d) => !(d.type === 'workflow' && d.agent === doer.agent && d.workflowId === doer.workflowId)), doer], agent: { name: input.agent, isNew: false }, ...(edited ? { edited } : {}) }));
379
393
  }
394
+ // ---- A job the person adds, in their own words: the planner shapes it
395
+ // (kind, measure, agent, request, a lever or a new generic one) and
396
+ // judges it: added, added with changes, added with a warning, or refused
397
+ // (deceptive, illegal, against a platform's rules). One that's added is
398
+ // saved, ready to build or assign.
399
+ export async function addJob(deps, id, input) {
400
+ const idea = typeof input.idea === 'string' ? input.idea.trim() : '';
401
+ if (idea.length < 5)
402
+ throw new GoalError('Say what the job is, e.g. "Thank every new customer by email within a day".');
403
+ if (idea.length > 1000)
404
+ throw new GoalError('Keep it under 1000 characters.');
405
+ const goal = getGoal(deps, id);
406
+ if (goal.status === 'planning')
407
+ throw new GoalError('Wait for the suggestions first.');
408
+ if (!goal.brief)
409
+ throw new GoalError('This goal hasn\'t been planned yet: generate suggestions first.');
410
+ const brief = { ...goal.brief, ...(goal.focus ? { focus: goal.focus } : {}) };
411
+ const shaped = await shapeJob(await deps.modelCall(), {
412
+ goal: goal.goal,
413
+ brief,
414
+ context: await deps.context(readAbout(deps)),
415
+ saved: goal.jobs.map((w) => ({ title: w.title, lever: w.lever, ...(w.leverId ? { leverId: w.leverId } : {}), state: w.state })),
416
+ idea,
417
+ });
418
+ if (shaped.verdict === 'refused' || !shaped.job) {
419
+ return { goal, verdict: 'refused', note: shaped.note || 'This couldn\'t be shaped into a job: say a little more about what it should do.', alternative: shaped.alternative };
420
+ }
421
+ // The person's own idea stays theirs unless they agreed to share its
422
+ // approach: then the lever written from it can become a candidate.
423
+ const share = input.share === true;
424
+ if (shaped.newLever) {
425
+ try {
426
+ addToLocalPlaybook(deps.projectDir(), { levers: [share ? shaped.newLever : { ...shaped.newLever, private: true }] });
427
+ }
428
+ catch (err) {
429
+ console.error('[loopengine] couldn\'t add the job\'s lever to the playbook:', err instanceof Error ? err.message : err);
430
+ }
431
+ }
432
+ const job = {
433
+ ...toJob(shaped.job, goal.rounds || 1, deps),
434
+ state: 'saved',
435
+ ...(share ? {} : { keepPrivate: true }),
436
+ added: { idea, verdict: shaped.verdict, ...(shaped.note ? { note: shaped.note } : {}), ...(shaped.alternative ? { alternative: shaped.alternative } : {}) },
437
+ };
438
+ const latest = getGoal(deps, id);
439
+ const updated = write(deps, { ...latest, jobs: [...latest.jobs, job], updatedAt: now() });
440
+ recordLeverEvent(deps, updated, job, 'added', { verdict: shaped.verdict });
441
+ return { goal: updated, verdict: shaped.verdict, note: shaped.note, alternative: shaped.alternative, jobId: job.id };
442
+ }
380
443
  const sameRef = (a, b) => a.agent === b.agent && a.workflowId === b.workflowId;
381
444
  const refText = (r) => `${r.agent}/${r.workflowId}`;
382
445
  function refFrom(raw, what) {
@@ -606,7 +669,7 @@ export function editAmount(before, after) {
606
669
  }
607
670
  export function recordLeverEvent(deps, goal, w, type, detail = {}) {
608
671
  const full = {
609
- id: newId('e'), type, at: now(), goal: goal.id, job: w.id, ...(w.leverId ? { leverId: w.leverId } : {}), lever: w.lever, focus: w.focus,
672
+ id: newId('e'), type, at: now(), goal: goal.id, job: w.id, ...(w.keepPrivate ? { private: true } : {}), ...(w.leverId ? { leverId: w.leverId } : {}), lever: w.lever, focus: w.focus,
610
673
  ...(goal.playbookVersion !== undefined ? { playbookVersion: goal.playbookVersion } : {}), detail,
611
674
  };
612
675
  mkdirSync(goalsDir(deps), { recursive: true });
@@ -95,6 +95,14 @@ export const goalsPageHtml = `<!doctype html>
95
95
  .gl-how-open:hover { text-decoration: underline; }
96
96
  .gl-waiting { color: var(--warn); font-weight: 600; }
97
97
  [data-attn][hidden] { display: none; }
98
+ .gl-add { display: grid; gap: 8px; }
99
+ .gl-add-form { display: grid; gap: 6px; padding: 12px 14px; border: 1px dashed var(--line); border-radius: 10px; }
100
+ .gl-add-form[hidden], #glAddToggle[hidden] { display: none; }
101
+ #glAddToggle { justify-self: start; }
102
+ .gl-notice { display: grid; gap: 4px; padding: 10px 14px; border-radius: 10px; font-size: 13.5px; }
103
+ .gl-notice.good { background: var(--good-soft); }
104
+ .gl-notice.warn { background: var(--warn-soft); }
105
+ .gl-notice.bad { background: var(--bad-soft); }
98
106
  .gl-try { display: grid; gap: 6px; padding: 10px 12px; border-radius: 8px; background: var(--surface); }
99
107
  .gl-try + .gl-try { margin-top: 6px; }
100
108
  .gl-result { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13.5px; line-height: 1.55; max-height: 360px; overflow: auto; padding: 10px 12px; border-radius: 8px; background: var(--bg); border: 1px solid var(--line); }
@@ -147,13 +155,15 @@ ${consoleShellScript}
147
155
  var page = document.getElementById('glPage');
148
156
  var ELLIPSIS = String.fromCharCode(8230);
149
157
  var ARROW = String.fromCharCode(8594);
158
+ // The focuses in use (the playbook's, and the workspace's own the
159
+ // planner named), from the server; these until it answers.
150
160
  var FOCUS = [['new-signups', 'Getting new signups or customers'], ['activation', 'Getting new users started'], ['retention', 'Keeping users'], ['faster-support', 'Faster support'], ['revenue-recovery', 'Recovering revenue'], ['ops-hygiene', 'Smoother operations'], ['other', 'Something else']];
151
161
  var KINDS = [['', 'Choose one'], ['ecommerce', 'Online store'], ['saas', 'Software or app'], ['agency', 'Agency or services'], ['local', 'Local business'], ['creator', 'Creator or media'], ['nonprofit', 'Nonprofit'], ['other', 'Something else']];
152
162
  var REASONS = [['not-relevant', 'Not relevant'], ['too-much-work', 'Too much work'], ['already-doing-it', 'Already doing it']];
153
163
  // Which view: the list (/goals), a new goal (?new=1, or the front page)
154
164
  // or one goal (?goal=).
155
165
  var startNew = location.pathname === '/' || new URLSearchParams(location.search).has('new');
156
- var state = { flows: {}, openJobs: {}, goals: [], about: '', settings: {}, current: null, creating: startNew, showDiscarded: false, justDiscarded: null, error: '', poll: null, startedAt: 0 };
166
+ var state = { addOpen: false, addDraft: '', addShare: false, addNotice: null, flows: {}, openJobs: {}, goals: [], about: '', settings: {}, current: null, creating: startNew, showDiscarded: false, justDiscarded: null, error: '', poll: null, startedAt: 0 };
157
167
 
158
168
  function esc(s) {
159
169
  return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
@@ -182,6 +192,7 @@ ${consoleShellScript}
182
192
  state.goals = r.body.goals || [];
183
193
  state.about = r.body.about || '';
184
194
  state.settings = r.body.settings || {};
195
+ if (Array.isArray(r.body.focuses) && r.body.focuses.length) FOCUS = r.body.focuses.map(function (f) { return [f.id, f.label]; }).concat([['other', 'Something else']]);
185
196
  var id = selectId || new URLSearchParams(location.search).get('goal');
186
197
  state.current = state.goals.filter(function (g) { return g.id === id; })[0] || null;
187
198
  render();
@@ -302,6 +313,7 @@ ${consoleShellScript}
302
313
  '<span class="gl-job-primary">' + primary + '</span>' +
303
314
  '</div>' +
304
315
  '<div class="gl-job-body"' + (open ? '' : ' hidden') + '>' +
316
+ (w.added ? '<p class="hint" style="margin:0">You added this: ' + String.fromCharCode(8220) + esc(w.added.idea) + String.fromCharCode(8221) + (w.added.note ? ' ' + String.fromCharCode(183) + ' ' + esc(w.added.note) : '') + (w.keepPrivate ? ' ' + String.fromCharCode(183) + ' kept to your workspace' : ' ' + String.fromCharCode(183) + ' its approach may be shared') + '</p>' : '') +
305
317
  (w.why && sub !== w.why ? '<p class="gl-why">' + esc(w.why) + '</p>' : '') +
306
318
  (w.measure && sub.indexOf(w.measure) < 0 ? '<p class="gl-job-measure">' + (once ? '' : 'Measured by ') + esc(w.measure) + '</p>' : '') +
307
319
  (w.state === 'active' || w.state === 'done' ? '' : '<div class="gl-row">' + agentHtml(w) + '</div>' + needsHtml(w)) +
@@ -314,6 +326,25 @@ ${consoleShellScript}
314
326
  '</div>';
315
327
  }
316
328
 
329
+ // A job of the person's own: typed in their words, shaped and judged by
330
+ // the planner (added, changed, warned or refused), with what it said.
331
+ function addJobHtml(planning) {
332
+ var n = state.addNotice;
333
+ var notice = !n ? '' : '<div class="gl-notice ' + (n.verdict === 'refused' ? 'bad' : n.verdict === 'added' ? 'good' : 'warn') + '">' +
334
+ '<strong>' + (n.verdict === 'refused' ? 'Not added' : n.verdict === 'changed' ? 'Added, with changes' : n.verdict === 'warned' ? 'Added, with a caution' : 'Added') + '</strong>' +
335
+ (n.note ? '<span>' + esc(n.note) + '</span>' : '') +
336
+ (n.alternative ? '<span class="hint">Instead, you could: ' + esc(n.alternative) + '</span>' : '') + '</div>';
337
+ return '<div class="gl-add">' +
338
+ '<button type="button" class="gl-link" id="glAddToggle"' + (state.addOpen ? ' hidden' : '') + '>+ Add your own job</button>' +
339
+ '<div class="gl-add-form"' + (state.addOpen ? '' : ' hidden') + '>' +
340
+ '<label for="glAddIdea"><strong>A job you have in mind</strong> <span class="hint">in your own words; LoopEngine shapes it into a job and says if anything looks off</span></label>' +
341
+ '<textarea id="glAddIdea" rows="2" placeholder="e.g. Thank every new customer by email within a day">' + esc(state.addDraft || '') + '</textarea>' +
342
+ '<label class="hint gl-share"><input type="checkbox" id="glAddShare"' + (state.addShare ? ' checked' : '') + '> Share the approach behind this job to improve suggestions for everyone</label>' +
343
+ '<p class="hint" style="margin:0">Your idea stays in your workspace unless you tick that. If you do, only a generic description of the approach is shared, never your words, and only once many workspaces use something similar.</p>' +
344
+ '<div class="gl-row"><button type="button" class="gl-btn soft" id="glAddJob"' + (planning ? ' disabled' : '') + '>Add it</button><button type="button" class="gl-btn plain" id="glAddCancel">Cancel</button><span class="hint" id="glAddStatus"></span></div>' +
345
+ '</div>' + notice + '</div>';
346
+ }
347
+
317
348
  // A one-off job's tries: the latest with its state and result, earlier
318
349
  // ones folded away.
319
350
  function tryHtml(t, n) {
@@ -424,7 +455,8 @@ ${consoleShellScript}
424
455
  var secs = state.startedAt ? Math.round((Date.now() - state.startedAt) / 1000) : 0;
425
456
  return '<div class="gl-card">' +
426
457
  '<h2 class="gl-goal-title">' + esc(g.goal) + '</h2>' +
427
- (focus ? '<div class="gl-focus">Planning for <select id="glFocus"' + (planning ? ' disabled' : '') + '>' + FOCUS.map(function (f) { return '<option value="' + f[0] + '"' + (f[0] === focus ? ' selected' : '') + '>' + f[1] + '</option>'; }).join('') + '</select>' +
458
+ (focus ? '<div class="gl-focus"><label for="glFocus">Focus</label> <select id="glFocus"' + (planning ? ' disabled' : '') + '>' + (FOCUS.some(function (f) { return f[0] === focus; }) ? FOCUS : FOCUS.concat([[focus, (g.brief && g.brief.newFocus && g.brief.newFocus.label) || focus]])).map(function (f) { return '<option value="' + esc(f[0]) + '"' + (f[0] === focus ? ' selected' : '') + '>' + esc(f[1]) + '</option>'; }).join('') + '</select>' +
459
+ (focus.indexOf('x-') === 0 ? '<span class="hint" title="No focus in the playbook fit this goal, so its planner named one and wrote the approaches it needed. They stay in this workspace for next time.">written for your goals</span>' : '') +
428
460
  (g.brief && g.brief.measure ? '<span>' + String.fromCharCode(183) + ' measured by ' + esc(g.brief.measure) + '</span>' : '') + '</div>' : '') +
429
461
  (g.message ? '<p class="gl-why">' + esc(g.message) + '</p>' : '') +
430
462
  (planning ? '<p class="gl-status">Suggesting jobs' + ELLIPSIS + (secs ? ' ' + secs + 's' : '') + ' It reads your workspace first; this takes about a minute.</p>' : '') +
@@ -440,6 +472,7 @@ ${consoleShellScript}
440
472
  '</div>' +
441
473
  '<div class="gl-section"><h3>Your jobs <span class="gl-count">' + kept.length + '</span></h3>' +
442
474
  (kept.length ? kept.map(jobHtml).join('') : '<p class="gl-empty">Save a suggestion to keep it here. Build a recurring job into a workflow on its agent; assign a one-off job to its agent.</p>') +
475
+ addJobHtml(planning) +
443
476
  '</div>' +
444
477
  (discarded.length ? '<div class="gl-section"><button type="button" class="gl-link" id="glShowDiscarded">' + (state.showDiscarded ? 'Hide' : 'Show') + ' discarded (' + discarded.length + ')</button>' +
445
478
  (state.showDiscarded ? discarded.map(jobHtml).join('') : '') + '</div>' : '') +
@@ -508,6 +541,30 @@ ${consoleShellScript}
508
541
  render();
509
542
  });
510
543
  });
544
+ var addToggle = document.getElementById('glAddToggle');
545
+ if (addToggle) addToggle.addEventListener('click', function () { state.addOpen = true; state.addNotice = null; render(); var box = document.getElementById('glAddIdea'); if (box) box.focus(); });
546
+ var addCancel = document.getElementById('glAddCancel');
547
+ if (addCancel) addCancel.addEventListener('click', function () { state.addOpen = false; state.addDraft = ''; render(); });
548
+ var addIdea = document.getElementById('glAddIdea');
549
+ if (addIdea) addIdea.addEventListener('input', function () { state.addDraft = addIdea.value; });
550
+ var addShare = document.getElementById('glAddShare');
551
+ if (addShare) addShare.addEventListener('change', function () { state.addShare = addShare.checked; });
552
+ var addJob = document.getElementById('glAddJob');
553
+ if (addJob) addJob.addEventListener('click', function () {
554
+ var idea = document.getElementById('glAddIdea').value.trim();
555
+ var status = document.getElementById('glAddStatus');
556
+ if (idea.length < 5) { status.textContent = 'Say what the job is first.'; return; }
557
+ addJob.disabled = true;
558
+ status.textContent = 'Shaping it into a job' + ELLIPSIS;
559
+ var shareBox = document.getElementById('glAddShare');
560
+ api('POST', base + '/jobs', { idea: idea, share: !!(shareBox && shareBox.checked) }).then(function (r) {
561
+ if (!r.ok) { addJob.disabled = false; status.textContent = r.body.error || 'Could not add it.'; return; }
562
+ state.addNotice = { verdict: r.body.verdict, note: r.body.note, alternative: r.body.alternative };
563
+ if (r.body.verdict !== 'refused') { state.addOpen = false; state.addDraft = ''; state.addShare = false; if (r.body.jobId) state.openJobs[r.body.jobId] = true; }
564
+ replaceGoal(r.body.goal);
565
+ render();
566
+ });
567
+ });
511
568
  var shown = document.getElementById('glShowDiscarded');
512
569
  if (shown) shown.addEventListener('click', function () { state.showDiscarded = !state.showDiscarded; render(); });
513
570
  var del = document.getElementById('glDelete');
@@ -12,7 +12,9 @@ export declare function leverEventsSyncConfig(env?: NodeJS.ProcessEnv): LeverEve
12
12
  * a Cloud workspace. */
13
13
  export declare function sharesLeverStats(projectDir: string, env?: NodeJS.ProcessEnv): boolean;
14
14
  export declare function signLeverEvents(body: string, timestamp: number, secret: string): string;
15
- /** An event as it leaves the workspace: only the anonymous fields. */
15
+ /** An event as it leaves the workspace: only the anonymous fields. A
16
+ * workspace's own focus or lever (written by its planner, "x-...") goes
17
+ * as "other" and as its generic label, not its id. */
16
18
  export declare function outgoingLeverEvent(e: Record<string, unknown>, businessKind: string | undefined): Record<string, unknown>;
17
19
  export type LeverEventsSendResult = {
18
20
  status: 'off';
@@ -57,14 +57,17 @@ export function sharesLeverStats(projectDir, env = process.env) {
57
57
  export function signLeverEvents(body, timestamp, secret) {
58
58
  return `t=${timestamp},v1=${createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex')}`;
59
59
  }
60
- /** An event as it leaves the workspace: only the anonymous fields. */
60
+ /** An event as it leaves the workspace: only the anonymous fields. A
61
+ * workspace's own focus or lever (written by its planner, "x-...") goes
62
+ * as "other" and as its generic label, not its id. */
61
63
  export function outgoingLeverEvent(e, businessKind) {
64
+ const local = (v) => typeof v === 'string' && /(^|\.)x-/.test(v);
62
65
  return {
63
66
  id: e.id,
64
67
  type: e.type,
65
- ...(typeof e.leverId === 'string' ? { leverId: e.leverId } : {}),
68
+ ...(typeof e.leverId === 'string' && !local(e.leverId) ? { leverId: e.leverId } : {}),
66
69
  lever: e.lever,
67
- focus: e.focus,
70
+ focus: local(e.focus) ? 'other' : e.focus,
68
71
  ...(typeof e.playbookVersion === 'number' ? { playbookVersion: e.playbookVersion } : {}),
69
72
  ...(businessKind ? { businessKind } : {}),
70
73
  // The job, as an opaque id (an event from before jobs: goalWorkflow).
@@ -104,9 +107,11 @@ export async function sendLeverEvents(projectDir, config, fetchImpl = fetch, env
104
107
  }
105
108
  if (!lines.length)
106
109
  break;
110
+ // An event from a job the person kept to their workspace isn't sent.
107
111
  const events = lines.flatMap((line) => {
108
112
  try {
109
- return [outgoingLeverEvent(JSON.parse(line), businessKind)];
113
+ const e = JSON.parse(line);
114
+ return e.private === true ? [] : [outgoingLeverEvent(e, businessKind)];
110
115
  }
111
116
  catch {
112
117
  return [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.3.66",
3
+ "version": "0.3.68",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",