create-posthuman 0.0.0-stage → 0.1.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +32 -2
  3. package/bin/create.mjs +72 -0
  4. package/package.json +32 -4
  5. package/template/AGENTS.md +207 -0
  6. package/template/CLAUDE.md +1 -0
  7. package/template/README.md +61 -0
  8. package/template/_env.example +9 -0
  9. package/template/_gitignore +5 -0
  10. package/template/_mcp.json +8 -0
  11. package/template/brand/about.md +22 -0
  12. package/template/brand/accounts.md +7 -0
  13. package/template/brand/sources.md +10 -0
  14. package/template/brand/voice.md +19 -0
  15. package/template/ideas/_template.md +8 -0
  16. package/template/ideas/inbox.md +5 -0
  17. package/template/library/INDEX.md +7 -0
  18. package/template/posts/_template.md +24 -0
  19. package/template/recipes/README.md +14 -0
  20. package/template/recipes/empty-days.md +23 -0
  21. package/template/recipes/humanize.md +32 -0
  22. package/template/recipes/photo-to-video.md +25 -0
  23. package/template/recipes/voiceover.md +29 -0
  24. package/template/recipes/weekly-batch.md +22 -0
  25. package/template/tools/account-rules.mjs +144 -0
  26. package/template/tools/brands.mjs +141 -0
  27. package/template/tools/fal.mjs +82 -0
  28. package/template/tools/humanize-rules.mjs +86 -0
  29. package/template/tools/humanize.mjs +84 -0
  30. package/template/tools/knowyou.mjs +240 -0
  31. package/template/tools/length-rules.mjs +76 -0
  32. package/template/tools/lib.mjs +84 -0
  33. package/template/tools/mix.mjs +37 -0
  34. package/template/tools/post-rules.mjs +99 -0
  35. package/template/tools/sources.mjs +196 -0
  36. package/template/tools/studio-accounts.mjs +132 -0
  37. package/template/tools/studio-more.mjs +254 -0
  38. package/template/tools/studio-stuff.mjs +104 -0
  39. package/template/tools/studio.html +1183 -0
  40. package/template/tools/studio.mjs +614 -0
  41. package/template/tools/substance-rules.mjs +37 -0
  42. package/template/tools/substance.mjs +37 -0
  43. package/template/tools/topic-rules.mjs +43 -0
  44. package/template/tools/vertical.mjs +60 -0
  45. package/template/tools/voice.mjs +56 -0
