loopengine 0.3.66 → 0.3.67

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…). */
@@ -27,6 +27,9 @@ export interface GoalBrief {
27
27
  /** How the goal was read, e.g. "literal" or "a stretch goal for the business". */
28
28
  reading: string;
29
29
  focus: GoalFocus | 'other';
30
+ /** When no focus in the playbook fits: the one the planner named
31
+ * (generic words; saved in the workspace's own playbook). */
32
+ newFocus?: Focus;
30
33
  measure: string;
31
34
  /** Where the measure's number comes from (a system, or "none"), and
32
35
  * whether that's connected: when it isn't, the plan says how the
@@ -101,6 +104,10 @@ export interface GoalPlan {
101
104
  };
102
105
  /** The playbook version the plan was made with. */
103
106
  playbookVersion: number;
107
+ /** Levers the planner wrote because the playbook had none that fit
108
+ * (generic, like the playbook's own; saved in the workspace's own
109
+ * playbook, and the jobs made from them refer to them). */
110
+ newLevers?: Lever[];
104
111
  }
105
112
  export interface GoalPipelineInput {
106
113
  goal: string;
@@ -109,9 +116,30 @@ export interface GoalPipelineInput {
109
116
  /** The focus the person chose, instead of the one the brief reads. */
110
117
  focus?: GoalFocus | 'other';
111
118
  }
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.";
119
+ 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- audience, weeklyHours (from the context, else 3), approvals (from the context's rules, else \"nothing is posted, sent or published without approval\").";
120
+ 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 businesses (no names of this business, its products, people, places or sites), 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.\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.";
121
+ 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.";
122
+ /** A job a person added in their own words, shaped like a planned one. */
123
+ 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.";
124
+ export interface ShapedJob {
125
+ verdict: 'added' | 'changed' | 'warned' | 'refused';
126
+ note: string;
127
+ alternative: string;
128
+ /** Missing when refused, or when the answer had no usable job. */
129
+ job?: PlannedGoalWorkflow;
130
+ /** The lever the planner wrote for it, when none fit. */
131
+ newLever?: Lever;
132
+ }
133
+ /** Shapes a job a person typed, under a goal already planned: its kind,
134
+ * measure, agent, request and lever (an existing one, or a new generic
135
+ * one), and judges it: added, changed, warned or refused. */
136
+ export declare function shapeJob(modelCall: ModelCall, input: {
137
+ goal: string;
138
+ brief: GoalBrief;
139
+ context: GoalContext;
140
+ saved?: SavedGoalWorkflow[];
141
+ idea: string;
142
+ }): Promise<ShapedJob>;
115
143
  export declare function contextText(context: GoalContext): string;
116
144
  /** A suggested agent's name as a folder name: lowercase, hyphens. */
117
145
  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,7 +8,7 @@ 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.
@@ -16,7 +16,8 @@ Call save_brief once:
16
16
  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
17
 
18
18
  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.
19
+ 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.
20
+ 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 businesses (no names of this business, its products, people, places or sites), 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
21
  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
22
  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.
22
23
  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.
@@ -41,11 +42,14 @@ export const GOAL_CRITIQUE_PROMPT = `You check a goal plan against its rules bef
41
42
  - a measure whose source isn't connected, with no setup step that connects it or a manual record, or no baseline;
42
43
  - a qualifier from the brief no workflow addresses;
43
44
  - a recurring job on a finite list that will run out (it should be kind "once");
45
+ - 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;
46
+ - a workflow made from no lever when the request listed none for this focus (it should come from one of newLevers);
44
47
  - a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.
45
48
  Call save_review once: passed true only when there are no issues.`;
46
49
  // ---------- tools ----------
47
- const focusEnum = [...GOAL_FOCUSES, 'other'];
48
- const BRIEF_TOOL = {
50
+ /** The focus ids the planner may pick: the playbook in use's, and "other". */
51
+ const focusEnum = () => [...activePlaybook().focuses.map((f) => f.id), 'other'];
52
+ const briefTool = () => ({
49
53
  name: 'save_brief',
50
54
  description: 'Save how the goal was read.',
51
55
  input_schema: {
@@ -54,7 +58,8 @@ const BRIEF_TOOL = {
54
58
  scope: { type: 'string', enum: ['in', 'partial', 'out'] },
55
59
  scopeReason: { type: 'string' },
56
60
  reading: { type: 'string' },
57
- focus: { type: 'string', enum: focusEnum },
61
+ focus: { type: 'string', enum: focusEnum() },
62
+ 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' },
58
63
  measure: { type: 'string' },
59
64
  measureSource: { type: 'string' },
60
65
  measureSourceConnected: { type: 'boolean' },
@@ -65,8 +70,27 @@ const BRIEF_TOOL = {
65
70
  },
66
71
  required: ['scope', 'scopeReason', 'reading', 'focus', 'measure', 'measureSource', 'measureSourceConnected', 'qualifiers', 'audience', 'weeklyHours', 'approvals'],
67
72
  },
73
+ });
74
+ const NEW_LEVER_SCHEMA = {
75
+ type: 'object',
76
+ description: 'a lever the playbook lacks, in generic words (no names of the business, its products, people, places or sites)',
77
+ properties: {
78
+ key: { type: 'string', description: 'a short lowercase-hyphenated key; workflows made from it put this key in leverId' },
79
+ name: { type: 'string', description: 'the approach in a few words' },
80
+ kind: { type: 'string', enum: ['recurring', 'once'] },
81
+ mechanism: { type: 'string', description: 'why it tends to move the measure, one sentence' },
82
+ fitsWhen: { type: 'array', items: { type: 'string' } },
83
+ notWhen: { type: 'array', items: { type: 'string' } },
84
+ needs: { type: 'array', items: { type: 'string' }, description: 'kinds of app or ability it uses (email, messaging, web-search, records, …)' },
85
+ humanMinutesPerWeek: { type: 'number' },
86
+ firstResultDays: { type: 'number' },
87
+ measureLink: { type: 'string', description: 'how its effect shows up, generically' },
88
+ guardrails: { type: 'array', items: { type: 'string' } },
89
+ template: { type: 'string', description: 'the request it starts from, generic, with {placeholders}' },
90
+ },
91
+ required: ['key', 'name', 'kind', 'mechanism', 'fitsWhen', 'notWhen', 'needs', 'humanMinutesPerWeek', 'firstResultDays', 'measureLink', 'guardrails', 'template'],
68
92
  };
69
- const PLAN_TOOL = {
93
+ const planTool = () => ({
70
94
  name: 'save_plan',
71
95
  description: 'Save the plan.',
72
96
  input_schema: {
@@ -81,9 +105,9 @@ const PLAN_TOOL = {
81
105
  title: { type: 'string' },
82
106
  kind: { type: 'string', enum: ['recurring', 'once'] },
83
107
  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" },
108
+ leverId: { type: 'string', description: "the playbook lever's id, or the key of one of your newLevers" },
85
109
  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 },
110
+ focus: { type: 'string' },
87
111
  mechanism: { type: 'string', description: 'why it moves the measure, one sentence' },
88
112
  request: { type: 'string', description: 'the workflow request, specific to this context' },
89
113
  agent: { type: 'string' },
@@ -97,13 +121,70 @@ const PLAN_TOOL = {
97
121
  required: ['title', 'lever', 'focus', 'mechanism', 'request', 'agent', 'needs', 'humanMinutesPerWeek', 'measureLink'],
98
122
  },
99
123
  },
124
+ newLevers: { type: 'array', items: NEW_LEVER_SCHEMA, description: 'levers the playbook lacks; required when the request lists none for this focus' },
100
125
  leftOut: { type: 'array', items: { type: 'string' } },
101
126
  assumptions: { type: 'array', items: { type: 'string' } },
102
127
  message: { type: 'string' },
103
128
  },
104
129
  required: ['setup', 'workflows', 'leftOut', 'assumptions', 'message'],
105
130
  },
131
+ });
132
+ /** A job a person added in their own words, shaped like a planned one. */
133
+ 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.
134
+
135
+ Shape it:
136
+ - 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.
137
+ - 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.
138
+
139
+ Judge it, in verdict:
140
+ - "added": it fits the goal and is safe.
141
+ - "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.
142
+ - "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.
143
+ - "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.
144
+
145
+ Call save_job once.`;
146
+ const addJobTool = () => {
147
+ const plan = planTool().input_schema;
148
+ return {
149
+ name: 'save_job',
150
+ description: 'Save the shaped job and your verdict.',
151
+ input_schema: {
152
+ type: 'object',
153
+ properties: {
154
+ verdict: { type: 'string', enum: ['added', 'changed', 'warned', 'refused'] },
155
+ note: { type: 'string', description: 'for changed, warned or refused: one or two sentences for the person' },
156
+ alternative: { type: 'string', description: 'for warned or refused: a better-aimed or legitimate job, in a sentence' },
157
+ job: plan.properties.workflows.items,
158
+ newLever: NEW_LEVER_SCHEMA,
159
+ },
160
+ required: ['verdict'],
161
+ },
162
+ };
106
163
  };
164
+ /** Shapes a job a person typed, under a goal already planned: its kind,
165
+ * measure, agent, request and lever (an existing one, or a new generic
166
+ * one), and judges it: added, changed, warned or refused. */
167
+ export async function shapeJob(modelCall, input) {
168
+ const focus = input.brief.focus;
169
+ const levers = focus === 'other' ? [] : leversFor(focus);
170
+ const user = [
171
+ contextText(input.context),
172
+ briefText(input.brief),
173
+ 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.',
174
+ savedText(input.saved),
175
+ `The goal:\n${input.goal}`,
176
+ `The job the person wants to add, in their words:\n${input.idea}`,
177
+ ].join('\n\n');
178
+ const raw = await callTool(modelCall, GOAL_ADD_JOB_PROMPT, user, addJobTool());
179
+ const verdict = raw.verdict === 'changed' || raw.verdict === 'warned' || raw.verdict === 'refused' ? raw.verdict : 'added';
180
+ const note = str(raw.note).slice(0, 600);
181
+ const alternative = str(raw.alternative).slice(0, 400);
182
+ if (verdict === 'refused')
183
+ return { verdict, note, alternative };
184
+ const shaped = parsePlan({ workflows: raw.job ? [raw.job] : [], newLevers: raw.newLever ? [raw.newLever] : [] }, focus);
185
+ const job = shaped.workflows[0];
186
+ return { verdict, note, alternative, ...(job ? { job } : {}), ...(job && shaped.newLevers?.[0] ? { newLever: shaped.newLevers[0] } : {}) };
187
+ }
107
188
  const REVIEW_TOOL = {
108
189
  name: 'save_review',
109
190
  description: 'Save the check.',
@@ -160,10 +241,18 @@ export function contextText(context) {
160
241
  context.weeklyHours ? `Time to review drafts: about ${context.weeklyHours} hours a week` : '',
161
242
  ].filter(Boolean).join('\n');
162
243
  }
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');
244
+ /** The focus's levers the plan may still use (none already under the
245
+ * goal). With none left, the planner writes new ones, as for a new focus,
246
+ * so Generate more keeps finding approaches. */
247
+ function leversText(focus, saved = []) {
248
+ const used = new Set(saved.flatMap((s) => (s.leverId ? [s.leverId] : [])));
249
+ const all = focus === 'other' ? [] : leversFor(focus);
250
+ const levers = all.filter((l) => !used.has(l.id));
251
+ if (!levers.length)
252
+ return all.length
253
+ ? '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.'
254
+ : '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.';
255
+ 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
256
  }
168
257
  function savedText(saved) {
169
258
  if (!saved?.length)
@@ -176,15 +265,74 @@ export function agentName(raw) {
176
265
  }
177
266
  const str = (v, fallback = '') => (typeof v === 'string' ? v.trim() : fallback);
178
267
  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');
268
+ const focusOf = (v) => (typeof v === 'string' && focusEnum().includes(v) ? v : 'other');
269
+ const slug = (v) => v.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '');
270
+ /** Text that shouldn't leave the workspace in a lever: links, addresses,
271
+ * handles, long numbers. */
272
+ const UNSAFE_LEVER_TEXT = /https?:|www\.|@|\.(com|co|io|app|net|org|ai)\b|\d{4,}/i;
273
+ /** The focus the brief named, as a workspace's own focus ("x-..."). */
274
+ function newFocusFrom(raw) {
275
+ const f = raw && typeof raw === 'object' ? raw : {};
276
+ const label = str(f.label).slice(0, 60);
277
+ const hint = str(f.hint).slice(0, 300);
278
+ const id = `x-${slug(label)}`;
279
+ if (!label || !hint || id === 'x-' || UNSAFE_LEVER_TEXT.test(`${label} ${hint}`))
280
+ return undefined;
281
+ return { id, label, hint };
282
+ }
283
+ /** The levers a plan wrote, as a workspace's own levers under the focus
284
+ * (ids "<focus>.x-<key>"), keyed by the key its workflows use. One with
285
+ * unsafe text or a missing part is dropped. */
286
+ function newLeversFrom(raw, focus) {
287
+ const out = new Map();
288
+ if (!Array.isArray(raw) || focus === 'other')
289
+ return out;
290
+ for (const item of raw.slice(0, 5)) {
291
+ const x = item && typeof item === 'object' ? item : {};
292
+ const key = slug(str(x.key) || str(x.name));
293
+ const lever = {
294
+ id: `${focus}.x-${key}`,
295
+ focus,
296
+ name: str(x.name).slice(0, 80),
297
+ kind: x.kind === 'once' ? 'once' : 'recurring',
298
+ mechanism: str(x.mechanism).slice(0, 400),
299
+ fitsWhen: strings(x.fitsWhen).slice(0, 5),
300
+ notWhen: strings(x.notWhen).slice(0, 5),
301
+ needs: { ...(strings(x.needs).length ? { anyOf: strings(x.needs).map((n) => n.toLowerCase()).slice(0, 5) } : {}) },
302
+ humanMinutesPerWeek: typeof x.humanMinutesPerWeek === 'number' && x.humanMinutesPerWeek >= 0 ? Math.round(x.humanMinutesPerWeek) : 20,
303
+ firstResultDays: typeof x.firstResultDays === 'number' && x.firstResultDays >= 0 ? Math.round(x.firstResultDays) : 7,
304
+ measureLink: str(x.measureLink).slice(0, 200),
305
+ guardrails: strings(x.guardrails).slice(0, 5),
306
+ template: str(x.template).slice(0, 800),
307
+ };
308
+ const text = [lever.name, lever.mechanism, ...lever.fitsWhen, ...lever.notWhen, lever.measureLink, ...lever.guardrails, lever.template].join(' ');
309
+ if (!key || !lever.name || !lever.mechanism || !lever.measureLink || !lever.template || !lever.fitsWhen.length || UNSAFE_LEVER_TEXT.test(text))
310
+ continue;
311
+ if (!lever.guardrails.length)
312
+ lever.guardrails = ['Nothing is posted, sent or published without the person\u2019s approval.'];
313
+ out.set(key, lever);
314
+ }
315
+ return out;
316
+ }
180
317
  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);
318
+ const focuses = activePlaybook().focuses.map((f) => `- ${f.id}: ${f.label} (${f.hint})`).join('\n');
319
+ 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
320
  const scope = raw.scope === 'partial' || raw.scope === 'out' ? raw.scope : 'in';
321
+ // A focus the planner named becomes the workspace's own, unless one by
322
+ // that name is already in use.
323
+ let focus = focusOf(raw.focus);
324
+ const named = focus === 'other' ? newFocusFrom(raw.newFocus) : undefined;
325
+ const existing = named && activePlaybook().focuses.find((f) => f.id === named.id || f.label.toLowerCase() === named.label.toLowerCase());
326
+ if (existing)
327
+ focus = existing.id;
328
+ else if (named)
329
+ focus = named.id;
183
330
  return {
184
331
  scope,
185
332
  scopeReason: str(raw.scopeReason),
186
333
  reading: str(raw.reading),
187
- focus: focusOf(raw.focus),
334
+ focus,
335
+ ...(named && !existing ? { newFocus: named } : {}),
188
336
  measure: str(raw.measure, 'unknown'),
189
337
  measureSource: str(raw.measureSource, 'none'),
190
338
  measureSourceConnected: raw.measureSourceConnected === true,
@@ -195,11 +343,12 @@ export async function readGoalBrief(modelCall, goal, context) {
195
343
  };
196
344
  }
197
345
  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}`;
346
+ 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
347
  }
200
- function parsePlan(raw) {
348
+ function parsePlan(raw, focus) {
201
349
  const { levers } = activePlaybook();
202
350
  const KNOWN_LEVER_IDS = new Set(levers.map((l) => l.id));
351
+ const written = newLeversFrom(raw.newLevers, focus);
203
352
  const workflows = (Array.isArray(raw.workflows) ? raw.workflows : []).flatMap((w) => {
204
353
  if (!w || typeof w !== 'object')
205
354
  return [];
@@ -208,8 +357,10 @@ function parsePlan(raw) {
208
357
  const request = str(x.request);
209
358
  if (!title || !request)
210
359
  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) : '');
360
+ // Some models put the playbook id in lever and leave leverId empty. A
361
+ // key of one of the plan's own levers means that lever.
362
+ const own = written.get(slug(str(x.leverId))) ?? written.get(slug(str(x.lever)));
363
+ 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
364
  const na = x.newAgent && typeof x.newAgent === 'object' ? x.newAgent : undefined;
214
365
  const newAgentName = na ? agentName(str(na.name) || str(x.agent)) : '';
215
366
  const needs = (Array.isArray(x.needs) ? x.needs : []).flatMap((n) => {
@@ -238,18 +389,20 @@ function parsePlan(raw) {
238
389
  newIdea: !leverId,
239
390
  }];
240
391
  });
241
- return { setup: strings(raw.setup), workflows, leftOut: strings(raw.leftOut), assumptions: strings(raw.assumptions), message: str(raw.message) };
392
+ // The plan's own levers that a workflow is made from: the ones to keep.
393
+ const used = [...written.values()].filter((l) => workflows.some((w) => w.leverId === l.id));
394
+ return { setup: strings(raw.setup), workflows, leftOut: strings(raw.leftOut), assumptions: strings(raw.assumptions), message: str(raw.message), ...(used.length ? { newLevers: used } : {}) };
242
395
  }
243
396
  export async function draftGoalPlan(modelCall, input, brief, issues = []) {
244
397
  const user = [
245
398
  contextText(input.context),
246
399
  briefText(brief),
247
- leversText(brief.focus),
400
+ leversText(brief.focus, input.saved),
248
401
  savedText(input.saved),
249
402
  `The goal, as the person said it:\n${input.goal}`,
250
403
  issues.length ? `A check found these issues in your last plan; fix every one:\n${issues.map((i) => `- ${i}`).join('\n')}` : '',
251
404
  ].filter(Boolean).join('\n\n');
252
- return parsePlan(await callTool(modelCall, GOAL_PLAN_PROMPT, user, PLAN_TOOL));
405
+ return parsePlan(await callTool(modelCall, GOAL_PLAN_PROMPT, user, planTool()), brief.focus);
253
406
  }
254
407
  export async function critiqueGoalPlan(modelCall, input, brief, plan) {
255
408
  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;
@@ -29,25 +41,47 @@ export interface Lever {
29
41
  /** The request it starts from, with {placeholders} filled from context. */
30
42
  template: string;
31
43
  }
32
- /** Checks the playbook's shape, naming the lever at fault. */
33
- export declare function parsePlaybook(raw: unknown): {
44
+ /** Checks the playbook's shape, naming the lever at fault. A lever's
45
+ * focus must be one the playbook lists, or one of `knownFocuses`. */
46
+ export declare function parsePlaybook(raw: unknown, knownFocuses?: readonly string[]): {
34
47
  version: number;
48
+ focuses: Focus[];
35
49
  levers: Lever[];
36
50
  };
37
51
  /** The playbook bundled with this package. */
38
52
  export declare const PLAYBOOK_VERSION: number;
39
53
  export declare const LEVERS: readonly Lever[];
54
+ export declare const FOCUSES: readonly Focus[];
40
55
  /** Where the fetched playbook is cached: the project folder. */
41
56
  export declare function setPlaybookProjectDir(dir: string | undefined): void;
42
57
  export declare function mergePlaybooks(bundled: readonly Lever[], fetched: {
43
58
  levers: Lever[];
44
59
  retired?: string[];
45
60
  } | 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). */
61
+ /** The workspace's own focuses and levers (empty when there are none, or
62
+ * the file doesn't pass the checks). */
63
+ export declare function readLocalPlaybook(dir?: string | undefined): {
64
+ focuses: Focus[];
65
+ levers: Lever[];
66
+ };
67
+ /** Adds focuses and levers to the workspace's own playbook (by id: a new
68
+ * one is added, one with an id already there replaces it). Only local
69
+ * ids ("x-...") are kept. */
70
+ export declare function addToLocalPlaybook(dir: string, add: {
71
+ focuses?: Focus[];
72
+ levers?: Lever[];
73
+ }): {
74
+ focuses: Focus[];
75
+ levers: Lever[];
76
+ };
77
+ /** The playbook in use: the bundled one, the fetched one over it, and the
78
+ * workspace's own focuses and levers; the version is the shared one's. */
48
79
  export declare function activePlaybook(): {
49
80
  version: number;
81
+ focuses: readonly Focus[];
50
82
  levers: readonly Lever[];
51
83
  };
84
+ /** A focus's label for people: its playbook label, else its id. */
85
+ export declare function focusLabel(id: string): string;
52
86
  /** The levers in use for a focus. */
53
87
  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}."`);
@@ -55,12 +90,13 @@ export function parsePlaybook(raw) {
55
90
  guardrails: list('guardrails'), template: text('template'),
56
91
  };
57
92
  });
58
- return { version, levers };
93
+ return { version, focuses, levers };
59
94
  }
60
95
  const playbook = parsePlaybook(JSON.parse(readFileSync(PLAYBOOK_FILE, 'utf8')));
61
96
  /** The playbook bundled with this package. */
62
97
  export const PLAYBOOK_VERSION = playbook.version;
63
98
  export const LEVERS = playbook.levers;
99
+ export const FOCUSES = playbook.focuses;
64
100
  // ---- The playbook in use: the bundled one, merged with the latest one a
65
101
  // Cloud workspace fetched (core/playbook-sync.ts keeps it in the project,
66
102
  // .loopengine/playbook-cache.json). By lever id: a fetched lever replaces
@@ -82,31 +118,87 @@ export function mergePlaybooks(bundled, fetched) {
82
118
  byId.set(l.id, l);
83
119
  return [...byId.values()].filter((l) => !retired.has(l.id));
84
120
  }
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). */
121
+ const localFile = (dir) => join(dir, '.loopengine', 'playbook-local.json');
122
+ const mtime = (file) => {
123
+ try {
124
+ return String(statSync(file).mtimeMs);
125
+ }
126
+ catch {
127
+ return 'none';
128
+ }
129
+ };
130
+ /** The workspace's own focuses and levers (empty when there are none, or
131
+ * the file doesn't pass the checks). */
132
+ export function readLocalPlaybook(dir = cacheDir) {
133
+ if (!dir || !existsSync(localFile(dir)))
134
+ return { focuses: [], levers: [] };
135
+ try {
136
+ const raw = JSON.parse(readFileSync(localFile(dir), 'utf8'));
137
+ const parsed = parsePlaybook({ levers: raw.levers ?? [], focuses: raw.focuses ?? [] }, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
138
+ return { focuses: parsed.focuses.filter((f) => isLocalId(f.id)), levers: parsed.levers.filter((l) => isLocalId(l.id)) };
139
+ }
140
+ catch {
141
+ return { focuses: [], levers: [] };
142
+ }
143
+ }
144
+ /** Adds focuses and levers to the workspace's own playbook (by id: a new
145
+ * one is added, one with an id already there replaces it). Only local
146
+ * ids ("x-...") are kept. */
147
+ export function addToLocalPlaybook(dir, add) {
148
+ const current = readLocalPlaybook(dir);
149
+ const focuses = new Map(current.focuses.map((f) => [f.id, f]));
150
+ for (const f of add.focuses ?? [])
151
+ if (isLocalId(f.id))
152
+ focuses.set(f.id, f);
153
+ const levers = new Map(current.levers.map((l) => [l.id, l]));
154
+ for (const l of add.levers ?? [])
155
+ if (isLocalId(l.id))
156
+ levers.set(l.id, l);
157
+ const next = { focuses: [...focuses.values()], levers: [...levers.values()] };
158
+ // Checked as a whole before it's written: a bad lever fails here.
159
+ parsePlaybook(next, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
160
+ mkdirSync(join(dir, '.loopengine'), { recursive: true });
161
+ const file = localFile(dir);
162
+ const temp = `${file}.${process.pid}.tmp`;
163
+ writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`);
164
+ renameSync(temp, file);
165
+ if (dir === cacheDir)
166
+ memo = undefined;
167
+ return next;
168
+ }
169
+ /** The playbook in use: the bundled one, the fetched one over it, and the
170
+ * workspace's own focuses and levers; the version is the shared one's. */
87
171
  export function activePlaybook() {
88
172
  if (!cacheDir)
89
- return { version: PLAYBOOK_VERSION, levers: LEVERS };
173
+ return { version: PLAYBOOK_VERSION, focuses: FOCUSES, levers: LEVERS };
90
174
  const file = join(cacheDir, '.loopengine', 'playbook-cache.json');
91
- let key = 'none';
92
- try {
93
- key = String(statSync(file).mtimeMs);
94
- }
95
- catch { }
175
+ const key = `${mtime(file)}|${mtime(localFile(cacheDir))}`;
96
176
  if (memo?.key === key)
97
177
  return memo;
98
178
  let fetched;
99
- if (key !== 'none') {
179
+ if (!key.startsWith('none|')) {
100
180
  try {
101
181
  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') : [] };
182
+ const parsed = parsePlaybook(raw, [...GOAL_FOCUSES, ...FOCUSES.map((f) => f.id)]);
183
+ fetched = { ...parsed, retired: Array.isArray(raw.retired) ? raw.retired.filter((x) => typeof x === 'string') : [] };
104
184
  }
105
185
  catch { }
106
186
  }
107
- memo = { key, levers: mergePlaybooks(LEVERS, fetched), version: fetched?.version ?? PLAYBOOK_VERSION };
187
+ const local = readLocalPlaybook(cacheDir);
188
+ const focusById = new Map(FOCUSES.map((f) => [f.id, f]));
189
+ for (const f of fetched?.focuses ?? [])
190
+ focusById.set(f.id, f);
191
+ for (const f of local.focuses)
192
+ focusById.set(f.id, f);
193
+ memo = { key, focuses: [...focusById.values()], levers: [...mergePlaybooks(LEVERS, fetched), ...local.levers], version: fetched?.version ?? PLAYBOOK_VERSION };
108
194
  return memo;
109
195
  }
196
+ /** A focus's label for people: its playbook label, else its id. */
197
+ export function focusLabel(id) {
198
+ if (id === 'other')
199
+ return 'Something else';
200
+ return activePlaybook().focuses.find((f) => f.id === id)?.label ?? id;
201
+ }
110
202
  /** The levers in use for a focus. */
111
203
  export function leversFor(focus) {
112
204
  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';
@@ -88,6 +88,18 @@ 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
+ /** The person asked to keep this job's approach to their workspace: its
100
+ * lever events are never sent, and its lever is never offered as a
101
+ * candidate for the shared playbook. */
102
+ keepPrivate?: true;
91
103
  /** How much the person changed the suggested request before building it
92
104
  * (edits to the built workflow's instructions later don't count). */
93
105
  edited?: EditAmount;
@@ -232,6 +244,16 @@ export declare function markBuilt(deps: GoalsDeps, id: string, workflowId: strin
232
244
  title?: unknown;
233
245
  description?: unknown;
234
246
  }): Goal;
247
+ export declare function addJob(deps: GoalsDeps, id: string, input: {
248
+ idea?: unknown;
249
+ private?: unknown;
250
+ }): Promise<{
251
+ goal: Goal;
252
+ verdict: 'added' | 'changed' | 'warned' | 'refused';
253
+ note: string;
254
+ alternative: string;
255
+ jobId?: string;
256
+ }>;
235
257
  /** Checks a chain against the job's workflows: each step joins two of
236
258
  * them, its condition and inputs make sense, every required input of the
237
259
  * next run is filled, and nothing loops. Returns it tidied, with ids. */
@@ -291,11 +313,12 @@ export declare function goalView(deps: GoalsDeps, goal: Goal): Promise<Goal & {
291
313
  /** none (same words), light (mostly the same: names, a schedule, tone)
292
314
  * or heavy (a different request), by how many words the two share. */
293
315
  export declare function editAmount(before: string, after: string): EditAmount;
294
- /** What happened to a lever's job: suggested, saved, discarded (with a
316
+ /** What happened to a lever's job: suggested (by the planner) or added
317
+ * (by the person, in their own words), saved, discarded (with a
295
318
  * reason), restored; built (a workflow does it) or done (a once job
296
319
  * finished); edited (its request, at Build); then, from its workflow,
297
320
  * kept_14d, used (weekly) and removed. */
298
- export type LeverEventType = 'suggested' | 'saved' | 'discarded' | 'discard_reason' | 'restored' | 'built' | 'done' | 'edited' | 'kept_14d' | 'used' | 'removed';
321
+ export type LeverEventType = 'suggested' | 'added' | 'saved' | 'discarded' | 'discard_reason' | 'restored' | 'built' | 'done' | 'edited' | 'kept_14d' | 'used' | 'removed';
299
322
  export interface LeverEvent {
300
323
  id: string;
301
324
  type: LeverEventType;
@@ -303,6 +326,8 @@ export interface LeverEvent {
303
326
  goal: string;
304
327
  /** The job (its id under the goal). */
305
328
  job: string;
329
+ /** From a job kept to the workspace: never sent. */
330
+ private?: true;
306
331
  leverId?: string;
307
332
  /** The lever's label (for a new idea, the planner's own, generic). */
308
333
  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 {
@@ -225,6 +225,16 @@ function startPlanning(deps, goal) {
225
225
  saved: planning.jobs.map((w) => ({ title: w.title, lever: w.lever, ...(w.leverId ? { leverId: w.leverId } : {}), state: w.state })),
226
226
  ...(planning.focus ? { focus: planning.focus } : {}),
227
227
  });
228
+ // A focus or levers the planner wrote, because the playbook had none
229
+ // that fit, go in the workspace's own playbook for next time.
230
+ if (plan.brief.newFocus || plan.newLevers?.length) {
231
+ try {
232
+ addToLocalPlaybook(deps.projectDir(), { ...(plan.brief.newFocus ? { focuses: [plan.brief.newFocus] } : {}), levers: plan.newLevers ?? [] });
233
+ }
234
+ catch (err) {
235
+ console.error('[loopengine] couldn\'t add the planner\'s focus and levers to the playbook:', err instanceof Error ? err.message : err);
236
+ }
237
+ }
228
238
  const latest = getGoal(deps, planning.id);
229
239
  // The planner is told what's there; anything it repeats anyway is dropped.
230
240
  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);
@@ -269,7 +279,7 @@ export function createGoal(deps, input) {
269
279
  export function generateMore(deps, id, input = {}) {
270
280
  const goal = getGoal(deps, id);
271
281
  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;
282
+ const focus = typeof input.focus === 'string' && [...activePlaybook().focuses.map((f) => f.id), 'other'].includes(input.focus) ? input.focus : goal.focus;
273
283
  return startPlanning(deps, { ...goal, goal: text, ...(focus ? { focus } : {}) });
274
284
  }
275
285
  // ---- What the person does with a job (/goals/<id>/jobs/<jobId>).
@@ -377,6 +387,52 @@ export function markBuilt(deps, id, workflowId, input) {
377
387
  recordLeverEvent(deps, goal, w, 'edited', { amount: edited });
378
388
  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
389
  }
390
+ // ---- A job the person adds, in their own words: the planner shapes it
391
+ // (kind, measure, agent, request, a lever or a new generic one) and
392
+ // judges it: added, added with changes, added with a warning, or refused
393
+ // (deceptive, illegal, against a platform's rules). One that's added is
394
+ // saved, ready to build or assign.
395
+ export async function addJob(deps, id, input) {
396
+ const idea = typeof input.idea === 'string' ? input.idea.trim() : '';
397
+ if (idea.length < 5)
398
+ throw new GoalError('Say what the job is, e.g. "Thank every new customer by email within a day".');
399
+ if (idea.length > 1000)
400
+ throw new GoalError('Keep it under 1000 characters.');
401
+ const goal = getGoal(deps, id);
402
+ if (goal.status === 'planning')
403
+ throw new GoalError('Wait for the suggestions first.');
404
+ if (!goal.brief)
405
+ throw new GoalError('This goal hasn\'t been planned yet: generate suggestions first.');
406
+ const brief = { ...goal.brief, ...(goal.focus ? { focus: goal.focus } : {}) };
407
+ const shaped = await shapeJob(await deps.modelCall(), {
408
+ goal: goal.goal,
409
+ brief,
410
+ context: await deps.context(readAbout(deps)),
411
+ saved: goal.jobs.map((w) => ({ title: w.title, lever: w.lever, ...(w.leverId ? { leverId: w.leverId } : {}), state: w.state })),
412
+ idea,
413
+ });
414
+ if (shaped.verdict === 'refused' || !shaped.job) {
415
+ 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 };
416
+ }
417
+ if (shaped.newLever) {
418
+ try {
419
+ addToLocalPlaybook(deps.projectDir(), { levers: [shaped.newLever] });
420
+ }
421
+ catch (err) {
422
+ console.error('[loopengine] couldn\'t add the job\'s lever to the playbook:', err instanceof Error ? err.message : err);
423
+ }
424
+ }
425
+ const job = {
426
+ ...toJob(shaped.job, goal.rounds || 1, deps),
427
+ state: 'saved',
428
+ ...(input.private === true ? { keepPrivate: true } : {}),
429
+ added: { idea, verdict: shaped.verdict, ...(shaped.note ? { note: shaped.note } : {}), ...(shaped.alternative ? { alternative: shaped.alternative } : {}) },
430
+ };
431
+ const latest = getGoal(deps, id);
432
+ const updated = write(deps, { ...latest, jobs: [...latest.jobs, job], updatedAt: now() });
433
+ recordLeverEvent(deps, updated, job, 'added', { verdict: shaped.verdict });
434
+ return { goal: updated, verdict: shaped.verdict, note: shaped.note, alternative: shaped.alternative, jobId: job.id };
435
+ }
380
436
  const sameRef = (a, b) => a.agent === b.agent && a.workflowId === b.workflowId;
381
437
  const refText = (r) => `${r.agent}/${r.workflowId}`;
382
438
  function refFrom(raw, what) {
@@ -606,7 +662,7 @@ export function editAmount(before, after) {
606
662
  }
607
663
  export function recordLeverEvent(deps, goal, w, type, detail = {}) {
608
664
  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,
665
+ 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
666
  ...(goal.playbookVersion !== undefined ? { playbookVersion: goal.playbookVersion } : {}), detail,
611
667
  };
612
668
  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: '', addPrivate: 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' : '') + '</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="glAddPrivate"' + (state.addPrivate ? ' checked' : '') + '> Keep this one to my workspace</label>' +
343
+ '<p class="hint" style="margin:0">Unless you tick that, the approach behind this job (never your words) may be shared anonymously to improve suggestions, 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 addPrivate = document.getElementById('glAddPrivate');
551
+ if (addPrivate) addPrivate.addEventListener('change', function () { state.addPrivate = addPrivate.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 keep = document.getElementById('glAddPrivate');
560
+ api('POST', base + '/jobs', { idea: idea, private: !!(keep && keep.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.addPrivate = 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.67",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",