@tangle-network/agent-app 0.57.20 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/copy-quality/index.ts"],"sourcesContent":["/**\n * `@tangle-network/agent-app/copy-quality` — deterministic checks for copy an\n * agent writes for a reader: ads, posts, subject lines, emails, landing pages.\n *\n * No model call. A scan returns findings an agent can fix before a person sees\n * the draft, and the same findings feed a product's outcome checks, so the\n * in-run feedback and the scored episode never disagree.\n *\n * Tiers follow the \"AI tells\" list in coreyhaines31/marketingskills (MIT,\n * revision f719a8079c694e3267d47b6b60a62aa926055f2c,\n * skills/copywriting/references/ai-tells.md):\n * - ban: a tell on one sighting.\n * - cap: fine once; a tell when two land in one paragraph.\n * - weak: reported, never failing on its own.\n * Weighting follows blader/humanizer (MIT, revision\n * 225a6f39ac85f76ee48dbad772ea4abe4ed6c9d8): staged contrasts, negation lists\n * and staged reveals count on one sighting; a dash or a curly quote in long\n * copy is weak alone. The density score mirrors the EQ-Bench Slop Score mix:\n * 60% tell-word rate, 25% contrast constructions, 15% repeated trigrams.\n *\n * Code blocks, inline code and URLs are removed before scanning: an SDK\n * snippet in a post is the product, not prose.\n */\n\nimport { canonicalizeValue, valuesInText } from '../work-product/claim-support'\n\nexport type CopySurface = 'short' | 'long'\n\nexport type CopyTellTier = 'ban' | 'cap' | 'weak'\n\nexport type CopyTellCategory =\n | 'banned-word'\n | 'cap-words'\n | 'contrast-reveal'\n | 'negation-list'\n | 'question-reveal'\n | 'colon-reveal'\n | 'opener-closer'\n | 'marketing-phrase'\n | 'puffery'\n | 'weasel-source'\n | 'chummy-opener'\n | 'hype-punctuation'\n | 'decoration'\n | 'fragment-drumbeat'\n | 'dash'\n | 'chat-wrapper'\n\nexport interface CopyTellFinding {\n tier: CopyTellTier\n category: CopyTellCategory\n /** The text that triggered the finding. */\n match: string\n /** Zero-based paragraph index, or -1 for a whole-text finding. */\n paragraph: number\n /** What to do instead, written for the agent that will fix it. */\n fix: string\n}\n\nexport interface CopyScanOptions {\n /**\n * `short` = headline, subject line, ad, social post, SMS, hero, CTA: no\n * dashes at all. `long` = article, email body, page: two dashes allowed.\n * Default `long`.\n */\n surface?: CopySurface\n /** Product-specific banned words or phrases (case-insensitive, whole word). */\n extraBanned?: readonly string[]\n}\n\nexport interface CopyScanResult {\n /** No ban-tier and no cap-tier findings. Weak findings never fail alone. */\n pass: boolean\n findings: CopyTellFinding[]\n counts: Record<CopyTellTier, number>\n /** 0 (clean) to 100 (dense with tells). Informational; `pass` is the gate. */\n slopScore: number\n words: number\n}\n\n/** Ban-tier vocabulary: ai-tells.md \"Vocabulary → Ban\", with inflections. */\nexport const BAN_WORDS: readonly string[] = [\n 'delve', 'delves', 'delving', 'delved',\n 'tapestry', 'testament to', 'realm', 'embark', 'embarks', 'embarking',\n 'beacon', 'multifaceted', 'paradigm', 'paradigm shift', 'synergy', 'synergies',\n 'myriad', 'plethora', 'meticulous', 'meticulously', 'intricate',\n 'utilize', 'utilizes', 'utilizing', 'utilized',\n 'leverage', 'leverages', 'leveraging', 'leveraged',\n 'supercharge', 'supercharges', 'supercharged', 'supercharging',\n 'turbocharge', 'turbocharged', 'game-changer', 'game changer', 'game-changing',\n 'ever-evolving landscape', 'plays a crucial role',\n]\n\n/** Cap-tier vocabulary: ai-tells.md \"Vocabulary → Cap\" plus empty intensifiers. */\nexport const CAP_WORDS: readonly string[] = [\n 'seamless', 'seamlessly', 'robust', 'streamline', 'streamlines', 'streamlined',\n 'empower', 'empowers', 'elevate', 'elevates', 'unlock', 'unlocks', 'unleash',\n 'harness', 'foster', 'enhance', 'enhances', 'optimize', 'optimizes',\n 'cutting-edge', 'innovative', 'revolutionary', 'transformative', 'holistic',\n 'comprehensive', 'pivotal', 'crucial', 'vital', 'powerful', 'next-level',\n 'world-class', 'best-in-class', 'landscape', 'navigate', 'ecosystem', 'journey',\n 'truly', 'genuinely', 'incredibly', 'deeply', 'fundamentally', 'significantly',\n 'simply', 'actually', 'literally', 'quietly',\n]\n\ninterface PhraseRule {\n readonly pattern: RegExp\n readonly category: CopyTellCategory\n readonly fix: string\n}\n\nconst rule = (category: CopyTellCategory, fix: string) => (pattern: RegExp): PhraseRule => ({ pattern, category, fix })\n\nconst CONTRAST_FIX = 'State the real point directly with its reason; do not stage a denial first.'\n\nconst PHRASE_RULES: readonly PhraseRule[] = [\n ...[\n /\\bin today'?s (?:fast-paced |digital |modern )?(?:world|landscape|market|age)\\b/i,\n /\\bwhether you'?re an? [^,.]{1,40},? or an? /i,\n /(?:^|[.!?]\\s+)imagine\\b/i,\n /\\bwhen it comes to\\b/i,\n /\\bhere'?s the thing\\b|\\bthe truth is\\b|\\blet me be clear\\b|\\bhere'?s what nobody tells you\\b/i,\n /\\bin this (?:guide|post|article),? we'?ll\\b|\\blet'?s dive in(?:to)?\\b/i,\n /\\bin conclusion\\b|\\bat the end of the day\\b/i,\n /(?:^|[.!?]\\s+)(?:it'?s worth noting|moreover|additionally|importantly|ultimately)\\b/i,\n ].map(rule('opener-closer', 'Delete the wind-up and start with the point.')),\n ...[\n /\\bsay (?:goodbye|hello) to\\b/i,\n /\\b(?:unlock|unleash) the (?:full )?power of\\b/i,\n /\\b\\w+, (?:reimagined|redefined)\\b/i,\n /\\bto the next level\\b/i,\n /\\btransform the way you\\b/i,\n /\\bthe \\w+ you deserve\\b/i,\n /\\bthe future of [\\w ]{1,30} is here\\b/i,\n /\\bbuilt for teams (?:who|that) move fast\\b/i,\n /\\beverything you need to\\b|\\ball-in-one\\b/i,\n /\\beffortless(?:ly)?\\b|\\bin just a few clicks\\b/i,\n /\\bjoin (?:thousands|millions|hundreds) of\\b/i,\n /\\bchanges everything\\b/i,\n /\\bexperience the power of\\b/i,\n ].map(rule('marketing-phrase', 'Replace with the concrete outcome, number or workflow.')),\n rule('puffery', 'State the fact; let the reader judge it.')(/\\b(?:marks|represents) a pivotal moment\\b|\\bredefines the category\\b/i),\n rule('weasel-source', 'Name the source or the customer, or cut the claim.')(/\\bexperts agree\\b|\\bstudies show\\b|\\btrusted by (?:industry )?leaders\\b/i),\n rule('chummy-opener', 'Cut the chummy opener.')(/^(?:great question|let'?s be honest|we get it)\\b/im),\n rule('contrast-reveal', CONTRAST_FIX)(\n /\\bit'?s not (?:just )?[^.,;!?]{1,60}[,;.]\\s*it'?s\\b|\\b(?:this|that) isn'?t [^.;!?]{1,60}\\.\\s*(?:this|that|it) is\\b|\\bnot just [^.;!?]{1,60},? but\\b|\\bnot because [^.;!?]{1,60}\\.\\s*because\\b|\\bless [a-z]+, more [a-z]+\\b|\\bthe question isn'?t\\b|\\?\\s*think again\\b/i,\n ),\n rule('contrast-reveal', CONTRAST_FIX)(/(?:^|[.!?]\\s+)Not [^.;!?]{1,40}\\.\\s+[A-Z][^.;!?]{1,60}\\./),\n rule('negation-list', 'Say what does happen. One plain \"No card required\" beside the CTA is fine.')(\n /\\bno [a-z-]+(?: [a-z-]+)?[,.]\\s*no [a-z-]+/i,\n ),\n rule('question-reveal', 'Delete the question and keep the answer.')(\n /\\bthe (?:result|catch|best part|secret|kicker|twist|answer|difference|outcome|upshot)\\?\\s+\\S/i,\n ),\n rule('colon-reveal', 'Write it as a normal sentence.')(\n /\\b(?:the best part|here'?s the (?:secret|thing|kicker|catch)|one word|the result|the truth|the secret)\\s*:\\s/i,\n ),\n rule('hype-punctuation', 'Remove the stacked punctuation.')(/[!?]{2,}/),\n rule('decoration', 'Remove decorative unicode letters and emoji bullets.')(\n /[\\u{1D400}-\\u{1D7FF}]|^\\s*(?:[-*•]\\s*)?[\\u{1F300}-\\u{1FAFF}\\u{2600}-\\u{27BF}]/mu,\n ),\n]\n\nconst CHAT_WRAPPERS: readonly RegExp[] = [\n /^\\s*(?:sure|certainly|absolutely|of course|great)[!,.]/i,\n /^\\s*here(?:'s| is| are) (?:a|an|the|your|my) (?:draft|version|post|email|ad|headline|copy|subject|options?|revised)/i,\n /\\bi hope (?:this|that) helps\\b/i,\n /\\blet me know if you(?:'d like| want| need)\\b/i,\n /\\b(?:want|would you like) me to\\b/i,\n /\\bfeel free to (?:adjust|tweak|edit)\\b/i,\n]\n\n// An em dash anywhere; an en dash, double hyphen or single hyphen used as a\n// dash between words. A range like 10–20 has no spaces and is not a dash.\nconst DASH = /—|(?<=\\S)[ \\t]+(?:–|--?)[ \\t]+(?=\\S)/g\nconst CURLY = /[‘’“”]/\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction wordRegex(word: string): RegExp {\n return new RegExp(`(?<![\\\\w-])${escapeRegExp(word).replace(/ /g, '\\\\s+')}(?![\\\\w-])`, 'gi')\n}\n\nconst BAN_REGEXES = BAN_WORDS.map((word) => ({ word, regex: wordRegex(word) }))\nconst CAP_REGEXES = CAP_WORDS.map((word) => ({ word, regex: wordRegex(word) }))\n\n/** The prose a reader reads: code, URLs and quote styles normalized away. */\nexport function proseOf(text: string): string {\n return text\n .replace(/```[\\s\\S]*?```/g, '\\n\\n')\n .replace(/`[^`\\n]*`/g, 'code')\n .replace(/https?:\\/\\/\\S+/g, 'link')\n .replace(/[‘’]/g, \"'\")\n .replace(/[“”]/g, '\"')\n}\n\nfunction paragraphsOf(prose: string): string[] {\n return prose.split(/\\n\\s*\\n/).map((p) => p.trim()).filter(Boolean)\n}\n\nfunction wordCount(text: string): number {\n return (text.match(/[A-Za-z0-9][\\w'-]*/g) ?? []).length\n}\n\nfunction repeatedTrigramRate(prose: string): number {\n const words = prose.toLowerCase().match(/[a-z0-9][a-z0-9'-]*/g) ?? []\n if (words.length < 12) return 0\n const seen = new Map<string, number>()\n for (let i = 0; i + 2 < words.length; i += 1) {\n const key = `${words[i]} ${words[i + 1]} ${words[i + 2]}`\n seen.set(key, (seen.get(key) ?? 0) + 1)\n }\n let repeats = 0\n for (const count of seen.values()) if (count > 1) repeats += count - 1\n return repeats / (words.length - 2)\n}\n\n/** Scan copy for AI tells. Deterministic and cheap; run it on every draft. */\nexport function scanCopy(text: string, options: CopyScanOptions = {}): CopyScanResult {\n const surface = options.surface ?? 'long'\n const prose = proseOf(text)\n const paragraphs = paragraphsOf(prose)\n const banned = [...BAN_REGEXES, ...(options.extraBanned ?? []).map((word) => ({ word, regex: wordRegex(word) }))]\n const findings: CopyTellFinding[] = []\n let contrastParagraphs = 0\n let tellWords = 0\n\n paragraphs.forEach((paragraph, index) => {\n for (const { word, regex } of banned) {\n for (const match of paragraph.matchAll(regex)) {\n tellWords += 1\n findings.push({ tier: 'ban', category: 'banned-word', match: match[0], paragraph: index, fix: `Replace \"${word}\" with the fact it stands in for.` })\n }\n }\n const capMatches = CAP_REGEXES.flatMap(({ regex }) => [...paragraph.matchAll(regex)].map((match) => match[0]))\n tellWords += capMatches.length\n if (capMatches.length >= 2) {\n findings.push({ tier: 'cap', category: 'cap-words', match: capMatches.join(', '), paragraph: index, fix: 'Two cap-tier words in one paragraph: rewrite it from the facts.' })\n }\n let contrast = false\n for (const { pattern, category, fix } of PHRASE_RULES) {\n const match = paragraph.match(pattern)\n if (!match) continue\n if (category === 'contrast-reveal') {\n if (contrast) continue\n contrast = true\n }\n findings.push({ tier: 'ban', category, match: match[0].trim(), paragraph: index, fix })\n }\n if (contrast) contrastParagraphs += 1\n let run = 0\n for (const sentence of paragraph.split(/(?<=[.!?])\\s+/)) {\n const count = wordCount(sentence)\n run = count > 0 && count <= 3 ? run + 1 : 0\n if (run === 3) {\n findings.push({ tier: 'cap', category: 'fragment-drumbeat', match: sentence, paragraph: index, fix: 'Merge the fragments into one sentence that carries a fact.' })\n break\n }\n }\n })\n\n const dashes = prose.match(DASH)?.length ?? 0\n if (dashes > 0) {\n const tier: CopyTellTier = surface === 'short' ? 'ban' : dashes > 2 ? 'cap' : 'weak'\n const fix = surface === 'short'\n ? 'Short copy uses no dashes between words: use a period, comma or colon.'\n : 'Long copy allows two dashes per page at most; prefer a period or comma.'\n findings.push({ tier, category: 'dash', match: `${dashes} dash${dashes === 1 ? '' : 'es'}`, paragraph: -1, fix })\n }\n if (CURLY.test(text)) {\n findings.push({ tier: 'weak', category: 'decoration', match: 'curly quotes', paragraph: -1, fix: 'Weak alone: use the quote style the target format uses.' })\n }\n const wrapper = chatWrapperIn(text)\n if (wrapper !== null) {\n findings.push({ tier: 'ban', category: 'chat-wrapper', match: wrapper, paragraph: -1, fix: 'Return only the deliverable, with no chat around it.' })\n }\n\n const counts: Record<CopyTellTier, number> = { ban: 0, cap: 0, weak: 0 }\n for (const finding of findings) counts[finding.tier] += 1\n const words = wordCount(prose)\n // Saturates at 40 tell words per 1,000, a contrast in every paragraph, and 10% repeated trigrams.\n const wordRate = Math.min(1, (tellWords * 1000) / Math.max(1, words) / 40)\n const contrastRate = paragraphs.length === 0 ? 0 : contrastParagraphs / paragraphs.length\n const trigramRate = Math.min(1, repeatedTrigramRate(prose) * 10)\n const slopScore = Math.round(100 * (0.6 * wordRate + 0.25 * contrastRate + 0.15 * trigramRate))\n return { pass: counts.ban === 0 && counts.cap === 0, findings, counts, slopScore, words }\n}\n\n/** The chat wrapper around a deliverable (\"Here's a draft…\", \"Hope this helps\"), or null. */\nexport function chatWrapperIn(text: string): string | null {\n const prose = proseOf(text)\n for (const pattern of CHAT_WRAPPERS) {\n const match = prose.match(pattern)\n if (match) return match[0].trim()\n }\n return null\n}\n\n/** Banned words and phrases, lowercased and deduplicated, for prompts that list them. */\nexport function bannedCopyVocabulary(extra: readonly string[] = []): string[] {\n return [...new Set([...extra, ...BAN_WORDS].map((word) => word.toLowerCase()))]\n}\n\nexport interface MetricClaim {\n /** The figure as written, e.g. \"$0.02/hr\", \"40%\", \"10x\", \"300ms\". */\n text: string\n /** Canonical value used to match it against sources (claim-support rules). */\n value: string\n}\n\n// A figure a reader takes as a measured fact: money, a percentage, a multiple,\n// a duration or size with its unit, a scaled count, or a grouped number.\n// Bare small integers (\"3 steps\") and years are not metrics.\nconst METRIC =\n /[$€£¥₹]\\s?\\d[\\d,]*(?:\\.\\d+)?(?:\\s?[kKmMbB]\\b)?|\\b\\d[\\d,]*(?:\\.\\d+)?\\s?(?:%|x\\b|×|ms\\b|s\\b|sec\\b|secs\\b|seconds?\\b|mins?\\b|minutes?\\b|hrs?\\b|hours?\\b|days?\\b|[kKmMbB]\\+?(?=\\s|$|[.,;])|[KMGT]B\\b|rps\\b|qps\\b|tokens?\\b)|\\b\\d{1,3}(?:,\\d{3})+(?:\\.\\d+)?\\b/g\n\n/** Every figure in `text` a reader would take as a measured fact. */\nexport function metricClaims(text: string): MetricClaim[] {\n const claims: MetricClaim[] = []\n for (const match of proseOf(text).matchAll(METRIC)) {\n const numeric = match[0].match(/[$€£¥₹]?\\s?\\d[\\d,]*(?:\\.\\d+)?/)?.[0]\n const value = numeric ? canonicalizeValue(numeric) : null\n if (value !== null) claims.push({ text: match[0].trim(), value })\n }\n return claims\n}\n\n/**\n * Metric claims in `copy` whose value appears in none of `sources`: figures\n * the writer cannot point to. Values match with claim-support's\n * canonicalization, so \"$1,200\" in copy matches \"1200.00\" in a source.\n */\nexport function unsourcedMetrics(copy: string, sources: readonly string[]): MetricClaim[] {\n const known = new Set(sources.flatMap((source) => valuesInText(source)))\n return metricClaims(copy).filter((claim) => !known.has(claim.value))\n}\n"],"mappings":";;;;;;AAiFO,IAAM,YAA+B;AAAA,EAC1C;AAAA,EAAS;AAAA,EAAU;AAAA,EAAW;AAAA,EAC9B;AAAA,EAAY;AAAA,EAAgB;AAAA,EAAS;AAAA,EAAU;AAAA,EAAW;AAAA,EAC1D;AAAA,EAAU;AAAA,EAAgB;AAAA,EAAY;AAAA,EAAkB;AAAA,EAAW;AAAA,EACnE;AAAA,EAAU;AAAA,EAAY;AAAA,EAAc;AAAA,EAAgB;AAAA,EACpD;AAAA,EAAW;AAAA,EAAY;AAAA,EAAa;AAAA,EACpC;AAAA,EAAY;AAAA,EAAa;AAAA,EAAc;AAAA,EACvC;AAAA,EAAe;AAAA,EAAgB;AAAA,EAAgB;AAAA,EAC/C;AAAA,EAAe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;AACxD,QAAM,SAAwB,CAAC;AAC/B,aAAW,SAAS,QAAQ,IAAI,EAAE,SAAS,MAAM,GAAG;AAClD,UAAM,UAAU,MAAM,CAAC,EAAE,MAAM,+BAA+B,IAAI,CAAC;AACnE,UAAM,QAAQ,UAAU,kBAAkB,OAAO,IAAI;AACrD,QAAI,UAAU,KAAM,QAAO,KAAK,EAAE,MAAM,MAAM,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;AAAA,EAClE;AACA,SAAO;AACT;AAOO,SAAS,iBAAiB,MAAc,SAA2C;AACxF,QAAM,QAAQ,IAAI,IAAI,QAAQ,QAAQ,CAAC,WAAW,aAAa,MAAM,CAAC,CAAC;AACvE,SAAO,aAAa,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,MAAM,IAAI,MAAM,KAAK,CAAC;AACrE;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The product system-prompt renderer: one layout for every product agent.
3
+ *
4
+ * identity who the agent is (product-owned, no heading)
5
+ * ## Operating contract the shared, versioned rules (./operating-contract)
6
+ * ## Environment facts about the machine and tools this turn has
7
+ * ## Tool conventions product tool rules beyond the contract
8
+ * ## Skills the task skill index (bodies stay mounted)
9
+ * ## Domain guidance fixed product standards, then learned guidance
10
+ * ## Workspace context the per-workspace overlay
11
+ *
12
+ * Products previously rendered this through agent-eval's `renderProfile` with a
13
+ * hand-copied operating discipline, learned-guidance loader, and overlay. Two
14
+ * defects came with the copies: an empty skill roster still rendered
15
+ * `_No skills configured._` ahead of the product's real skill index, and an
16
+ * empty learned-guidance section rendered a placeholder sentence. Empty
17
+ * sections are omitted here instead.
18
+ *
19
+ * Learned guidance is the one section the self-improvement loop changes. The
20
+ * loop renders a candidate by passing its body as `learnedGuidance`, so the
21
+ * prompt it scores is byte-identical to the prompt production would render if
22
+ * that candidate were promoted.
23
+ */
24
+ import { type ComposeProfileBudget } from './budget';
25
+ import { type OperatingContractClauseId, type OperatingContractOptions } from './operating-contract';
26
+ /** Section id of the evolvable learned guidance, shared by every product and its loop. */
27
+ export declare const LEARNED_GUIDANCE_SECTION_ID = "learned-guidance";
28
+ /** A titled prompt section a product supplies. */
29
+ export interface AgentPromptSection {
30
+ id: string;
31
+ title: string;
32
+ body: string;
33
+ }
34
+ /** Inputs to {@link renderAgentPrompt}. */
35
+ export interface AgentPromptInput {
36
+ /** Who the agent is and what it is for. Rendered first, without a heading. */
37
+ identity: string;
38
+ /** Product adjustments to the shared operating contract, which always renders. */
39
+ contract?: OperatingContractOptions;
40
+ /** Facts about the machine and tools this turn runs with. Pass the lane the
41
+ * turn actually executes on; a sandbox description on a lane without one
42
+ * sends the model after tools it does not have. */
43
+ environment: string;
44
+ /** Product tool rules beyond the shared contract. Omitted when empty. */
45
+ toolConventions?: string;
46
+ /** The task skill index, normally `composeSkillsForHarness(...).promptSection`.
47
+ * A `## Skills` heading is added when the index has none. Omitted when empty. */
48
+ skillIndex?: string;
49
+ /** Fixed product standards, rendered in order under `## Domain guidance`. */
50
+ standards?: readonly AgentPromptSection[];
51
+ /** Deployed or candidate learned guidance. Raw file content is fine: HTML
52
+ * comments are stripped, and a body that is empty after stripping falls back
53
+ * to {@link learnedGuidanceBaseline}. */
54
+ learnedGuidance?: string;
55
+ /** In-tree guidance used until the loop promotes a body. */
56
+ learnedGuidanceBaseline?: string;
57
+ /** Per-workspace overlay: workspace configuration, custom instructions, and
58
+ * profile knowledge. Rendered last under `## Workspace context`; sections
59
+ * with empty bodies are dropped. */
60
+ overlay?: readonly AgentPromptSection[];
61
+ /** Byte budget, enforced only when supplied. Pass the product's ceiling when
62
+ * this render is the final system prompt; when later turn sections are
63
+ * appended, gate the final string with `assertSystemPromptWithinBudget`. */
64
+ budget?: ComposeProfileBudget;
65
+ }
66
+ /** One rendered section, in prompt order. */
67
+ export interface RenderedAgentPromptSection {
68
+ /** `identity`, `operating-contract`, `environment`, `tool-conventions`,
69
+ * `skills`, a standard's id, {@link LEARNED_GUIDANCE_SECTION_ID}, or an
70
+ * overlay section's id. */
71
+ id: string;
72
+ title: string;
73
+ /** Exact text this section contributes, including its heading. */
74
+ text: string;
75
+ bytes: number;
76
+ }
77
+ export interface RenderedAgentPrompt {
78
+ /** Sections joined with a blank line. */
79
+ prompt: string;
80
+ bytes: number;
81
+ contractVersion: number;
82
+ /** Shared contract clauses this prompt carries. */
83
+ contractClauseIds: OperatingContractClauseId[];
84
+ sections: RenderedAgentPromptSection[];
85
+ }
86
+ /** Body of a loaded markdown file with HTML comments removed and whitespace
87
+ * trimmed, so an all-comment placeholder counts as empty. */
88
+ export declare function stripComments(raw: string): string;
89
+ /** Render the product system prompt. Throws on duplicate section ids, an empty
90
+ * identity or environment, or a prompt over a supplied budget. */
91
+ export declare function renderAgentPrompt(input: AgentPromptInput): RenderedAgentPrompt;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Profile composer + evolvable-section seam for agent products.
2
+ * Profile composer and system-prompt renderer for agent products.
3
3
  *
4
4
  * The standard "load a deployable AgentProfile, including skills, plus the
5
5
  * skills the end user added to their own instance" entry point. A product holds
@@ -24,14 +24,12 @@
24
24
  * delegation/app-tool MCP map, and the override strings; nothing here reaches
25
25
  * for env, a glob, or a specific product's profile.
26
26
  *
27
- * The evolvable-section seam is the loader closure. A product's single
28
- * self-improvable domain section (the one `applyDomainPatch` targets) loads its
29
- * body from a deployed markdown override, falling back to an in-tree baseline.
30
- * The `import.meta.glob('<lit>', ...)` literal must stay at the CONSUMER call
31
- * site (Vite static-analyzes it), so `makeEvolvableSection` takes the loader as
32
- * a closure and a REQUIRED `baseline` — it never constructs a glob and never
33
- * defaults the baseline, so a product can't render an empty learned-guidance
34
- * section. `stripComments` is the shared "is this addendum really empty?" test.
27
+ * The system prompt itself comes from `renderAgentPrompt` (./agent-prompt):
28
+ * identity, the shared operating contract (./operating-contract), environment,
29
+ * tool conventions, the skill index, domain guidance ending in the evolvable
30
+ * learned guidance, and the workspace overlay. The default quality skills
31
+ * (./quality-skills) join the product's skills, and `captureModelInput`
32
+ * (./model-input) stores what the model saw for the turn's receipt.
35
33
  */
36
34
  import type { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer, AgentProfileResourceRef } from '@tangle-network/agent-interface';
37
35
  import { profile } from '@tangle-network/agent-eval';
@@ -41,13 +39,15 @@ import { type ComposeProfileBudget } from './budget';
41
39
  * run the same gate without pulling agent-eval through this module. Re-exported
42
40
  * here so the published `/profile` surface is unchanged. */
43
41
  export { assertProfilePromptWithinBudget, assertSystemPromptWithinBudget, DEFAULT_MAX_SYSTEM_PROMPT_BYTES, largestPromptSections, type ComposeProfileBudget, } from './budget';
44
- /** Re-expose the agent-eval section/render substrate so a product wires the
45
- * evolvable surface through ONE subpath: `makeEvolvableSection` builds the
46
- * section, `profile.renderProfile` renders it, `profile.applyDomainPatch` lets
47
- * the loop patch it by id. The rendering/patching engine stays in agent-eval;
48
- * reach it through this namespace (re-exporting the bare fns would leak
49
- * agent-eval's un-nameable AgentProfile type into our generated d.ts). */
42
+ /** Re-expose agent-eval's `profile` namespace for products that still render
43
+ * through `profile.renderProfile`; new prompts use {@link renderAgentPrompt}.
44
+ * Re-exporting the bare functions would leak agent-eval's un-nameable
45
+ * AgentProfile type into our generated d.ts. */
50
46
  export { profile };
47
+ export { LEARNED_GUIDANCE_SECTION_ID, renderAgentPrompt, stripComments, type AgentPromptInput, type AgentPromptSection, type RenderedAgentPrompt, type RenderedAgentPromptSection, } from './agent-prompt';
48
+ export { OPERATING_CONTRACT_CLAUSES, OPERATING_CONTRACT_VERSION, renderOperatingContract, type OperatingContractClause, type OperatingContractClauseId, type OperatingContractOptions, type RenderedOperatingContract, } from './operating-contract';
49
+ export { defaultQualitySkills, HUMAN_PROSE_SKILL_ID, humanProseSkill, withDefaultQualitySkills, type HumanProseSkillOptions, type QualitySkillOptions, } from './quality-skills';
50
+ export { captureModelInput, createMemoryModelInputStore, MODEL_INPUT_RECORD_SCHEMA, modelInputBlob, readModelInput, type CaptureModelInputInput, type ModelInputBlob, type ModelInputKind, type ModelInputMediaType, type ModelInputOutcome, type ModelInputRecord, type ModelInputRef, type ModelInputSectionRef, type ModelInputStore, } from './model-input';
51
51
  /** The file-mount channels layered onto `resources.files`. The first three
52
52
  * mirror {@link ComposeShellResourcesInput}; `userSkills` is the per-user /
53
53
  * per-workspace channel — skills the END USER added to their own instance,
@@ -134,40 +134,6 @@ export declare function userSkillMounts(userSkills: UserSkill[]): AgentProfileFi
134
134
  * default {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES}, `warnOnly` escape hatch).
135
135
  */
136
136
  export declare function composeAgentProfile(base: AgentProfile, channels?: ProfileChannels, overlay?: ProfileOverlay, budget?: ComposeProfileBudget): AgentProfile;
137
- /** True body of an addendum file with HTML comments stripped — an all-comment
138
- * placeholder counts as empty, so the loader falls back to the baseline. */
139
- export declare function stripComments(raw: string): string;
140
- /** Inputs to {@link makeEvolvableSection}. */
141
- export interface EvolvableSectionInput {
142
- /** Section id the self-improvement loop targets with `applyDomainPatch`. */
143
- id: string;
144
- /** Section title rendered as `### <title>`. */
145
- title: string;
146
- /**
147
- * Load the deployed section body. The CONSUMER supplies this closure and runs
148
- * its own `import.meta.glob('<lit>', { eager: true, query: '?raw', import:
149
- * 'default' })` inside it — the literal must stay at the call site so Vite can
150
- * static-analyze it; a glob constructed here would not resolve the product's
151
- * files. Return the raw markdown (comments and all); `makeEvolvableSection`
152
- * applies {@link stripComments} to decide whether it is really populated.
153
- */
154
- load: () => string;
155
- /**
156
- * The in-tree fallback body, used when `load()` returns an
157
- * all-comments/empty placeholder. REQUIRED — no internal default — so a
158
- * product can never accidentally render an empty evolvable section.
159
- */
160
- baseline: string;
161
- }
162
- /**
163
- * Build the one evolvable (`evolvable: true`) domain section whose body comes
164
- * from the product's loader, falling back to the required baseline when the
165
- * loaded body is empty after stripping comments. Returns the agent-eval
166
- * `AgentProfileSection` shape — drop it straight into `prodProfile`'s shipped
167
- * sections. The loader is the only seam; the empty-vs-populated rule and the
168
- * baseline fallback are the lifted algebra.
169
- */
170
- export declare function makeEvolvableSection(input: EvolvableSectionInput): profile.AgentProfileSection;
171
137
  export { assertSkillDeliveryDisjoint, composeShellResources, composeSkills, corpusSkills, loadMarkdownCorpus, mergeComposedSkills, parseCorpusSkills, parseSkillFrontmatter, registrySkills, renderInlineSkills, renderSkillIndex, skillEntryFromMarkdown, skillMountPath, skillRefs, } from '../skills/index';
172
138
  export type { ComposedSkills, ComposeShellResourcesInput, CorpusEntry, CorpusLoadResult, GlobModules, LoadCorpusOptions, ParsedSkill, SkillDeliveryMode, SkillEntry, SkillFrontmatter, } from '../skills/index';
173
139
  export { diffProfileFingerprints, fingerprintAgentProfile, formatProfileDrift, } from './fingerprint';
@@ -1,3 +1,8 @@
1
+ import {
2
+ CAP_WORDS,
3
+ bannedCopyVocabulary
4
+ } from "../chunk-M6WST7ZH.js";
5
+ import "../chunk-3NVVBQ2U.js";
1
6
  import {
2
7
  DEFAULT_HOME_LIMITS,
3
8
  defaultHomeFiles,
@@ -32,6 +37,302 @@ import {
32
37
  // src/profile/index.ts
33
38
  import { mergeAgentProfiles } from "@tangle-network/agent-interface";
34
39
  import { profile } from "@tangle-network/agent-eval";
40
+
41
+ // src/profile/operating-contract.ts
42
+ var OPERATING_CONTRACT_VERSION = 1;
43
+ var UNVERIFIED_LABEL_SLOT = "{unverified}";
44
+ var DEFAULT_UNVERIFIED_LABEL = "Unverified: <claim>";
45
+ var OPERATING_CONTRACT_CLAUSES = Object.freeze([
46
+ {
47
+ id: "deliver",
48
+ text: "Do the work instead of describing it. Produce the artifact the request needs, check it, and say what you checked. Done means produced and verified."
49
+ },
50
+ {
51
+ id: "evidence",
52
+ text: `Ground each material claim in a source you can name: a tool result, a file path, a document, or the user's own words. Keep what a source shows separate from what you infer. Mark a claim you cannot support with \`${UNVERIFIED_LABEL_SLOT}\` and name the lookup that would settle it. Never invent a source, quote, number, customer, or completed action.`
53
+ },
54
+ {
55
+ id: "inspect-results",
56
+ text: "Tools, integrations, and delegated tasks can fail. Read each result before you rely on it or report it as done, and state a failure plainly."
57
+ },
58
+ {
59
+ id: "authority",
60
+ text: "Research, drafts, and workspace edits inside the request are yours to do. Sending, publishing, spending, contacting someone, or changing an integration needs the user's explicit approval for that target and content. A plan is not approval, a pending approval is not execution, and you never approve your own request."
61
+ },
62
+ {
63
+ id: "this-turn",
64
+ text: "Promise only what this turn does. Do not offer to follow up, monitor, or remind later unless a tool confirmed it is scheduled; finish what you can now, then name what remains and what it needs."
65
+ },
66
+ {
67
+ id: "read-back",
68
+ text: "After you save a file or record, confirm it from the save result or by reading it back before you call it saved, and refer to it by its workspace path."
69
+ },
70
+ {
71
+ id: "vault-memory",
72
+ text: "Workspace files are your memory between turns. Read the relevant ones before you answer, and write decisions, evidence, and corrections back so the next turn starts from them."
73
+ }
74
+ ]);
75
+ var CLAUSE_IDS = new Set(OPERATING_CONTRACT_CLAUSES.map((clause) => clause.id));
76
+ function renderOperatingContract(options = {}) {
77
+ const omit = new Set(options.omit ?? []);
78
+ const unknown = [...omit].filter((id) => !CLAUSE_IDS.has(id));
79
+ if (unknown.length > 0) {
80
+ throw new Error(`renderOperatingContract: unknown clause id(s) in omit: ${unknown.join(", ")}`);
81
+ }
82
+ const label = options.unverifiedLabel?.trim() || DEFAULT_UNVERIFIED_LABEL;
83
+ const kept = OPERATING_CONTRACT_CLAUSES.filter((clause) => !omit.has(clause.id));
84
+ const bullets = [
85
+ ...kept.map((clause) => clause.text.replace(UNVERIFIED_LABEL_SLOT, label)),
86
+ ...(options.additions ?? []).map((text) => text.trim()).filter((text) => text.length > 0)
87
+ ];
88
+ return {
89
+ version: OPERATING_CONTRACT_VERSION,
90
+ text: `## Operating contract
91
+
92
+ ${bullets.map((bullet) => `- ${bullet}`).join("\n")}`,
93
+ clauseIds: kept.map((clause) => clause.id)
94
+ };
95
+ }
96
+
97
+ // src/profile/agent-prompt.ts
98
+ var LEARNED_GUIDANCE_SECTION_ID = "learned-guidance";
99
+ var encoder = new TextEncoder();
100
+ function byteLength(text) {
101
+ return encoder.encode(text).byteLength;
102
+ }
103
+ function stripComments(raw) {
104
+ return raw.replace(/<!--[\s\S]*?-->/g, "").trim();
105
+ }
106
+ function renderAgentPrompt(input) {
107
+ const identity = input.identity.trim();
108
+ if (!identity) throw new Error("renderAgentPrompt: identity is empty");
109
+ const environment = input.environment.trim();
110
+ if (!environment) throw new Error("renderAgentPrompt: environment is empty");
111
+ const contract = renderOperatingContract(input.contract);
112
+ const sections = [
113
+ { id: "identity", title: "Identity", text: identity },
114
+ { id: "operating-contract", title: "Operating contract", text: contract.text },
115
+ { id: "environment", title: "Environment", text: `## Environment
116
+
117
+ ${environment}` }
118
+ ];
119
+ const toolConventions = input.toolConventions?.trim();
120
+ if (toolConventions) {
121
+ sections.push({ id: "tool-conventions", title: "Tool conventions", text: `## Tool conventions
122
+
123
+ ${toolConventions}` });
124
+ }
125
+ const skillIndex = input.skillIndex?.trim();
126
+ if (skillIndex) {
127
+ sections.push({ id: "skills", title: "Skills", text: skillIndex.startsWith("#") ? skillIndex : `## Skills
128
+
129
+ ${skillIndex}` });
130
+ }
131
+ const learned = stripComments(input.learnedGuidance ?? "") || stripComments(input.learnedGuidanceBaseline ?? "");
132
+ const domain = [
133
+ ...input.standards ?? [],
134
+ ...learned ? [{ id: LEARNED_GUIDANCE_SECTION_ID, title: "Learned guidance", body: learned }] : []
135
+ ];
136
+ sections.push(...headedGroup("Domain guidance", domain));
137
+ sections.push(...headedGroup("Workspace context", input.overlay ?? []));
138
+ const seen = /* @__PURE__ */ new Set();
139
+ for (const section of sections) {
140
+ if (seen.has(section.id)) throw new Error(`renderAgentPrompt: duplicate section id "${section.id}"`);
141
+ seen.add(section.id);
142
+ }
143
+ const prompt = sections.map((section) => section.text).join("\n\n");
144
+ if (input.budget) assertSystemPromptWithinBudget(prompt, input.budget, "rendered agent prompt");
145
+ return {
146
+ prompt,
147
+ bytes: byteLength(prompt),
148
+ contractVersion: contract.version,
149
+ contractClauseIds: contract.clauseIds,
150
+ sections: sections.map((section) => ({ ...section, bytes: byteLength(section.text) }))
151
+ };
152
+ }
153
+ function headedGroup(heading, group) {
154
+ return group.map((section) => ({ ...section, body: section.body.trim() })).filter((section) => section.body.length > 0).map((section, index) => ({
155
+ id: section.id,
156
+ title: section.title,
157
+ text: `${index === 0 ? `## ${heading}
158
+
159
+ ` : ""}### ${section.title}
160
+
161
+ ${section.body}`
162
+ }));
163
+ }
164
+
165
+ // src/profile/quality-skills.ts
166
+ var HUMAN_PROSE_SKILL_ID = "human-prose";
167
+ var HUMAN_PROSE_DESCRIPTION = "Remove the structural tells that make prose read as machine-written. Load before writing anything for an audience: briefs, emails, posts, captions, ad copy, client replies.";
168
+ var HUMAN_PROSE_BODY = `# Write Like a Human
169
+
170
+ Load before writing anything for an audience: briefs, emails, posts, captions, ad copy, chat replies. This skill kills the *structural* tells, the sentence-level patterns that read as machine-written even when every word is allowed.
171
+
172
+ ## The patterns to cut
173
+
174
+ **Throat-clearing openers.** Drop "Here's the thing", "The truth is", "It turns out", "Let me be clear", "The real X is", "I'll be honest". Open on the actual claim.
175
+
176
+ **Emphasis crutches.** No "Let that sink in", "Make no mistake", "This matters because", "Full stop". The point carries its own weight.
177
+
178
+ **Rhetorical setups and meta-commentary.** No "What if...?", "Think about it:", "Here's what I mean". No narrating your own writing: "Let me walk you through", "In this section", "As we'll see", "Plot twist:", "Spoiler:". Deliver the point; let the reader conclude.
179
+
180
+ **Telegraphed contrasts.** No "It's not X, it's Y" and no negative listings ("Not a tool. Not a framework. A..."). State what it is. The reader does not need the runway.
181
+
182
+ **Manufactured fragmentation.** No fragments for drama ("Revenue. That's it." / "Fast. Cheap. Done."). Use complete sentences and vary their length naturally instead of a staccato beat.
183
+
184
+ **Passive voice and false agency.** Every sentence has someone doing something. "A packet was sent" becomes "the SDR sent the packet". Do not anthropomorphize objects ("a complaint becomes a fix" becomes "the team fixed it that week"). Do not narrate from a distance; put the reader in the scene.
185
+
186
+ **Vague declaratives.** "The implications are significant", "the stakes are high", "the reasons are structural" say nothing. Name the specific implication, stake, or reason.
187
+
188
+ **Filler adverbs.** Delete "really, just, literally, actually, simply, honestly, genuinely, truly, fundamentally, importantly, crucially". The sentence is stronger without them.
189
+
190
+ **Punctuation.** Prefer commas and periods over em-dashes. Overusing the em-dash is itself a machine tell.
191
+
192
+ ## Self-check before sending
193
+
194
+ Score the draft on five dimensions, 1-10 each:
195
+ - Directness: a statement, not an announcement?
196
+ - Rhythm: sentence length varied, not metronomic?
197
+ - Trust: respects the reader's intelligence, no over-explaining?
198
+ - Authenticity: sounds like a sharp person wrote it?
199
+ - Density: anything cuttable?
200
+
201
+ Below 35/50, cut and rewrite. Do not ship slop.`;
202
+ var HUMAN_PROSE_ATTRIBUTION = "Adapted from the stop-slop ruleset (github.com/hardikpandya/stop-slop).";
203
+ function vocabularySection(options) {
204
+ const banned = bannedCopyVocabulary((options.bannedWords ?? []).map((word) => word.trim()).filter(Boolean));
205
+ const capped = CAP_WORDS.filter((word) => !banned.includes(word));
206
+ const preferred = Object.entries(options.preferredTerms ?? {}).map(([avoid, use]) => [avoid.trim(), use.trim()]).filter(([avoid, use]) => avoid && use);
207
+ const parts = [
208
+ "## Vocabulary",
209
+ `Never use these in audience-facing prose: ${banned.join(", ")}.`,
210
+ `Use at most one of these per paragraph: ${capped.join(", ")}.`
211
+ ];
212
+ if (preferred.length > 0) {
213
+ parts.push(["Use the product term:", ...preferred.map(([avoid, use]) => `- "${use}", not "${avoid}"`)].join("\n"));
214
+ }
215
+ return parts.join("\n\n");
216
+ }
217
+ function humanProseSkill(options = {}) {
218
+ const review = options.reviewSkillId?.trim();
219
+ const sections = [
220
+ HUMAN_PROSE_BODY,
221
+ vocabularySection(options),
222
+ review ? `For a long draft, finish with a full review pass using the \`${review}\` skill.` : "",
223
+ HUMAN_PROSE_ATTRIBUTION
224
+ ].filter(Boolean);
225
+ const skillMd = [
226
+ "---",
227
+ `name: ${HUMAN_PROSE_SKILL_ID}`,
228
+ `description: ${JSON.stringify(HUMAN_PROSE_DESCRIPTION)}`,
229
+ "user-invocable: false",
230
+ "---",
231
+ "",
232
+ `${sections.join("\n\n")}
233
+ `
234
+ ].join("\n");
235
+ return skillEntryFromMarkdown(skillMd, HUMAN_PROSE_SKILL_ID);
236
+ }
237
+ function defaultQualitySkills(options = {}) {
238
+ return [humanProseSkill(options.writing)];
239
+ }
240
+ function withDefaultQualitySkills(productSkills, options = {}) {
241
+ const defaults = defaultQualitySkills(options);
242
+ const defaultIds = new Set(defaults.map((skill) => skill.id));
243
+ const copies = productSkills.filter((skill) => defaultIds.has(skill.id)).map((skill) => skill.id);
244
+ if (copies.length > 0) {
245
+ throw new Error(
246
+ `withDefaultQualitySkills: product skill(s) ${copies.join(", ")} duplicate a default quality skill; delete the product copy and pass its additions as options`
247
+ );
248
+ }
249
+ return [...productSkills, ...defaults];
250
+ }
251
+
252
+ // src/profile/model-input.ts
253
+ var MODEL_INPUT_RECORD_SCHEMA = "agent-app.model-input.v1";
254
+ var encoder2 = new TextEncoder();
255
+ async function sha256Hex(text) {
256
+ const digest = await crypto.subtle.digest("SHA-256", encoder2.encode(text));
257
+ return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
258
+ }
259
+ var DEFAULT_MEDIA_TYPE = {
260
+ "system-prompt": "text/markdown",
261
+ "workspace-plan": "application/json",
262
+ "turn-context": "text/markdown"
263
+ };
264
+ async function modelInputBlob(kind, content, mediaType = DEFAULT_MEDIA_TYPE[kind]) {
265
+ return { digest: await sha256Hex(content), kind, mediaType, bytes: encoder2.encode(content).byteLength, content };
266
+ }
267
+ function failed(error) {
268
+ return { succeeded: false, error };
269
+ }
270
+ async function captureModelInput(input) {
271
+ const rendered = typeof input.systemPrompt === "string" ? null : input.systemPrompt;
272
+ const prompt = rendered ? rendered.prompt : input.systemPrompt;
273
+ const blobs = await Promise.all([
274
+ modelInputBlob("system-prompt", prompt),
275
+ ...(input.inputs ?? []).map((extra) => modelInputBlob(extra.kind, extra.content, extra.mediaType))
276
+ ]);
277
+ for (const blob of blobs) {
278
+ let stored;
279
+ try {
280
+ stored = await input.store.put(blob);
281
+ } catch (error) {
282
+ return failed(`model-input store threw storing ${blob.kind} ${blob.digest}: ${error instanceof Error ? error.message : String(error)}`);
283
+ }
284
+ if (!stored.succeeded) return failed(`model-input store refused ${blob.kind} ${blob.digest}: ${stored.error}`);
285
+ }
286
+ const sections = rendered ? await Promise.all(rendered.sections.map(async (section) => ({
287
+ id: section.id,
288
+ title: section.title,
289
+ bytes: section.bytes,
290
+ digest: await sha256Hex(section.text)
291
+ }))) : [];
292
+ const body = {
293
+ schema: MODEL_INPUT_RECORD_SCHEMA,
294
+ inputs: blobs.map((blob) => ({ digest: blob.digest, kind: blob.kind, mediaType: blob.mediaType, bytes: blob.bytes })),
295
+ sections,
296
+ contractVersion: rendered?.contractVersion ?? null,
297
+ planDigest: input.planDigest ?? null,
298
+ model: input.model ?? null,
299
+ harness: input.harness ?? null
300
+ };
301
+ return { succeeded: true, value: { ...body, digest: await sha256Hex(JSON.stringify(body)) } };
302
+ }
303
+ async function readModelInput(store, ref) {
304
+ let loaded;
305
+ try {
306
+ loaded = await store.get(ref.digest);
307
+ } catch (error) {
308
+ return failed(`model-input store threw reading ${ref.digest}: ${error instanceof Error ? error.message : String(error)}`);
309
+ }
310
+ if (!loaded.succeeded) return loaded;
311
+ if (!loaded.value) return failed(`model input ${ref.digest} is not in the store`);
312
+ const actual = await sha256Hex(loaded.value.content);
313
+ if (actual !== ref.digest) return failed(`model input ${ref.digest} content hashes to ${actual}`);
314
+ return { succeeded: true, value: loaded.value };
315
+ }
316
+ function createMemoryModelInputStore() {
317
+ const blobs = /* @__PURE__ */ new Map();
318
+ return {
319
+ get size() {
320
+ return blobs.size;
321
+ },
322
+ async put(blob) {
323
+ const actual = await sha256Hex(blob.content);
324
+ if (actual !== blob.digest) return failed(`digest ${blob.digest} does not match content (${actual})`);
325
+ if (!blobs.has(blob.digest)) blobs.set(blob.digest, { ...blob });
326
+ return { succeeded: true, value: void 0 };
327
+ },
328
+ async get(digest) {
329
+ const blob = blobs.get(digest);
330
+ return { succeeded: true, value: blob ? { ...blob } : null };
331
+ }
332
+ };
333
+ }
334
+
335
+ // src/profile/index.ts
35
336
  function userSkillMounts(userSkills) {
36
337
  return userSkills.map(
37
338
  (s) => ({
@@ -82,43 +383,48 @@ function pruneEmptyResourceChannels(profile2) {
82
383
  if (kept && Object.keys(kept).length === 0) delete out.resources;
83
384
  return out;
84
385
  }
85
- function stripComments(raw) {
86
- return raw.replace(/<!--[\s\S]*?-->/g, "").trim();
87
- }
88
- function makeEvolvableSection(input) {
89
- const loaded = input.load();
90
- const body = stripComments(loaded) ? loaded.trim() : input.baseline;
91
- return { id: input.id, title: input.title, body, evolvable: true };
92
- }
93
386
  export {
94
387
  DEFAULT_HOME_LIMITS,
95
388
  DEFAULT_MAX_SYSTEM_PROMPT_BYTES,
389
+ HUMAN_PROSE_SKILL_ID,
390
+ LEARNED_GUIDANCE_SECTION_ID,
391
+ MODEL_INPUT_RECORD_SCHEMA,
392
+ OPERATING_CONTRACT_CLAUSES,
393
+ OPERATING_CONTRACT_VERSION,
96
394
  assertProfilePromptWithinBudget,
97
395
  assertSkillDeliveryDisjoint,
98
396
  assertSystemPromptWithinBudget,
397
+ captureModelInput,
99
398
  composeAgentProfile,
100
399
  composeShellResources,
101
400
  composeSkills,
102
401
  corpusSkills,
402
+ createMemoryModelInputStore,
103
403
  defaultHomeFiles,
404
+ defaultQualitySkills,
104
405
  diffProfileFingerprints,
105
406
  fingerprintAgentProfile,
106
407
  formatProfileDrift,
408
+ humanProseSkill,
107
409
  largestPromptSections,
108
410
  loadMarkdownCorpus,
109
- makeEvolvableSection,
110
411
  mergeComposedSkills,
412
+ modelInputBlob,
111
413
  parseCorpusSkills,
112
414
  parseSkillFrontmatter,
113
415
  profile,
416
+ readModelInput,
114
417
  registrySkills,
418
+ renderAgentPrompt,
115
419
  renderInlineSkills,
420
+ renderOperatingContract,
116
421
  renderSkillIndex,
117
422
  skillEntryFromMarkdown,
118
423
  skillMountPath,
119
424
  skillRefs,
120
425
  stripComments,
121
426
  userSkillMounts,
122
- withDefaultAgentHome
427
+ withDefaultAgentHome,
428
+ withDefaultQualitySkills
123
429
  };
124
430
  //# sourceMappingURL=index.js.map