@@ -0,0 +1,1183 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Studio</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:wdth,wght@62..125,100..900&display=swap">
9
+ <style>
10
+ :root {
11
+ /* Posthuman's own: violet ground, cream paper, volt = lit */
12
+ --paper: #f6f1e6; --card: #fcfaf5; --ink: #1a0f3d; --soft: #6b6282; --line: #ddd3bf;
13
+ --accent: #4a22d4; --accent-ink: #f6f1e6; --ok: #d2ff3a; --ok-ink: #1b2600; --ok-edge: #a8d400; --night: #1a0f3d;
14
+ --rail: #4a22d4; --rail-ink: #f6f1e6;
15
+ --warn: #fff1c2; --warn-line: #e8c95a; --bad: #c8321f;
16
+ --shadow: 0 1px 2px rgba(26,15,61,.05), 0 8px 28px rgba(26,15,61,.07);
17
+ --display: "Archivo", system-ui, -apple-system, "Segoe UI", sans-serif;
18
+ }
19
+ @media (prefers-color-scheme: dark) {
20
+ :root { --paper: #120b2b; --card: #1c1342; --ink: #f6f1e6; --soft: #c2bbde; --line: #51449a; --accent: #7a5af5; --accent-ink: #f6f1e6;
21
+ --rail: #1c1342; --warn: #3a3218; --warn-line: #6d5b1f; --bad: #ff8a75; --shadow: 0 1px 2px rgba(0,0,0,.3), 0 8px 28px rgba(0,0,0,.3); color-scheme: dark; }
22
+ }
23
+ * { box-sizing: border-box; }
24
+ html, body { margin: 0; background: var(--paper); color: var(--ink); font: 15px/1.5 var(--display); -webkit-font-smoothing: antialiased; }
25
+ h1, h2.big { font-family: var(--display); font-weight: 800; letter-spacing: -0.045em; font-stretch: 108%; line-height: .95; margin: 0; }
26
+ button, input, textarea, select { font: inherit; color: inherit; }
27
+ button { cursor: pointer; border: 1px solid var(--line); background: var(--card); border-radius: 999px; padding: 6px 14px; }
28
+ button:hover { border-color: var(--soft); }
29
+ button.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); font-weight: 600; }
30
+ button.ok, button.lit { background: var(--ok); color: var(--ok-ink); border-color: var(--ok-edge); font-weight: 700; }
31
+ button.ghost { border-color: transparent; background: transparent; }
32
+ button:disabled { opacity: .45; cursor: default; }
33
+ textarea, input[type=text] { width: 100%; border: 1px solid var(--line); background: var(--card); border-radius: 12px; padding: 10px 12px; outline: none; }
34
+ textarea:focus, input[type=text]:focus { border-color: var(--accent); }
35
+ .muted { color: var(--soft); }
36
+ .small { font-size: 13px; }
37
+ .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
38
+
39
+ /* the rail, like the real app */
40
+ .app { display: grid; grid-template-columns: 236px minmax(0, 1fr); min-height: 100dvh; }
41
+ .rail { background: var(--rail); color: var(--rail-ink); padding: 20px 14px; display: flex; flex-direction: column; gap: 4px; position: sticky; top: 0; height: 100dvh; }
42
+ .wordmark { font-family: var(--display); font-weight: 800; letter-spacing: -0.045em; white-space: nowrap; font-size: 26px; padding: 0 8px; }
43
+ .wordmark .hollow { -webkit-text-fill-color: transparent; -webkit-text-stroke: 0.04em currentColor; paint-order: stroke fill; }
44
+ .studio-chip { display: inline-block; margin-left: 6px; font-size: 11px; font-weight: 800; letter-spacing: .02em; background: var(--ok); color: var(--ok-ink); border-radius: 999px; padding: 1px 8px; vertical-align: 5px; }
45
+ .rail .who { padding: 2px 8px 14px; font-size: 13px; color: color-mix(in srgb, var(--rail-ink) 70%, transparent); }
46
+ .rail .go { margin: 0 0 12px; width: 100%; padding: 10px 14px; }
47
+ .rail .place { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border-radius: 999px; font-weight: 600; color: color-mix(in srgb, var(--rail-ink) 76%, transparent); text-decoration: none; }
48
+ .rail .place:hover { color: var(--rail-ink); background: color-mix(in srgb, var(--rail-ink) 10%, transparent); }
49
+ .rail .place[aria-current="page"] { background: var(--rail-ink); color: var(--night); }
50
+ .rail .place .n { margin-left: auto; background: var(--ok); color: var(--ok-ink); border-radius: 999px; font-size: 11px; font-weight: 800; padding: 0 7px; }
51
+ .rail .foot { margin-top: auto; font-size: 12px; color: color-mix(in srgb, var(--rail-ink) 62%, transparent); padding: 0 10px; display: grid; gap: 3px; }
52
+ .rail .foot b { color: var(--rail-ink); font-weight: 600; }
53
+ .view-head { display: flex; align-items: flex-end; gap: 14px; flex-wrap: wrap; margin-bottom: 18px; }
54
+ .view-head h1 { font-size: clamp(30px, 4vw, 46px); }
55
+ .view-head .sub { color: var(--soft); max-width: 60ch; }
56
+ .view-head .grow { flex: 1; }
57
+ .week { display: flex; align-items: center; gap: 4px; font-weight: 600; }
58
+ .counts { display: flex; gap: 6px; }
59
+ .panel { background: var(--card); border: 1px solid var(--line); border-radius: 16px; padding: 16px; box-shadow: var(--shadow); }
60
+ .cols { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(260px, 1fr); gap: 18px; align-items: start; }
61
+ .angles { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; margin-top: 16px; }
62
+ .angle h3 { font-family: var(--display); font-weight: 800; letter-spacing: -0.03em; font-size: 20px; line-height: 1.1; margin: 6px 0; }
63
+ .angle .first { white-space: pre-wrap; margin: 6px 0; }
64
+ .angle .needs { background: var(--warn); border: 1px solid var(--warn-line); border-radius: 10px; padding: 6px 9px; font-size: 13px; margin-top: 6px; }
65
+ .angle.kept { opacity: .55; }
66
+ .chips { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
67
+ .chip-file { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--line); border-radius: 999px; padding: 2px 4px 2px 2px; background: var(--paper); font-size: 12px; }
68
+ .chip-file img { width: 26px; height: 26px; border-radius: 50%; object-fit: cover; }
69
+ .list-edit { display: grid; gap: 8px; }
70
+ .list-edit .row { flex-wrap: nowrap; }
71
+ .recipes { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 14px; }
72
+ .recipe h3 { font-family: var(--display); font-weight: 800; letter-spacing: -0.03em; font-size: 22px; margin: 0 0 4px; }
73
+ .recipe .cost { font-size: 13px; color: var(--soft); margin-bottom: 10px; }
74
+ .recipe label { display: block; font-size: 12px; color: var(--soft); margin: 10px 0 4px; text-transform: uppercase; letter-spacing: .05em; }
75
+ .recipe select { width: 100%; border: 1px solid var(--line); border-radius: 12px; padding: 9px 10px; background: var(--card); }
76
+ .steps { display: grid; gap: 14px; }
77
+ .step h2 { font-family: var(--display); font-weight: 800; letter-spacing: -0.03em; font-size: 24px; margin: 0 0 4px; }
78
+ .step .n1 { display: inline-grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; background: var(--accent); color: var(--accent-ink); font-size: 14px; font-weight: 800; margin-right: 8px; vertical-align: 3px; }
79
+ .step.done .n1 { background: var(--ok); color: var(--ok-ink); }
80
+ .step label { display: block; font-size: 12px; color: var(--soft); margin: 10px 0 4px; text-transform: uppercase; letter-spacing: .05em; }
81
+ .past-card { background: var(--paper); border: 1px solid var(--line); border-radius: 14px; padding: 14px; margin-top: 10px; }
82
+ .past-card .words { white-space: pre-wrap; font-size: 16px; margin: 6px 0 10px; }
83
+ .aims button.on { background: var(--ink); color: var(--paper); border-color: var(--ink); }
84
+ .stuff-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; margin-top: 12px; }
85
+ .stuff { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--card); display: flex; flex-direction: column; }
86
+ .stuff.picked { outline: 2px solid var(--accent); outline-offset: 1px; }
87
+ .stuff .pic { position: relative; aspect-ratio: 1; background: var(--paper); cursor: pointer; }
88
+ .stuff .pic img, .stuff .pic video { width: 100%; height: 100%; object-fit: cover; display: block; }
89
+ .stuff .pic input { position: absolute; top: 6px; left: 6px; width: 18px; height: 18px; }
90
+ .stuff .cap { padding: 6px 8px; font-size: 12px; display: grid; gap: 2px; }
91
+ .stuff .cap .angle { color: var(--accent); font-weight: 600; }
92
+ .stuff .acts { display: flex; gap: 4px; flex-wrap: wrap; padding: 0 6px 6px; }
93
+ .stuff .acts button { font-size: 12px; padding: 3px 9px; }
94
+ .where { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
95
+ @media (max-width: 760px) { .where { grid-template-columns: 1fr; } }
96
+ .where li { display: flex; justify-content: space-between; gap: 8px; align-items: center; font-size: 13px; padding: 3px 0; }
97
+ .project li { font-size: 13px; list-style: none; }
98
+ .project ul { padding: 0; margin: 6px 0; }
99
+ .acct-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }
100
+ .acct-card h3 { font-family: var(--display); font-weight: 800; letter-spacing: -0.03em; font-size: 20px; line-height: 1.1; margin: 0; }
101
+ .acct-card dl { margin: 8px 0 0; font-size: 13px; padding: 0; display: grid; grid-template-columns: max-content 1fr; gap: 4px 10px; }
102
+ .acct-card dt { color: var(--soft); }
103
+ .acct-card dd { margin: 0; }
104
+ .acct-card.unset { border-style: dashed; }
105
+ .example { background: var(--paper); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; margin-top: 8px; white-space: pre-wrap; font-size: 14px; }
106
+ .needkey { background: var(--warn); border: 1px solid var(--warn-line); border-radius: 10px; padding: 8px 10px; font-size: 13px; }
107
+ @media (max-width: 760px) {
108
+ .app { grid-template-columns: 1fr; }
109
+ .rail { position: fixed; bottom: 0; top: auto; left: 0; right: 0; height: auto; flex-direction: row; padding: 6px; z-index: 9; justify-content: space-around; }
110
+ .rail .wordmark, .rail .who, .rail .foot, .rail .go { display: none; }
111
+ .rail .place { padding: 8px 10px; font-size: 13px; }
112
+ .cols { grid-template-columns: 1fr; }
113
+ main { padding-bottom: 90px !important; }
114
+ }
115
+ main { padding: 26px 28px 80px; min-width: 0; }
116
+ .view[hidden] { display: none; }
117
+ .board { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 12px; }
118
+ .day h2 { font-size: 13px; font-weight: 600; margin: 0 0 8px; color: var(--soft); text-transform: uppercase; letter-spacing: .04em; }
119
+ .day.today h2 { color: var(--accent); }
120
+ .day .empty { border: 1px dashed var(--line); border-radius: 14px; padding: 14px; color: var(--soft); font-size: 13px; text-align: center; }
121
+ .card { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 10px 12px; margin-bottom: 10px; box-shadow: var(--shadow); cursor: pointer;
122
+ transition: transform .12s ease, border-color .12s; }
123
+ .card:hover { transform: translateY(-1px); border-color: var(--soft); }
124
+ .card.dropped { opacity: .5; }
125
+ .card .top { display: flex; justify-content: space-between; gap: 6px; font-size: 12px; color: var(--soft); margin-bottom: 4px; }
126
+ .card .txt { font-size: 14px; display: -webkit-box; -webkit-line-clamp: 5; -webkit-box-orient: vertical; overflow: hidden; white-space: pre-line; }
127
+ .card .foot { display: flex; gap: 6px; align-items: center; margin-top: 8px; flex-wrap: wrap; }
128
+ .card .plats { font-size: 12px; font-weight: 600; color: var(--ink); margin-bottom: 4px; }
129
+ .card .topic { font-size: 11px; color: var(--soft); }
130
+ .card .flag { background: var(--warn); border: 1px solid var(--warn-line); border-radius: 999px; font-size: 11px; padding: 1px 7px; }
131
+ .thumbs { display: flex; gap: 4px; margin-top: 6px; }
132
+ .thumbs img, .thumbs video { width: 40px; height: 40px; object-fit: cover; border-radius: 8px; border: 1px solid var(--line); }
133
+ .undated { margin-top: 28px; }
134
+ .undated h2 { font-size: 13px; color: var(--soft); text-transform: uppercase; letter-spacing: .04em; }
135
+ .undated .list { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; }
136
+ @media (max-width: 1180px) {
137
+ .board { grid-template-columns: 1fr; }
138
+ .day .empty { display: none; }
139
+ .day:has(.empty) { display: none; }
140
+ }
141
+
142
+ /* the sheet */
143
+ .scrim { position: fixed; inset: 0; background: rgba(20,15,5,.28); z-index: 10; display: none; }
144
+ .scrim.open { display: block; }
145
+ .sheet { position: fixed; top: 0; right: 0; bottom: 0; width: min(980px, 100%); background: var(--paper); z-index: 11; transform: translateX(100%);
146
+ transition: transform .2s ease; display: flex; flex-direction: column; border-left: 1px solid var(--line); }
147
+ .sheet.open { transform: none; }
148
+ .sheet .bar { display: flex; align-items: center; gap: 10px; padding: 14px 18px; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
149
+ .sheet .bar .title { font-weight: 600; flex: 1; min-width: 180px; }
150
+ .sheet .body { overflow: auto; padding: 18px; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 22px; }
151
+ @media (max-width: 800px) { .sheet .body { grid-template-columns: 1fr; } }
152
+ .sheet h3 { font-size: 12px; text-transform: uppercase; letter-spacing: .05em; color: var(--soft); margin: 18px 0 8px; }
153
+ .sheet h3:first-child { margin-top: 0; }
154
+ .notes { background: var(--warn); border: 1px solid var(--warn-line); border-radius: 12px; padding: 10px 12px; font-size: 13px; white-space: pre-line; margin-bottom: 14px; }
155
+ .counts-line { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; }
156
+ .count { font-size: 12px; padding: 1px 8px; border-radius: 999px; background: var(--card); border: 1px solid var(--line); }
157
+ .count.over { background: var(--bad); color: #fff; border-color: var(--bad); }
158
+ .status-row button.on { outline: 2px solid var(--ink); outline-offset: 1px; }
159
+
160
+ .tabs { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 10px; }
161
+ .tabs button { padding: 4px 11px; font-size: 13px; }
162
+ .tabs button.on { background: var(--ink); color: var(--paper); border-color: var(--ink); }
163
+ .preview { background: var(--card); border: 1px solid var(--line); border-radius: 16px; padding: 14px; box-shadow: var(--shadow); }
164
+ .preview + .preview { margin-top: 0; border-top-left-radius: 0; border-top-right-radius: 0; border-top: 0; }
165
+ .preview .who { display: flex; gap: 10px; align-items: center; margin-bottom: 8px; }
166
+ .avatar { width: 38px; height: 38px; border-radius: 50%; background: var(--accent); color: var(--accent-ink); display: grid; place-items: center; font-weight: 700; flex: none; }
167
+ .preview .name { font-weight: 700; }
168
+ .preview .handle { color: var(--soft); font-size: 13px; }
169
+ .preview .text { white-space: pre-wrap; word-wrap: break-word; font-size: 15px; }
170
+ .preview .media { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 4px; margin-top: 10px; border-radius: 14px; overflow: hidden; }
171
+ .preview .media img, .preview .media video { width: 100%; max-height: 360px; object-fit: cover; display: block; }
172
+ .preview .meta { margin-top: 8px; font-size: 12px; color: var(--soft); }
173
+ .joined { border-left: 2px solid var(--line); margin-left: 18px; height: 10px; }
174
+
175
+ .media-edit { display: grid; gap: 10px; }
176
+ .media-item { display: grid; grid-template-columns: 72px 1fr auto; gap: 10px; align-items: center; }
177
+ .media-item img, .media-item video { width: 72px; height: 72px; object-fit: cover; border-radius: 10px; border: 1px solid var(--line); }
178
+ .drop { border: 1.5px dashed var(--line); border-radius: 12px; padding: 14px; text-align: center; color: var(--soft); font-size: 13px; }
179
+ .drop.over { border-color: var(--accent); color: var(--accent); }
180
+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 8px; }
181
+ .grid .tile { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--card); cursor: pointer; }
182
+ .grid .tile img, .grid .tile video { width: 100%; aspect-ratio: 1; object-fit: cover; display: block; }
183
+ .grid .tile .cap { font-size: 11px; padding: 4px 6px; color: var(--soft); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
184
+ .grid .tile.audio { display: grid; place-items: center; aspect-ratio: 1; font-size: 26px; }
185
+
186
+ .compare { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; }
187
+ .compare > div { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 10px; white-space: pre-wrap; font-size: 14px; }
188
+ .compare > div.new { border-color: var(--accent); }
189
+ h3.label { margin: 0 0 10px; font-size: 12px; text-transform: uppercase; letter-spacing: .05em; color: var(--soft); }
190
+ .pill.gives { background: transparent; border-style: dashed; }
191
+ .pill.tells { background: var(--warn); border-color: var(--warn-line); }
192
+ .tell-list { margin: 0; padding-left: 18px; font-size: 13px; }
193
+ .tell-list li { margin-bottom: 4px; }
194
+ .tell-list mark { background: var(--warn); color: inherit; border-radius: 4px; padding: 0 3px; }
195
+ .spin { display: inline-block; width: 14px; height: 14px; border: 2px solid var(--line); border-top-color: var(--accent); border-radius: 50%; animation: s .8s linear infinite; vertical-align: -2px; }
196
+ @keyframes s { to { transform: rotate(360deg); } }
197
+ @media (prefers-reduced-motion: reduce) { .spin { animation: none; } .sheet { transition: none; } }
198
+
199
+ /* side drawers + job */
200
+ .drawer { position: fixed; top: 0; right: 0; bottom: 0; width: min(520px, 100%); background: var(--paper); z-index: 11; transform: translateX(100%); transition: transform .2s; border-left: 1px solid var(--line); display: flex; flex-direction: column; }
201
+ .drawer.open { transform: none; }
202
+ .drawer .body { overflow: auto; padding: 18px; display: block; }
203
+ .ideas li { margin: 0 0 8px; }
204
+ .job { position: fixed; right: 16px; bottom: 16px; width: min(460px, calc(100% - 32px)); background: var(--card); border: 1px solid var(--line); border-radius: 16px; box-shadow: var(--shadow); z-index: 20; padding: 12px 14px; display: none; }
205
+ .job.open { display: block; }
206
+ .job pre { max-height: 260px; overflow: auto; white-space: pre-wrap; font-size: 12px; margin: 8px 0 0; }
207
+ .toast { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); background: var(--ink); color: var(--paper); padding: 8px 16px; border-radius: 999px; font-size: 14px; z-index: 30; opacity: 0; transition: opacity .2s; pointer-events: none; }
208
+ .toast.show { opacity: 1; }
209
+ </style>
210
+ </head>
211
+ <body>
212
+ <div class="app">
213
+ <nav class="rail" aria-label="Studio">
214
+ <div class="wordmark" aria-label="Posthuman Studio"><span aria-hidden="true">Post</span><span class="hollow" aria-hidden="true">human</span><span class="studio-chip">Studio</span></div>
215
+ <div class="who" id="brand">your folder</div>
216
+ <button class="lit go" id="scheduleBtn" disabled>Schedule approved</button>
217
+ <a class="place" href="#week" data-view="week">Week <span class="n" id="nWeek" hidden></span></a>
218
+ <a class="place" href="#know" data-view="know">Get to know you <span class="n" id="nKnow" hidden></span></a>
219
+ <a class="place" href="#stuff" data-view="stuff">Your stuff</a>
220
+ <a class="place" href="#brainstorm" data-view="brainstorm">Brainstorm</a>
221
+ <a class="place" href="#raw" data-view="raw">This week's raw <span class="n" id="nRaw" hidden></span></a>
222
+ <a class="place" href="#accounts" data-view="accounts">Accounts</a>
223
+ <a class="place" href="#make" data-view="make">Make</a>
224
+ <a class="place" href="#library" data-view="library">Library</a>
225
+ <div class="foot" id="foot"></div>
226
+ </nav>
227
+ <main>
228
+ <section class="view" id="v-week">
229
+ <div class="view-head">
230
+ <h1 id="weeklabel">This week</h1>
231
+ <div class="week"><button class="ghost" id="prev" aria-label="Previous week">‹</button><button class="ghost" id="next" aria-label="Next week">›</button></div>
232
+ <div class="counts" id="counts"></div>
233
+ </div>
234
+ <div class="counts" id="mix" style="margin:-8px 0 14px;flex-wrap:wrap"></div>
235
+ <div class="board" id="board"></div>
236
+ <div class="undated" id="undated"></div>
237
+ </section>
238
+ <section class="view" id="v-know" hidden></section>
239
+ <section class="view" id="v-stuff" hidden></section>
240
+ <section class="view" id="v-brainstorm" hidden></section>
241
+ <section class="view" id="v-raw" hidden></section>
242
+ <section class="view" id="v-accounts" hidden></section>
243
+ <section class="view" id="v-make" hidden></section>
244
+ <section class="view" id="v-library" hidden></section>
245
+ </main>
246
+ </div>
247
+
248
+ <div class="scrim" id="scrim"></div>
249
+ <section class="sheet" id="sheet" aria-label="Post"></section>
250
+ <div class="job" id="job"></div>
251
+ <div class="toast" id="toast"></div>
252
+
253
+ <script>
254
+ const TOKEN = "__TOKEN__";
255
+ const $ = (s, el = document) => el.querySelector(s);
256
+ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
257
+ const api = async (method, url, body, raw) => {
258
+ const r = await fetch(url, { method, headers: { "X-Studio-Token": TOKEN, ...(raw ? {} : { "Content-Type": "application/json" }) }, body: raw ? body : body === undefined ? undefined : JSON.stringify(body) });
259
+ const j = await r.json().catch(() => ({}));
260
+ if (!r.ok) throw Object.assign(new Error(j.error || `HTTP ${r.status}`), { status: r.status });
261
+ return j;
262
+ };
263
+ const media = (f) => `/library/${f.split("/").map(encodeURIComponent).join("/")}?t=${TOKEN}`;
264
+ const toast = (msg) => { const t = $("#toast"); t.textContent = msg; t.classList.add("show"); clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove("show"), 2200); };
265
+
266
+ // platforms: limits and how the card looks
267
+ const PLATFORMS = [
268
+ { re: /\bx\b|twitter/i, name: "X", limit: 280 },
269
+ { re: /bluesky|bsky/i, name: "Bluesky", limit: 300 },
270
+ { re: /mastodon/i, name: "Mastodon", limit: 500 },
271
+ { re: /threads/i, name: "Threads", limit: 500 },
272
+ { re: /instagram/i, name: "Instagram", limit: 2200 },
273
+ { re: /tiktok/i, name: "TikTok", limit: 2200 },
274
+ { re: /linkedin/i, name: "LinkedIn", limit: 3000 },
275
+ { re: /pinterest/i, name: "Pinterest", limit: 800 },
276
+ { re: /telegram/i, name: "Telegram", limit: 4096 },
277
+ { re: /discord/i, name: "Discord", limit: 2000 },
278
+ { re: /nostr/i, name: "Nostr", limit: 10000 },
279
+ { re: /facebook/i, name: "Facebook", limit: 63206 },
280
+ { re: /youtube/i, name: "YouTube", limit: 5000 },
281
+ ];
282
+ const platformOf = (acct) => PLATFORMS.find((p) => p.re.test(acct)) || { name: acct, limit: 0 };
283
+ const handleOf = (acct) => (acct.match(/@[\w.@-]+/) || [""])[0];
284
+ const parts = (t) => t.split(/\n---\n/);
285
+ const glyphs = (s) => [...s].length;
286
+
287
+ let S = { posts: [], library: [], ideas: [], agent: null, brand: "" };
288
+ let humanCheck = null; // the same check as tools/humanize.mjs, loaded from the server
289
+ let substanceCheck = null, GIVES_LIST = { story: "", tip: "", number: "", show: "", opinion: "" };
290
+ import(`/substance-rules.mjs?t=${TOKEN}`).then((m) => { substanceCheck = m.substance; GIVES_LIST = m.GIVES; if (open) drawSheet(); }).catch(() => {});
291
+ import(`/humanize-rules.mjs?t=${TOKEN}`).then((m) => { humanCheck = m.check; if (open) drawTells(); }).catch(() => {});
292
+ // the same counting as tools/humanize.mjs: X counts a link as 23 and an emoji as 2, Bluesky counts emoji as one
293
+ let lengthsFor = null;
294
+ import(`/length-rules.mjs?t=${TOKEN}`).then((m) => { lengthsFor = m.lengthsFor; if (open) drawCounts(); }).catch(() => {});
295
+ let fitCheck = null, setupFor = null;
296
+ import(`/account-rules.mjs?t=${TOKEN}`).then((m) => { fitCheck = m.fitCheck; setupFor = m.setupFor; if (open) drawTells(); }).catch(() => {});
297
+ let weekStart = startOfWeek(new Date());
298
+ // which brand the Week shows when there's more than one (brands/): "*" = all
299
+ let BRAND_PICK = (() => { try { return localStorage.getItem("studio-brand") || "*"; } catch { return "*"; } })();
300
+ const brandName = (slug) => (S.brands || []).find((b) => b.slug === (slug || ""))?.name || "";
301
+ const topicsFor = (slug) => ((S.brands || []).length > 1 ? S.topicsBy?.[slug || ""] || [] : S.topics || []);
302
+ let open = null; // the post being edited: { slug, draft fields, dirty }
303
+
304
+ function startOfWeek(d) { const x = new Date(d.getFullYear(), d.getMonth(), d.getDate()); x.setDate(x.getDate() - x.getDay()); return x; }
305
+ const ymd = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
306
+ const fmtDay = (d) => d.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" });
307
+
308
+ async function load(redraw = true) {
309
+ S = await api("GET", "/api/state");
310
+ document.title = `${S.brand} · Studio`;
311
+ drawRail();
312
+ if (redraw !== false && view === "week") render();
313
+ }
314
+
315
+ function render() {
316
+ const days = [...Array(7)].map((_, i) => { const d = new Date(weekStart); d.setDate(d.getDate() + i); return d; });
317
+ $("#weeklabel").textContent = ymd(days[0]) === ymd(startOfWeek(new Date())) ? "This week" : `Week of ${fmtDay(days[0])}`;
318
+ // more than one brand (brands/): show one, or all
319
+ const many = (S.brands || []).length > 1;
320
+ if (!many || (BRAND_PICK !== "*" && !S.brands.some((b) => b.slug === BRAND_PICK))) BRAND_PICK = "*"; // a brand that's gone: show all
321
+ const mine = (p) => !many || BRAND_PICK === "*" || (p.brand || "") === BRAND_PICK;
322
+ const inWeek = S.posts.filter((p) => p.date && p.date >= ymd(days[0]) && p.date <= ymd(days[6]) && mine(p));
323
+ const count = (st) => inWeek.filter((p) => p.status === st).length;
324
+ $("#counts").innerHTML = (many ? `<select id="brandPick" aria-label="Brand"><option value="*">All brands</option>${S.brands.map((b) => `<option value="${esc(b.slug)}" ${BRAND_PICK === b.slug ? "selected" : ""}>${esc(b.name)}</option>`).join("")}</select>` : "") + ["draft", "approved", "scheduled", "posted"].map((st) => count(st) ? `<span class="pill ${st}">${count(st)} ${st}</span>` : "").join("");
325
+ $("#brandPick") && ($("#brandPick").onchange = (e) => { BRAND_PICK = e.target.value; try { localStorage.setItem("studio-brand", BRAND_PICK); } catch {} render(); });
326
+ // the week's mix, against the topics in that brand's about.md ("Building 3/7"); all brands at once: no mix
327
+ const T = many ? (BRAND_PICK === "*" ? [] : S.topicsBy?.[BRAND_PICK] || []) : S.topics || [];
328
+ const live = inWeek.filter((p) => p.status !== "dropped");
329
+ const tOf = (p) => { const v = (p.topic || "").toLowerCase(); return v && (T.find((t) => t.name.toLowerCase() === v) || T.find((t) => t.name.toLowerCase().startsWith(v) || v.startsWith(t.name.toLowerCase()))); };
330
+ $("#mix").innerHTML = T.length && live.length ? T.map((t) => { const n = live.filter((p) => tOf(p) === t).length; return `<span class="pill ${t.per_week && n < t.per_week ? "" : "approved"}" title="${esc(t.name)}${t.per_week ? `: you want about ${t.per_week} a week` : ""}">${esc(t.name.split(" ").slice(0, 3).join(" "))} ${n}${t.per_week ? `/${t.per_week}` : ""}</span>`; }).join("") + (live.some((p) => !tOf(p)) ? `<span class="pill" title="Posts with no topic">no topic ${live.filter((p) => !tOf(p)).length}</span>` : "") : "";
331
+ const approved = S.posts.filter((p) => p.status === "approved").length;
332
+ const sb = $("#scheduleBtn");
333
+ sb.textContent = approved ? `Schedule approved (${approved})` : "Schedule approved";
334
+ sb.disabled = !approved;
335
+ sb.title = S.agent ? "Your agent schedules them through Posthuman" : "Needs Claude Code installed (or ask your agent: schedule the approved posts)";
336
+ const today = ymd(new Date());
337
+ $("#board").innerHTML = days.map((d) => {
338
+ const ps = inWeek.filter((p) => p.date === ymd(d)).sort((a, b) => (a.time || "99").localeCompare(b.time || "99"));
339
+ return `<div class="day${ymd(d) === today ? " today" : ""}"><h2>${esc(fmtDay(d))}</h2>${ps.map(card).join("") || `<div class="empty">Nothing yet</div>`}</div>`;
340
+ }).join("");
341
+ const undated = S.posts.filter((p) => !p.date && mine(p));
342
+ $("#undated").innerHTML = undated.length ? `<h2>No date</h2><div class="list">${undated.map(card).join("")}</div>` : "";
343
+ document.querySelectorAll(".card").forEach((c) => c.addEventListener("click", () => openPost(c.dataset.slug)));
344
+ }
345
+
346
+ function card(p) {
347
+ const first = parts(p.everywhere)[0];
348
+ const n = parts(p.everywhere).length;
349
+ const thumbs = p.media.slice(0, 4).map((f) => /\.(mp4|mov)$/i.test(f) ? `<video src="${media(f)}" muted preload="metadata"></video>` : /\.(mp3|wav|m4a)$/i.test(f) ? "" : `<img src="${media(f)}" alt="">`).join("");
350
+ return `<div class="card ${esc(p.status)}" data-slug="${esc(p.slug)}" tabindex="0">
351
+ <div class="top"><span>${esc(p.time || "")}${p.time && p.kind ? " · " : ""}${esc(p.kind)}</span>${(S.brands || []).length > 1 && BRAND_PICK === "*" ? `<span class="pill">${esc(brandName(p.brand))}</span>` : ""}</div>
352
+ ${p.accounts?.length ? `<div class="plats">${esc(platformsLine(p.accounts))}</div>` : ""}
353
+ <div class="txt">${esc(first)}</div>
354
+ ${thumbs ? `<div class="thumbs">${thumbs}</div>` : ""}
355
+ <div class="foot"><span class="pill ${esc(p.status)}">${esc(p.status)}</span>${n > 1 ? `<span class="pill">${n} parts</span>` : ""}${p.flagged ? `<span class="flag">needs you</span>` : ""}${p.substance?.length ? `<span class="flag" title="${esc(p.substance.map((x) => x.issue).join(", "))}">${p.gives ? "thin" : "gives nothing"}</span>` : ""}${p.tells?.length ? `<span class="pill tells" title="${esc(p.tells.map((t) => t.tell).join(", "))}">${p.tells.length} AI tell${p.tells.length === 1 ? "" : "s"}</span>` : ""}${p.fits?.length ? `<span class="flag" title="${esc(p.fits.map((f) => `${f.account}: ${f.issues.map((i) => i.issue).join(", ")}`).join("; "))}">breaks a no</span>` : ""}${p.long?.length ? `<span class="flag" title="${esc(p.long.map((f) => `${f.account}: ${f.issues.map((i) => i.issue).join(", ")}`).join("; "))}">too long</span>` : ""}${p.first_draft ? `<span class="pill" title="You edited it; your agent learns from the change">edited</span>` : ""}${p.topic ? `<span class="topic" title="${esc(p.gives ? `gives: ${p.gives}. ${p.payload || ""}` : "")}">${esc(p.topic)}</span>` : ""}</div>
356
+ </div>`;
357
+ }
358
+ /** "X · Bluesky · Threads", or "X · Bluesky +3" when there are many. */
359
+ function platformsLine(accounts) {
360
+ const names = [...new Set(accounts.map((a) => platformOf(a).name))];
361
+ return names.length > 3 ? `${names.slice(0, 2).join(" · ")} +${names.length - 2}` : names.join(" · ");
362
+ }
363
+
364
+ // ---------- the post sheet ----------
365
+
366
+ function openPost(slug) {
367
+ const p = S.posts.find((x) => x.slug === slug);
368
+ if (!p) return;
369
+ open = { slug, base: p, brand: p.brand || "", topic: p.topic || "", gives: p.gives || "", payload: p.payload || "", everywhere: p.everywhere, per: p.per.map((x) => ({ ...x })), media: [...p.media], made_with_ai: p.made_with_ai, status: p.status, tab: p.accounts[0] || "", rewrite: null, dirty: false };
370
+ $("#scrim").classList.add("open");
371
+ $("#sheet").classList.add("open");
372
+ drawSheet();
373
+ setTimeout(() => $("#words")?.focus(), 50);
374
+ }
375
+ function closeSheet(force) {
376
+ if (open?.dirty && !force && !confirm("You have changes that aren't saved. Close anyway?")) return;
377
+ open = null;
378
+ $("#sheet").classList.remove("open");
379
+ $("#scrim").classList.remove("open");
380
+ closeDrawers();
381
+ }
382
+ const resolved = (acct) => {
383
+ const own = open.per.find((x) => x.account === acct)?.words;
384
+ if (!own) return open.everywhere;
385
+ // "…same words… + #tag": the main words, then the rest on its own line at the end
386
+ return own.replace(/…\s*same (words|thread)\s*…\s*\+?\s*/i, `${open.everywhere}\n\n`).trim();
387
+ };
388
+
389
+ function drawSheet() {
390
+ const p = open.base;
391
+ const d = p.date ? new Date(`${p.date}T12:00:00`) : null;
392
+ const accts = p.accounts.length ? p.accounts : ["Everywhere"];
393
+ const live = isLive(p);
394
+ $("#sheet").innerHTML = `
395
+ <div class="bar">
396
+ <div class="title">${d ? esc(fmtDay(d)) : "No date"}${p.time ? ` · ${esc(p.time)}` : ""}${p.kind ? ` <span class="muted">· ${esc(p.kind)}</span>` : ""}</div>
397
+ ${live || p.status === "posted" ? `<span class="pill ${esc(p.status)}">${p.status === "posted" ? "Posted" : "Scheduled in Posthuman"}</span>` : `<div class="row status-row">
398
+ <button class="ok ${open.status === "approved" ? "on" : ""}" data-st="approved">Approve</button>
399
+ <button class="${open.status === "draft" ? "on" : ""}" data-st="draft">Draft</button>
400
+ <button class="${open.status === "dropped" ? "on" : ""}" data-st="dropped">Drop</button>
401
+ </div>`}
402
+ <button class="primary" id="save" ${open.dirty ? "" : "disabled"}>${live && S.agent ? "Save and send" : "Save"}</button>
403
+ <button class="ghost" id="close" aria-label="Close">✕</button>
404
+ </div>
405
+ <div class="body">
406
+ <div>
407
+ ${p.notes ? `<div class="notes">${esc(p.notes)}</div>` : ""}
408
+ ${p.status === "posted" ? `<div class="notes">This one already went out. Changes here only change your copy.</div>` : live ? `<div class="notes">Scheduled in Posthuman (post ${esc(p.post_id)}). ${S.agent ? "<b>Save and send</b> changes it there too: your agent updates the same post, it doesn't make a new one." : "Save keeps your change here. To change it in Posthuman, ask your agent to update it, or edit it in Posthuman."}</div>` : p.status === "scheduled" ? `<div class="notes">Marked scheduled, but there's no Posthuman post number in the file, so Studio can't send changes. Ask your agent to check it.</div>` : ""}
409
+ ${(S.brands || []).length > 1 ? `<h3>Brand</h3><select id="brandOf">${S.brands.map((b) => `<option value="${esc(b.slug)}" ${open.brand === b.slug ? "selected" : ""}>${esc(b.name)}</option>`).join("")}</select>` : ""}
410
+ ${topicsFor(open.brand).length ? `<h3>What it's about</h3><div class="tabs" id="topics">${topicsFor(open.brand).map((t) => `<button class="${open.topic.toLowerCase() === t.name.toLowerCase() ? "on" : ""}" data-t="${esc(t.name)}">${esc(t.name)}</button>`).join("")}</div>` : ""}
411
+ <h3>What it gives the reader</h3>
412
+ <div class="tabs" id="gives">${Object.keys(GIVES_LIST).map((g) => `<button class="${open.gives === g ? "on" : ""}" data-g="${g}" title="${esc(GIVES_LIST[g])}">${g}</button>`).join("")}</div>
413
+ <input type="text" id="payload" value="${esc(open.payload)}" placeholder="The one real thing, in a line: the true detail, the tip, the number, the reason">
414
+ <div id="substance" style="margin-top:6px"></div>
415
+
416
+ <h3>Words, everywhere</h3>
417
+ <textarea id="words" rows="${Math.min(18, Math.max(6, open.everywhere.split("\n").length + 2))}" spellcheck="true">${esc(open.everywhere)}</textarea>
418
+ <div class="small muted" style="margin-top:4px">A line with only --- splits it into a thread.</div>
419
+ <div class="counts-line" id="counts-line"></div>
420
+
421
+ <h3>Own words for one account</h3>
422
+ <div id="per"></div>
423
+ <div class="row" style="margin-top:6px">
424
+ <select id="perAdd"><option value="">+ add for…</option>${accts.filter((a) => !open.per.some((x) => x.account === a)).map((a) => `<option>${esc(a)}</option>`).join("")}</select>
425
+ <span class="small muted">"…same words… + #tag" adds to the main words.</span>
426
+ </div>
427
+
428
+ <h3>Reads human?</h3>
429
+ <div id="tells"></div>
430
+
431
+ <h3>Fits each account?</h3>
432
+ <div id="fits"></div>
433
+
434
+ <h3>Rewrite</h3>
435
+ <div class="row" style="flex-wrap:nowrap">
436
+ <input type="text" id="note" placeholder="${S.agent ? "punchier · less salesy · end on a question" : "a note for your agent (it picks it up next time)"}">
437
+ <button id="rewrite">${S.agent ? "Rewrite" : "Save note"}</button>
438
+ <button class="primary" id="humanize" title="The last pass: plain words, shorter, no AI giveaways. Same facts, same joke.">Humanize</button>
439
+ </div>
440
+ <div id="rewriteOut">${p.rewrite_asked ? `<div class="small muted" style="margin-top:6px">Waiting for your agent: ${esc(p.rewrite_asked)}</div>` : ""}</div>
441
+ ${p.first_draft ? `<h3>Your agent's first draft</h3><div class="small muted" style="white-space:pre-wrap">${esc(p.first_draft.replace(/<!--[\s\S]*?-->\n?/, ""))}</div>` : ""}
442
+ </div>
443
+ <div>
444
+ <h3>How it looks</h3>
445
+ <div class="tabs" id="tabs">${accts.map((a) => `<button class="${a === open.tab ? "on" : ""}" data-tab="${esc(a)}">${esc(platformOf(a).name)}</button>`).join("")}</div>
446
+ <div id="preview"></div>
447
+
448
+ <h3>Pictures and video</h3>
449
+ <div class="media-edit" id="mediaEdit"></div>
450
+ <div class="row" style="margin-top:8px">
451
+ <button id="pick">Add from library</button>
452
+ <label class="row small"><input type="checkbox" id="ai" ${open.made_with_ai ? "checked" : ""}> Made with AI (labels it on the platforms)</label>
453
+ </div>
454
+ <div class="drop" id="drop" style="margin-top:8px">Drop a picture or clip here</div>
455
+ <div id="picker"></div>
456
+ </div>
457
+ </div>`;
458
+ $("#close").onclick = () => closeSheet();
459
+ $("#save").onclick = save;
460
+ $("#sheet").querySelectorAll("[data-st]").forEach((b) => (b.onclick = async () => { open.status = b.dataset.st; open.dirty = true; await save(); }));
461
+ $("#words").oninput = (e) => { open.everywhere = e.target.value; dirty(); drawCounts(); drawPreview(); drawTells(); drawSubstance(); };
462
+ $("#brandOf") && ($("#brandOf").onchange = (e) => { open.brand = e.target.value; dirty(); drawSheet(); });
463
+ $("#topics")?.querySelectorAll("[data-t]").forEach((b) => (b.onclick = () => { open.topic = open.topic === b.dataset.t ? "" : b.dataset.t; dirty(); drawSheet(); }));
464
+ $("#gives").querySelectorAll("[data-g]").forEach((b) => (b.onclick = () => { open.gives = open.gives === b.dataset.g ? "" : b.dataset.g; dirty(); drawSheet(); }));
465
+ $("#payload").oninput = (e) => { open.payload = e.target.value; dirty(); drawSubstance(); };
466
+ $("#perAdd").onchange = (e) => { if (!e.target.value) return; open.per.push({ account: e.target.value, words: "…same words…" }); dirty(); drawSheet(); };
467
+ $("#tabs").querySelectorAll("button").forEach((b) => (b.onclick = () => { open.tab = b.dataset.tab; drawSheet(); }));
468
+ $("#ai").onchange = (e) => { open.made_with_ai = e.target.checked; dirty(); };
469
+ $("#rewrite").onclick = () => rewrite();
470
+ $("#humanize").onclick = () => rewrite(true);
471
+ $("#note").onkeydown = (e) => { if (e.key === "Enter") rewrite(); };
472
+ $("#pick").onclick = () => drawPicker();
473
+ dropZone($("#drop"), async (file) => { open.media.push(file); dirty(); drawSheet(); });
474
+ drawPer(); drawCounts(); drawPreview(); drawMedia(); drawTells(); drawSubstance();
475
+ }
476
+ function drawSubstance() {
477
+ const el = $("#substance");
478
+ if (!el) return;
479
+ const t = substanceCheck ? substanceCheck({ gives: open.gives, payload: open.payload, words: open.everywhere, media: open.media }) : open.base.substance || [];
480
+ el.innerHTML = t.length
481
+ ? `<ul class="tell-list">${t.map((x) => `<li><b>${esc(x.issue)}</b>. <span class="muted">${esc(x.fix)}</span></li>`).join("")}</ul>`
482
+ : `<div class="small muted">It gives the reader something real.</div>`;
483
+ }
484
+ function drawTells() {
485
+ const el = $("#tells");
486
+ if (!el) return;
487
+ const t = humanCheck ? humanCheck(open.everywhere, { voice: S.voices?.[open.brand] ?? S.voice }) : open.base.tells || [];
488
+ el.innerHTML = t.length
489
+ ? `<ul class="tell-list">${t.map((x) => `<li><b>${esc(x.tell)}</b>: ${x.found.map((f) => `<mark>${esc(f)}</mark>`).join(" ")} <span class="muted">${esc(x.fix)}</span></li>`).join("")}</ul>`
490
+ : `<div class="small muted">Nothing that sounds like AI. Still read it out loud once.</div>`;
491
+ drawFits();
492
+ }
493
+ // Does it fit each account's setup (brand/accounts.md)?
494
+ function drawFits() {
495
+ const el = $("#fits");
496
+ if (!el) return;
497
+ const accts = S.accounts?.accounts || [];
498
+ const fits = fitCheck && setupFor ? open.base.accounts.map((a) => ({ account: a, issues: fitCheck(setupFor(a, accts)?.setup, resolved(a)) })).filter((f) => f.issues.length) : open.base.fits || [];
499
+ const known = open.base.accounts.filter((a) => setupFor?.(a, accts)?.setup).length;
500
+ const items = [
501
+ ...fits.flatMap((f) => f.issues.map((x) => `<li><b>${esc(platformOf(f.account).name)}</b>: ${esc(x.issue)}. <span class="muted">${esc(x.fix)}</span></li>`)),
502
+ ];
503
+ el.innerHTML = items.length
504
+ ? `<ul class="tell-list">${items.join("")}</ul>`
505
+ : `<div class="small muted">${known ? "Fits how each account works." : `No account setups here yet: <a href="#accounts">Accounts</a>.`}</div>`;
506
+ }
507
+ function dirty() { open.dirty = true; const s = $("#save"); if (s) s.disabled = false; }
508
+
509
+ function drawPer() {
510
+ $("#per").innerHTML = open.per.length ? open.per.map((x, i) => `
511
+ <div style="margin-bottom:8px"><div class="row small" style="justify-content:space-between"><b>${esc(x.account)}</b><button class="ghost small" data-rm="${i}">Remove</button></div>
512
+ <textarea rows="${Math.min(12, Math.max(2, x.words.split("\n").length + 1))}" data-per="${i}">${esc(x.words)}</textarea></div>`).join("") : `<div class="small muted">None: every account gets the main words.</div>`;
513
+ $("#per").querySelectorAll("[data-per]").forEach((t) => (t.oninput = () => { open.per[t.dataset.per].words = t.value; dirty(); drawCounts(); drawPreview(); drawFits(); }));
514
+ $("#per").querySelectorAll("[data-rm]").forEach((b) => (b.onclick = () => { open.per.splice(Number(b.dataset.rm), 1); dirty(); drawSheet(); }));
515
+ }
516
+ function drawCounts() {
517
+ const accts = open.base.accounts;
518
+ $("#counts-line").innerHTML = accts.map((a) => {
519
+ const pf = platformOf(a);
520
+ if (lengthsFor) {
521
+ const l = lengthsFor(a, resolved(a), { media: open.media.length });
522
+ if (l.length) {
523
+ const worst = l.reduce((m, x) => (x.length - x.limit > m.length - m.limit ? x : m));
524
+ return `<span class="count ${worst.length > worst.limit ? "over" : ""}" title="${esc(a)}${worst.part ? `: part ${worst.part}` : ""}">${esc(pf.name)} ${worst.length}/${worst.limit}</span>`;
525
+ }
526
+ }
527
+ if (!pf.limit) return `<span class="count">${esc(pf.name)}</span>`;
528
+ const longest = Math.max(...parts(resolved(a)).map(glyphs));
529
+ return `<span class="count ${longest > pf.limit ? "over" : ""}" title="${esc(a)}">${esc(pf.name)} ${longest}/${pf.limit}</span>`;
530
+ }).join("");
531
+ }
532
+ function drawPreview() {
533
+ const a = open.tab || "Everywhere";
534
+ const pf = platformOf(a);
535
+ const name = (open?.brand && brandName(open.brand)) || S.brand;
536
+ const ps = parts(resolved(a));
537
+ const m = open.media.filter((f) => !/\.(mp3|wav|m4a)$/i.test(f));
538
+ $("#preview").innerHTML = ps.map((t, i) => `
539
+ ${i ? `<div class="joined"></div>` : ""}
540
+ <div class="preview">
541
+ <div class="who"><div class="avatar">${esc(name[0]?.toUpperCase() || "?")}</div><div><div class="name">${esc(name)}</div><div class="handle">${esc(handleOf(a) || pf.name)}</div></div></div>
542
+ <div class="text">${esc(t)}</div>
543
+ ${i === 0 && m.length ? `<div class="media">${m.slice(0, 4).map((f) => /\.(mp4|mov)$/i.test(f) ? `<video src="${media(f)}" controls preload="metadata"></video>` : `<img src="${media(f)}" alt="${esc(altOf(f))}">`).join("")}</div>` : ""}
544
+ <div class="meta">${esc(pf.name)}${pf.limit ? ` · ${glyphs(t)}/${pf.limit}` : ""}${ps.length > 1 ? ` · part ${i + 1} of ${ps.length}` : ""}${open.made_with_ai && i === 0 ? " · AI label" : ""}</div>
545
+ </div>`).join("");
546
+ }
547
+ const altOf = (f) => S.library.find((x) => x.file === f)?.alt || "";
548
+ function drawMedia() {
549
+ $("#mediaEdit").innerHTML = open.media.map((f, i) => {
550
+ const isAudio = /\.(mp3|wav|m4a)$/i.test(f);
551
+ const thumb = /\.(mp4|mov)$/i.test(f) ? `<video src="${media(f)}" muted preload="metadata"></video>` : isAudio ? `<div class="tile audio" style="width:72px;height:72px;display:grid;place-items:center;border:1px solid var(--line);border-radius:10px">♪</div>` : `<img src="${media(f)}" alt="">`;
552
+ return `<div class="media-item">${thumb}<div><div class="small muted">${esc(f)}</div><input type="text" data-alt="${esc(f)}" value="${esc(altOf(f))}" placeholder="One sentence describing it (alt text)"></div><button class="ghost" data-rmm="${i}">Remove</button></div>`;
553
+ }).join("") || `<div class="small muted">No pictures: a text post.</div>`;
554
+ $("#mediaEdit").querySelectorAll("[data-alt]").forEach((inp) => (inp.onchange = async () => {
555
+ await api("PUT", "/api/alt", { file: inp.dataset.alt, alt: inp.value });
556
+ const x = S.library.find((y) => y.file === inp.dataset.alt); if (x) x.alt = inp.value;
557
+ drawPreview(); toast("Description saved");
558
+ }));
559
+ $("#mediaEdit").querySelectorAll("[data-rmm]").forEach((b) => (b.onclick = () => { open.media.splice(Number(b.dataset.rmm), 1); dirty(); drawSheet(); }));
560
+ }
561
+ function drawPicker() {
562
+ const el = $("#picker");
563
+ if (el.innerHTML) { el.innerHTML = ""; return; }
564
+ el.innerHTML = S.library.length ? `<h3>Library</h3><div class="grid">${S.library.map((x) => tile(x)).join("")}</div>` : `<div class="small muted" style="margin-top:8px">The library is empty. Drop a file above, or ask your agent to make one (recipes/).</div>`;
565
+ el.querySelectorAll(".tile").forEach((t) => (t.onclick = () => { if (!open.media.includes(t.dataset.file)) open.media.push(t.dataset.file); dirty(); drawSheet(); }));
566
+ }
567
+ const tile = (x) => `<div class="tile ${x.type === "audio" ? "audio" : ""}" data-file="${esc(x.file)}" title="${esc(x.alt || x.file)}">${x.type === "video" ? `<video src="${media(x.file)}" muted preload="metadata"></video>` : x.type === "audio" ? "♪" : `<img src="${media(x.file)}" alt="${esc(x.alt)}" loading="lazy">`}${x.type === "audio" ? "" : `<div class="cap">${esc(x.alt || x.file)}</div>`}</div>`;
568
+
569
+ async function save() {
570
+ if (!open) return;
571
+ try {
572
+ const r = await api("PUT", `/api/post/${encodeURIComponent(open.slug)}`, { everywhere: open.everywhere, brand: open.brand, topic: open.topic, gives: open.gives, payload: open.payload, per: open.per, media: open.media, made_with_ai: open.made_with_ai, status: open.status, mtime: open.base.mtime });
573
+ const i = S.posts.findIndex((x) => x.slug === open.slug);
574
+ S.posts[i] = r.post;
575
+ open.base = r.post; open.dirty = false;
576
+ render(); drawSheet();
577
+ if (isLive(r.post) && S.agent) {
578
+ const { job } = await api("POST", `/api/send/${encodeURIComponent(open.slug)}`);
579
+ showJob(job, "Sending your change to Posthuman…");
580
+ } else toast(open.status === "approved" ? "Approved" : "Saved");
581
+ } catch (e) {
582
+ alert(e.message);
583
+ if (e.status === 409) { await load(); openPost(open.slug); }
584
+ }
585
+ }
586
+
587
+ async function rewrite(humanize = false) {
588
+ const note = $("#note").value.trim();
589
+ const out = $("#rewriteOut");
590
+ if (!S.agent) {
591
+ const r = await api("POST", `/api/rewrite/${encodeURIComponent(open.slug)}`, { note, humanize });
592
+ out.innerHTML = `<div class="small muted" style="margin-top:6px">${esc(r.message)}</div>`;
593
+ await load(); return;
594
+ }
595
+ if (open.dirty) await save();
596
+ out.innerHTML = `<div class="small muted" style="margin-top:8px"><span class="spin"></span> ${humanize ? "Making it sound human…" : "Your agent is rewriting it…"}</div>`;
597
+ const slug = open.slug;
598
+ const { job } = await api("POST", `/api/rewrite/${encodeURIComponent(slug)}`, { note, humanize }).catch((e) => ({ error: e.message }));
599
+ if (!job) { out.innerHTML = `<div class="notes" style="margin-top:8px">Couldn't start the rewrite.</div>`; return; }
600
+ const j = await waitJob(job);
601
+ if (!open || open.slug !== slug) return;
602
+ if (j.state !== "done") { out.innerHTML = `<div class="notes" style="margin-top:8px">The rewrite didn't work:\n${esc((j.err || j.out).slice(-600))}</div>`; return; }
603
+ const fresh = j.out.trim();
604
+ if (!fresh) { out.innerHTML = `<div class="notes" style="margin-top:8px">Your agent came back with nothing. Try again, or a different note.</div>`; return; }
605
+ out.innerHTML = `<div class="compare"><div><div class="small muted">Now</div>${esc(open.everywhere)}</div><div class="new"><div class="small muted">${humanize ? "Humanized" : "Rewrite"}${humanCheck ? ` · ${humanCheck(fresh).length ? `${humanCheck(fresh).length} still flagged` : "reads human"}` : ""}</div>${esc(fresh)}</div></div>
606
+ <div class="row" style="margin-top:8px"><button class="primary" id="useIt">Use the rewrite</button><button id="keep">Keep mine</button><button class="ghost" id="again">Try again</button></div>`;
607
+ $("#useIt").onclick = () => { open.everywhere = fresh; dirty(); drawSheet(); };
608
+ $("#keep").onclick = () => (out.innerHTML = "");
609
+ $("#again").onclick = () => rewrite(humanize);
610
+ }
611
+
612
+ const isLive = (p) => p.status === "scheduled" && !!p.post_id;
613
+
614
+ /** The job box at the bottom: what the agent is doing, live, until it's done. */
615
+ function showJob(job, title) {
616
+ const box = $("#job");
617
+ box.classList.add("open");
618
+ box.innerHTML = `<div class="row" style="justify-content:space-between"><b><span class="spin"></span> ${esc(title)}</b><button class="ghost" id="jobClose">✕</button></div><pre id="jobOut"></pre>`;
619
+ $("#jobClose").onclick = () => box.classList.remove("open");
620
+ const poll = async () => {
621
+ const j = await api("GET", `/api/job/${job}`).catch(() => ({ state: "failed", out: "lost it" }));
622
+ const o = $("#jobOut"); if (o) { o.textContent = (j.out + (j.state === "failed" && j.err ? `\n${j.err}` : "")).slice(-4000); o.scrollTop = o.scrollHeight; }
623
+ if (j.state === "running") return setTimeout(poll, 1500);
624
+ box.querySelector("b").innerHTML = j.state === "done" ? "Done" : "It stopped. See why below.";
625
+ await load();
626
+ };
627
+ poll();
628
+ }
629
+
630
+ function waitJob(id, onTick) {
631
+ return new Promise((ok) => {
632
+ const tick = async () => {
633
+ const j = await api("GET", `/api/job/${id}`).catch(() => ({ state: "failed", out: "lost it" }));
634
+ if (j.state === "running") { onTick?.(j); setTimeout(tick, 1500); } else ok(j);
635
+ };
636
+ tick();
637
+ });
638
+ }
639
+
640
+ // ---------- schedule ----------
641
+
642
+ $("#scheduleBtn").onclick = async () => {
643
+ const n = S.posts.filter((p) => p.status === "approved").length;
644
+ if (!S.agent) { alert("Claude Code isn't installed on this computer. Open your agent in this folder and say: schedule the approved posts."); return; }
645
+ if (!confirm(`Hand ${n} approved post${n === 1 ? "" : "s"} to your agent to schedule through Posthuman?`)) return;
646
+ const { job } = await api("POST", "/api/schedule");
647
+ showJob(job, `Scheduling ${n}…`);
648
+ };
649
+
650
+ // ---------- ideas + library drawers ----------
651
+
652
+ function closeDrawers() { if (!open) $("#scrim").classList.remove("open"); }
653
+ $("#scrim").onclick = () => closeSheet();
654
+
655
+ // ---------- places: the rail ----------
656
+
657
+ const VIEWS = ["week", "know", "stuff", "brainstorm", "raw", "accounts", "make", "library"];
658
+ let view = "week";
659
+ function go() {
660
+ view = VIEWS.includes(location.hash.slice(1)) ? location.hash.slice(1) : "week";
661
+ VIEWS.forEach((v) => ($(`#v-${v}`).hidden = v !== view));
662
+ document.querySelectorAll(".rail .place").forEach((a) => (a.dataset.view === view ? a.setAttribute("aria-current", "page") : a.removeAttribute("aria-current")));
663
+ ({ week: render, know: drawKnow, stuff: drawStuff, brainstorm: drawBrainstorm, raw: drawRaw, accounts: drawAccounts, make: drawMake, library: drawLibrary })[view]();
664
+ }
665
+ window.addEventListener("hashchange", go);
666
+ function drawRail() {
667
+ $("#brand").textContent = S.brand;
668
+ const drafts = S.posts.filter((p) => p.status === "draft").length;
669
+ $("#nWeek").hidden = !drafts; $("#nWeek").textContent = drafts;
670
+ const todo = S.know?.todo || 0;
671
+ $("#nKnow").hidden = !todo; $("#nKnow").textContent = todo; $("#nKnow").title = `${todo} step${todo === 1 ? "" : "s"} left`;
672
+ $("#foot").innerHTML = `<div>Agent: <b>${S.agent ? "Claude Code" : "none found"}</b></div><div>fal: <b>${S.keys?.fal ? "key set" : "no key"}</b> · ElevenLabs: <b>${S.keys?.elevenlabs ? "key set" : "no key"}</b></div><div>${S.ideas.length} open idea${S.ideas.length === 1 ? "" : "s"}</div>`;
673
+ }
674
+ const head = (title, sub, extra = "") => `<div class="view-head"><div><h1>${title}</h1>${sub ? `<div class="sub">${sub}</div>` : ""}</div><div class="grow"></div>${extra}</div>`;
675
+ const needAgent = () => (S.agent ? "" : `<div class="needkey" style="margin-bottom:14px">This needs Claude Code on this computer. Without it, open your agent in this folder and ask it the same thing.</div>`);
676
+ const fileChip = (f, rm) => `<span class="chip-file">${/\.(png|jpe?g|webp|gif)$/i.test(f) ? `<img src="${media(f)}" alt="">` : "🎞"}${esc(f)}${rm ? `<button class="ghost small" data-rmf="${esc(f)}" aria-label="Remove">✕</button>` : ""}</span>`;
677
+ const picker = (filter, onPick) => {
678
+ const items = S.library.filter(filter);
679
+ return items.length ? `<div class="grid" style="margin-top:8px">${items.map(tile).join("")}</div>` : `<div class="small muted" style="margin-top:6px">Nothing in the library yet. Drop one in.</div>`;
680
+ };
681
+
682
+ // ---------- Brainstorm ----------
683
+
684
+ let BS = { text: "", files: [], angles: [], running: false, saved: "" };
685
+ function drawBrainstorm() {
686
+ const days = [...Array(7)].map((_, i) => { const d = new Date(startOfWeek(new Date())); d.setDate(d.getDate() + i); return d; });
687
+ const taken = new Set(S.posts.map((p) => p.date));
688
+ const firstFree = days.find((d) => !taken.has(ymd(d)) && ymd(d) >= ymd(new Date())) || days[6];
689
+ $("#v-brainstorm").innerHTML = head("Brainstorm", "Bring a thought, a link or a picture. Your agent pitches five angles, each one giving the reader something real.") + needAgent() + `
690
+ <div class="cols">
691
+ <div>
692
+ <div class="panel">
693
+ <textarea id="bsText" rows="4" placeholder="What happened, what you shipped, a screenshot you're proud of, a take you can't shake…">${esc(BS.text)}</textarea>
694
+ <div class="chips">${BS.files.map((f) => fileChip(f, true)).join("")}</div>
695
+ <div class="drop" id="bsDrop" style="margin-top:10px">Drop a picture or clip, or <button class="ghost small" id="bsPick">pick from the library</button></div>
696
+ <div id="bsPicker"></div>
697
+ <div class="row" style="margin-top:12px"><button class="lit" id="bsGo" ${BS.running || !S.agent ? "disabled" : ""}>${BS.running ? `<span class="spin"></span> Thinking…` : "Brainstorm 5 angles"}</button>${BS.saved ? `<span class="small muted">Saved to ${esc(BS.saved)}</span>` : ""}</div>
698
+ </div>
699
+ <div class="angles">${BS.angles.map((a, i) => `
700
+ <div class="panel angle ${a.kept ? "kept" : ""}">
701
+ <div class="row">${a.topic ? `<span class="pill">${esc(a.topic)}</span>` : ""}<span class="pill gives">${esc(a.gives || "?")}</span>${a.kept ? `<span class="pill approved">${esc(a.kept)}</span>` : ""}</div>
702
+ <h3>${esc(a.angle)}</h3>
703
+ <div class="first">${esc(a.first_line)}</div>
704
+ <div class="small muted">Gives: ${esc(a.payload)}</div>
705
+ ${a.needs ? `<div class="needs">Needs from you: ${esc(a.needs)}</div>` : ""}
706
+ ${a.kept ? "" : `<div class="row" style="margin-top:10px">
707
+ <button data-keep="${i}" data-as="idea">Keep as idea</button>
708
+ <select data-day="${i}">${days.map((d) => `<option value="${ymd(d)}" ${ymd(d) === ymd(firstFree) ? "selected" : ""}>${esc(fmtDay(d))}${taken.has(ymd(d)) ? " ·" : ""}</option>`).join("")}</select>
709
+ <button class="primary" data-keep="${i}" data-as="draft">Draft it</button>
710
+ <button class="ghost" data-toss="${i}">Toss</button></div>`}
711
+ </div>`).join("")}</div>
712
+ </div>
713
+ <div class="panel">
714
+ <h3 style="margin:0 0 8px;font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:var(--soft)">Ideas inbox</h3>
715
+ <div class="row" style="flex-wrap:nowrap"><input type="text" id="newIdea" placeholder="One line"><button id="addIdea">Add</button></div>
716
+ <ul class="ideas" style="padding-left:18px;margin:12px 0 0">${S.ideas.map((i) => `<li>${esc(i.text)} <button class="ghost small" data-use="${esc(i.text)}" title="Brainstorm from this">↗</button></li>`).join("") || `<li class="muted">No open ideas.</li>`}</ul>
717
+ </div>
718
+ </div>`;
719
+ const v = $("#v-brainstorm");
720
+ $("#bsText").oninput = (e) => (BS.text = e.target.value);
721
+ v.querySelectorAll("[data-rmf]").forEach((b) => (b.onclick = () => { BS.files = BS.files.filter((f) => f !== b.dataset.rmf); drawBrainstorm(); }));
722
+ $("#bsPick").onclick = () => {
723
+ const el = $("#bsPicker");
724
+ if (el.innerHTML) return (el.innerHTML = "");
725
+ el.innerHTML = picker((x) => x.type !== "audio");
726
+ el.querySelectorAll(".tile").forEach((t) => (t.onclick = () => { if (!BS.files.includes(t.dataset.file)) BS.files.push(t.dataset.file); drawBrainstorm(); }));
727
+ };
728
+ dropZone($("#bsDrop"), (file) => { BS.files.push(file); drawBrainstorm(); });
729
+ $("#bsGo").onclick = async () => {
730
+ BS.running = true; drawBrainstorm();
731
+ try {
732
+ const { job } = await api("POST", "/api/brainstorm", { text: BS.text, files: BS.files });
733
+ const j = await waitJob(job);
734
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
735
+ BS.angles = j.angles || []; BS.saved = j.saved || "";
736
+ } catch (e) { alert(e.message); }
737
+ BS.running = false; if (view === "brainstorm") drawBrainstorm();
738
+ };
739
+ v.querySelectorAll("[data-keep]").forEach((b) => (b.onclick = async () => {
740
+ const i = Number(b.dataset.keep), a = BS.angles[i];
741
+ const r = await api("POST", "/api/keep", { angle: a, as: b.dataset.as, date: v.querySelector(`[data-day="${i}"]`)?.value, files: BS.files });
742
+ a.kept = r.kept === "draft" ? "drafted" : "kept"; await load(false); drawBrainstorm();
743
+ toast(r.kept === "draft" ? "Drafted: it's on the Week" : "Saved to your ideas");
744
+ }));
745
+ v.querySelectorAll("[data-toss]").forEach((b) => (b.onclick = () => { BS.angles.splice(Number(b.dataset.toss), 1); drawBrainstorm(); }));
746
+ v.querySelectorAll("[data-use]").forEach((b) => (b.onclick = () => { BS.text = b.dataset.use; drawBrainstorm(); $("#bsText").focus(); }));
747
+ const add = async () => { const t = $("#newIdea").value.trim(); if (!t) return; const r = await api("POST", "/api/idea", { text: t }); S.ideas = r.ideas; drawRail(); drawBrainstorm(); toast("Idea saved"); };
748
+ $("#addIdea").onclick = add; $("#newIdea").onkeydown = (e) => e.key === "Enter" && add();
749
+ }
750
+
751
+ // ---------- This week's raw ----------
752
+
753
+ let RAW = null, rawTimer = null;
754
+ async function drawRaw() {
755
+ if (!RAW || RAW.week !== S.week) RAW = await api("GET", `/api/raw?week=${S.week}`);
756
+ const wk = new Date(`${RAW.week}T12:00:00`);
757
+ const listEdit = (key, ph) => `<div class="list-edit">${RAW[key].map((x, i) => `<div class="row"><input type="text" data-k="${key}" data-i="${i}" value="${esc(x)}" placeholder="${ph}"><button class="ghost" data-rm="${key}" data-i="${i}" aria-label="Remove">✕</button></div>`).join("")}
758
+ <div class="row"><input type="text" data-new="${key}" placeholder="${ph}"><button data-add="${key}">Add</button></div></div>`;
759
+ $("#v-raw").innerHTML = head("This week's raw", `The week of ${esc(fmtDay(wk))}. Three real things are enough: a screenshot, a number, something that happened. Each line becomes one post, so true things only, and say how it should come across if you know ("hyped, I love this one").`) + needAgent() + `
760
+ <div class="cols">
761
+ <div class="stack" style="display:grid;gap:14px">
762
+ <div class="panel"><h3 class="label">Screenshots</h3>
763
+ <div class="list-edit">${RAW.shots.map((x, i) => `<div class="media-item">${/\.(mp4|mov)$/i.test(x.file) ? `<video src="${media(x.file)}" muted preload="metadata"></video>` : `<img src="${media(x.file)}" alt="">`}<input type="text" data-shot="${i}" value="${esc(x.note)}" placeholder="What it shows, in a few words"><button class="ghost" data-rmshot="${i}" aria-label="Remove">✕</button></div>`).join("")}</div>
764
+ <div class="drop" id="rawDrop" style="margin-top:10px">Drop a screenshot or clip</div></div>
765
+ <div class="panel"><h3 class="label">Numbers</h3>${listEdit("numbers", "e.g. 3 sign-ups, 40 hours saved, $0 MRR")}</div>
766
+ <div class="panel"><h3 class="label">What happened</h3>${listEdit("happened", "e.g. the app logged me out at midnight. Make it funny, the joke's on me")}</div>
767
+ </div>
768
+ <div class="panel">
769
+ <h3 class="label">Then</h3>
770
+ <p class="small">Your agent writes one post for each line here, and nothing it picked itself. Where a line doesn't say how it should feel, you get two takes to choose from. Every post says what it gives, gets the substance check and the humanize pass, and lands on the Week as a draft. Nothing is scheduled.</p>
771
+ <button class="lit" id="draftWeek" ${S.agent ? "" : "disabled"} style="width:100%">Draft the week from this</button>
772
+ <pre id="draftOut" class="small" style="white-space:pre-wrap;max-height:300px;overflow:auto"></pre>
773
+ </div>
774
+ </div>`;
775
+ const v = $("#v-raw");
776
+ const save = () => { clearTimeout(rawTimer); rawTimer = setTimeout(async () => { RAW = await api("PUT", "/api/raw", RAW); drawRailRaw(); }, 400); };
777
+ v.querySelectorAll("[data-k]").forEach((inp) => (inp.oninput = () => { RAW[inp.dataset.k][inp.dataset.i] = inp.value; save(); }));
778
+ v.querySelectorAll("[data-rm]").forEach((b) => (b.onclick = () => { RAW[b.dataset.rm].splice(Number(b.dataset.i), 1); save(); drawRaw(); }));
779
+ v.querySelectorAll("[data-add]").forEach((b) => (b.onclick = () => { const inp = v.querySelector(`[data-new="${b.dataset.add}"]`); if (!inp.value.trim()) return; RAW[b.dataset.add].push(inp.value.trim()); save(); drawRaw(); }));
780
+ v.querySelectorAll("[data-new]").forEach((inp) => (inp.onkeydown = (e) => e.key === "Enter" && v.querySelector(`[data-add="${inp.dataset.new}"]`).click()));
781
+ v.querySelectorAll("[data-shot]").forEach((inp) => (inp.oninput = () => { RAW.shots[inp.dataset.shot].note = inp.value; save(); }));
782
+ v.querySelectorAll("[data-rmshot]").forEach((b) => (b.onclick = () => { RAW.shots.splice(Number(b.dataset.rmshot), 1); save(); drawRaw(); }));
783
+ dropZone($("#rawDrop"), async (file) => { RAW.shots.push({ file, note: "" }); RAW = await api("PUT", "/api/raw", RAW); drawRaw(); });
784
+ $("#draftWeek").onclick = async () => {
785
+ if (!confirm("Have your agent draft the week from this? It writes drafts only; nothing is scheduled.")) return;
786
+ const out = $("#draftOut"); out.innerHTML = `<span class="spin"></span> Drafting… (a few minutes)`;
787
+ try {
788
+ const { job } = await api("POST", "/api/draft-week", { week: RAW.week });
789
+ const j = await waitJob(job, (j) => (out.textContent = j.out.slice(-3000) || "Drafting…"));
790
+ out.textContent = j.state === "done" ? j.out.trim() : `It stopped:\n${(j.err || j.out).slice(-600)}`;
791
+ await load(false);
792
+ } catch (e) { out.textContent = e.message; }
793
+ };
794
+ }
795
+ function drawRailRaw() { const n = RAW ? RAW.shots.length + RAW.numbers.length + RAW.happened.length : 0; $("#nRaw").hidden = !n; $("#nRaw").textContent = n; }
796
+
797
+ // ---------- Get to know you ----------
798
+
799
+ let KN = { data: null, urls: "", draft: null, busy: "", out: "", aims: null, why: "" };
800
+ async function drawKnow(reload = false) {
801
+ if (!KN.data || reload) KN.data = await api("GET", "/api/know");
802
+ const D = KN.data, A = D.about;
803
+ KN.aims ??= Object.keys(D.aims).filter((k) => A.goals.includes(D.aims[k]));
804
+ const goal = (re) => (A.goals.match(re) || [, ""])[1];
805
+ const next = D.past.find((p) => !p.verdict);
806
+ const judged = D.past.filter((p) => p.verdict && p.verdict !== "skip").length;
807
+ $("#v-know").innerHTML = head("Get to know you", "Three things make every post sound like you and aim somewhere: what you make (from your own links), what posting is for, and your real posts, one at a time. Your edits keep teaching it after that.", `<button id="knSync" ${KN.busy || !S.agent ? "disabled" : ""} title="Posthuman keeps a short About you that your phone and other chats read. This fills what's empty here from it, and sends this folder's version there (if Posthuman already has one, you see it as a suggestion to take or leave).">${KN.busy === "sync" ? `<span class="spin"></span> Syncing…` : "Sync with Posthuman"}</button>`) + needAgent() + `
808
+ ${KN.out ? `<div class="notes">${esc(KN.out)}</div>` : ""}
809
+ <div class="steps">
810
+ <div class="panel step ${A.what_it_is ? "done" : ""}">
811
+ <h2><span class="n1">1</span>What you make, or who you are</h2>
812
+ <div class="small muted">Got a website, app store page, shop or newsletter? Paste the links: your agent reads them and drafts brand/about.md from what's really on them. No website is fine too: say it in a few lines below, or skip this and it learns from your posts.</div>
813
+ ${A.what_it_is && !KN.draft ? `<div class="small" style="margin-top:8px;white-space:pre-wrap">${esc(A.what_it_is)}</div>` : ""}
814
+ <textarea id="knUrls" rows="2" style="margin-top:8px" placeholder="https://yourapp.com&#10;https://apps.apple.com/app/…">${esc(KN.urls)}</textarea>
815
+ <div class="row" style="margin-top:8px"><button class="lit" id="knRead" ${KN.busy || !S.agent ? "disabled" : ""}>${KN.busy === "links" ? `<span class="spin"></span> Reading…` : A.what_it_is ? "Read them again" : "Read them"}</button></div>
816
+ ${KN.draft ? "" : `<details style="margin-top:10px" ${A.what_it_is ? "" : "open"}><summary class="small"><b>No website? Say it instead</b></summary>
817
+ <label>What you make or post about</label><textarea id="sWhat" rows="2" placeholder="I'm a dad who builds small apps after the kids go to bed, and posts what happens.">${esc(A.what_it_is.split("\n")[0] || "")}</textarea>
818
+ <label>Who it's for</label><input type="text" id="sWho" value="${esc(A.who_its_for)}" placeholder="People with a day job building something on the side">
819
+ <div class="row" style="margin-top:8px"><button class="primary" id="knSay">Save it</button></div></details>`}
820
+ ${KN.draft ? `<div style="margin-top:10px">
821
+ <label>What it is</label><textarea id="dWhat" rows="2">${esc(KN.draft.what_it_is)}</textarea>
822
+ <label>Who it's for</label><input type="text" id="dWho" value="${esc(KN.draft.who_its_for)}">
823
+ <label>Facts a post can use (one per line, true ones only)</label><textarea id="dFacts" rows="4">${esc(KN.draft.facts.join("\n"))}</textarea>
824
+ <label>Links</label><textarea id="dLinks" rows="2">${esc(KN.draft.links.join("\n"))}</textarea>
825
+ <div class="row" style="margin-top:8px"><button class="primary" id="knSaveAbout">Put it in about.md</button><button class="ghost" id="knToss">Toss it</button></div></div>` : ""}
826
+ </div>
827
+ <div class="panel step ${A.goals ? "done" : ""}">
828
+ <h2><span class="n1">2</span>What posting is for</h2>
829
+ <div class="small muted">Every week aims at this, and "how did it do" is measured against it.</div>
830
+ <div class="tabs aims" style="margin-top:10px">${Object.entries(D.aims).map(([k, v]) => `<button data-aim="${k}" class="${KN.aims.includes(k) ? "on" : ""}">${esc(v)}</button>`).join("")}</div>
831
+ <label>It worked if…</label><input type="text" id="gNum" value="${esc(goal(/It worked if: (.+)/))}" placeholder="10 paying customers · 1,000 followers on X · 50 sign-ups">
832
+ <label>By when</label><input type="text" id="gBy" value="${esc(goal(/By: (.+)/))}" placeholder="Dec 16 · end of the year · no rush">
833
+ <label>Why it matters to you (optional)</label><input type="text" id="gWhy" value="${esc(goal(/Why it matters: (.+)/))}" placeholder="it would pay for the kids' camp">
834
+ <div class="row" style="margin-top:8px"><button class="primary" id="knGoals">Save the goal</button></div>
835
+ </div>
836
+ <div class="panel step ${judged >= 5 ? "done" : ""}">
837
+ <h2><span class="n1">3</span>Your posts, one at a time</h2>
838
+ <div class="small muted">Your real posts from Posthuman (bring in your last 50 on its Accounts screen first). For each: so me, or not me, and why in a few words. Ten is plenty. Every answer goes into brand/voice.md as your own line.</div>
839
+ <div class="row" style="margin-top:8px"><button class="lit" id="knPast" ${KN.busy || !S.agent ? "disabled" : ""}>${KN.busy === "past" ? `<span class="spin"></span> Bringing them in…` : D.past.length ? "Bring in new ones" : "Bring in your past posts"}</button>${D.past.length ? `<span class="small muted">${judged} looked at · ${D.left} to go</span>` : ""}</div>
840
+ ${next ? `<div class="past-card">
841
+ <div class="small muted">${esc(next.account)} · ${esc(fmtDay(new Date(`${next.date}T12:00:00`)))}${next.stats ? ` · ${esc(next.stats)}` : ""}</div>
842
+ <div class="words">${esc(next.words)}</div>
843
+ <input type="text" id="pWhy" value="${esc(KN.why)}" placeholder="Why, in a few words (“the joke's on me”, “too salesy”)">
844
+ <div class="row" style="margin-top:8px"><button class="ok" data-v="so me">So me</button><button data-v="not me">Not me</button><button class="ghost" data-v="skip">Skip</button></div>
845
+ </div>` : D.past.length ? `<p class="small" style="margin-top:8px">That's all of them. Your agent writes from brand/voice.md now, and keeps learning from your edits.</p>` : ""}
846
+ </div>
847
+ </div>`;
848
+ const v = $("#v-know");
849
+ $("#knUrls").oninput = (e) => (KN.urls = e.target.value);
850
+ $("#knSync").onclick = async () => {
851
+ KN.busy = "sync"; KN.out = ""; drawKnow();
852
+ try {
853
+ const { job } = await api("POST", "/api/know/sync");
854
+ const j = await waitJob(job);
855
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
856
+ const sent = { saved: "Sent to Posthuman: your phone and other chats know it now.", suggested: "Posthuman already had an About you, so this folder's version waits there as a suggestion: take it or leave it on its Accounts screen.", same: "Posthuman already matches.", skipped: "Nothing here to send yet." }[j.result] || "";
857
+ KN.out = [j.filled?.length ? `Filled from Posthuman: ${j.filled.join(", ")}.` : "", sent].filter(Boolean).join(" ") || "Done.";
858
+ } catch (e) { KN.out = e.message; }
859
+ KN.busy = ""; if (view === "know") drawKnow(true);
860
+ };
861
+ $("#knRead").onclick = async () => {
862
+ const urls = KN.urls.split(/\s+/).filter(Boolean);
863
+ if (!urls.length) return alert("Paste a link or two first.");
864
+ KN.busy = "links"; KN.out = ""; drawKnow();
865
+ try {
866
+ const { job } = await api("POST", "/api/know/links", { urls });
867
+ const j = await waitJob(job);
868
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
869
+ KN.draft = j.about;
870
+ } catch (e) { KN.out = e.message; }
871
+ KN.busy = ""; if (view === "know") drawKnow();
872
+ };
873
+ $("#knSaveAbout") && ($("#knSaveAbout").onclick = async () => {
874
+ const lines = (id) => $(id).value.split("\n").map((x) => x.trim()).filter(Boolean);
875
+ await api("PUT", "/api/know/about", { what_it_is: $("#dWhat").value, who_its_for: $("#dWho").value, facts: lines("#dFacts"), links: lines("#dLinks") });
876
+ KN.draft = null; toast("Saved in brand/about.md"); drawKnow(true);
877
+ });
878
+ $("#knToss") && ($("#knToss").onclick = () => { KN.draft = null; drawKnow(); });
879
+ $("#knSay") && ($("#knSay").onclick = async () => {
880
+ const what = $("#sWhat").value.trim(), who = $("#sWho").value.trim();
881
+ if (!what && !who) return alert("A line or two is enough.");
882
+ const facts = A.what_it_is.split("\n").slice(1).map((x) => x.replace(/^- /, "")).filter(Boolean); // keep any facts already there
883
+ await api("PUT", "/api/know/about", { what_it_is: what, who_its_for: who, facts, links: [] });
884
+ toast("Saved in brand/about.md"); drawKnow(true);
885
+ });
886
+ v.querySelectorAll("[data-aim]").forEach((b) => (b.onclick = () => { const k = b.dataset.aim; KN.aims = KN.aims.includes(k) ? KN.aims.filter((x) => x !== k) : [...KN.aims, k]; b.classList.toggle("on"); }));
887
+ $("#knGoals").onclick = async () => {
888
+ try { await api("PUT", "/api/know/goals", { aims: KN.aims, number: $("#gNum").value, by: $("#gBy").value, why: $("#gWhy").value }); toast("Goal saved in brand/about.md"); drawKnow(true); }
889
+ catch (e) { alert(e.message); }
890
+ };
891
+ $("#knPast").onclick = async () => {
892
+ KN.busy = "past"; KN.out = ""; drawKnow();
893
+ try {
894
+ const { job } = await api("POST", "/api/know/past");
895
+ const j = await waitJob(job);
896
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
897
+ KN.out = j.none ? "No past posts in Posthuman yet. On its Accounts screen, press Bring in last 50 on each account, then come back." : j.count ? `Brought in ${j.count} posts.` : "Nothing new since last time.";
898
+ } catch (e) { KN.out = e.message; }
899
+ KN.busy = ""; if (view === "know") drawKnow(true);
900
+ };
901
+ $("#pWhy") && ($("#pWhy").oninput = (e) => (KN.why = e.target.value));
902
+ v.querySelectorAll("[data-v]").forEach((b) => (b.onclick = async () => {
903
+ if (b.dataset.v === "not me" && !KN.why.trim() && !confirm("No why? A few words (“too salesy”) is what teaches it. Save without one?")) return;
904
+ try { await api("POST", "/api/know/judge", { i: next.i, verdict: b.dataset.v, why: KN.why }); KN.why = ""; drawKnow(true); }
905
+ catch (e) { alert(e.message); }
906
+ }));
907
+ }
908
+
909
+ // ---------- Your stuff ----------
910
+
911
+ let ST = { data: null, days: 60, picked: new Set(), open: null, busy: "", out: "", where: false, chosen: {} };
912
+ const found = (p) => `/found?p=${encodeURIComponent(p)}&t=${TOKEN}`;
913
+ async function drawStuff(reload = false) {
914
+ if (!ST.data || reload) ST.data = await api("GET", `/api/stuff?days=${ST.days}`);
915
+ const D = ST.data;
916
+ const none = !D.sources.media.length && !D.sources.projects.length;
917
+ const byWeek = new Map();
918
+ for (const m of D.media) { const k = ymd(startOfWeek(new Date(m.mtime))); if (!byWeek.has(k)) byWeek.set(k, []); byWeek.get(k).push(m); }
919
+ const list = (key, xs, ph) => `<ul style="padding:0;margin:6px 0">${xs.map((x, i) => `<li><span>${esc(x)}</span><button class="ghost small" data-rmsrc="${key}" data-i="${i}" aria-label="Remove">✕</button></li>`).join("") || `<li class="muted">None yet.</li>`}</ul>
920
+ <div class="row" style="flex-wrap:nowrap"><input type="text" data-newsrc="${key}" placeholder="${ph}"><button data-addsrc="${key}">Add</button></div>`;
921
+ $("#v-stuff").innerHTML = head("Your stuff", "The screenshots, clips and projects you already have, right where they are. Nothing is copied or sent anywhere until you pick something.", `<div class="row">
922
+ <select id="stDays">${[[7, "This week"], [30, "Last 30 days"], [60, "Last 60 days"], [365, "This year"]].map(([d, l]) => `<option value="${d}" ${ST.days === d ? "selected" : ""}>${l}</option>`).join("")}</select>
923
+ <button class="lit" id="stPhone" ${ST.busy || !S.agent ? "disabled" : ""} title="What you saved for later on your phone (Posthuman): into the library and this week's raw">${ST.busy === "phone" ? `<span class="spin"></span> Bringing in…` : "Bring in from your phone"}</button></div>`) + `
924
+ ${ST.out ? `<div class="notes">${esc(ST.out)}</div>` : ""}
925
+ <details class="panel" ${none || ST.where ? "open" : ""} id="stWhere"><summary><b>Where to look</b> <span class="small muted">brand/sources.md</span></summary>
926
+ <div class="where" style="margin-top:10px">
927
+ <div><h3 class="label">Pictures and clips</h3><div class="small muted">Your Screenshots folder, screen recordings, the folder your phone's photos sync to.</div>${list("media", D.sources.media, "~/Pictures/Screenshots")}</div>
928
+ <div><h3 class="label">Projects</h3><div class="small muted">Folders with git: what you committed this week becomes raw material.</div>${list("projects", D.sources.projects, "~/code/my-app")}</div>
929
+ </div>
930
+ </details>
931
+ ${D.projects.length ? `<div class="panel project" style="margin-top:14px"><h3 class="label">This week in your projects</h3>${D.projects.map((p, i) => `<div style="margin-top:8px"><b>${esc(p.name)}</b> <span class="small muted">${p.commits} commit${p.commits === 1 ? "" : "s"} since Sunday</span>
932
+ ${p.subjects.length ? `<ul>${p.subjects.map((x, j) => `<li><label class="row" style="flex-wrap:nowrap;gap:6px"><input type="checkbox" data-pc="${i}" data-j="${j}" ${ST.chosen[`${i}:${j}`] ? "checked" : ""}> ${esc(x)}</label></li>`).join("")}</ul>` : ""}
933
+ ${p.commits ? `<button class="small" data-praw="${i}">Add to this week's raw</button>` : ""}</div>`).join("")}</div>` : ""}
934
+ <div class="row" style="margin-top:16px;justify-content:space-between">
935
+ <b>${D.media.length} picture${D.media.length === 1 ? "" : "s"} and clips</b>
936
+ <span class="row">${ST.picked.size ? `<span class="small muted">${ST.picked.size} picked</span>` : ""}<button class="primary" id="stDescribe" ${ST.busy || !S.agent || !D.media.length ? "disabled" : ""} title="Your agent looks at them and says what each shows and what post it could be (up to 12 at a time)">${ST.busy === "describe" ? `<span class="spin"></span> Looking…` : ST.picked.size ? "Describe the picked ones" : "Describe 12 new ones"}</button></span>
937
+ </div>
938
+ ${[...byWeek].map(([wk, ms]) => `<h3 class="label" style="margin-top:16px">Week of ${esc(fmtDay(new Date(`${wk}T12:00:00`)))}</h3><div class="stuff-grid">${ms.map((m) => `<div class="stuff ${ST.picked.has(m.path) ? "picked" : ""}">
939
+ <div class="pic" data-open="${esc(m.path)}">${m.kind === "video" ? `<video src="${found(m.path)}" muted preload="metadata"></video>` : `<img src="${found(m.path)}" alt="${esc(m.says || "")}" loading="lazy">`}<input type="checkbox" data-pick="${esc(m.path)}" ${ST.picked.has(m.path) ? "checked" : ""} aria-label="Pick"></div>
940
+ <div class="cap">${m.says ? `<span>${esc(m.says)}</span>` : `<span class="muted">${esc(m.shown.split("/").pop())}</span>`}${m.angle ? `<span class="angle">${esc(m.angle)}</span>` : ""}</div>
941
+ ${ST.open === m.path ? `<div class="acts"><button data-use="${esc(m.path)}" data-raw="1">Into this week's raw</button><button data-use="${esc(m.path)}" data-bs="1">Brainstorm from it</button><button class="ghost" data-use="${esc(m.path)}">Copy to library</button></div>` : ""}
942
+ </div>`).join("")}</div>`).join("") || (D.sources.media.length ? `<p class="small muted">Nothing in those folders from that time.</p>` : "")}`;
943
+ const v = $("#v-stuff");
944
+ $("#stWhere").ontoggle = (e) => (ST.where = e.target.open);
945
+ $("#stDays").onchange = (e) => { ST.days = Number(e.target.value); drawStuff(true); };
946
+ const saveSrc = async (next) => { try { await api("PUT", "/api/sources", next); ST.where = true; drawStuff(true); } catch (e) { alert(e.message); } };
947
+ v.querySelectorAll("[data-addsrc]").forEach((b) => (b.onclick = () => { const k = b.dataset.addsrc, val = v.querySelector(`[data-newsrc="${k}"]`).value.trim(); if (!val) return; saveSrc({ ...D.sources, [k]: [...D.sources[k], val] }); }));
948
+ v.querySelectorAll("[data-newsrc]").forEach((inp) => (inp.onkeydown = (e) => e.key === "Enter" && v.querySelector(`[data-addsrc="${inp.dataset.newsrc}"]`).click()));
949
+ v.querySelectorAll("[data-rmsrc]").forEach((b) => (b.onclick = () => { const k = b.dataset.rmsrc; saveSrc({ ...D.sources, [k]: D.sources[k].filter((_, i) => i !== Number(b.dataset.i)) }); }));
950
+ v.querySelectorAll("[data-pick]").forEach((c) => (c.onclick = (e) => { e.stopPropagation(); c.checked ? ST.picked.add(c.dataset.pick) : ST.picked.delete(c.dataset.pick); drawStuff(); }));
951
+ v.querySelectorAll("[data-open]").forEach((d) => (d.onclick = (e) => { if (e.target.matches("input")) return; ST.open = ST.open === d.dataset.open ? null : d.dataset.open; drawStuff(); }));
952
+ v.querySelectorAll("[data-pc]").forEach((c) => (c.onchange = () => (ST.chosen[`${c.dataset.pc}:${c.dataset.j}`] = c.checked)));
953
+ v.querySelectorAll("[data-praw]").forEach((b) => (b.onclick = async () => {
954
+ const i = Number(b.dataset.praw), p = D.projects[i];
955
+ const r = await api("GET", `/api/raw?week=${D.week}`);
956
+ const num = `${p.commits} commit${p.commits === 1 ? "" : "s"} on ${p.name} this week`;
957
+ r.numbers = [...r.numbers.filter((x) => !x.endsWith(`on ${p.name} this week`)), num];
958
+ const picked = p.subjects.filter((_, j) => ST.chosen[`${i}:${j}`]);
959
+ r.happened = [...r.happened, ...picked.map((x) => `${p.name}: ${x}`).filter((x) => !r.happened.includes(x))];
960
+ RAW = await api("PUT", "/api/raw", r); drawRailRaw();
961
+ toast(picked.length ? `Added the number and ${picked.length} thing${picked.length === 1 ? "" : "s"} you did` : "Added the number: tick commits to add what you did too");
962
+ }));
963
+ v.querySelectorAll("[data-use]").forEach((b) => (b.onclick = async () => {
964
+ const m = D.media.find((x) => x.path === b.dataset.use);
965
+ try {
966
+ const r = await api("POST", "/api/stuff/use", { path: m.path, raw: !!b.dataset.raw, note: m.says || "" });
967
+ await load(false);
968
+ if (b.dataset.bs) { BS.files = [...new Set([...BS.files, r.file])]; BS.text ||= m.angle || ""; location.hash = "#brainstorm"; return; }
969
+ toast(b.dataset.raw ? "In this week's raw (and the library)" : `In the library as ${r.file}`);
970
+ } catch (e) { alert(e.message); }
971
+ }));
972
+ $("#stDescribe").onclick = async () => {
973
+ const paths = ST.picked.size ? [...ST.picked] : D.media.filter((m) => !m.says && m.kind === "image").slice(0, 12).map((m) => m.path);
974
+ if (!paths.length) return alert("Everything here has been looked at. Pick some to look again.");
975
+ if (!confirm(`Have your agent look at ${Math.min(12, paths.length)} of your pictures? They're read on this computer by your own agent (Claude Code), nothing else.`)) return;
976
+ ST.busy = "describe"; ST.out = ""; drawStuff();
977
+ try {
978
+ const { job } = await api("POST", "/api/stuff/describe", { paths });
979
+ const j = await waitJob(job);
980
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
981
+ ST.picked.clear(); ST.out = `Looked at ${j.described}. What each shows and the post it could be are under the pictures (and in library/found.md).`;
982
+ } catch (e) { ST.out = e.message; }
983
+ ST.busy = ""; if (view === "stuff") drawStuff(true);
984
+ };
985
+ $("#stPhone").onclick = async () => {
986
+ ST.busy = "phone"; ST.out = ""; drawStuff();
987
+ try {
988
+ const { job } = await api("POST", "/api/stuff/phone");
989
+ const j = await waitJob(job);
990
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
991
+ ST.out = j.pulled?.length ? `Brought in ${j.pulled.length} from your phone: ${j.pulled.map((x) => x.note || x.file).join(", ")}. They're in the library and this week's raw.` : "Nothing new saved on your phone. Share a photo to Posthuman and tap Save for later.";
992
+ await load(false);
993
+ } catch (e) { ST.out = e.message; }
994
+ ST.busy = ""; if (view === "stuff") drawStuff(true);
995
+ };
996
+ }
997
+
998
+ // ---------- Accounts ----------
999
+
1000
+ let AC = { busy: false, out: "", sugg: {}, working: {} };
1001
+ const ROLE_TXT = { own: "its own posts, written for here", copy: "the same posts as my main account", big: "only the big moments" };
1002
+ function suggForm(a, x) {
1003
+ const id = a.account_id;
1004
+ const inp = (k, label, ph, max) => `<label class="small">${label}</label><input type="text" data-sg="${id}" data-k="${k}" maxlength="${max}" value="${esc(x[k] || "")}" placeholder="${esc(ph)}">`;
1005
+ const box = (k, label) => `<label class="small row" style="gap:6px"><input type="checkbox" data-sg="${id}" data-k="${k}" ${x[k] ? "checked" : ""}> ${label}</label>`;
1006
+ return `<div class="suggest" style="display:grid;gap:6px;margin-top:8px">
1007
+ <div class="small muted">Suggested${x.why ? `: ${esc(x.why)}` : ""}. Nothing is saved until you press Save.</div>
1008
+ ${inp("audience", "Who reads it", "parents of 5 to 8 year olds", 200)}
1009
+ ${inp("sound", "How you sound here", "warmer, shorter", 200)}
1010
+ <label class="small">What goes here</label><select data-sg="${id}" data-k="role">${Object.entries(ROLE_TXT).map(([k, v]) => `<option value="${k}" ${x.role === k ? "selected" : ""}>${esc(v)}</option>`).join("")}</select>
1011
+ ${inp("rhythm", "How often", "twice a week, mornings", 120)}
1012
+ <div class="row" style="gap:12px;flex-wrap:wrap">${box("no_hashtags", "no hashtags")}${box("no_links", "no links")}${box("no_emoji", "no emoji")}</div>
1013
+ ${inp("never_name", "Never name", "my day job, the kids' names", 200)}
1014
+ <label class="small">A post of yours that's so you</label><textarea rows="3" data-sg="${id}" data-k="example" maxlength="600">${esc(x.example || "")}</textarea>
1015
+ <div class="row"><button class="lit" data-save="${id}" ${AC.working[id] ? "disabled" : ""}>${AC.working[id] === "save" ? `<span class="spin"></span> Saving…` : "Save to Posthuman"}</button><button class="ghost" data-dismiss="${id}">Not this</button></div>
1016
+ </div>`;
1017
+ }
1018
+ function drawAccounts() {
1019
+ const A = S.accounts || { accounts: [] };
1020
+ const ph = A.posthuman ? `${A.posthuman}/accounts` : "";
1021
+ const synced = A.synced ? new Date(A.synced).toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "";
1022
+ const row = (k, v) => (v ? `<dt>${k}</dt><dd>${esc(Array.isArray(v) ? v.join("; ") : v)}</dd>` : "");
1023
+ const unset = A.accounts.filter((a) => !a.setup && a.account_id);
1024
+ const shown = Object.keys(AC.sugg).length;
1025
+ const busy = (id) => !!AC.working[id];
1026
+ $("#v-accounts").innerHTML = head("Accounts", "How each account works, as you set it up in Posthuman (Make it yours): who reads it, how you sound there, what goes there, how often, the hard no's. Your agent writes to fit it, and the Week flags a post that breaks a no.", `<div class="row">${ph ? `<a class="small" href="${esc(ph)}" target="_blank" rel="noopener">Change it in Posthuman ↗</a>` : ""}${unset.length > 1 ? `<button id="acSuggestAll" ${!S.agent || AC.working.all ? "disabled" : ""}>${AC.working.all ? `<span class="spin"></span> Suggesting…` : `You choose: suggest all ${unset.length}`}</button>` : ""}${shown > 1 ? `<button class="lit" id="acSaveAll" ${!S.agent ? "disabled" : ""}>Save all ${shown}</button>` : ""}<button class="lit" id="acRefresh" ${AC.busy || !S.agent ? "disabled" : ""}>${AC.busy ? `<span class="spin"></span> Refreshing…` : "Refresh from Posthuman"}</button></div>`) + needAgent() + `
1027
+ ${synced ? `<p class="small muted" style="margin-top:-6px">This copy is from ${esc(synced)} (brand/accounts.md).</p>` : `<div class="panel small" style="margin-bottom:14px">No copy here yet. Press <b>Refresh from Posthuman</b>, or open your agent in this folder: it refreshes the copy at the start of every session.</div>`}
1028
+ ${AC.out ? `<div class="notes">${esc(AC.out)}</div>` : ""}
1029
+ <div class="acct-grid">${A.accounts.map((a) => `<div class="panel acct-card ${a.setup ? "" : "unset"}">
1030
+ <div class="row" style="justify-content:space-between"><h3>${esc(a.account)}</h3><span>${a.intro === "yes" ? `<span class="pill">new here</span>` : ""}${a.setup ? "" : `<span class="pill">not set up</span>`}</span></div>
1031
+ ${a.setup ? `<dl>${row("Who reads it", a.setup.who_reads_it)}${row("Sounds", a.setup.sounds)}${row("What goes here", a.setup.what_goes_here)}${row("How often", a.setup.how_often)}${row("Never", a.setup.never)}</dl>${a.setup.like_this ? `<div class="example">${esc(a.setup.like_this)}</div>` : ""}`
1032
+ : AC.sugg[a.account_id] ? suggForm(a, AC.sugg[a.account_id])
1033
+ : `<p class="small">Six quick answers make it yours. Answer them in Posthuman${ph ? ` (<a href="${esc(ph)}" target="_blank" rel="noopener">Accounts</a>)` : ""}, tell your agent “set up my ${esc(platformOf(a.account).name)} account” (it asks one at a time), or let your agent suggest them from your posts.</p>
1034
+ ${a.account_id ? `<button data-suggest="${a.account_id}" ${!S.agent || busy(a.account_id) || AC.working.all ? "disabled" : ""}>${AC.working[a.account_id] === "suggest" ? `<span class="spin"></span> Reading your posts…` : "You choose: suggest the six"}</button>` : ""}`}
1035
+ ${a.intro === "yes" ? `<div class="row small" style="margin-top:10px;justify-content:space-between"><span class="muted">No posts here yet. Say hello first?</span><button data-intro="${esc(a.account)}" ${!S.agent || AC.working[`i${a.account_id}`] ? "disabled" : ""}>${AC.working[`i${a.account_id}`] ? `<span class="spin"></span> Writing…` : "Write an intro"}</button></div>` : ""}
1036
+ ${a.intro === "skip" ? `<p class="small muted" style="margin-top:10px">No posts here yet, but people find posts here by searching, so a hello reaches no one. Start with a real post.</p>` : ""}
1037
+ </div>`).join("")}</div>`;
1038
+ const v = $("#v-accounts");
1039
+ const answers = (id) => {
1040
+ const x = { ...AC.sugg[id] };
1041
+ v.querySelectorAll(`[data-sg="${id}"]`).forEach((el) => (x[el.dataset.k] = el.type === "checkbox" ? el.checked : el.value));
1042
+ return x;
1043
+ };
1044
+ v.querySelectorAll("[data-sg]").forEach((el) => (el.oninput = el.onchange = () => (AC.sugg[el.dataset.sg] = answers(el.dataset.sg))));
1045
+ const suggest = async (ids, key) => {
1046
+ ids.forEach((id) => (AC.working[id] = "suggest")); AC.working[key] = 1; AC.out = ""; drawAccounts();
1047
+ try {
1048
+ const { job } = await api("POST", "/api/accounts/suggest", { ids });
1049
+ const j = await waitJob(job);
1050
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
1051
+ for (const x of j.suggestions || []) AC.sugg[x.account_id] = x;
1052
+ if (!(j.suggestions || []).length) AC.out = "Your agent didn't suggest anything. Try again, or answer them in Posthuman.";
1053
+ } catch (e) { AC.out = e.message; }
1054
+ ids.forEach((id) => delete AC.working[id]); delete AC.working[key];
1055
+ if (view === "accounts") drawAccounts();
1056
+ };
1057
+ const save = async (ids) => {
1058
+ const items = ids.map((id) => ({ account_id: Number(id), ...answers(id) }));
1059
+ ids.forEach((id) => (AC.working[id] = "save")); AC.out = ""; drawAccounts();
1060
+ try {
1061
+ const { job } = await api("POST", "/api/accounts/save", { items });
1062
+ const j = await waitJob(job);
1063
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
1064
+ for (const id of j.saved || []) delete AC.sugg[id];
1065
+ const missed = (j.results || []).filter((r) => !r.saved);
1066
+ if (missed.length) AC.out = missed.map((r) => `Not saved (${r.account_id}): ${r.say || "Posthuman said no"}`).join("\n");
1067
+ await load(false); toast(`${(j.saved || []).length} saved to Posthuman`);
1068
+ } catch (e) { AC.out = e.message; }
1069
+ ids.forEach((id) => delete AC.working[id]);
1070
+ if (view === "accounts") drawAccounts();
1071
+ };
1072
+ v.querySelectorAll("[data-suggest]").forEach((b) => (b.onclick = () => suggest([Number(b.dataset.suggest)], `s${b.dataset.suggest}`)));
1073
+ $("#acSuggestAll") && ($("#acSuggestAll").onclick = () => suggest(unset.map((a) => a.account_id), "all"));
1074
+ v.querySelectorAll("[data-save]").forEach((b) => (b.onclick = () => save([b.dataset.save])));
1075
+ $("#acSaveAll") && ($("#acSaveAll").onclick = () => save(Object.keys(AC.sugg)));
1076
+ v.querySelectorAll("[data-dismiss]").forEach((b) => (b.onclick = () => { delete AC.sugg[b.dataset.dismiss]; drawAccounts(); }));
1077
+ v.querySelectorAll("[data-intro]").forEach((b) => (b.onclick = async () => {
1078
+ const a = A.accounts.find((x) => x.account === b.dataset.intro);
1079
+ const key = `i${a.account_id}`;
1080
+ AC.working[key] = 1; AC.out = ""; drawAccounts();
1081
+ try {
1082
+ const { job } = await api("POST", "/api/accounts/intro", { account: a.account });
1083
+ const j = await waitJob(job);
1084
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
1085
+ await load(false); toast(j.file ? `Intro drafted: ${j.file.replace(/^posts\//, "")}. It's on the Week, not scheduled.` : "Intro drafted. It's on the Week, not scheduled.");
1086
+ } catch (e) { AC.out = e.message; }
1087
+ delete AC.working[key];
1088
+ if (view === "accounts") drawAccounts();
1089
+ }));
1090
+ $("#acRefresh").onclick = async () => {
1091
+ AC.busy = true; AC.out = ""; drawAccounts();
1092
+ try {
1093
+ const { job } = await api("POST", "/api/accounts/refresh");
1094
+ const j = await waitJob(job);
1095
+ if (j.state !== "done") throw new Error((j.err || j.out || "It stopped.").slice(-400));
1096
+ await load(false); toast(`${j.count} account${j.count === 1 ? "" : "s"} refreshed`);
1097
+ } catch (e) { AC.out = e.message; }
1098
+ AC.busy = false; if (view === "accounts") drawAccounts();
1099
+ };
1100
+ }
1101
+
1102
+ // ---------- Make ----------
1103
+
1104
+ function drawMake() {
1105
+ const R = S.recipes || {}, K = S.keys || {};
1106
+ const photos = S.library.filter((x) => /\.(jpe?g|png|webp)$/i.test(x.file));
1107
+ const clips = S.library.filter((x) => /\.(mp4|mov)$/i.test(x.file));
1108
+ const opts = (xs) => xs.map((x) => `<option value="${esc(x.file)}">${esc(x.alt || x.file)}</option>`).join("");
1109
+ const missing = (k) => (k === "fal" ? !K.fal && "Add FAL_KEY to .env (fal.ai/dashboard/keys)." : !K.elevenlabs && "Add ELEVENLABS_API_KEY (and ELEVENLABS_VOICE_ID) to .env.");
1110
+ const card = (id, body) => `<div class="panel recipe"><h3>${esc(R[id]?.title || id)}</h3><div class="cost">${esc(R[id]?.cost || "")} · paid to the service with your key</div>${missing(R[id]?.needs) ? `<div class="needkey">${esc(missing(R[id].needs))}</div>` : ""}${body}<button class="lit" data-make="${id}" style="margin-top:12px" ${missing(R[id]?.needs) ? "disabled" : ""}>Make it</button><pre class="small" id="out-${id}" style="white-space:pre-wrap"></pre></div>`;
1111
+ $("#v-make").innerHTML = head("Make", "Pictures, clips and voiceovers, made on your computer with your own keys. Everything lands in the Library. Your own photos and clips beat made-up ones.") + `
1112
+ <div class="recipes">
1113
+ ${card("video", `<label>Your photo</label>${photos.length ? `<select id="m-photo">${opts(photos)}</select>` : `<div class="small muted">Add a photo to the Library first.</div>`}<label>The motion</label><input type="text" id="m-motion" placeholder="a slow push-in, steam rising from the mug">`)}
1114
+ ${card("voiceover", `<label>Your clip</label>${clips.length ? `<select id="m-clip">${opts(clips)}</select>` : `<div class="small muted">Add a clip to the Library first.</div>`}<label>Script (about 2.5 words a second)</label><textarea id="m-script" rows="3"></textarea><label>Voice id (optional)</label><input type="text" id="m-voice" placeholder="from .env if empty">`)}
1115
+ ${card("image", `<label>What it shows</label><input type="text" id="m-prompt" placeholder="a printed worksheet on a wooden kitchen table, morning light"><label>Shape</label><select id="m-size"><option value="4:5">4:5 Instagram</option><option value="2:3">2:3 Pinterest</option><option value="1:1">1:1 square</option><option value="9:16">9:16 Reels, TikTok</option></select>`)}
1116
+ </div>`;
1117
+ $("#v-make").querySelectorAll("[data-make]").forEach((b) => (b.onclick = async () => {
1118
+ const id = b.dataset.make, out = $(`#out-${id}`);
1119
+ const o = id === "video" ? { photo: $("#m-photo")?.value, motion: $("#m-motion").value } : id === "voiceover" ? { clip: $("#m-clip")?.value, script: $("#m-script").value, voice: $("#m-voice").value } : { prompt: $("#m-prompt").value, size: $("#m-size").value };
1120
+ if (!confirm(`Make it? It costs ${R[id].cost}, paid to the service with your key.`)) return;
1121
+ out.innerHTML = `<span class="spin"></span> Making…`;
1122
+ try {
1123
+ const r = await api("POST", "/api/make", { recipe: id, ...o });
1124
+ const j = await waitJob(r.job);
1125
+ out.textContent = j.state === "done" ? `Done: ${r.file}. It's in the Library.` : `It stopped:\n${(j.err || j.out).slice(-600)}`;
1126
+ await load(false);
1127
+ } catch (e) { out.textContent = e.message; }
1128
+ }));
1129
+ }
1130
+
1131
+ // ---------- Library ----------
1132
+
1133
+ function drawLibrary() {
1134
+ $("#v-library").innerHTML = head("Library", "Everything made or dropped in, newest first. Click one to describe it: the description becomes its alt text.") + `
1135
+ <div class="drop" id="libDrop">Drop pictures, clips or audio here</div>
1136
+ <div class="grid" style="margin-top:14px;grid-template-columns:repeat(auto-fill,minmax(150px,1fr))">${S.library.map(tile).join("")}</div>${S.library.length ? "" : `<p class="small muted">Nothing yet.</p>`}`;
1137
+ dropZone($("#libDrop"), () => drawLibrary());
1138
+ $("#v-library").querySelectorAll(".tile").forEach((t) => (t.onclick = async () => {
1139
+ const x = S.library.find((y) => y.file === t.dataset.file);
1140
+ const alt = prompt(`Describe ${x.file} in one sentence (alt text):`, x.alt || "");
1141
+ if (alt === null) return;
1142
+ await api("PUT", "/api/alt", { file: x.file, alt }); x.alt = alt; drawLibrary(); toast("Description saved");
1143
+ }));
1144
+ }
1145
+
1146
+ function dropZone(el, done) {
1147
+ el.ondragover = (e) => { e.preventDefault(); el.classList.add("over"); };
1148
+ el.ondragleave = () => el.classList.remove("over");
1149
+ el.ondrop = async (e) => {
1150
+ e.preventDefault(); el.classList.remove("over");
1151
+ for (const f of e.dataTransfer.files) {
1152
+ el.innerHTML = `<span class="spin"></span> Adding ${esc(f.name)}…`;
1153
+ try {
1154
+ const r = await api("POST", `/api/upload?name=${encodeURIComponent(f.name)}`, f, true);
1155
+ await load(); await done(r.file);
1156
+ toast(`Added ${r.file}`);
1157
+ } catch (err) { alert(err.message); }
1158
+ }
1159
+ };
1160
+ }
1161
+
1162
+ // ---------- keys, week nav ----------
1163
+
1164
+ $("#prev").onclick = () => { weekStart.setDate(weekStart.getDate() - 7); render(); };
1165
+ $("#next").onclick = () => { weekStart.setDate(weekStart.getDate() + 7); render(); };
1166
+ document.addEventListener("keydown", (e) => {
1167
+ if ((e.metaKey || e.ctrlKey) && e.key === "s") { e.preventDefault(); if (open?.dirty) save(); }
1168
+ if (e.key === "Escape") { if (document.querySelector(".drawer.open")) closeDrawers(); else if (open) closeSheet(); }
1169
+ if (e.key === "Enter" && e.target.classList?.contains("card")) openPost(e.target.dataset.slug);
1170
+ });
1171
+ window.addEventListener("beforeunload", (e) => { if (open?.dirty) { e.preventDefault(); e.returnValue = ""; } });
1172
+ window.addEventListener("focus", () => { if (!open && view === "week") load(); }); // the agent may have changed files meanwhile
1173
+
1174
+ load().then(() => {
1175
+ if (!location.hash && S.know?.todo === 3) location.hash = "#know"; // a new folder starts by getting to know them
1176
+ go();
1177
+ // start on the week of the next post that still needs you, if there is one
1178
+ const next = S.posts.filter((p) => p.date && ["draft", "approved"].includes(p.status)).map((p) => p.date).sort()[0];
1179
+ if (next && next > ymd(new Date(weekStart.getTime() + 6 * 864e5))) { weekStart = startOfWeek(new Date(`${next}T12:00:00`)); render(); }
1180
+ });
1181
+ </script>
1182
+ </body>
1183
+ </html>