@takeokunn/gbrainx 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -27
- package/dist/core.mjs +82 -34
- package/dist/gbrainx.mjs +81 -34
- package/dist/web/client/assets/{gbrainx-DfnQgPxe.js → gbrainx-DHJfi3id.js} +62 -8
- package/dist/web/client/assets/{manifest-813cc1a4.js → manifest-df2f285a.js} +1 -1
- package/dist/web/server/assets/{server-build-B915Unu9.js → server-build-BVJ_AFpB.js} +86 -38
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
# @takeokunn/gbrainx
|
|
2
2
|
|
|
3
|
-
The local app and command line for GbrainX, a marketplace for verified, secret-scrubbed [GBrain](https://github.com/garrytan/gbrain) memory packs.
|
|
4
|
-
|
|
5
|
-
## What it does
|
|
6
|
-
|
|
7
|
-
- Serves the app and its local API on `127.0.0.1:4747`. The API offers search, buy and load for packs, and four compile gates: pruning (classify), secret scrubbing, distillation and evaluation.
|
|
8
|
-
- Seeds its store from a folder of exported Markdown pages when you pass one on first start.
|
|
9
|
-
- Imports a purchased pack into a folder as Markdown files with front matter, keeping `[[wikilinks]]`.
|
|
3
|
+
The local app and command line for GbrainX, a marketplace for verified, secret-scrubbed [GBrain](https://github.com/garrytan/gbrain) memory packs. It serves the compile gates that turn exported GBrain pages into packs, serves packs to Claude Code through [`@takeokunn/gbrainx-mcp`](https://www.npmjs.com/package/@takeokunn/gbrainx-mcp), and imports purchased packs into a GBrain folder.
|
|
10
4
|
|
|
11
5
|
## Quick start
|
|
12
6
|
|
|
@@ -16,44 +10,36 @@ Requires Node.js 22.13 or later.
|
|
|
16
10
|
npx -y @takeokunn/gbrainx [brain-directory]
|
|
17
11
|
```
|
|
18
12
|
|
|
19
|
-
Open <http://127.0.0.1:4747/app
|
|
13
|
+
Open <http://127.0.0.1:4747/app>. The optional `brain-directory` is a folder of exported Markdown pages (for example from `gbrain export --dir ./my-brain-export`). It only seeds a store that does not exist yet.
|
|
20
14
|
|
|
21
|
-
To let Claude Code search, buy and load packs from the running app
|
|
15
|
+
To let Claude Code search, buy and load packs from the running app:
|
|
22
16
|
|
|
23
17
|
```sh
|
|
24
18
|
claude mcp add gbrainx -- npx -y @takeokunn/gbrainx-mcp
|
|
25
19
|
```
|
|
26
20
|
|
|
27
|
-
The MCP server offers `gbrainx.search`, `gbrainx.buy` and `gbrainx.load`. Keep the local app running while you use it.
|
|
28
|
-
|
|
29
21
|
## Commands
|
|
30
22
|
|
|
31
23
|
| Command | What it does |
|
|
32
24
|
| --- | --- |
|
|
33
|
-
| `npx -y @takeokunn/gbrainx [brain-directory]` | Start the local
|
|
34
|
-
| `npx -y @takeokunn/gbrainx import <packId> [--to <dir>] [--force]` | Write a purchased pack into `<dir>` (default `~/brain`)
|
|
35
|
-
| `npx -y @takeokunn/gbrainx cache clear` | Delete `~/.gbrainx/cache
|
|
25
|
+
| `npx -y @takeokunn/gbrainx [brain-directory]` | Start the app and its local API on `127.0.0.1:4747`. |
|
|
26
|
+
| `npx -y @takeokunn/gbrainx import <packId> [--to <dir>] [--force]` | Write a purchased pack into `<dir>` (default `~/brain`) as Markdown with front matter, keeping `[[wikilinks]]`. It stops on an existing file unless `--force` is given, and prints the `gbrain import` command to run next. It never writes into GBrain itself. |
|
|
27
|
+
| `npx -y @takeokunn/gbrainx cache clear` | Delete `~/.gbrainx/cache`. |
|
|
36
28
|
|
|
37
29
|
`import` reads the store, so start the app and buy the pack first. Imported pages carry `source: gbrainx` and are left out when you compile your own packs.
|
|
38
30
|
|
|
39
|
-
##
|
|
31
|
+
## Data
|
|
40
32
|
|
|
41
|
-
- `~/.gbrainx/store.json` holds
|
|
33
|
+
- `~/.gbrainx/store.json` holds pages, packs, wallet and purchases. `GBRAINX_STORE_DIR` selects another folder.
|
|
42
34
|
- `~/.gbrainx/cache/` holds content the MCP server has loaded.
|
|
43
|
-
- Pack content is not sent anywhere unless you use the model-assisted gates (see Limits).
|
|
44
35
|
|
|
45
36
|
## Limits
|
|
46
37
|
|
|
47
|
-
- The app listens on `127.0.0.1` only
|
|
48
|
-
- Purchases move a balance inside the local store
|
|
49
|
-
- The
|
|
50
|
-
- The `/app` screen keeps its
|
|
38
|
+
- The app listens on `127.0.0.1:4747` only.
|
|
39
|
+
- Purchases move a balance inside the local store; no real payment is made. A purchase is refused when the match score is below 0.5, or when it exceeds the per-purchase cap, the session cap or the balance.
|
|
40
|
+
- The `/api/claude/*` gate endpoints run `claude -p`: they need a logged-in Claude Code and send page text to the model. `GBRAINX_CLAUDE_EXECUTABLE` selects another executable.
|
|
41
|
+
- The `/app` screen keeps its data in browser storage. It does not call those endpoints or share data with the local store.
|
|
51
42
|
|
|
52
43
|
## Links
|
|
53
44
|
|
|
54
|
-
|
|
55
|
-
- MCP server: <https://www.npmjs.com/package/@takeokunn/gbrainx-mcp>
|
|
56
|
-
|
|
57
|
-
## License
|
|
58
|
-
|
|
59
|
-
MIT
|
|
45
|
+
[Source and issues](https://github.com/takeokunn/gbrainx) · [MCP server](https://www.npmjs.com/package/@takeokunn/gbrainx-mcp) · MIT
|
package/dist/core.mjs
CHANGED
|
@@ -741,6 +741,50 @@ function evaluateKeywords(markdown, keywords) {
|
|
|
741
741
|
missing
|
|
742
742
|
};
|
|
743
743
|
}
|
|
744
|
+
// ../core/src/double-charge-seed.ts
|
|
745
|
+
var doubleChargeSeed = {
|
|
746
|
+
"id": "stripe-double-charge-prevention",
|
|
747
|
+
"title": "Stripe Double-Charge Prevention",
|
|
748
|
+
"version": "v1",
|
|
749
|
+
"domain": "payments",
|
|
750
|
+
"errorSignatures": [
|
|
751
|
+
"double charge",
|
|
752
|
+
"charged twice",
|
|
753
|
+
"idempotency",
|
|
754
|
+
"orderKey",
|
|
755
|
+
"stripe double charge on retry"
|
|
756
|
+
],
|
|
757
|
+
"nodes": [
|
|
758
|
+
"stripe-idempotency",
|
|
759
|
+
"payment-retries",
|
|
760
|
+
"webhook-dedupe"
|
|
761
|
+
],
|
|
762
|
+
"markdown": "## [[stripe-idempotency]]\n\n# Stripe idempotency\n\nImport `orderKey` from `./pay-client.mjs` and use `payClient.charge(order, { orderKey: orderKey(order) })`. The key is derived from `order.merchantId`, `order.id`, and `order.revision`. Retry the same operation with the same values. A new revision represents a new operation. The client does not use `Idempotency-Key` for deduplication.\n\nSee [[payment-retries]] for retry handling and [[webhook-dedupe]] for duplicate events.\n\n\n## [[payment-retries]]\n\n# Payment retries\n\nRetry the same checkout operation with the same `order.merchantId`, `order.id`, and `order.revision`. Import `orderKey` from `./pay-client.mjs` and pass `orderKey(order)` as the `orderKey` option to `payClient.charge`. Generating a new key for each attempt can create a duplicate charge.\n\nSee [[stripe-idempotency]] and [[webhook-dedupe]] for the charge and event boundaries.\n\n\n## [[webhook-dedupe]]\n\n# Webhook deduplication\n\nUse the webhook event ID to detect duplicate deliveries before applying the event's effects. Record the ID only when processing succeeds, so a failed delivery can be retried.\n\nSee [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.\n\n\n## Sources\n\n- [[stripe-idempotency]]\n- [[payment-retries]]\n- [[webhook-dedupe]]",
|
|
763
|
+
"summary": "## symptom\n\nRetries can produce a duplicate charge. [payment-retries#2]\n\n## cause\n\nA new key on each attempt creates separate operations. [payment-retries#2]\n\n## fix\n\nImport orderKey from ./pay-client.mjs and pass orderKey(order) as the orderKey option to payClient.charge. [stripe-idempotency#2]\n\n## avoid\n\nDo not generate a new key for retries. [payment-retries#2]\n\n## verify\n\nDeduplicate webhook deliveries using the event ID after successful processing. [webhook-dedupe#2]",
|
|
764
|
+
"pages": [
|
|
765
|
+
{
|
|
766
|
+
"id": "stripe-idempotency",
|
|
767
|
+
"markdown": "# Stripe idempotency\n\nImport `orderKey` from `./pay-client.mjs` and use `payClient.charge(order, { orderKey: orderKey(order) })`. The key is derived from `order.merchantId`, `order.id`, and `order.revision`. Retry the same operation with the same values. A new revision represents a new operation. The client does not use `Idempotency-Key` for deduplication.\n\nSee [[payment-retries]] for retry handling and [[webhook-dedupe]] for duplicate events.\n"
|
|
768
|
+
},
|
|
769
|
+
{
|
|
770
|
+
"id": "payment-retries",
|
|
771
|
+
"markdown": "# Payment retries\n\nRetry the same checkout operation with the same `order.merchantId`, `order.id`, and `order.revision`. Import `orderKey` from `./pay-client.mjs` and pass `orderKey(order)` as the `orderKey` option to `payClient.charge`. Generating a new key for each attempt can create a duplicate charge.\n\nSee [[stripe-idempotency]] and [[webhook-dedupe]] for the charge and event boundaries.\n"
|
|
772
|
+
},
|
|
773
|
+
{
|
|
774
|
+
"id": "webhook-dedupe",
|
|
775
|
+
"markdown": "# Webhook deduplication\n\nUse the webhook event ID to detect duplicate deliveries before applying the event's effects. Record the ID only when processing succeeds, so a failed delivery can be retried.\n\nSee [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.\n"
|
|
776
|
+
}
|
|
777
|
+
],
|
|
778
|
+
"scrubbed": [],
|
|
779
|
+
"eval": {
|
|
780
|
+
"without": "Not recorded",
|
|
781
|
+
"with": "Not recorded",
|
|
782
|
+
"recorded": true
|
|
783
|
+
},
|
|
784
|
+
"priceUsd": .5,
|
|
785
|
+
"author": "seed",
|
|
786
|
+
"createdAt": "2026-01-01T00:00:00.000Z"
|
|
787
|
+
};
|
|
744
788
|
// ../core/src/import-files.ts
|
|
745
789
|
function safeSegment(value) {
|
|
746
790
|
return typeof value === "string" && value.length > 0 && value !== "." && value !== ".." && !Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 || "<>:\"/\\|?*[]".includes(char)) && !/[. ]$/.test(value) && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value);
|
|
@@ -1237,40 +1281,44 @@ function createInitialStore() {
|
|
|
1237
1281
|
},
|
|
1238
1282
|
ledger: [],
|
|
1239
1283
|
sessions: [],
|
|
1240
|
-
packs: [
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1284
|
+
packs: [
|
|
1285
|
+
{
|
|
1286
|
+
...common,
|
|
1287
|
+
id: "stripe-webhook-signature-errors",
|
|
1288
|
+
title: "Stripe Webhook Signature Errors",
|
|
1289
|
+
version: "v3",
|
|
1290
|
+
domain: "payments",
|
|
1291
|
+
errorSignatures: ["webhook signature verification failed", "raw body parsing"],
|
|
1292
|
+
nodes: ["stripe-webhook-signature", "raw-body-parsing"],
|
|
1293
|
+
markdown: "Verify the webhook signature against the raw request body.",
|
|
1294
|
+
summary: "Verify the webhook signature against the raw request body.",
|
|
1295
|
+
pages: [{
|
|
1296
|
+
id: "stripe-webhook-signature",
|
|
1297
|
+
markdown: "Verify the webhook signature against the raw request body."
|
|
1298
|
+
}, {
|
|
1299
|
+
id: "raw-body-parsing",
|
|
1300
|
+
markdown: "Keep the raw request body for verification."
|
|
1301
|
+
}],
|
|
1302
|
+
priceUsd: .5
|
|
1303
|
+
},
|
|
1304
|
+
{
|
|
1305
|
+
...common,
|
|
1306
|
+
id: "postgres-zero-downtime-migrations",
|
|
1307
|
+
title: "Postgres Zero-Downtime Migrations",
|
|
1308
|
+
version: "v2",
|
|
1309
|
+
domain: "data",
|
|
1310
|
+
errorSignatures: ["database migration downtime", "add column safely"],
|
|
1311
|
+
nodes: ["pg-add-column-safely"],
|
|
1312
|
+
markdown: "Add columns in stages and migrate data before enforcing constraints.",
|
|
1313
|
+
summary: "Add columns in stages and migrate data before enforcing constraints.",
|
|
1314
|
+
pages: [{
|
|
1315
|
+
id: "pg-add-column-safely",
|
|
1316
|
+
markdown: "Add columns in stages and migrate data before enforcing constraints."
|
|
1317
|
+
}],
|
|
1318
|
+
priceUsd: .8
|
|
1319
|
+
},
|
|
1320
|
+
structuredClone(doubleChargeSeed)
|
|
1321
|
+
]
|
|
1274
1322
|
};
|
|
1275
1323
|
}
|
|
1276
1324
|
function createSkillMarkdown(pack) {
|
package/dist/gbrainx.mjs
CHANGED
|
@@ -5631,6 +5631,49 @@ function classifyParagraphs(pages) {
|
|
|
5631
5631
|
});
|
|
5632
5632
|
});
|
|
5633
5633
|
}
|
|
5634
|
+
var doubleChargeSeed = {
|
|
5635
|
+
"id": "stripe-double-charge-prevention",
|
|
5636
|
+
"title": "Stripe Double-Charge Prevention",
|
|
5637
|
+
"version": "v1",
|
|
5638
|
+
"domain": "payments",
|
|
5639
|
+
"errorSignatures": [
|
|
5640
|
+
"double charge",
|
|
5641
|
+
"charged twice",
|
|
5642
|
+
"idempotency",
|
|
5643
|
+
"orderKey",
|
|
5644
|
+
"stripe double charge on retry"
|
|
5645
|
+
],
|
|
5646
|
+
"nodes": [
|
|
5647
|
+
"stripe-idempotency",
|
|
5648
|
+
"payment-retries",
|
|
5649
|
+
"webhook-dedupe"
|
|
5650
|
+
],
|
|
5651
|
+
"markdown": "## [[stripe-idempotency]]\n\n# Stripe idempotency\n\nImport `orderKey` from `./pay-client.mjs` and use `payClient.charge(order, { orderKey: orderKey(order) })`. The key is derived from `order.merchantId`, `order.id`, and `order.revision`. Retry the same operation with the same values. A new revision represents a new operation. The client does not use `Idempotency-Key` for deduplication.\n\nSee [[payment-retries]] for retry handling and [[webhook-dedupe]] for duplicate events.\n\n\n## [[payment-retries]]\n\n# Payment retries\n\nRetry the same checkout operation with the same `order.merchantId`, `order.id`, and `order.revision`. Import `orderKey` from `./pay-client.mjs` and pass `orderKey(order)` as the `orderKey` option to `payClient.charge`. Generating a new key for each attempt can create a duplicate charge.\n\nSee [[stripe-idempotency]] and [[webhook-dedupe]] for the charge and event boundaries.\n\n\n## [[webhook-dedupe]]\n\n# Webhook deduplication\n\nUse the webhook event ID to detect duplicate deliveries before applying the event's effects. Record the ID only when processing succeeds, so a failed delivery can be retried.\n\nSee [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.\n\n\n## Sources\n\n- [[stripe-idempotency]]\n- [[payment-retries]]\n- [[webhook-dedupe]]",
|
|
5652
|
+
"summary": "## symptom\n\nRetries can produce a duplicate charge. [payment-retries#2]\n\n## cause\n\nA new key on each attempt creates separate operations. [payment-retries#2]\n\n## fix\n\nImport orderKey from ./pay-client.mjs and pass orderKey(order) as the orderKey option to payClient.charge. [stripe-idempotency#2]\n\n## avoid\n\nDo not generate a new key for retries. [payment-retries#2]\n\n## verify\n\nDeduplicate webhook deliveries using the event ID after successful processing. [webhook-dedupe#2]",
|
|
5653
|
+
"pages": [
|
|
5654
|
+
{
|
|
5655
|
+
"id": "stripe-idempotency",
|
|
5656
|
+
"markdown": "# Stripe idempotency\n\nImport `orderKey` from `./pay-client.mjs` and use `payClient.charge(order, { orderKey: orderKey(order) })`. The key is derived from `order.merchantId`, `order.id`, and `order.revision`. Retry the same operation with the same values. A new revision represents a new operation. The client does not use `Idempotency-Key` for deduplication.\n\nSee [[payment-retries]] for retry handling and [[webhook-dedupe]] for duplicate events.\n"
|
|
5657
|
+
},
|
|
5658
|
+
{
|
|
5659
|
+
"id": "payment-retries",
|
|
5660
|
+
"markdown": "# Payment retries\n\nRetry the same checkout operation with the same `order.merchantId`, `order.id`, and `order.revision`. Import `orderKey` from `./pay-client.mjs` and pass `orderKey(order)` as the `orderKey` option to `payClient.charge`. Generating a new key for each attempt can create a duplicate charge.\n\nSee [[stripe-idempotency]] and [[webhook-dedupe]] for the charge and event boundaries.\n"
|
|
5661
|
+
},
|
|
5662
|
+
{
|
|
5663
|
+
"id": "webhook-dedupe",
|
|
5664
|
+
"markdown": "# Webhook deduplication\n\nUse the webhook event ID to detect duplicate deliveries before applying the event's effects. Record the ID only when processing succeeds, so a failed delivery can be retried.\n\nSee [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.\n"
|
|
5665
|
+
}
|
|
5666
|
+
],
|
|
5667
|
+
"scrubbed": [],
|
|
5668
|
+
"eval": {
|
|
5669
|
+
"without": "Not recorded",
|
|
5670
|
+
"with": "Not recorded",
|
|
5671
|
+
"recorded": true
|
|
5672
|
+
},
|
|
5673
|
+
"priceUsd": .5,
|
|
5674
|
+
"author": "seed",
|
|
5675
|
+
"createdAt": "2026-01-01T00:00:00.000Z"
|
|
5676
|
+
};
|
|
5634
5677
|
function safeSegment(value) {
|
|
5635
5678
|
return typeof value === "string" && value.length > 0 && value !== "." && value !== ".." && !Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 || "<>:\"/\\|?*[]".includes(char)) && !/[. ]$/.test(value) && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value);
|
|
5636
5679
|
}
|
|
@@ -5813,40 +5856,44 @@ function createInitialStore() {
|
|
|
5813
5856
|
},
|
|
5814
5857
|
ledger: [],
|
|
5815
5858
|
sessions: [],
|
|
5816
|
-
packs: [
|
|
5817
|
-
|
|
5818
|
-
|
|
5819
|
-
|
|
5820
|
-
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
|
|
5824
|
-
|
|
5825
|
-
|
|
5826
|
-
|
|
5827
|
-
|
|
5828
|
-
|
|
5829
|
-
|
|
5830
|
-
|
|
5831
|
-
|
|
5832
|
-
|
|
5833
|
-
|
|
5834
|
-
|
|
5835
|
-
|
|
5836
|
-
|
|
5837
|
-
|
|
5838
|
-
|
|
5839
|
-
|
|
5840
|
-
|
|
5841
|
-
|
|
5842
|
-
|
|
5843
|
-
|
|
5844
|
-
|
|
5845
|
-
|
|
5846
|
-
|
|
5847
|
-
|
|
5848
|
-
|
|
5849
|
-
|
|
5859
|
+
packs: [
|
|
5860
|
+
{
|
|
5861
|
+
...common,
|
|
5862
|
+
id: "stripe-webhook-signature-errors",
|
|
5863
|
+
title: "Stripe Webhook Signature Errors",
|
|
5864
|
+
version: "v3",
|
|
5865
|
+
domain: "payments",
|
|
5866
|
+
errorSignatures: ["webhook signature verification failed", "raw body parsing"],
|
|
5867
|
+
nodes: ["stripe-webhook-signature", "raw-body-parsing"],
|
|
5868
|
+
markdown: "Verify the webhook signature against the raw request body.",
|
|
5869
|
+
summary: "Verify the webhook signature against the raw request body.",
|
|
5870
|
+
pages: [{
|
|
5871
|
+
id: "stripe-webhook-signature",
|
|
5872
|
+
markdown: "Verify the webhook signature against the raw request body."
|
|
5873
|
+
}, {
|
|
5874
|
+
id: "raw-body-parsing",
|
|
5875
|
+
markdown: "Keep the raw request body for verification."
|
|
5876
|
+
}],
|
|
5877
|
+
priceUsd: .5
|
|
5878
|
+
},
|
|
5879
|
+
{
|
|
5880
|
+
...common,
|
|
5881
|
+
id: "postgres-zero-downtime-migrations",
|
|
5882
|
+
title: "Postgres Zero-Downtime Migrations",
|
|
5883
|
+
version: "v2",
|
|
5884
|
+
domain: "data",
|
|
5885
|
+
errorSignatures: ["database migration downtime", "add column safely"],
|
|
5886
|
+
nodes: ["pg-add-column-safely"],
|
|
5887
|
+
markdown: "Add columns in stages and migrate data before enforcing constraints.",
|
|
5888
|
+
summary: "Add columns in stages and migrate data before enforcing constraints.",
|
|
5889
|
+
pages: [{
|
|
5890
|
+
id: "pg-add-column-safely",
|
|
5891
|
+
markdown: "Add columns in stages and migrate data before enforcing constraints."
|
|
5892
|
+
}],
|
|
5893
|
+
priceUsd: .8
|
|
5894
|
+
},
|
|
5895
|
+
structuredClone(doubleChargeSeed)
|
|
5896
|
+
]
|
|
5850
5897
|
};
|
|
5851
5898
|
}
|
|
5852
5899
|
// startup-error.mjs
|
|
@@ -23,27 +23,81 @@ Use the webhook event ID to detect duplicate deliveries before applying the even
|
|
|
23
23
|
|
|
24
24
|
See [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.
|
|
25
25
|
`,_=[{kind:`STRIPE_KEY`,pattern:/\bsk_(?:live|test)_[0-9A-Za-z]{8,}/g},{kind:`API_KEY`,pattern:/\bsk-[0-9A-Za-z_-]{16,}/g},{kind:`AWS_KEY`,pattern:/AKIA[0-9A-Z]{16}/g},{kind:`GITHUB_TOKEN`,pattern:/\bgh[pousr]_[0-9A-Za-z]{20,}/g},{kind:`JWT`,pattern:/(?<![\w-])eyJ[\w-]+\.[\w-]+\.[\w-]+/g},{kind:`CONNECTION`,pattern:/\b[a-zA-Z][a-zA-Z0-9+.-]{0,31}:\/\/[^\s/@]+@/g},{kind:`QUERY_TOKEN`,pattern:/[?&](?:access_token|token|api_key|apikey|key|secret|password)=([^&#\s]+)/gi,group:1},{kind:`ENV`,pattern:/^[ \t]*(?:export[ \t]+)?[A-Za-z_][A-Za-z0-9_]{0,127}[ \t]*=[ \t]*("[^\r\n]*|'[^\r\n]*|[^\s#]+)/gm,group:1},{kind:`EMAIL`,pattern:/[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63}){1,8}/g},{kind:`HOST`,pattern:/[\w.-]{1,253}\.(?:local|internal|corp)\b/gi},{kind:`IP`,pattern:/\b(?:\d{1,3}\.){3}\d{1,3}\b/g}];function v(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let n=0;for(let r of t.values()){let t=r/e.length;n-=t*Math.log2(t)}return n}var y=/(?:\/(?:Users|home)\/[^/\s\\]+(?:\/|\\)|\b[A-Za-z]:\\Users\\[^/\s\\]+\\)/gi,b=/~[\\/]\.gbrain(?:[\\/](?:\\[ \t]|[^\s\]})"'<>,;])*)?(?=$|[\s\]})"'<>,;])/gi;function x(e,t){let n=e.split(/(?<=\n)|(?<=\r)(?!\n)/),r=-1,i=``;for(let e=0;e<n.length;e++){let a=n[e],o=/^ {0,3}(`{3,}|~{3,})/.exec(a)?.[1];if(o)i?o[0]===i[0]&&o.length>=i.length&&(i=``):i=o;else if(!i&&/^\uFEFF?(?:---|\.\.\.)[ \t]*(?:#.*)?(?:\r\n|\n|\r)?$/.test(a)){if(r<0)a.replace(/^\uFEFF/,``).startsWith(`---`)&&(r=e);else{for(let i=r+1;i<e;i++){let r=/^[ \t]*(?:-[ \t]+)?\?[ \t]+["']?(raw_source|source_path|source_file|source_uri|source_url|import_source|transcript_source|original_source|origin|source)["']?[ \t]*(?:\r\n|\n|\r)$/i.exec(n[i]);if(r&&i+1<e){let a=/^([ \t]*:[ \t]*)([^\r\n]*)(\r\n|\n|\r|$)/.exec(n[i+1]);if(a){let o=a[2],s=i+2,c=/^[ \t]*/.exec(n[i+1])[0].length;for(;s<e&&(!n[s].trim()||/^[ \t]+\S/.test(n[s])&&/^[ \t]*/.exec(n[s])[0].length>c);)o+=a[3]+n[s].replace(/(?:\r\n|\n|\r)$/,``),n[s++]=``;let l=r[1].toLowerCase()===`source`&&/^(?:gbrainx|"gbrainx"|'gbrainx')\s*(?:#.*)?$/i.test(a[2]);l&&o===a[2]||t(o),n[i]=l?`source: gbrainx${a[3]}`:``,n[i+1]=``,i=s-1;continue}}if(/[{,][ \t]*["']?(?:raw_source|source_path|source_file|source_uri|source_url|import_source|transcript_source|original_source|origin|source)["']?[ \t]*:/i.test(n[i])||/[{,][ \t]*"[^"\r\n]*\\/.test(n[i])){let e=n[i].replace(/(?:\r\n|\n|\r)$/,``),r=n[i].slice(e.length),a=/[{,][ \t]*["']?source["']?[ \t]*:[ \t]*(?:gbrainx|"gbrainx"|'gbrainx')[ \t]*(?=[,}])/i.test(e),o=/^[ \t]*/.exec(e)[0];t(e),n[i]=a?`${o}source: gbrainx${r}`:``;continue}let a=/^([ \t]*(?:-[ \t]+)*("(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z_][A-Za-z0-9_-]*)[ \t]*:[ \t]*)([^\r\n]*)(\r\n|\n|\r|$)/.exec(n[i]),o=/^[ \t]*/.exec(n[i])[0].length,s=i+1<e&&/^[ \t]+\S/.test(n[i+1])&&!/^[ \t]+["']?[A-Za-z_][A-Za-z0-9_-]*["']?[ \t]*:/.test(n[i+1]);if(!a)continue;let c=a[2].replace(/^["']|["']$/g,``),l=c.replace(/\\x([0-9a-f]{2})|\\u([0-9a-f]{4})/gi,(e,t,n)=>String.fromCharCode(parseInt(t??n,16))).toLowerCase();if(!/^(?:raw_source|source_path|source_file|source_uri|source_url|import_source|transcript_source|original_source|origin|source)$/.test(l)&&!c.includes(`\\`))continue;if(l===`source`&&/^(?:gbrainx|"gbrainx"|'gbrainx')\s*(?:#.*)?$/i.test(a[3])){if(s){let r=[],o=i+1;for(;o<e&&/^[ \t]+\S/.test(n[o])&&!/^[ \t]+["']?[A-Za-z_][A-Za-z0-9_-]*["']?[ \t]*:/.test(n[o]);)r.push(n[o].replace(/(?:\r\n|\n|\r)$/,``)),n[o++]=``;t(r.join(a[4])),i=o-1}continue}let u=a[3],d=i+1,f=u[0]===`"`||u[0]===`'`?u[0]:``,p=(e,t)=>{for(let n=t;n<e.length;n++)if(f===`"`&&e[n]===`\\`)n++;else if(e[n]===f){if(f===`'`&&e[n+1]===`'`)n++;else return!0}return!1};if(f&&!p(u,1))for(;d<e;){let e=n[d].replace(/(?:\r\n|\n|\r)$/,``);if(u+=a[4]+e,n[d++]=``,p(e,0))break}else if(!f)for(;d<e&&(!n[d].trim()||/^[ \t]+\S/.test(n[d])&&/^[ \t]*/.exec(n[d])[0].length>o);)u+=a[4]+n[d].replace(/(?:\r\n|\n|\r)$/,``),n[d++]=``;t(u),n[i]=``,i=d-1}r=-1}}}return n.join(``)}function S(e){return/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(e)?e.split(`-`).filter(e=>/^[a-z]{3,}$/.test(e)).length>=2:!1}function C(e){if(/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(e))return!0;let t=/^(.*)-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.exec(e);return t&&(e=t[1]),S(e)?!0:/^(?:[a-z0-9]+(?:[-_][a-z0-9]+)*|[A-Z][a-z]+)$/.test(e)?e.split(/[-_]/).every(e=>{let t=e.match(/(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])/g);return!(e.length>=20&&/[a-z]/.test(e)&&/[0-9]/.test(e)&&v(e)>=4)&&(t?.length??0)<=2&&!/^[a-f0-9]{20,}$/.test(e)}):!1}function w(e){if(/^sk-[A-Za-z0-9_-]{16,}$/.test(e))return!0;if(/^[a-f0-9]{20,}$/i.test(e)&&/[a-f]/i.test(e)&&/[0-9]/.test(e))return v(e.toLowerCase())>=3.2;if(e.startsWith(`REDACTED_`)||v(e)<4||e.includes(`-`)&&C(e))return!1;if(e.includes(`/`)){let t=e.split(`/`).filter(Boolean);if(t.length>1&&t.every(C))return!1}return!0}function T(e,t,n){let r=/^[A-Za-z0-9]+$/.test(t),i=0,a=0,o=[];for(;;){let s=e.indexOf(t,a);if(s<0)break;let c=s+t.length;r&&(/[A-Za-z0-9]/.test(e[s-1]??``)||/[A-Za-z0-9]/.test(e[c]??``))?a=s+1:(o.push(e.slice(i,s),n()),i=c,a=c)}return o.push(e.slice(i)),o.join(``)}function E(e,t){let n=new Set;for(let t of e)for(let e of[t.title,t.id,...t.markdown.match(/\b[A-Z][a-zA-Z]{2,}\b/g)??[]])e.trim()&&n.add(e.trim());let r=[...n].sort((e,t)=>t.length-e.length||e.localeCompare(t));return{terms:r,shared:r.filter(e=>t.some(t=>t.includes(e)))}}function D(e,t={terms:[],shared:[]}){let n=e,r=[],i=new Map,a=new Map,o=(e,t)=>{let n=`${e}\0${t}`,o=i.get(n);if(!o){let t=(a.get(e)??0)+1;a.set(e,t),o=`[REDACTED_${e}_${t}]`,i.set(n,o)}return r.push({kind:e,before:t,after:o}),o},s=0,c=0,l=[];for(;;){let e=n.indexOf(`-----BEGIN `,s);if(e<0)break;let t=n.indexOf(`
|
|
26
|
-
`,e);if(t<0)break;let r=n.slice(e,t).trimEnd(),i=/^-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----$/.exec(r);if(!i){s=t+1;continue}let a=`-----END ${i[1]}-----`,u=n.indexOf(a,t);if(u<0)break;let d=u+a.length;l.push(n.slice(c,e),o(`PRIVATE_KEY`,n.slice(e,d))),s=d,c=d}l.push(n.slice(c)),n=l.join(``),n=n.replace(y,e=>(r.push({kind:`HOME_PATH`,before:e,after:`~/`}),`~/`)),n=n.replace(b,e=>o(`GBRAIN_PATH`,e)),n=x(n,e=>o(`SOURCE`,e));for(let{kind:e,pattern:t,group:r}of _)n=n.replace(t,(...t)=>{let n=t[0],i=r?t[r]:n;if(/^\[REDACTED_[A-Z_]+_\d+\]$/.test(i))return n;let a=o(e,i);return r?n.slice(0,n.lastIndexOf(i))+a:a});n=n.replace(/[A-Za-z0-9+/_=-]{20,}/g,e=>w(e)?o(`ENTROPY`,e):e);for(let e of t.terms)e&&n.includes(e)&&(n=n.split(/(\[REDACTED_[A-Z_]+_\d+\])/g).map(t=>/^\[REDACTED_[A-Z_]+_\d+\]$/.test(t)?t:T(t,e,()=>o(`NAME`,e))).join(``));let u=[...new Set(r.map(e=>e.kind))].map(e=>({kind:e,count:r.filter(t=>t.kind===e).length}));return{markdown:n,scrubbed:u,changes:r,remaining:O(n,t)}}function O(e,t){let n=0;n+=[...e.matchAll(y)].length,n+=[...e.matchAll(b)].length,x(e,()=>(n++,``)),/-----BEGIN [A-Z ]{0,32}PRIVATE KEY-----/.test(e)&&n++;for(let{pattern:t,group:r}of _)for(let i of e.matchAll(t))/^\[REDACTED_[A-Z_]+_\d+\]$/.test(r?i[r]:i[0])||n++;for(let t of e.matchAll(/[A-Za-z0-9+/_=-]{20,}/g))w(t[0])&&n++;let r=e.split(/\[REDACTED_[A-Z_]+_\d+\]/g);for(let e of t.terms){if(!e)continue;let t=!1;for(let n of r)if(n.includes(e)&&(T(n,e,()=>(t=!0,``)),t))break;t&&n++}return n}function k(e,t){return O(e,t??{terms:[],shared:[]})}function A(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0&&Number.isSafeInteger(Math.round(e*100))&&Math.round(e*100)/100===e}function ee(e,t,n){return e.sessions.find(e=>e.id===t)??{id:t,startedAt:n,spentUsd:0,calls:[]}}function te(e,t){let n=e.sessions.findIndex(e=>e.id===t.id);return n<0?[...e.sessions,t]:e.sessions.map((e,r)=>r===n?t:e)}function j(e,t){return e.ledger.some(e=>e.packId===t)}function M(e,t,n,r){let i=e.packs.find(e=>e.id===t);if(!i)return{ok:!1,code:`pack_not_found`};if(j(e,t))return{ok:!0};let a=e.sessions.find(e=>e.id===n)?.spentUsd??0;if(![i.priceUsd,e.wallet.buyerUsd,e.wallet.perPurchaseCapUsd,e.wallet.sessionCapUsd,a].every(A))return{ok:!1,code:`invalid_amount`};let o=Math.round(i.priceUsd*100);return o>Math.round(e.wallet.buyerUsd*100)?{ok:!1,code:`insufficient_balance`,needsApproval:!0}:o>Math.round(e.wallet.perPurchaseCapUsd*100)?{ok:!1,code:`over_purchase_cap`,needsApproval:!0}:o+Math.round(a*100)>Math.round(e.wallet.sessionCapUsd*100)?{ok:!1,code:`over_session_cap`,needsApproval:!0}:!Number.isFinite(r)||r<.5||r>1?{ok:!1,code:`low_score`,needsApproval:!0}:{ok:!0}}function ne(e,t,n,r,i,a,o,s){let c=e.ledger.find(e=>e.packId===t);if(c)return{ok:!0,store:e,tx:c,rev:e.rev,alreadyPurchased:!0};if(e.rev!==o)return{ok:!1,code:`revision_conflict`};let l=M(e,t,n,s);if(!l.ok)return l;if(e.ledger.some(e=>e.id===a))return{ok:!1,code:`duplicate_tx_id`};let u=e.packs.find(e=>e.id===t),d=ee(e,n,i),f=Math.round(u.priceUsd*100),p=Math.round(f*.9),m={id:a,packId:t,sessionId:n,at:i,amountUsd:f/100,authorUsd:p/100,feeUsd:(f-p)/100,via:r,result:`running`,pagesUsed:[]},h={...d,spentUsd:(Math.round(d.spentUsd*100)+f)/100,calls:[...d.calls,{tool:`buy`,at:i,summary:t,txId:a}]},g={...e,rev:e.rev+1,wallet:{...e.wallet,buyerUsd:(Math.round(e.wallet.buyerUsd*100)-f)/100},ledger:[...e.ledger,m],sessions:te(e,h)};return{ok:!0,store:g,tx:m,rev:g.rev,alreadyPurchased:!1}}function re(e,t,n){let r=e.packs.find(e=>e.id===t);if(!r)return{ok:!1,code:`pack_not_found`};if(!j(e,t))return{ok:!1,code:`not_purchased`};if(n===void 0)return{ok:!0,content:r.summary,pages:r.pages.map(e=>e.id)};let i=r.pages.find(e=>e.id===n);return i?{ok:!0,content:i.markdown,page:i.id}:{ok:!1,code:`page_not_found`}}function N(e,t,n,r=[]){let i=e.ledger.find(e=>e.id===t);if(!i)return{ok:!1,code:`tx_not_found`};let a={...i,result:n,pagesUsed:[...r]};return{ok:!0,store:{...e,rev:e.rev+1,ledger:e.ledger.map(e=>e.id===t?a:e)},tx:a}}function P(e){let t=new Map(e.packs.filter(e=>e.author===`you`).map(e=>[e.id,{packId:e.id,uses:0,solved:0,authorUsd:0}])),n=0,r=0,i=0,a=0;for(let o of e.ledger){let e=t.get(o.packId);e&&(a++,e.uses++,o.result===`solved`&&(i++,e.solved++),n+=Math.round(o.authorUsd*100),r+=Math.round(o.feeUsd*100),e.authorUsd=(Math.round(e.authorUsd*100)+Math.round(o.authorUsd*100))/100)}return{uses:a,solved:i,authorUsd:n/100,feeUsd:r/100,byPack:[...t.values()]}}function ie(e,t){if(t.includes(e))return e;let n=e=>e.split(/[\\/]/).pop().replace(/\.md$/i,``),r=n(e),i=t.filter(e=>n(e)===r);return i.length===1?i[0]:void 0}function ae(e){let t=new Map,n=e.map(e=>e.id);for(let r of e)for(let e of new Set(r.links)){let i=ie(e,n);if(i===void 0||i===r.id)continue;let a=t.get(i)??[];a.push(r),t.set(i,a)}return e.flatMap(e=>{let n=t.get(e.id)??[],r=n.length>0&&n.every(e=>e.class===`personal`||e.class===`customer`);return e.markdown.split(/\r?\n[\t ]*\r?\n/).map(e=>e.trim()).filter(Boolean).map((t,n)=>{let i=
|
|
26
|
+
`,e);if(t<0)break;let r=n.slice(e,t).trimEnd(),i=/^-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----$/.exec(r);if(!i){s=t+1;continue}let a=`-----END ${i[1]}-----`,u=n.indexOf(a,t);if(u<0)break;let d=u+a.length;l.push(n.slice(c,e),o(`PRIVATE_KEY`,n.slice(e,d))),s=d,c=d}l.push(n.slice(c)),n=l.join(``),n=n.replace(y,e=>(r.push({kind:`HOME_PATH`,before:e,after:`~/`}),`~/`)),n=n.replace(b,e=>o(`GBRAIN_PATH`,e)),n=x(n,e=>o(`SOURCE`,e));for(let{kind:e,pattern:t,group:r}of _)n=n.replace(t,(...t)=>{let n=t[0],i=r?t[r]:n;if(/^\[REDACTED_[A-Z_]+_\d+\]$/.test(i))return n;let a=o(e,i);return r?n.slice(0,n.lastIndexOf(i))+a:a});n=n.replace(/[A-Za-z0-9+/_=-]{20,}/g,e=>w(e)?o(`ENTROPY`,e):e);for(let e of t.terms)e&&n.includes(e)&&(n=n.split(/(\[REDACTED_[A-Z_]+_\d+\])/g).map(t=>/^\[REDACTED_[A-Z_]+_\d+\]$/.test(t)?t:T(t,e,()=>o(`NAME`,e))).join(``));let u=[...new Set(r.map(e=>e.kind))].map(e=>({kind:e,count:r.filter(t=>t.kind===e).length}));return{markdown:n,scrubbed:u,changes:r,remaining:O(n,t)}}function O(e,t){let n=0;n+=[...e.matchAll(y)].length,n+=[...e.matchAll(b)].length,x(e,()=>(n++,``)),/-----BEGIN [A-Z ]{0,32}PRIVATE KEY-----/.test(e)&&n++;for(let{pattern:t,group:r}of _)for(let i of e.matchAll(t))/^\[REDACTED_[A-Z_]+_\d+\]$/.test(r?i[r]:i[0])||n++;for(let t of e.matchAll(/[A-Za-z0-9+/_=-]{20,}/g))w(t[0])&&n++;let r=e.split(/\[REDACTED_[A-Z_]+_\d+\]/g);for(let e of t.terms){if(!e)continue;let t=!1;for(let n of r)if(n.includes(e)&&(T(n,e,()=>(t=!0,``)),t))break;t&&n++}return n}function k(e,t){return O(e,t??{terms:[],shared:[]})}function A(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0&&Number.isSafeInteger(Math.round(e*100))&&Math.round(e*100)/100===e}function ee(e,t,n){return e.sessions.find(e=>e.id===t)??{id:t,startedAt:n,spentUsd:0,calls:[]}}function te(e,t){let n=e.sessions.findIndex(e=>e.id===t.id);return n<0?[...e.sessions,t]:e.sessions.map((e,r)=>r===n?t:e)}function j(e,t){return e.ledger.some(e=>e.packId===t)}function M(e,t,n,r){let i=e.packs.find(e=>e.id===t);if(!i)return{ok:!1,code:`pack_not_found`};if(j(e,t))return{ok:!0};let a=e.sessions.find(e=>e.id===n)?.spentUsd??0;if(![i.priceUsd,e.wallet.buyerUsd,e.wallet.perPurchaseCapUsd,e.wallet.sessionCapUsd,a].every(A))return{ok:!1,code:`invalid_amount`};let o=Math.round(i.priceUsd*100);return o>Math.round(e.wallet.buyerUsd*100)?{ok:!1,code:`insufficient_balance`,needsApproval:!0}:o>Math.round(e.wallet.perPurchaseCapUsd*100)?{ok:!1,code:`over_purchase_cap`,needsApproval:!0}:o+Math.round(a*100)>Math.round(e.wallet.sessionCapUsd*100)?{ok:!1,code:`over_session_cap`,needsApproval:!0}:!Number.isFinite(r)||r<.5||r>1?{ok:!1,code:`low_score`,needsApproval:!0}:{ok:!0}}function ne(e,t,n,r,i,a,o,s){let c=e.ledger.find(e=>e.packId===t);if(c)return{ok:!0,store:e,tx:c,rev:e.rev,alreadyPurchased:!0};if(e.rev!==o)return{ok:!1,code:`revision_conflict`};let l=M(e,t,n,s);if(!l.ok)return l;if(e.ledger.some(e=>e.id===a))return{ok:!1,code:`duplicate_tx_id`};let u=e.packs.find(e=>e.id===t),d=ee(e,n,i),f=Math.round(u.priceUsd*100),p=Math.round(f*.9),m={id:a,packId:t,sessionId:n,at:i,amountUsd:f/100,authorUsd:p/100,feeUsd:(f-p)/100,via:r,result:`running`,pagesUsed:[]},h={...d,spentUsd:(Math.round(d.spentUsd*100)+f)/100,calls:[...d.calls,{tool:`buy`,at:i,summary:t,txId:a}]},g={...e,rev:e.rev+1,wallet:{...e.wallet,buyerUsd:(Math.round(e.wallet.buyerUsd*100)-f)/100},ledger:[...e.ledger,m],sessions:te(e,h)};return{ok:!0,store:g,tx:m,rev:g.rev,alreadyPurchased:!1}}function re(e,t,n){let r=e.packs.find(e=>e.id===t);if(!r)return{ok:!1,code:`pack_not_found`};if(!j(e,t))return{ok:!1,code:`not_purchased`};if(n===void 0)return{ok:!0,content:r.summary,pages:r.pages.map(e=>e.id)};let i=r.pages.find(e=>e.id===n);return i?{ok:!0,content:i.markdown,page:i.id}:{ok:!1,code:`page_not_found`}}function N(e,t,n,r=[]){let i=e.ledger.find(e=>e.id===t);if(!i)return{ok:!1,code:`tx_not_found`};let a={...i,result:n,pagesUsed:[...r]};return{ok:!0,store:{...e,rev:e.rev+1,ledger:e.ledger.map(e=>e.id===t?a:e)},tx:a}}function P(e){let t=new Map(e.packs.filter(e=>e.author===`you`).map(e=>[e.id,{packId:e.id,uses:0,solved:0,authorUsd:0}])),n=0,r=0,i=0,a=0;for(let o of e.ledger){let e=t.get(o.packId);e&&(a++,e.uses++,o.result===`solved`&&(i++,e.solved++),n+=Math.round(o.authorUsd*100),r+=Math.round(o.feeUsd*100),e.authorUsd=(Math.round(e.authorUsd*100)+Math.round(o.authorUsd*100))/100)}return{uses:a,solved:i,authorUsd:n/100,feeUsd:r/100,byPack:[...t.values()]}}function ie(e,t){if(t.includes(e))return e;let n=e=>e.split(/[\\/]/).pop().replace(/\.md$/i,``),r=n(e),i=t.filter(e=>n(e)===r);return i.length===1?i[0]:void 0}function ae(e){let t=new Map,n=e.map(e=>e.id);for(let r of e)for(let e of new Set(r.links)){let i=ie(e,n);if(i===void 0||i===r.id)continue;let a=t.get(i)??[];a.push(r),t.set(i,a)}return e.flatMap(e=>{let n=t.get(e.id)??[],r=n.length>0&&n.every(e=>e.class===`personal`||e.class===`customer`);return e.markdown.split(/\r?\n[\t ]*\r?\n/).map(e=>e.trim()).filter(Boolean).map((t,n)=>{let i=Ee({...e,markdown:t}),a=r?`Only personal or customer pages link to this page.`:{secret:`Contains sensitive data.`,customer:`Matches customer information.`,personal:`Matches personal notes.`,purchased:`Imported from a purchased pack.`,expertise:`No personal, customer, or secret rule matched.`}[i];return{id:`${e.id}#${n+1}`,pageId:e.id,markdown:t,class:i,confidence:r?.6:.95,reason:a,keep:i===`expertise`,confirmed:!1}})})}function F(e){return e.some(e=>e.confidence<.7&&!e.confirmed)}function I(e){return!F(e)&&!e.some(e=>e.keep&&(e.class===`customer`||e.class===`secret`||e.class===`purchased`))}var L=[`symptom`,`cause`,`fix`,`avoid`,`verify`],R=[[`symptom`,/症状|symptom/i],[`cause`,/原因|cause/i],[`fix`,/直し方|fix/i],[`avoid`,/避ける|avoid/i],[`verify`,/確認|verify/i]];function oe(e,t=ae(e),n){let r={fields:{symptom:[],cause:[],fix:[],avoid:[],verify:[]},errorSignatures:[],sourceIds:[],nodes:[]};for(let n of e.filter(e=>e.keep)){r.nodes.push({id:n.id,links:n.links});let e;for(let i of t.filter(e=>e.pageId===n.id)){let t=i.id;i.keep&&r.sourceIds.push(t);let n=[],a=()=>{let a=n.join(`
|
|
27
27
|
`).trim();i.keep&&e&&a&&r.fields[e].push({text:a,sourceId:t}),n=[]};for(let t of i.markdown.split(/\r?\n/)){let r=/^##\s+(.+?)\s*#*\s*$/.exec(t);r?(a(),e=R.find(([,e])=>e.test(r[1]))?.[0]):n.push(t)}a()}}let i=new Set(e.filter(e=>e.keep&&e.class!==`purchased`).map(e=>e.id)),a=t.filter(e=>e.keep&&e.class===`expertise`&&i.has(e.pageId)),o=new Set(a.map(e=>e.pageId)),s=E(e.filter(e=>!o.has(e.id)),a.map(e=>e.markdown)),c={terms:[...new Set([...s.terms,...n?.terms??[]])],shared:[]},l=a.flatMap(e=>e.markdown.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/,``).split(/\r?\n/).filter(e=>!/^\s*#/.test(e)).join(` `).split(/(?<=[。!?!?])\s*|(?<=\.)\s+/).map(e=>e.trim()).filter(e=>e&&k(e,c)===0).map(t=>({text:t,sourceId:e.id,confidence:.5})));r.fallbackCandidates=L.filter(e=>r.fields[e].length===0).flatMap(e=>l.slice(0,5).map(t=>({field:e,...t})));let u=(r.fields.symptom.length?r.fields.symptom:r.fallbackCandidates.filter(e=>e.field===`symptom`)).flatMap(({text:e})=>e.split(/[\n。.!?]+/));return r.errorSignatures=[...new Set(u.map(e=>e.replace(/\S*[\\/]\S*/g,` `).replace(/\d+/g,` `).replace(/\s+/g,` `).trim()).filter(e=>!!e&&k(e,c)===0))].slice(0,5),r}function z(e){return L.map(t=>`## ${t}\n\n${e.fields[t].flatMap(({text:e,sourceId:t})=>e.split(/(?<=[。!?!?])\s*|(?<=\.)\s+|\n+/).map(e=>e.trim()).filter(Boolean).map(e=>`${e} [${t}]`)).join(`
|
|
28
28
|
|
|
29
29
|
`)}`).join(`
|
|
30
30
|
|
|
31
|
-
`)}function se(e){let t=[...new Set(e.map(({id:e})=>e))],n=new Map(t.map(e=>[e,new Set]));for(let r of e)for(let e of r.links){let i=ie(e,t);i!==void 0&&i!==r.id&&(n.get(r.id).add(i),n.get(i).add(r.id))}return n}function ce(e){let t=new Set(e.sourceIds),n=L.flatMap(t=>e.fields[t]).every(({text:e,sourceId:n})=>!e.trim()||!!n.trim()&&t.has(n)),r=z(e).length/4<=2e3,i=[...se(e.nodes)].filter(([,e])=>e.size===0).map(([e])=>e),a=e.nodes.length>0&&i.length===0;return{cited:n,withinLength:r,connected:a,isolatedPageIds:i,passed:n&&r&&a}}function le({pack:e,testNames:t,testCode:n,dictionary:r}){let i=z(e),a=ce(e),o=L.every(t=>e.fields[t].some(({text:e})=>!!e.trim()))&&e.errorSignatures.length>=3&&e.errorSignatures.length<=5&&e.errorSignatures.every(e=>!!e.trim()&&!/[\d\\/]/.test(e))&&a.connected,s=a.cited,c=k(i,r)===0,l=a.withinLength,u=[...t,...n].every(e=>!e.trim()||!i.includes(e));return{format:o,citations:s,rescan:c,length:l,copying:u,isolatedPageIds:a.isolatedPageIds,passed:o&&s&&c&&l&&u}}function ue(e,t){let n=t.filter(t=>!t||!e.includes(t));return{passed:t.length>0&&n.length===0,missing:n}}
|
|
31
|
+
`)}function se(e){let t=[...new Set(e.map(({id:e})=>e))],n=new Map(t.map(e=>[e,new Set]));for(let r of e)for(let e of r.links){let i=ie(e,t);i!==void 0&&i!==r.id&&(n.get(r.id).add(i),n.get(i).add(r.id))}return n}function ce(e){let t=new Set(e.sourceIds),n=L.flatMap(t=>e.fields[t]).every(({text:e,sourceId:n})=>!e.trim()||!!n.trim()&&t.has(n)),r=z(e).length/4<=2e3,i=[...se(e.nodes)].filter(([,e])=>e.size===0).map(([e])=>e),a=e.nodes.length>0&&i.length===0;return{cited:n,withinLength:r,connected:a,isolatedPageIds:i,passed:n&&r&&a}}function le({pack:e,testNames:t,testCode:n,dictionary:r}){let i=z(e),a=ce(e),o=L.every(t=>e.fields[t].some(({text:e})=>!!e.trim()))&&e.errorSignatures.length>=3&&e.errorSignatures.length<=5&&e.errorSignatures.every(e=>!!e.trim()&&!/[\d\\/]/.test(e))&&a.connected,s=a.cited,c=k(i,r)===0,l=a.withinLength,u=[...t,...n].every(e=>!e.trim()||!i.includes(e));return{format:o,citations:s,rescan:c,length:l,copying:u,isolatedPageIds:a.isolatedPageIds,passed:o&&s&&c&&l&&u}}function ue(e,t){let n=t.filter(t=>!t||!e.includes(t));return{passed:t.length>0&&n.length===0,missing:n}}var de={id:`stripe-double-charge-prevention`,title:`Stripe Double-Charge Prevention`,version:`v1`,domain:`payments`,errorSignatures:[`double charge`,`charged twice`,`idempotency`,`orderKey`,`stripe double charge on retry`],nodes:[`stripe-idempotency`,`payment-retries`,`webhook-dedupe`],markdown:`## [[stripe-idempotency]]
|
|
32
|
+
|
|
33
|
+
# Stripe idempotency
|
|
34
|
+
|
|
35
|
+
Import \`orderKey\` from \`./pay-client.mjs\` and use \`payClient.charge(order, { orderKey: orderKey(order) })\`. The key is derived from \`order.merchantId\`, \`order.id\`, and \`order.revision\`. Retry the same operation with the same values. A new revision represents a new operation. The client does not use \`Idempotency-Key\` for deduplication.
|
|
36
|
+
|
|
37
|
+
See [[payment-retries]] for retry handling and [[webhook-dedupe]] for duplicate events.
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
## [[payment-retries]]
|
|
41
|
+
|
|
42
|
+
# Payment retries
|
|
43
|
+
|
|
44
|
+
Retry the same checkout operation with the same \`order.merchantId\`, \`order.id\`, and \`order.revision\`. Import \`orderKey\` from \`./pay-client.mjs\` and pass \`orderKey(order)\` as the \`orderKey\` option to \`payClient.charge\`. Generating a new key for each attempt can create a duplicate charge.
|
|
45
|
+
|
|
46
|
+
See [[stripe-idempotency]] and [[webhook-dedupe]] for the charge and event boundaries.
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
## [[webhook-dedupe]]
|
|
50
|
+
|
|
51
|
+
# Webhook deduplication
|
|
52
|
+
|
|
53
|
+
Use the webhook event ID to detect duplicate deliveries before applying the event's effects. Record the ID only when processing succeeds, so a failed delivery can be retried.
|
|
54
|
+
|
|
55
|
+
See [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
## Sources
|
|
59
|
+
|
|
60
|
+
- [[stripe-idempotency]]
|
|
61
|
+
- [[payment-retries]]
|
|
62
|
+
- [[webhook-dedupe]]`,summary:`## symptom
|
|
63
|
+
|
|
64
|
+
Retries can produce a duplicate charge. [payment-retries#2]
|
|
65
|
+
|
|
66
|
+
## cause
|
|
67
|
+
|
|
68
|
+
A new key on each attempt creates separate operations. [payment-retries#2]
|
|
69
|
+
|
|
70
|
+
## fix
|
|
71
|
+
|
|
72
|
+
Import orderKey from ./pay-client.mjs and pass orderKey(order) as the orderKey option to payClient.charge. [stripe-idempotency#2]
|
|
73
|
+
|
|
74
|
+
## avoid
|
|
75
|
+
|
|
76
|
+
Do not generate a new key for retries. [payment-retries#2]
|
|
77
|
+
|
|
78
|
+
## verify
|
|
79
|
+
|
|
80
|
+
Deduplicate webhook deliveries using the event ID after successful processing. [webhook-dedupe#2]`,pages:[{id:`stripe-idempotency`,markdown:"# Stripe idempotency\n\nImport `orderKey` from `./pay-client.mjs` and use `payClient.charge(order, { orderKey: orderKey(order) })`. The key is derived from `order.merchantId`, `order.id`, and `order.revision`. Retry the same operation with the same values. A new revision represents a new operation. The client does not use `Idempotency-Key` for deduplication.\n\nSee [[payment-retries]] for retry handling and [[webhook-dedupe]] for duplicate events.\n"},{id:`payment-retries`,markdown:"# Payment retries\n\nRetry the same checkout operation with the same `order.merchantId`, `order.id`, and `order.revision`. Import `orderKey` from `./pay-client.mjs` and pass `orderKey(order)` as the `orderKey` option to `payClient.charge`. Generating a new key for each attempt can create a duplicate charge.\n\nSee [[stripe-idempotency]] and [[webhook-dedupe]] for the charge and event boundaries.\n"},{id:`webhook-dedupe`,markdown:`# Webhook deduplication
|
|
81
|
+
|
|
82
|
+
Use the webhook event ID to detect duplicate deliveries before applying the event's effects. Record the ID only when processing succeeds, so a failed delivery can be retried.
|
|
83
|
+
|
|
84
|
+
See [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.
|
|
85
|
+
`}],scrubbed:[],eval:{without:`Not recorded`,with:`Not recorded`,recorded:!0},priceUsd:.5,author:`seed`,createdAt:`2026-01-01T00:00:00.000Z`};function B(e){return typeof e==`string`&&e.length>0&&e!==`.`&&e!==`..`&&!Array.from(e).some(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127||`<>:"/\\|?*[]`.includes(e))&&!/[. ]$/.test(e)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(e)}function fe(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``).normalize(`NFC`).toLowerCase()}function pe(e,t){if(!B(e.id)||typeof e.version!=`string`||typeof e.summary!=`string`||typeof t!=`string`||!Array.isArray(e.pages))throw Error(`Invalid import pack`);if(k(e.summary)||e.pages.some(e=>e&&typeof e.markdown==`string`&&k(e.markdown)))throw Error(`Sensitive data in import pack`);let n=`packs/${e.id}`,r=new Set([fe(`${n}/index.md`)]),i=`---\nsource: gbrainx\npack: ${JSON.stringify(e.id)}\nversion: ${JSON.stringify(e.version)}\nlicense: personal-use\npurchasedAt: ${JSON.stringify(t)}\n---\n\n`,a=e.pages.map(e=>{if(!e||!B(e.id)||typeof e.markdown!=`string`)throw Error(`Invalid import page`);let t=`${n}/${e.id}.md`,a=fe(t);if(r.has(a))throw Error(`Duplicate import path`);return r.add(a),{path:t,markdown:i+e.markdown}}),o=e.pages.map(({id:e})=>`- [[${e}]]`).join(`
|
|
32
86
|
`);return[{path:`${n}/index.md`,markdown:i+e.summary+(o?`\n\n${o}`:``)+`
|
|
33
|
-
`},...a]}var
|
|
87
|
+
`},...a]}var me=`gbrainx:v1`,V=e=>typeof e==`object`&&!!e&&!Array.isArray(e),H=e=>typeof e==`string`,U=e=>Array.isArray(e)&&e.every(H),W=(e,t)=>H(e)&&t.includes(e),he=e=>new Set(e.map(e=>e.id)).size===e.length;function ge(e){return V(e)&&H(e.id)&&H(e.title)&&H(e.markdown)&&U(e.links)&&W(e.class,[`expertise`,`personal`,`customer`,`secret`,`purchased`])&&typeof e.keep==`boolean`}function _e(e){return V(e)&&H(e.id)&&H(e.title)&&H(e.version)&&H(e.domain)&&U(e.errorSignatures)&&U(e.nodes)&&H(e.markdown)&&H(e.summary)&&e.summary.length<=2e3&&Array.isArray(e.pages)&&e.pages.every(e=>V(e)&&H(e.id)&&H(e.markdown))&&Array.isArray(e.scrubbed)&&e.scrubbed.every(e=>V(e)&&H(e.kind)&&typeof e.count==`number`&&Number.isSafeInteger(e.count)&&e.count>=0)&&V(e.eval)&&H(e.eval.without)&&H(e.eval.with)&&e.eval.recorded===!0&&A(e.priceUsd)&&W(e.author,[`you`,`seed`])&&H(e.createdAt)}function ve(e){return V(e)&&H(e.id)&&H(e.packId)&&H(e.sessionId)&&H(e.at)&&A(e.amountUsd)&&A(e.authorUsd)&&A(e.feeUsd)&&W(e.via,[`web`,`mcp`])&&W(e.result,[`running`,`solved`,`unsolved`])&&U(e.pagesUsed)}function ye(e){return V(e)&&H(e.id)&&H(e.startedAt)&&A(e.spentUsd)&&Array.isArray(e.calls)&&e.calls.every(e=>V(e)&&W(e.tool,[`search`,`buy`,`load`])&&H(e.at)&&H(e.summary)&&(e.tool===`buy`?H(e.txId):e.txId===void 0||H(e.txId)))}function be(e){return!(!V(e)||e.version!==1||typeof e.rev!=`number`||!Number.isSafeInteger(e.rev)||e.rev<0||!V(e.brain)||!Array.isArray(e.brain.pages)||!e.brain.pages.every(ge)||!Array.isArray(e.packs)||!e.packs.every(_e)||!he(e.packs)||!V(e.wallet)||!A(e.wallet.buyerUsd)||!A(e.wallet.perPurchaseCapUsd)||!A(e.wallet.sessionCapUsd)||!Array.isArray(e.ledger)||!e.ledger.every(ve)||!he(e.ledger)||!Array.isArray(e.sessions)||!e.sessions.every(ye)||!he(e.sessions))}function xe(e){let t=0;for(let n of e){let e=n.codePointAt(0);if(t+=e<=127?1:e<=2047?2:e<=65535?3:4,t>4194304)return t}return t}function Se(e){if(typeof e!=`string`||xe(e)>4194304)throw Error(`Invalid store size`);let t=JSON.parse(e);if(!be(t))throw Error(`Invalid store`);return t}function Ce(e){if(!be(e))throw Error(`Invalid store`);let t=JSON.stringify(e);if(xe(t)>4194304)throw Error(`Invalid store size`);return t}function we(e){let t=D(e);return{markdown:t.markdown.replace(/\[REDACTED_([A-Z_]+)_\d+\]/g,(e,t)=>t===`NAME`?e:`[REDACTED_${t}]`),scrubbed:t.scrubbed,remaining:t.remaining}}function Te(e){let t=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(e)?.[1];return t!==void 0&&/^source[ \t]*:[ \t]*(?:gbrainx|"gbrainx"|'gbrainx')[ \t]*(?:#.*)?$/m.test(t)}function Ee(e){if(e.class===`purchased`||Te(e.markdown))return`purchased`;let t=D(e.markdown),n=e=>e!==`HOME_PATH`&&e!==`GBRAIN_PATH`&&e!==`SOURCE`;if(t.scrubbed.some(({kind:e})=>n(e))||t.changes.some(({kind:e,before:t})=>(e===`SOURCE`||e===`GBRAIN_PATH`)&&D(e===`GBRAIN_PATH`?t.replace(/^~[\\/]\.gbrain[\\/]?/i,``):t).scrubbed.some(e=>n(e.kind))))return`secret`;let r=[...e.markdown.matchAll(/\+?\d[\d ()-]*/g)].some(t=>{let n=t[0].trimEnd(),r=n.length;for(;r>0&&(n[r-1]===`-`||n[r-1]===`(`);)r--;n=n.slice(0,r).trimEnd();let i=e.markdown[t.index-1]??``,a=e.markdown[t.index+n.length]??``,o=n.replace(/\D/g,``).length;return!/[A-Za-z0-9-]/.test(i)&&!/[A-Za-z0-9-]/.test(a)&&!/^\d{4}-\d{2}-\d{2}$/.test(n)&&/[ ()+-]/.test(n)&&o>=9&&o<=15});return/^customer-/i.test(e.id)||r?`customer`:/standup|1on1|oncall|retro|休暇/i.test(`${e.id}\n${e.markdown}`)?`personal`:`expertise`}function De(e){return e.filter(({name:e})=>/\.md$/i.test(e)).map(({name:e,markdown:t})=>{let n=e.split(/[\\/]/).pop().replace(/\.md$/i,``),r={id:n,title:/^#\s+(.+)$/m.exec(t)?.[1].trim()||n,markdown:t,links:[...t.matchAll(/\[\[([^\][|]+)(?:\|[^\][]*)?\]\]/g)].map(e=>e[1].trim()),class:`expertise`,keep:!0};return r.class=Ee(r),r.keep=r.class===`expertise`,r})}var G=class extends Error{issues;constructor(e,t=`Static evaluation failed`){super(t),this.issues=e,this.name=`StaticEvaluationError`}};function Oe(e,t){if(!t.staticEvaluation||!Array.isArray(t.staticEvaluation.testNames)||!Array.isArray(t.staticEvaluation.testCode)||!Array.isArray(t.staticEvaluation.keywords)||!t.staticEvaluation.distilled)throw new G([{code:`invalid_input`}],`Static evaluation input is required`);let{testNames:n,testCode:r,keywords:i}=t.staticEvaluation;if(![...n,...r].some(e=>typeof e==`string`&&e.trim())||[...n,...r].some(e=>typeof e!=`string`))throw new G([{code:`invalid_input`}],`Static evaluation input is required`);let a=t.errorSignatures.map(e=>e.trim()).filter(Boolean);if(!a.length)throw Error(`At least one error signature is required`);if(!t.title.trim())throw Error(`A title is required`);let o=14695981039346656037n;for(let e of t.title)o^=BigInt(e.codePointAt(0)),o=BigInt.asUintN(64,o*1099511628211n);let s=t.title.toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``)||`pack-${o.toString(36)}`,c=new Set(t.existingIds??[]),l=s;for(let e=2;c.has(l);e++)l=`${s}-${e}`;if(typeof t.eval!=`object`||t.eval===null||Object.keys(t.eval).sort().join(`,`)!==`recorded,with,without`||typeof t.eval.without!=`string`||typeof t.eval.with!=`string`||t.eval.recorded!==!0)throw Error(`Invalid evaluation`);if(t.author!==void 0&&t.author!==`you`&&t.author!==`seed`)throw Error(`Invalid author`);let u=t.priceUsd===void 0?.5:t.priceUsd;if(!Number.isFinite(u)||u<0)throw Error(`Invalid price`);let d=e.filter(e=>e.keep&&e.class!==`purchased`&&!Te(e.markdown));if(!d.length)throw Error(`At least one kept page is required`);let f=new Set(d.map(e=>e.id)),p=E(e.filter(e=>!f.has(e.id)),d.map(e=>e.markdown)),m={terms:[...new Set([...p.terms,...t.forbiddenDictionary?.terms??[]])],shared:[...new Set([...p.shared,...t.forbiddenDictionary?.shared??[]])]},h=e=>e.replace(/\[REDACTED_([A-Z_]+)_\d+\]/g,(e,t)=>t===`NAME`?e:`[REDACTED_${t}]`),g=e=>{let t=D(e,m);return{...t,markdown:h(t.markdown)}},_=(e,t,n)=>{if(!t)return;let r=[];throw D(e,m).changes.some(({kind:e})=>e===`NAME`)&&r.push({code:`forbidden_term`,location:n}),(k(e)>0||!r.length)&&r.push({code:`rescan`,location:n}),new G(r,`Sensitive data remains after scrubbing`)},v=()=>({generated:new Set,existing:new Set}),y=(e,t,n)=>{for(let n of t.matchAll(/\[REDACTED_[A-Z_]+(?:_\d+)?\]|~\//g))e.existing.add(h(n[0]));for(let t of n)e.generated.add(t.kind===`HOME_PATH`?`~/`:h(t.after))},b=[t.title,t.version,t.domain,...t.errorSignatures,t.eval.without,t.eval.with,t.createdAt,...d.map(e=>e.id)],x=[];if(b.some(e=>D(e,m).changes.some(({kind:e})=>e===`NAME`))&&x.push({code:`forbidden_term`,location:`metadata`}),b.some(e=>we(e).scrubbed.length>0)&&x.push({code:`rescan`,location:`metadata`}),x.length)throw new G(x,`Sensitive data in pack metadata`);let S=new Map(d.map(e=>[e.id,e]));if(S.size!==d.length)throw Error(`Duplicate page id`);let C=[...S.keys()],w=[],T=new Set;for(let e of d){let t=[e];for(;t.length;){let e=t.pop();if(!T.has(e.id)){T.add(e.id),w.push(e);for(let n=e.links.length-1;n>=0;n--){let r=ie(e.links[n],C),i=r===void 0?void 0:S.get(r);i&&t.push(i)}}}}let O=g(`${w.map(e=>`## [[${e.id}]]\n\n${e.markdown}`).join(`
|
|
34
88
|
|
|
35
89
|
`)}\n\n## Sources\n\n${w.map(e=>`- [[${e.id}]]`).join(`
|
|
36
90
|
`)}`);_(O.markdown,O.remaining,`markdown`);let A=new Map,ee=w.map(e=>{let t=g(e.markdown);_(t.markdown,t.remaining,{pageId:e.id});let n=v();return y(n,e.markdown,t.changes),A.set(e.id,n),{id:e.id,markdown:t.markdown}}),te=[`symptom`,`cause`,`fix`,`avoid`,`verify`],j=t.staticEvaluation.distilled,M=new Set(ae(w).filter(e=>e.class===`expertise`||e.class===`personal`).map(e=>e.id));if(!j.fields||!Array.isArray(j.errorSignatures)||a.join(`
|
|
37
91
|
`)!==j.errorSignatures.join(`
|
|
38
|
-
`))throw new G([{code:`invalid_input`}]);let ne={},re=v(),N=[];for(let e of te)Array.isArray(j.fields[e])?ne[e]=j.fields[e].flatMap(e=>{if(!e||typeof e.text!=`string`||typeof e.sourceId!=`string`)return N.push({code:`invalid_input`}),[];if(!M.has(e.sourceId))return N.push({code:`citations`}),[];let t=g(e.text);return _(t.markdown,t.remaining,`summary`),y(re,e.text,t.changes),[{text:t.markdown,sourceId:e.sourceId}]}):N.push({code:`invalid_input`});if(N.length)throw new G(N.filter((e,t)=>N.findIndex(t=>t.code===e.code)===t));let P={fields:ne,errorSignatures:a,sourceIds:[...M],nodes:w.map(({id:e,links:t})=>({id:e,links:t.map(e=>ie(e,C)??e)}))};for(;z(P).length>2e3;){let e=te.flatMap(e=>P.fields[e]).reduce((e,t)=>e.text.length>=t.text.length?e:t);if(e.text.length<=1)throw new G([{code:`length`}]);let t=Math.max(1,e.text.length-(z(P).length-2e3)-1);/[\uD800-\uDBFF]/.test(e.text[t-1])&&t--;for(let n of e.text.matchAll(/\[REDACTED_[A-Z_]+(?:_\d+)?\]|~\//g))n.index<t&&n.index+n[0].length>t&&(t=n.index);e.text=e.text.slice(0,t)+(t<e.text.length-1?`…`:``)}let F=z(P),I=[...n,...r].filter(e=>e.trim()),L=le({pack:P,testNames:n,testCode:r,dictionary:m}),R=[],oe=ce(P).connected;oe||R.push({code:`connected`}),!L.format&&(oe||!te.every(e=>P.fields[e].some(({text:e})=>!!e.trim()))||a.length<3||a.length>5||a.some(e=>!e.trim()||/[\d\\/]/.test(e)))&&R.push({code:`format`}),L.citations||R.push({code:`citations`}),L.length||R.push({code:`length`}),L.copying||R.push({code:`summary_copying`,location:`summary`}),(i.length<2||i.length>3)&&R.push({code:`keyword_count`});let se=i.filter(e=>typeof e==`string`&&e.trim());se.length!==i.length&&R.push({code:`keyword_invalid`}),se.length&&!ue(F,se).passed&&R.push({code:`keyword_missing`,location:`summary`}),I.some(e=>O.markdown.includes(e))&&R.push({code:`markdown_copying`,location:`markdown`});for(let e of ee)I.some(t=>e.markdown.includes(t))&&R.push({code:`page_copying`,location:{pageId:e.id}});let de=[{text:F,location:`summary`},{text:O.markdown,location:`markdown`},...ee.map(e=>({text:e.markdown,location:{pageId:e.id}}))];for(let e of de)D(e.text,m).changes.some(({kind:e})=>e===`NAME`)&&R.push({code:`forbidden_term`,location:e.location}),k(e.text)>0&&R.push({code:`rescan`,location:e.location});if(R.length)throw new G(R);let B={id:l,title:t.title,version:t.version,domain:t.domain,errorSignatures:a,nodes:w.map(e=>e.id),markdown:O.markdown,summary:F,pages:ee,scrubbed:O.scrubbed,eval:t.eval,priceUsd:u,author:t.author??`you`,createdAt:t.createdAt};return{pack:B,redactions:
|
|
92
|
+
`))throw new G([{code:`invalid_input`}]);let ne={},re=v(),N=[];for(let e of te)Array.isArray(j.fields[e])?ne[e]=j.fields[e].flatMap(e=>{if(!e||typeof e.text!=`string`||typeof e.sourceId!=`string`)return N.push({code:`invalid_input`}),[];if(!M.has(e.sourceId))return N.push({code:`citations`}),[];let t=g(e.text);return _(t.markdown,t.remaining,`summary`),y(re,e.text,t.changes),[{text:t.markdown,sourceId:e.sourceId}]}):N.push({code:`invalid_input`});if(N.length)throw new G(N.filter((e,t)=>N.findIndex(t=>t.code===e.code)===t));let P={fields:ne,errorSignatures:a,sourceIds:[...M],nodes:w.map(({id:e,links:t})=>({id:e,links:t.map(e=>ie(e,C)??e)}))};for(;z(P).length>2e3;){let e=te.flatMap(e=>P.fields[e]).reduce((e,t)=>e.text.length>=t.text.length?e:t);if(e.text.length<=1)throw new G([{code:`length`}]);let t=Math.max(1,e.text.length-(z(P).length-2e3)-1);/[\uD800-\uDBFF]/.test(e.text[t-1])&&t--;for(let n of e.text.matchAll(/\[REDACTED_[A-Z_]+(?:_\d+)?\]|~\//g))n.index<t&&n.index+n[0].length>t&&(t=n.index);e.text=e.text.slice(0,t)+(t<e.text.length-1?`…`:``)}let F=z(P),I=[...n,...r].filter(e=>e.trim()),L=le({pack:P,testNames:n,testCode:r,dictionary:m}),R=[],oe=ce(P).connected;oe||R.push({code:`connected`}),!L.format&&(oe||!te.every(e=>P.fields[e].some(({text:e})=>!!e.trim()))||a.length<3||a.length>5||a.some(e=>!e.trim()||/[\d\\/]/.test(e)))&&R.push({code:`format`}),L.citations||R.push({code:`citations`}),L.length||R.push({code:`length`}),L.copying||R.push({code:`summary_copying`,location:`summary`}),(i.length<2||i.length>3)&&R.push({code:`keyword_count`});let se=i.filter(e=>typeof e==`string`&&e.trim());se.length!==i.length&&R.push({code:`keyword_invalid`}),se.length&&!ue(F,se).passed&&R.push({code:`keyword_missing`,location:`summary`}),I.some(e=>O.markdown.includes(e))&&R.push({code:`markdown_copying`,location:`markdown`});for(let e of ee)I.some(t=>e.markdown.includes(t))&&R.push({code:`page_copying`,location:{pageId:e.id}});let de=[{text:F,location:`summary`},{text:O.markdown,location:`markdown`},...ee.map(e=>({text:e.markdown,location:{pageId:e.id}}))];for(let e of de)D(e.text,m).changes.some(({kind:e})=>e===`NAME`)&&R.push({code:`forbidden_term`,location:e.location}),k(e.text)>0&&R.push({code:`rescan`,location:e.location});if(R.length)throw new G(R);let B={id:l,title:t.title,version:t.version,domain:t.domain,errorSignatures:a,nodes:w.map(e=>e.id),markdown:O.markdown,summary:F,pages:ee,scrubbed:O.scrubbed,eval:t.eval,priceUsd:u,author:t.author??`you`,createdAt:t.createdAt};return{pack:B,redactions:je(B,re,A)}}function ke(e,t){return Oe(e,t).pack}function Ae(e,t){return Oe(e,t).redactions}function je(e,t,n){let r=[],i=(e,t,n)=>{for(let i of e.matchAll(/\[REDACTED(?:_[A-Z0-9_]*)?\]?|~\//g)){let e=i[0],a=n.generated.has(e),o=n.existing.has(e);if(e===`~/`&&!a)continue;let s=a&&o?`ambiguous`:a?`generated`:`existing`;if(e===`~/`)r.push({location:t,symbol:e,kind:`HOME_PATH`,origin:s});else{let n=/^\[REDACTED_([A-Z_]+?)(?:_\d+)?\]$/.exec(e);if(!n)throw Error(`Incomplete redaction marker`);r.push({location:t,symbol:e,kind:n[1],origin:s})}}};i(e.summary,`summary`,t);for(let t of e.pages)i(t.markdown,{pageId:t.id},n.get(t.id));return r}function Me(e){let t=e.toLowerCase().replace(/\S+/g,e=>/[\\/]/.test(e)?` `:e),n=new Set(t.match(/[a-z]+/g)??[]);for(let e of t.matchAll(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu)){let t=Array.from(e[0]);t.length===1&&n.add(t[0]);for(let e=0;e<t.length-1;e++)n.add(t[e]+t[e+1])}return n}function Ne(e,t){if(!e.size||!t.size)return 0;let n=0;for(let r of e)t.has(r)&&n++;return n/(e.size+t.size-n)}function Pe(e,t){let n=Me(e),r=new Set(t.ledger.map(e=>e.packId));return t.packs.map(e=>({id:e.id,title:e.title,description:e.domain,priceUsd:e.priceUsd,owned:r.has(e.id),score:Math.max(0,...[...e.errorSignatures,e.title,...e.nodes].map(e=>Ne(n,Me(e))))})).filter(({score:e})=>e>=.2).sort((e,t)=>t.score-e.score).slice(0,5)}function K(){let e={scrubbed:[],eval:{without:`Not recorded`,with:`Not recorded`,recorded:!0},author:`seed`,createdAt:`2026-01-01T00:00:00.000Z`};return{version:1,rev:0,brain:{pages:[]},wallet:{buyerUsd:10,perPurchaseCapUsd:1,sessionCapUsd:3},ledger:[],sessions:[],packs:[{...e,id:`stripe-webhook-signature-errors`,title:`Stripe Webhook Signature Errors`,version:`v3`,domain:`payments`,errorSignatures:[`webhook signature verification failed`,`raw body parsing`],nodes:[`stripe-webhook-signature`,`raw-body-parsing`],markdown:`Verify the webhook signature against the raw request body.`,summary:`Verify the webhook signature against the raw request body.`,pages:[{id:`stripe-webhook-signature`,markdown:`Verify the webhook signature against the raw request body.`},{id:`raw-body-parsing`,markdown:`Keep the raw request body for verification.`}],priceUsd:.5},{...e,id:`postgres-zero-downtime-migrations`,title:`Postgres Zero-Downtime Migrations`,version:`v2`,domain:`data`,errorSignatures:[`database migration downtime`,`add column safely`],nodes:[`pg-add-column-safely`],markdown:`Add columns in stages and migrate data before enforcing constraints.`,summary:`Add columns in stages and migrate data before enforcing constraints.`,pages:[{id:`pg-add-column-safely`,markdown:`Add columns in stages and migrate data before enforcing constraints.`}],priceUsd:.8},structuredClone(de)]}}function Fe(e){let t=`${e.domain} の専門知識。`;if(t.length+8>1e3)throw Error(`Domain is too long`);let n=e.errorSignatures.slice(0,2).join(`、`).slice(0,1e3-t.length-8);/[\uD800-\uDBFF]$/.test(n)&&(n=n.slice(0,-1));let r=t+n+` のときに使う。`;return we(`---\nname: ${JSON.stringify(e.id)}\ndescription: ${JSON.stringify(r)}\n---\n\n${e.markdown}\n`).markdown}function Ie(e){let t=[];for(let n of e){let e=n.codePointAt(0);e>=55296&&e<=57343&&(e=65533),e<128?t.push(e):e<2048?t.push(192|e>>6,128|e&63):e<65536?t.push(224|e>>12,128|e>>6&63,128|e&63):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|e&63)}return new Uint8Array(t)}function Le(e){let t=0xffffffff;for(let n of e){t^=n;for(let e=0;e<8;e++)t=t>>>1^-(t&1)&0xedb88320}return(t^0xffffffff)>>>0}function Re(e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e.id))throw Error(`Invalid pack id`);let t=Ie(`.claude/skills/${e.id}/SKILL.md`),n=Ie(Fe(e));if(t.length>65535||n.length>0xffffffff-t.length-76)throw Error(`Skill is too large for ZIP`);let r=30+t.length+n.length,i=46+t.length,a=new Uint8Array(r+i+22),o=new DataView(a.buffer),s=(e,t)=>o.setUint16(e,t,!0),c=(e,t)=>o.setUint32(e,t,!0),l=Le(n);c(0,67324752),s(4,20),s(6,2048),s(12,33),c(14,l),c(18,n.length),c(22,n.length),s(26,t.length),a.set(t,30),a.set(n,30+t.length);let u=r;c(u,33639248),s(u+4,20),s(u+6,20),s(u+8,2048),s(u+14,33),c(u+16,l),c(u+20,n.length),c(u+24,n.length),s(u+28,t.length),a.set(t,u+46);let d=u+i;return c(d,0x6054b50),s(d+8,1),s(d+10,1),c(d+12,i),c(d+16,r),a}var ze=()=>({problem:``,testNames:[],testCode:[],keywords:[],static:null,keyword:null}),Be={pages:[],stage:0,draft:null,title:`Stripe Double-Charge Prevention`,signature:`duplicate charge`,domain:`payments`,paragraphs:[],unconfirmed:!1,removedIsolatedCount:0,pruningPassed:!1,distilled:null,distillationCheck:null,scrub:null,evaluation:ze()};function q(e){return{...e,draft:null,distilled:null,distillationCheck:null,scrub:null,evaluation:{...e.evaluation,static:null,keyword:null}}}function Ve(e,t){if(!e.distilled||!e.scrub)throw Error(`コンパイルが必要です。`);let n=new Map,r=e.pages.flatMap(t=>{let r=e.paragraphs.filter(e=>e.pageId===t.id&&e.keep);if(!r.length)return[];r.forEach((e,r)=>n.set(e.id,`${t.id}#${r+1}`));let i=r.map(e=>e.markdown).join(`
|
|
39
93
|
|
|
40
|
-
`);return[{...t,markdown:i,links:
|
|
94
|
+
`);return[{...t,markdown:i,links:De([{name:`${t.id}.md`,markdown:i}])[0].links,keep:!0}]}),i=Object.fromEntries(Object.entries(e.distilled.fields).map(([e,t])=>[e,t.map(e=>({...e,sourceId:n.get(e.sourceId)??``}))])),a={...e.distilled,fields:i};return{pages:r,input:{title:e.title,domain:e.domain,version:`v1`,errorSignatures:a.errorSignatures,eval:{without:`事前に記録した結果`,with:`事前に記録した結果`,recorded:!0},createdAt:t,forbiddenDictionary:e.scrub.dictionary,staticEvaluation:{distilled:a,testNames:e.evaluation.testNames,testCode:[...e.evaluation.testCode,...e.evaluation.problem.split(/\r?\n/)],keywords:e.evaluation.keywords}}}}function He(e,t){let{pages:n,input:r}=Ve(e,t);return ke(n,r)}function J(e,t){let n=e.paragraphs.filter(e=>e.keep),r=new Set(n.map(e=>e.pageId)),i=E(e.pages.filter(e=>!r.has(e.id)),n.map(e=>e.markdown)),a=z(t),o=D(a,i),s=Object.fromEntries(Object.entries(t.fields).map(([e,t])=>[e,t.map(e=>({...e,text:D(e.text,i).markdown}))])),c=le({pack:{...t,fields:s,errorSignatures:t.errorSignatures.map(e=>D(e,i).markdown)},testNames:e.evaluation.testNames,testCode:[...e.evaluation.testCode,...e.evaluation.problem.split(/\r?\n/)],dictionary:i}),l=[...e.evaluation.testNames,...e.evaluation.testCode].some(e=>e.trim());return{...e,draft:null,distilled:t,distillationCheck:ce(t),scrub:{dictionary:i,result:o,before:a,confirmed:!1,adversarialReview:`not-applicable`},evaluation:{...e.evaluation,static:l?c:{...c,copying:!1,passed:!1},keyword:ue(o.markdown,e.evaluation.keywords)}}}function Ue(e,t){switch(t.type){case`load`:return{...q(e),pages:t.pages,paragraphs:[],unconfirmed:!1,removedIsolatedCount:0,pruningPassed:!1,evaluation:ze(),stage:1};case`classify`:{let t=e.pages.map(e=>{let t=Ee(e);return{...e,class:t,keep:t===`expertise`}}),n=ae(t);return{...q(e),pages:t,paragraphs:n,unconfirmed:F(n),removedIsolatedCount:0,pruningPassed:I(n),stage:2}}case`review`:{if(!e.paragraphs.some(e=>e.id===t.id))return e;let n=e.paragraphs.map(e=>e.id===t.id?{...e,keep:t.keep,confirmed:!0}:e);return{...q(e),paragraphs:n,unconfirmed:F(n),removedIsolatedCount:0,pruningPassed:I(n),stage:2}}case`compile`:{if(!I(e.paragraphs)||!e.paragraphs.some(e=>e.keep))return e;let t=new Set(e.paragraphs.filter(e=>e.keep).map(e=>e.pageId)),n=e.pages.map(n=>{let r=e.paragraphs.filter(e=>e.pageId===n.id&&e.keep).map(e=>e.markdown).join(`
|
|
41
95
|
|
|
42
|
-
`);return{...n,keep:t.has(n.id),links:Ee([{name:`${n.id}.md`,markdown:r}])[0].links}}),r=E(e.pages.filter(e=>!t.has(e.id)),e.paragraphs.filter(e=>e.keep).map(e=>e.markdown));return J({...e,pages:n,stage:3},oe(n,e.paragraphs,r))}case`select-connected`:{if(!e.distilled)return e;let t=new Set(e.distillationCheck?.isolatedPageIds??[]);if(!t.size)return e;let n=e.paragraphs.map(e=>t.has(e.pageId)?{...e,keep:!1,confirmed:!0}:e),r={...e,paragraphs:n,removedIsolatedCount:t.size,unconfirmed:F(n),pruningPassed:I(n)};return n.some(e=>e.keep)?He(r,{type:`compile`}):{...q(r),pages:e.pages.map(e=>t.has(e.id)?{...e,keep:!1}:e),stage:2}}case`distill-field`:return e.distilled?J(e,{...e.distilled,fields:{...e.distilled.fields,[t.field]:t.entries}}):e;case`signatures`:return e.distilled?J(e,{...e.distilled,errorSignatures:t.values}):e;case`evaluation-input`:{let n={...e,evaluation:{...e.evaluation,problem:t.problem,testNames:t.testNames,testCode:t.testCode,keywords:t.keywords}};return n.distilled?J(n,n.distilled):n}case`confirm-scrub`:if(!e.scrub||e.scrub.result.remaining!==0)return e;try{let{pages:t,input:n}=Be(e,new Date().toISOString());return ke(t,n),{...e,scrub:{...e.scrub,confirmed:!0}}}catch{return e}case`scrub`:return{...e,stage:3};case`field`:return{...e,[t.field]:t.value,draft:null,stage:3,scrub:e.scrub&&{...e.scrub,confirmed:!1}};case`draft`:return!e.pruningPassed||!e.distillationCheck?.passed||!e.scrub?.confirmed||e.scrub.result.remaining!==0||!e.evaluation.problem.trim()||!e.evaluation.static?.passed||e.evaluation.keywords.length<2||e.evaluation.keywords.length>3||!e.evaluation.keyword?.passed?e:{...e,draft:t.draft,stage:4};case`reset`:return{...ze,title:e.title,signature:e.signature,domain:e.domain}}}var Y=r(),Ue={invalid_input:{ja:`テスト名かテストコードを入力してください。`,en:`Enter a test name or test code.`},format:{ja:`蒸留の5項目と3〜5個の検索語を確認してください。`,en:`Complete the five distilled fields and provide 3–5 search terms.`},connected:{ja:`ページ間のリンクを確認してください。`,en:`Check the links between pages.`},citations:{ja:`各項目の出典を確認してください。`,en:`Check the source of each field.`},length:{ja:`蒸留した内容を短くしてください。`,en:`Shorten the distilled content.`},summary_copying:{ja:`要約にテスト名やコードが含まれています。`,en:`Remove copied test names or code from the summary.`},page_copying:{ja:`ページにテスト名やコードが含まれています。`,en:`Remove copied test names or code from the page.`},markdown_copying:{ja:`出品本文にテスト名やコードが含まれています。`,en:`Remove copied test names or code from the pack text.`},keyword_count:{ja:`合言葉を2〜3個入力してください。`,en:`Enter 2–3 keywords.`},keyword_invalid:{ja:`空でない合言葉を入力してください。`,en:`Enter non-empty keywords.`},keyword_missing:{ja:`合言葉を要約に含めてください。`,en:`Include the keywords in the summary.`},forbidden_term:{ja:`禁止語を確認してください。`,en:`Check the forbidden terms.`},rescan:{ja:`秘密情報を確認してください。`,en:`Check for sensitive information.`}};function We({state:e,lang:t,dispatch:n}){let r=(0,c.useMemo)(()=>{if(!e.distilled||!e.scrub)return null;try{return Ve(e,`2000-01-01T00:00:00.000Z`),null}catch(e){return e instanceof G?{issues:e.issues,other:``}:{issues:[],other:e instanceof Error?e.message:String(e)}}},[e]),i=e.distillationCheck?.isolatedPageIds??[];return(0,Y.jsxs)(`div`,{children:[e.removedIsolatedCount>0&&(0,Y.jsx)(`p`,{"data-testid":`removed-isolated-pages`,children:t===`ja`?`孤立したページを ${e.removedIsolatedCount} 件外しました`:`Removed ${e.removedIsolatedCount} isolated ${e.removedIsolatedCount===1?`page`:`pages`}`}),i.length>0&&(0,Y.jsxs)(`div`,{"data-testid":`isolated-pages`,children:[(0,Y.jsx)(`p`,{children:t===`ja`?`孤立したページ: ${i.length} 件`:`Isolated pages: ${i.length}`}),(0,Y.jsx)(`button`,{type:`button`,"data-testid":`select-connected-pages`,onClick:()=>n({type:`select-connected`}),children:t===`ja`?`孤立したページ(${i.length} 件)を外して作り直す`:`Remove ${i.length} isolated ${i.length===1?`page`:`pages`} and rebuild`})]}),r&&(0,Y.jsxs)(`div`,{"data-testid":`evaluation-issues`,children:[r.issues.map((e,n)=>(0,Y.jsxs)(`p`,{"data-testid":`evaluation-issue-${e.code}`,children:[Ue[e.code][t],typeof e.location==`object`?` (${e.location.pageId})`:``]},`${e.code}-${n}`)),r.other&&(0,Y.jsx)(`p`,{children:r.other})]})]})}var X={background:s.white,border:`1px solid ${s.border}`,borderRadius:20,padding:20},Z={background:s.navy,color:s.white,border:0,borderRadius:999,padding:`12px 20px`,cursor:`pointer`},Ge=Object.entries(Object.assign({"../../samples/brain/acme-checkout.md":l,"../../samples/brain/aws-prod-account.md":u,"../../samples/brain/customer-8812.md":d,"../../samples/brain/oncall-rotation.md":f,"../../samples/brain/payment-retries.md":p,"../../samples/brain/standup-notes.md":m,"../../samples/brain/stripe-idempotency.md":h,"../../samples/brain/webhook-dedupe.md":g})).map(([e,t])=>({name:e,markdown:t}));async function Ke(e){if(e.isFile)return[await new Promise((t,n)=>e.file(t,n))];if(!e.isDirectory)return[];let t=e.createReader(),n=[];for(;;){let e=await new Promise((e,n)=>t.readEntries(e,n));if(!e.length)return n;for(let t of e)n.push(...await Ke(t))}}async function qe(e){return Promise.all(e.filter(e=>/\.md$/i.test(e.name)).map(async e=>({name:e.name,markdown:await e.text()})))}function Je(e,t=`en`){let[n,r]=(0,c.useReducer)(He,ze),[i,a]=(0,c.useState)(``);function o(){r({type:`reset`}),a(``)}function s(t){let n=Ee(t);if(!n.length)throw Error(`Markdown ファイルがありません。`);r({type:`load`,pages:n}),e(`${n.length} ページを読み込みました。`)}async function l(t){try{s(await qe(t))}catch(t){e(t instanceof Error?t.message:`読み込みに失敗しました。`)}}async function u(t){t.preventDefault();try{let e=Array.from(t.dataTransfer.items).map(e=>e.webkitGetAsEntry()).filter(e=>e!==null);await l(e.length?(await Promise.all(e.map(Ke))).flat():Array.from(t.dataTransfer.files))}catch(t){e(t instanceof Error?t.message:`読み込みに失敗しました。`)}}function d(){r({type:`classify`})}let f=n.pages.filter(e=>e.keep),p=f.map(e=>Ce(e.markdown)),m=p.flatMap(e=>e.scrubbed).reduce((e,t)=>e+t.count,0),h=p.reduce((e,t)=>e+t.remaining,0);function g(){a(``);try{let t=Ve(n,new Date().toISOString());r({type:`draft`,draft:t}),e(``)}catch(n){let r=n instanceof Error?n.message:`パックを作れませんでした。`;r===`Static evaluation failed`||r===`Static evaluation input is required`?(e(``),a({"Static evaluation failed":{ja:`静的検査に合格しませんでした。出典と評価入力を確認してください。`,en:`Static evaluation failed. Check the sources and evaluation inputs.`},"Static evaluation input is required":{ja:`静的検査の入力が必要です。テスト名またはテストコードを入力してください。`,en:`Static evaluation inputs are required. Enter a test name or test code.`}}[r][t])):e(r)}}function _(e,t){r({type:`field`,field:e,value:t})}return{state:n,lang:t,reset:o,load:s,loadSelected:l,drop:u,runClassify:d,kept:f,scrubCount:m,remaining:h,makePack:g,updateField:_,dispatch:r,packError:i}}function Ye({factory:e}){return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{onDragOver:e=>e.preventDefault(),onDrop:t=>{e.drop(t)},style:{border:`2px dashed ${s.borderStrong}`,borderRadius:16,padding:`2rem`,background:s.background},children:[(0,Y.jsxs)(`label`,{children:[`GBrain フォルダを選択 `,(0,Y.jsx)(`input`,{style:{display:`block`,maxWidth:`100%`},ref:e=>{e?.setAttribute(`webkitdirectory`,``)},type:`file`,multiple:!0,onChange:t=>{e.loadSelected(Array.from(t.currentTarget.files??[]))}})]}),(0,Y.jsx)(`p`,{children:`ここにフォルダまたは Markdown ファイルをドロップ`}),(0,Y.jsx)(`button`,{type:`button`,style:Z,onClick:()=>e.load(Ge),children:`サンプルの GBrain で試す`})]}),e.state.stage>=1&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{children:`1. 読み込み`}),(0,Y.jsxs)(`p`,{children:[e.state.pages.length,` ページ`]}),(0,Y.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:8},children:e.state.pages.map(e=>(0,Y.jsxs)(`span`,{style:{border:`1px solid ${e.keep?s.greenText:s.borderStrong}`,borderRadius:999,padding:`6px 10px`},children:[e.title,` (`,e.class,`)`]},e.id))}),(0,Y.jsx)(`p`,{children:(0,Y.jsx)(`button`,{type:`button`,style:Z,onClick:e.runClassify,children:`分類する`})})]})]})}function Xe({factory:e}){return e.state.stage<2?null:(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{children:`段落の判定`}),e.state.paragraphs.map(t=>(0,Y.jsx)(`div`,{"data-testid":`paragraph-${t.id}`,style:{border:`1px solid ${s.border}`,borderRadius:10,padding:10,marginTop:8},children:(0,Y.jsxs)(`div`,{"data-testid":t.confidence<.7&&!t.confirmed?`paragraph-review-pending`:void 0,children:[(0,Y.jsx)(`code`,{children:t.id}),` · `,t.reason,(0,Y.jsx)(`p`,{children:t.markdown}),(0,Y.jsx)(`button`,{type:`button`,"aria-pressed":t.keep,onClick:()=>e.dispatch({type:`review`,id:t.id,keep:!0}),children:`残す`}),` `,(0,Y.jsx)(`button`,{type:`button`,"aria-pressed":!t.keep,onClick:()=>e.dispatch({type:`review`,id:t.id,keep:!1}),children:`外す`})]})},t.id)),(0,Y.jsxs)(`p`,{children:[`保持 `,e.state.paragraphs.filter(e=>e.keep).length,` 段落`]}),(0,Y.jsx)(`button`,{type:`button`,style:Z,disabled:!e.state.pruningPassed||!e.state.paragraphs.some(e=>e.keep),onClick:()=>e.dispatch({type:`compile`}),children:`コンパイル&検証`})]})}function Ze({factory:e}){if(e.state.stage<3)return null;let t=e.state.scrub;if(!t)return null;let n=null;try{let{pages:t,input:r}=Be(e.state,new Date().toISOString());n=ke(t,r)}catch{}let r=e.lang===`ja`;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`h3`,{children:r?`秘密情報の除去`:`Redaction review`}),n?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{children:r?`出品物の伏せ字 ${n.length} 件`:`${n.length} redactions in the pack`}),(0,Y.jsx)(`ul`,{children:n.map((e,t)=>(0,Y.jsxs)(`li`,{children:[e.location===`summary`?r?`要約`:`Summary`:`${r?`ページ`:`Page`} ${e.location.pageId}`,` · `,(0,Y.jsx)(`code`,{children:e.symbol}),` · `,e.kind,` · `,e.origin===`ambiguous`?r?`既存か生成か判別できません`:`Cannot determine whether existing or generated`:e.origin===`existing`?r?`既存`:`Existing`:r?`生成`:`Generated`]},t))})]}):(0,Y.jsx)(`p`,{role:`status`,children:r?`パックの入力と検査を完了すると伏せ字を確認できます。現在は確認できません。`:`Complete pack inputs and checks to review redactions. Review is currently unavailable.`}),(0,Y.jsx)(`button`,{type:`button`,disabled:n===null||t.result.remaining!==0||t.confirmed,onClick:()=>e.dispatch({type:`confirm-scrub`}),children:r?`確認した`:`Confirm`})]})}function Qe({factory:e,ready:t,publish:n}){let{state:r}=e;return r.stage<3?null:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`h3`,{children:`パック`}),e.packError&&(0,Y.jsx)(`p`,{role:`alert`,children:e.packError}),(0,Y.jsxs)(`label`,{children:[`パック名 `,(0,Y.jsx)(`input`,{value:r.title,onChange:t=>e.updateField(`title`,t.target.value)})]}),(0,Y.jsx)(`br`,{}),(0,Y.jsxs)(`label`,{children:[`ドメイン `,(0,Y.jsx)(`input`,{value:r.domain,onChange:t=>e.updateField(`domain`,t.target.value)})]}),(0,Y.jsx)(`br`,{}),(0,Y.jsxs)(`label`,{children:[`エラー文の例 `,(0,Y.jsx)(`input`,{value:r.signature,onChange:t=>e.updateField(`signature`,t.target.value)})]}),(0,Y.jsx)(`br`,{}),(0,Y.jsx)(`button`,{type:`button`,style:Z,disabled:!r.pruningPassed||!r.distillationCheck?.passed||!r.scrub?.confirmed||!r.evaluation.static?.passed||!r.evaluation.keyword?.passed||!r.evaluation.problem.trim(),onClick:e.makePack,children:`パックを作る`}),(0,Y.jsx)(We,{state:r,lang:e.lang,dispatch:e.dispatch}),r.stage>=4&&r.draft&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`p`,{children:[r.draft.title,` · `,r.draft.nodes.length,` ページ`]}),(0,Y.jsx)(`button`,{type:`button`,style:Z,onClick:n,disabled:!t,children:`出品する`})]})]})}function $e({factory:e,ready:t,publish:n}){let{state:r,dispatch:i}=e,a=[`symptom`,`cause`,`fix`,`avoid`,`verify`],o={symptom:`症状`,cause:`原因`,fix:`直し方`,avoid:`避けること`,verify:`確認方法`},c=r.evaluation;function l(e){let t={...c,...e};i({type:`evaluation-input`,problem:t.problem,testNames:t.testNames,testCode:t.testCode,keywords:t.keywords})}return(0,Y.jsxs)(`section`,{"aria-labelledby":`factory`,style:{color:s.navy,padding:`28px 24px 48px`,background:s.background},children:[(0,Y.jsx)(`h2`,{id:`factory`,children:`ファクトリー`}),(0,Y.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit,minmax(280px,1fr))`,gap:20},children:[(0,Y.jsxs)(`div`,{style:X,children:[(0,Y.jsx)(Ye,{factory:e}),(0,Y.jsx)(Xe,{factory:e})]}),(0,Y.jsxs)(`div`,{style:X,children:[(0,Y.jsx)(`h3`,{children:`4ゲート`}),(0,Y.jsx)(`div`,{style:{display:`flex`,justifyContent:`space-between`,gap:8,flexWrap:`wrap`},children:[`枝刈り`,`蒸留`,`秘密除去`,`効果測定`].map((e,t)=>(0,Y.jsxs)(`div`,{style:{textAlign:`center`,flex:`1 1 70px`},children:[(0,Y.jsx)(`div`,{style:{margin:`0 auto 8px`,width:54,height:54,borderRadius:`50%`,display:`grid`,placeItems:`center`,background:[r.pruningPassed,r.distillationCheck?.passed,r.scrub?.confirmed,r.evaluation.static?.passed&&r.evaluation.keyword?.passed][t]?s.green:s.background,color:s.navy},children:t+1}),e]},e))}),(0,Y.jsx)(Qe,{factory:e,ready:t,publish:n})]}),(0,Y.jsxs)(`div`,{style:{...X,background:e.state.draft?s.navy:s.background,color:e.state.draft?s.white:s.muted},children:[(0,Y.jsx)(`h3`,{children:`Expert brain`}),e.state.draft?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`strong`,{children:e.state.draft.title}),(0,Y.jsxs)(`p`,{children:[e.state.draft.nodes.length,` ページ`]})]}):(0,Y.jsx)(`p`,{children:`パックを作成するとここに表示されます。`})]})]}),(0,Y.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit,minmax(260px,1fr))`,gap:20,marginTop:20},children:[(0,Y.jsxs)(`div`,{style:X,"data-testid":`gate-prune`,"data-status":r.pruningPassed?`passed`:`pending`,children:[(0,Y.jsx)(`h3`,{children:`枝刈り`}),(0,Y.jsx)(`p`,{children:r.unconfirmed?`要確認の段落があります。`:r.pruningPassed?`判定完了`:`分類後に結果を表示します。`})]}),(0,Y.jsxs)(`div`,{style:X,"data-testid":`gate-distill`,"data-status":r.distillationCheck?.passed?`passed`:`pending`,children:[(0,Y.jsx)(`h3`,{children:`蒸留`}),r.distilled?(0,Y.jsxs)(Y.Fragment,{children:[!!r.distilled.fallbackCandidates?.length&&(0,Y.jsx)(`p`,{children:`保持した段落から低確信度の候補を表示しています。内容を確認し、5項目を記入してください。`}),a.map(e=>{let t=r.distilled.fields[e],n=r.distilled.fallbackCandidates?.filter(t=>(t.field??`symptom`)===e)??[];return(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`label`,{style:{display:`block`},children:[e,(0,Y.jsx)(`textarea`,{"data-testid":`distill-${e}`,value:t.map(e=>e.text).join(`
|
|
96
|
+
`);return{...n,keep:t.has(n.id),links:De([{name:`${n.id}.md`,markdown:r}])[0].links}}),r=E(e.pages.filter(e=>!t.has(e.id)),e.paragraphs.filter(e=>e.keep).map(e=>e.markdown));return J({...e,pages:n,stage:3},oe(n,e.paragraphs,r))}case`select-connected`:{if(!e.distilled)return e;let t=new Set(e.distillationCheck?.isolatedPageIds??[]);if(!t.size)return e;let n=e.paragraphs.map(e=>t.has(e.pageId)?{...e,keep:!1,confirmed:!0}:e),r={...e,paragraphs:n,removedIsolatedCount:t.size,unconfirmed:F(n),pruningPassed:I(n)};return n.some(e=>e.keep)?Ue(r,{type:`compile`}):{...q(r),pages:e.pages.map(e=>t.has(e.id)?{...e,keep:!1}:e),stage:2}}case`distill-field`:return e.distilled?J(e,{...e.distilled,fields:{...e.distilled.fields,[t.field]:t.entries}}):e;case`signatures`:return e.distilled?J(e,{...e.distilled,errorSignatures:t.values}):e;case`evaluation-input`:{let n={...e,evaluation:{...e.evaluation,problem:t.problem,testNames:t.testNames,testCode:t.testCode,keywords:t.keywords}};return n.distilled?J(n,n.distilled):n}case`confirm-scrub`:if(!e.scrub||e.scrub.result.remaining!==0)return e;try{let{pages:t,input:n}=Ve(e,new Date().toISOString());return Ae(t,n),{...e,scrub:{...e.scrub,confirmed:!0}}}catch{return e}case`scrub`:return{...e,stage:3};case`field`:return{...e,[t.field]:t.value,draft:null,stage:3,scrub:e.scrub&&{...e.scrub,confirmed:!1}};case`draft`:return!e.pruningPassed||!e.distillationCheck?.passed||!e.scrub?.confirmed||e.scrub.result.remaining!==0||!e.evaluation.problem.trim()||!e.evaluation.static?.passed||e.evaluation.keywords.length<2||e.evaluation.keywords.length>3||!e.evaluation.keyword?.passed?e:{...e,draft:t.draft,stage:4};case`reset`:return{...Be,title:e.title,signature:e.signature,domain:e.domain}}}var Y=r(),We={invalid_input:{ja:`テスト名かテストコードを入力してください。`,en:`Enter a test name or test code.`},format:{ja:`蒸留の5項目と3〜5個の検索語を確認してください。`,en:`Complete the five distilled fields and provide 3–5 search terms.`},connected:{ja:`ページ間のリンクを確認してください。`,en:`Check the links between pages.`},citations:{ja:`各項目の出典を確認してください。`,en:`Check the source of each field.`},length:{ja:`蒸留した内容を短くしてください。`,en:`Shorten the distilled content.`},summary_copying:{ja:`要約にテスト名やコードが含まれています。`,en:`Remove copied test names or code from the summary.`},page_copying:{ja:`ページにテスト名やコードが含まれています。`,en:`Remove copied test names or code from the page.`},markdown_copying:{ja:`出品本文にテスト名やコードが含まれています。`,en:`Remove copied test names or code from the pack text.`},keyword_count:{ja:`合言葉を2〜3個入力してください。`,en:`Enter 2–3 keywords.`},keyword_invalid:{ja:`空でない合言葉を入力してください。`,en:`Enter non-empty keywords.`},keyword_missing:{ja:`合言葉を要約に含めてください。`,en:`Include the keywords in the summary.`},forbidden_term:{ja:`禁止語を確認してください。`,en:`Check the forbidden terms.`},rescan:{ja:`秘密情報を確認してください。`,en:`Check for sensitive information.`}};function Ge({state:e,lang:t,dispatch:n}){let r=(0,c.useMemo)(()=>{if(!e.distilled||!e.scrub)return null;try{return He(e,`2000-01-01T00:00:00.000Z`),null}catch(e){return e instanceof G?{issues:e.issues,other:``}:{issues:[],other:e instanceof Error?e.message:String(e)}}},[e]),i=e.distillationCheck?.isolatedPageIds??[];return(0,Y.jsxs)(`div`,{children:[e.removedIsolatedCount>0&&(0,Y.jsx)(`p`,{"data-testid":`removed-isolated-pages`,children:t===`ja`?`孤立したページを ${e.removedIsolatedCount} 件外しました`:`Removed ${e.removedIsolatedCount} isolated ${e.removedIsolatedCount===1?`page`:`pages`}`}),i.length>0&&(0,Y.jsxs)(`div`,{"data-testid":`isolated-pages`,children:[(0,Y.jsx)(`p`,{children:t===`ja`?`孤立したページ: ${i.length} 件`:`Isolated pages: ${i.length}`}),(0,Y.jsx)(`button`,{type:`button`,"data-testid":`select-connected-pages`,onClick:()=>n({type:`select-connected`}),children:t===`ja`?`孤立したページ(${i.length} 件)を外して作り直す`:`Remove ${i.length} isolated ${i.length===1?`page`:`pages`} and rebuild`})]}),r&&(0,Y.jsxs)(`div`,{"data-testid":`evaluation-issues`,children:[r.issues.map((e,n)=>(0,Y.jsxs)(`p`,{"data-testid":`evaluation-issue-${e.code}`,children:[We[e.code][t],typeof e.location==`object`?` (${e.location.pageId})`:``]},`${e.code}-${n}`)),r.other&&(0,Y.jsx)(`p`,{children:r.other})]})]})}var X={background:s.white,border:`1px solid ${s.border}`,borderRadius:20,padding:20},Z={background:s.navy,color:s.white,border:0,borderRadius:999,padding:`12px 20px`,cursor:`pointer`},Ke=Object.entries(Object.assign({"../../samples/brain/acme-checkout.md":l,"../../samples/brain/aws-prod-account.md":u,"../../samples/brain/customer-8812.md":d,"../../samples/brain/oncall-rotation.md":f,"../../samples/brain/payment-retries.md":p,"../../samples/brain/standup-notes.md":m,"../../samples/brain/stripe-idempotency.md":h,"../../samples/brain/webhook-dedupe.md":g})).map(([e,t])=>({name:e,markdown:t}));async function qe(e){if(e.isFile)return[await new Promise((t,n)=>e.file(t,n))];if(!e.isDirectory)return[];let t=e.createReader(),n=[];for(;;){let e=await new Promise((e,n)=>t.readEntries(e,n));if(!e.length)return n;for(let t of e)n.push(...await qe(t))}}async function Je(e){return Promise.all(e.filter(e=>/\.md$/i.test(e.name)).map(async e=>({name:e.name,markdown:await e.text()})))}function Ye(e,t=`en`){let[n,r]=(0,c.useReducer)(Ue,Be),[i,a]=(0,c.useState)(``);function o(){r({type:`reset`}),a(``)}function s(t){let n=De(t);if(!n.length)throw Error(`Markdown ファイルがありません。`);r({type:`load`,pages:n}),e(`${n.length} ページを読み込みました。`)}async function l(t){try{s(await Je(t))}catch(t){e(t instanceof Error?t.message:`読み込みに失敗しました。`)}}async function u(t){t.preventDefault();try{let e=Array.from(t.dataTransfer.items).map(e=>e.webkitGetAsEntry()).filter(e=>e!==null);await l(e.length?(await Promise.all(e.map(qe))).flat():Array.from(t.dataTransfer.files))}catch(t){e(t instanceof Error?t.message:`読み込みに失敗しました。`)}}function d(){r({type:`classify`})}let f=n.pages.filter(e=>e.keep),p=f.map(e=>we(e.markdown)),m=p.flatMap(e=>e.scrubbed).reduce((e,t)=>e+t.count,0),h=p.reduce((e,t)=>e+t.remaining,0);function g(){a(``);try{let t=He(n,new Date().toISOString());r({type:`draft`,draft:t}),e(``)}catch(n){let r=n instanceof Error?n.message:`パックを作れませんでした。`;r===`Static evaluation failed`||r===`Static evaluation input is required`?(e(``),a({"Static evaluation failed":{ja:`静的検査に合格しませんでした。出典と評価入力を確認してください。`,en:`Static evaluation failed. Check the sources and evaluation inputs.`},"Static evaluation input is required":{ja:`静的検査の入力が必要です。テスト名またはテストコードを入力してください。`,en:`Static evaluation inputs are required. Enter a test name or test code.`}}[r][t])):e(r)}}function _(e,t){r({type:`field`,field:e,value:t})}return{state:n,lang:t,reset:o,load:s,loadSelected:l,drop:u,runClassify:d,kept:f,scrubCount:m,remaining:h,makePack:g,updateField:_,dispatch:r,packError:i}}function Xe({factory:e}){return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{onDragOver:e=>e.preventDefault(),onDrop:t=>{e.drop(t)},style:{border:`2px dashed ${s.borderStrong}`,borderRadius:16,padding:`2rem`,background:s.background},children:[(0,Y.jsxs)(`label`,{children:[`GBrain フォルダを選択 `,(0,Y.jsx)(`input`,{style:{display:`block`,maxWidth:`100%`},ref:e=>{e?.setAttribute(`webkitdirectory`,``)},type:`file`,multiple:!0,onChange:t=>{e.loadSelected(Array.from(t.currentTarget.files??[]))}})]}),(0,Y.jsx)(`p`,{children:`ここにフォルダまたは Markdown ファイルをドロップ`}),(0,Y.jsx)(`button`,{type:`button`,style:Z,onClick:()=>e.load(Ke),children:`サンプルの GBrain で試す`})]}),e.state.stage>=1&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{children:`1. 読み込み`}),(0,Y.jsxs)(`p`,{children:[e.state.pages.length,` ページ`]}),(0,Y.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:8},children:e.state.pages.map(e=>(0,Y.jsxs)(`span`,{style:{border:`1px solid ${e.keep?s.greenText:s.borderStrong}`,borderRadius:999,padding:`6px 10px`},children:[e.title,` (`,e.class,`)`]},e.id))}),(0,Y.jsx)(`p`,{children:(0,Y.jsx)(`button`,{type:`button`,style:Z,onClick:e.runClassify,children:`分類する`})})]})]})}function Ze({factory:e}){return e.state.stage<2?null:(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{children:`段落の判定`}),e.state.paragraphs.map(t=>(0,Y.jsx)(`div`,{"data-testid":`paragraph-${t.id}`,style:{border:`1px solid ${s.border}`,borderRadius:10,padding:10,marginTop:8},children:(0,Y.jsxs)(`div`,{"data-testid":t.confidence<.7&&!t.confirmed?`paragraph-review-pending`:void 0,children:[(0,Y.jsx)(`code`,{children:t.id}),` · `,t.reason,(0,Y.jsx)(`p`,{children:t.markdown}),(0,Y.jsx)(`button`,{type:`button`,"aria-pressed":t.keep,onClick:()=>e.dispatch({type:`review`,id:t.id,keep:!0}),children:`残す`}),` `,(0,Y.jsx)(`button`,{type:`button`,"aria-pressed":!t.keep,onClick:()=>e.dispatch({type:`review`,id:t.id,keep:!1}),children:`外す`})]})},t.id)),(0,Y.jsxs)(`p`,{children:[`保持 `,e.state.paragraphs.filter(e=>e.keep).length,` 段落`]}),(0,Y.jsx)(`button`,{type:`button`,style:Z,disabled:!e.state.pruningPassed||!e.state.paragraphs.some(e=>e.keep),onClick:()=>e.dispatch({type:`compile`}),children:`コンパイル&検証`})]})}function Qe({factory:e}){if(e.state.stage<3)return null;let t=e.state.scrub;if(!t)return null;let n=null;try{let{pages:t,input:r}=Ve(e.state,new Date().toISOString());n=Ae(t,r)}catch{}let r=e.lang===`ja`;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`h3`,{children:r?`秘密情報の除去`:`Redaction review`}),n?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{children:r?`出品物の伏せ字 ${n.length} 件`:`${n.length} redactions in the pack`}),(0,Y.jsx)(`ul`,{children:n.map((e,t)=>(0,Y.jsxs)(`li`,{children:[e.location===`summary`?r?`要約`:`Summary`:`${r?`ページ`:`Page`} ${e.location.pageId}`,` · `,(0,Y.jsx)(`code`,{children:e.symbol}),` · `,e.kind,` · `,e.origin===`ambiguous`?r?`既存か生成か判別できません`:`Cannot determine whether existing or generated`:e.origin===`existing`?r?`既存`:`Existing`:r?`生成`:`Generated`]},t))})]}):(0,Y.jsx)(`p`,{role:`status`,children:r?`パックの入力と検査を完了すると伏せ字を確認できます。現在は確認できません。`:`Complete pack inputs and checks to review redactions. Review is currently unavailable.`}),(0,Y.jsx)(`button`,{type:`button`,disabled:n===null||t.result.remaining!==0||t.confirmed,onClick:()=>e.dispatch({type:`confirm-scrub`}),children:r?`確認した`:`Confirm`})]})}function $e({factory:e,ready:t,publish:n}){let{state:r}=e;return r.stage<3?null:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`h3`,{children:`パック`}),e.packError&&(0,Y.jsx)(`p`,{role:`alert`,children:e.packError}),(0,Y.jsxs)(`label`,{children:[`パック名 `,(0,Y.jsx)(`input`,{value:r.title,onChange:t=>e.updateField(`title`,t.target.value)})]}),(0,Y.jsx)(`br`,{}),(0,Y.jsxs)(`label`,{children:[`ドメイン `,(0,Y.jsx)(`input`,{value:r.domain,onChange:t=>e.updateField(`domain`,t.target.value)})]}),(0,Y.jsx)(`br`,{}),(0,Y.jsxs)(`label`,{children:[`エラー文の例 `,(0,Y.jsx)(`input`,{value:r.signature,onChange:t=>e.updateField(`signature`,t.target.value)})]}),(0,Y.jsx)(`br`,{}),(0,Y.jsx)(`button`,{type:`button`,style:Z,disabled:!r.pruningPassed||!r.distillationCheck?.passed||!r.scrub?.confirmed||!r.evaluation.static?.passed||!r.evaluation.keyword?.passed||!r.evaluation.problem.trim(),onClick:e.makePack,children:`パックを作る`}),(0,Y.jsx)(Ge,{state:r,lang:e.lang,dispatch:e.dispatch}),r.stage>=4&&r.draft&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`p`,{children:[r.draft.title,` · `,r.draft.nodes.length,` ページ`]}),(0,Y.jsx)(`button`,{type:`button`,style:Z,onClick:n,disabled:!t,children:`出品する`})]})]})}function et({factory:e,ready:t,publish:n}){let{state:r,dispatch:i}=e,a=[`symptom`,`cause`,`fix`,`avoid`,`verify`],o={symptom:`症状`,cause:`原因`,fix:`直し方`,avoid:`避けること`,verify:`確認方法`},c=r.evaluation;function l(e){let t={...c,...e};i({type:`evaluation-input`,problem:t.problem,testNames:t.testNames,testCode:t.testCode,keywords:t.keywords})}return(0,Y.jsxs)(`section`,{"aria-labelledby":`factory`,style:{color:s.navy,padding:`28px 24px 48px`,background:s.background},children:[(0,Y.jsx)(`h2`,{id:`factory`,children:`ファクトリー`}),(0,Y.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit,minmax(280px,1fr))`,gap:20},children:[(0,Y.jsxs)(`div`,{style:X,children:[(0,Y.jsx)(Xe,{factory:e}),(0,Y.jsx)(Ze,{factory:e})]}),(0,Y.jsxs)(`div`,{style:X,children:[(0,Y.jsx)(`h3`,{children:`4ゲート`}),(0,Y.jsx)(`div`,{style:{display:`flex`,justifyContent:`space-between`,gap:8,flexWrap:`wrap`},children:[`枝刈り`,`蒸留`,`秘密除去`,`効果測定`].map((e,t)=>(0,Y.jsxs)(`div`,{style:{textAlign:`center`,flex:`1 1 70px`},children:[(0,Y.jsx)(`div`,{style:{margin:`0 auto 8px`,width:54,height:54,borderRadius:`50%`,display:`grid`,placeItems:`center`,background:[r.pruningPassed,r.distillationCheck?.passed,r.scrub?.confirmed,r.evaluation.static?.passed&&r.evaluation.keyword?.passed][t]?s.green:s.background,color:s.navy},children:t+1}),e]},e))}),(0,Y.jsx)($e,{factory:e,ready:t,publish:n})]}),(0,Y.jsxs)(`div`,{style:{...X,background:e.state.draft?s.navy:s.background,color:e.state.draft?s.white:s.muted},children:[(0,Y.jsx)(`h3`,{children:`Expert brain`}),e.state.draft?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`strong`,{children:e.state.draft.title}),(0,Y.jsxs)(`p`,{children:[e.state.draft.nodes.length,` ページ`]})]}):(0,Y.jsx)(`p`,{children:`パックを作成するとここに表示されます。`})]})]}),(0,Y.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit,minmax(260px,1fr))`,gap:20,marginTop:20},children:[(0,Y.jsxs)(`div`,{style:X,"data-testid":`gate-prune`,"data-status":r.pruningPassed?`passed`:`pending`,children:[(0,Y.jsx)(`h3`,{children:`枝刈り`}),(0,Y.jsx)(`p`,{children:r.unconfirmed?`要確認の段落があります。`:r.pruningPassed?`判定完了`:`分類後に結果を表示します。`})]}),(0,Y.jsxs)(`div`,{style:X,"data-testid":`gate-distill`,"data-status":r.distillationCheck?.passed?`passed`:`pending`,children:[(0,Y.jsx)(`h3`,{children:`蒸留`}),r.distilled?(0,Y.jsxs)(Y.Fragment,{children:[!!r.distilled.fallbackCandidates?.length&&(0,Y.jsx)(`p`,{children:`保持した段落から低確信度の候補を表示しています。内容を確認し、5項目を記入してください。`}),a.map(e=>{let t=r.distilled.fields[e],n=r.distilled.fallbackCandidates?.filter(t=>(t.field??`symptom`)===e)??[];return(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`label`,{style:{display:`block`},children:[e,(0,Y.jsx)(`textarea`,{"data-testid":`distill-${e}`,value:t.map(e=>e.text).join(`
|
|
43
97
|
`),onChange:n=>i({type:`distill-field`,field:e,entries:[{text:n.target.value,sourceId:t[0]?.sourceId??r.distilled.sourceIds[0]??``}]})}),(0,Y.jsx)(`small`,{children:t.map(e=>e.sourceId).join(`, `)})]}),n.length>0&&(0,Y.jsx)(`div`,{"data-testid":e===`symptom`?`distill-fallback-candidates`:`distill-fallback-${e}`,children:(0,Y.jsx)(`ul`,{children:n.map((t,n)=>(0,Y.jsxs)(`li`,{children:[(0,Y.jsx)(`p`,{children:t.text}),(0,Y.jsxs)(`small`,{children:[`出典 `,t.sourceId,` · 確信度 `,t.confidence]}),(0,Y.jsx)(`br`,{}),(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>i({type:`distill-field`,field:e,entries:[{text:t.text,sourceId:t.sourceId}]}),children:[o[e],`に使う`]})]},`${t.sourceId}-${n}`))})})]},e)}),(0,Y.jsxs)(`label`,{children:[`検索語(改行区切り)`,(0,Y.jsx)(`textarea`,{value:r.distilled.errorSignatures.join(`
|
|
44
98
|
`),onChange:e=>i({type:`signatures`,values:e.target.value.split(`
|
|
45
|
-
`).filter(Boolean)})})]})]}):(0,Y.jsx)(`p`,{children:`コンパイル後に結果を表示します。`})]}),(0,Y.jsxs)(`div`,{style:X,"data-testid":`gate-scrub`,"data-status":r.scrub?.confirmed&&r.scrub.result.remaining===0?`passed`:`pending`,children:[(0,Y.jsx)(
|
|
99
|
+
`).filter(Boolean)})})]})]}):(0,Y.jsx)(`p`,{children:`コンパイル後に結果を表示します。`})]}),(0,Y.jsxs)(`div`,{style:X,"data-testid":`gate-scrub`,"data-status":r.scrub?.confirmed&&r.scrub.result.remaining===0?`passed`:`pending`,children:[(0,Y.jsx)(Qe,{factory:e}),!r.scrub&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`h3`,{children:`秘密情報の除去`}),(0,Y.jsx)(`p`,{children:`コンパイル後に結果を表示します。`})]})]}),(0,Y.jsxs)(`div`,{style:X,"data-testid":`gate-evaluation`,"data-status":c.static?.passed&&c.keyword?.passed?`passed`:`pending`,children:[(0,Y.jsx)(`h3`,{children:`効果測定`}),r.distilled&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`label`,{children:[`課題`,(0,Y.jsx)(`textarea`,{"data-testid":`evaluation-problem`,value:c.problem,onChange:e=>l({problem:e.target.value})})]}),(0,Y.jsxs)(`label`,{children:[`テスト名(改行区切り)`,(0,Y.jsx)(`textarea`,{value:c.testNames.join(`
|
|
46
100
|
`),onChange:e=>l({testNames:e.target.value.split(`
|
|
47
101
|
`)})})]}),(0,Y.jsxs)(`label`,{children:[`テストコード`,(0,Y.jsx)(`textarea`,{value:c.testCode.join(`
|
|
48
102
|
`),onChange:e=>l({testCode:e.target.value.split(`
|
|
49
|
-
`)})})]}),(0,Y.jsxs)(`label`,{children:[`合言葉(カンマ区切り)`,(0,Y.jsx)(`input`,{"data-testid":`evaluation-keywords`,value:c.keywords.join(`, `),onChange:e=>l({keywords:e.target.value.split(`,`).map(e=>e.trim()).filter(Boolean)})})]}),(0,Y.jsxs)(`p`,{"data-testid":`evaluation-stage-0`,"data-status":c.static?.passed?`passed`:`pending`,children:[`静的検査 `,c.static?.passed?`✓`:`未完了`]}),(0,Y.jsxs)(`p`,{"data-testid":`evaluation-stage-1`,"data-status":c.keyword?.passed?`passed`:`pending`,children:[`合言葉 `,c.keyword?.passed?`✓`:`未完了`]})]})]})]})]})}var Q=pe;function et(e){let t=e.getItem(Q);if(t===null)return{store:K(),recovered:!1};try{return{store:xe(t),recovered:!1}}catch{let n=1;for(;e.getItem(`${Q}:backup:${n}`)!==null;)n++;e.setItem(`${Q}:backup:${n}`,t);let r=K();if(e.getItem(Q)!==t)throw Error(`Store changed during recovery`);return e.setItem(Q,Se(r)),{store:r,recovered:!0}}}function tt(e,t,n){if(n!==void 0){let t=e.getItem(Q);if((t===null?0:xe(t).rev)!==n)throw Error(`Store revision conflict`)}e.setItem(Q,Se(t))}function nt(e,t,n){let r=r=>{if(r.key!==Q&&r.key!==null)return;let i;try{if(r.storageArea!==e.localStorage)return;i=et(e.localStorage)}catch(e){n(e);return}t(i)};return e.addEventListener(`storage`,r),()=>e.removeEventListener(`storage`,r)}async function rt(){let e=new AbortController,t;try{let n=await Promise.race([fetch(`http://127.0.0.1:4747/api/health`,{signal:e.signal}),new Promise((n,r)=>{t=setTimeout(()=>{e.abort(),r(Error(`Health check timed out`))},500)})]);if(!n.ok)return`browser`;let r=await Promise.race([n.json(),new Promise((t,n)=>{e.signal.addEventListener(`abort`,()=>n(Error(`Health check timed out`)),{once:!0})})]);return typeof r==`object`&&r&&`ok`in r&&r.ok===!0?`local`:`browser`}catch{return`browser`}finally{clearTimeout(t),e.abort()}}function it(e){let t=new Set(e.packs.filter(e=>e.author===`you`).map(e=>e.id)),n=e.ledger.filter(e=>t.has(e.packId)),r=P(e),i=Math.round(r.authorUsd*100),a=[1,1,2,1,2,2,1,2,1,2,1,1,2,4,1,2,3,5,3,4,6,2,6,3,4,4,5,7,4,4];a[a.length-1]+=n.length;let o=[...n.map(e=>({amountUsd:e.authorUsd,solved:e.result===`solved`,pages:e.pagesUsed})),{amountUsd:.45,solved:!0,pages:[`stripe-webhook-signature`,`raw-body-parsing`]},{amountUsd:.72,solved:!0,pages:[`pg-add-column-safely`]},{amountUsd:.45,solved:!1,pages:[`stripe-webhook-signature`]}],s={"stripe-webhook-signature":41,"pg-add-column-safely":27,"raw-body-parsing":22,"stripe-idempotency":0,"webhook-dedupe":0};for(let e of n)for(let t of e.pagesUsed)s[t]=(s[t]??0)+1;return{balanceUsd:(1336+i)/100,earned30dUsd:(4788+i)/100,uses30d:86+r.uses,solved30d:78+r.solved,dailyUses30d:a,recentUses:o,pageUses:s}}var $={background:s.white,border:`1px solid ${s.border}`,borderRadius:14,padding:22};function at({query:e,setQuery:t,searched:n,search:r,results:i,store:a,ready:l,sessionId:u,buy:d,download:f,markResult:p}){let[m,h]=(0,c.useState)(()=>new Set),[g,_]=(0,c.useState)(``);function v(e){let t=f(e,`brain`);if(!t.ok){_(t.reason);return}_(``);let n=a.ledger.find(t=>t.packId===e);n&&h(e=>new Set(e).add(n.id))}return(0,Y.jsxs)(`section`,{"aria-labelledby":`market`,style:{padding:`28px 24px 48px`,background:s.background,color:s.navy},children:[(0,Y.jsx)(`h2`,{id:`market`,children:`Claude Code`}),(0,Y.jsxs)(`div`,{style:{...$,background:s.navy,color:s.white,fontFamily:`ui-monospace, monospace`},children:[(0,Y.jsx)(`p`,{children:`● ● ● Claude Code`}),(0,Y.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),r()},children:[(0,Y.jsxs)(`label`,{children:[`検索 `,(0,Y.jsx)(`input`,{value:e,onChange:e=>t(e.target.value)})]}),` `,(0,Y.jsx)(`button`,{type:`submit`,children:`検索する`})]}),g&&(0,Y.jsx)(`p`,{role:`alert`,children:g}),n&&i.length===0&&(0,Y.jsx)(`p`,{children:`一致するパックはありません。`}),(0,Y.jsx)(`ul`,{children:i.map(e=>(0,Y.jsxs)(`li`,{children:[(0,Y.jsx)(`strong`,{children:e.title}),` · 一致度 `,Math.round(e.score*100),`% · $`,e.priceUsd.toFixed(2),` `,(0,Y.jsx)(`button`,{type:`button`,onClick:()=>d(e),disabled:!l||!u,children:`購入する`}),` `,(0,Y.jsx)(`button`,{type:`button`,disabled:!e.owned,onClick:()=>f(e.id,`skill`),children:`スキルを書き出す`}),` `,(0,Y.jsx)(`button`,{type:`button`,disabled:!e.owned||a.ledger.some(t=>t.packId===e.id&&m.has(t.id)),onClick:()=>v(e.id),children:a.ledger.some(t=>t.packId===e.id&&m.has(t.id))?o(`ja`).importDone:o(`ja`).importBtn}),a.ledger.filter(t=>t.packId===e.id).map(e=>(0,Y.jsxs)(`div`,{"data-testid":`transaction-result`,children:[`利用結果: `,e.result===`solved`?`解決`:e.result===`unsolved`?`未解決`:`実行中`,` `,(0,Y.jsx)(`button`,{type:`button`,disabled:!l,"aria-pressed":e.result===`solved`,onClick:()=>p(e.id,`solved`),children:`解決`}),` `,(0,Y.jsx)(`button`,{type:`button`,disabled:!l,"aria-pressed":e.result===`unsolved`,onClick:()=>p(e.id,`unsolved`),children:`未解決`})]},e.id))]},e.id))}),(0,Y.jsxs)(`p`,{children:[`ローカルでは `,(0,Y.jsx)(`code`,{children:`gbrainx import`}),` を使えます。同名ファイルがある場合は取り込みが止まります。内容を確認してから操作してください。`]})]})]})}function ot({store:e}){let t=it(e);return(0,Y.jsxs)(`section`,{"aria-labelledby":`earnings`,style:{padding:`32px 24px 48px`,background:s.background,color:s.navy},children:[(0,Y.jsx)(`h2`,{id:`earnings`,children:`収益`}),(0,Y.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit,minmax(260px,1fr))`,gap:16},children:[(0,Y.jsxs)(`div`,{style:{...$,background:s.navy,color:s.white},children:[(0,Y.jsxs)(`div`,{"data-testid":`earnings-balance`,children:[`作者収益 `,(0,Y.jsxs)(`strong`,{style:{fontSize:38},children:[`$`,t.balanceUsd.toFixed(2)]})]}),(0,Y.jsxs)(`p`,{children:[`購入者残高 $`,e.wallet.buyerUsd.toFixed(2)]})]}),(0,Y.jsxs)(`div`,{style:$,children:[(0,Y.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Y.jsxs)(`div`,{children:[`利用回数`,(0,Y.jsx)(`h2`,{children:t.uses30d})]}),(0,Y.jsxs)(`div`,{children:[`解決率`,(0,Y.jsxs)(`h2`,{"data-testid":`earnings-solve-rate`,children:[Math.round(t.solved30d/t.uses30d*100),`%`]})]}),(0,Y.jsxs)(`div`,{children:[`30日間の収益`,(0,Y.jsxs)(`h2`,{children:[`$`,t.earned30dUsd.toFixed(2)]})]})]}),(0,Y.jsx)(`div`,{"aria-label":`30日間の利用回数`,style:{height:66,display:`flex`,alignItems:`end`,gap:3},children:t.dailyUses30d.map((e,n)=>(0,Y.jsx)(`div`,{title:`${e}回`,style:{flex:1,height:Math.max(3,e/Math.max(...t.dailyUses30d)*66),background:n===29?s.blue:s.border,borderRadius:3}},n))})]})]}),(0,Y.jsxs)(`div`,{style:{...$,marginTop:16,overflowX:`auto`},children:[(0,Y.jsx)(`h3`,{children:`出品中の Expert brain`}),(0,Y.jsxs)(`table`,{style:{width:`100%`,textAlign:`left`},children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:`パック`}),(0,Y.jsx)(`th`,{children:`価格`}),(0,Y.jsx)(`th`,{children:`利用`}),(0,Y.jsx)(`th`,{children:`解決`}),(0,Y.jsx)(`th`,{children:`収益`})]})}),(0,Y.jsx)(`tbody`,{children:e.packs.map(t=>{let n=e.ledger.filter(e=>e.packId===t.id&&t.author===`you`);return(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{children:t.title}),(0,Y.jsxs)(`td`,{children:[`$`,t.priceUsd.toFixed(2)]}),(0,Y.jsx)(`td`,{children:t.author===`you`?n.length:`—`}),(0,Y.jsx)(`td`,{children:t.author===`you`?n.filter(e=>e.result===`solved`).length:`—`}),(0,Y.jsx)(`td`,{children:t.author===`you`?`$${n.reduce((e,t)=>e+t.authorUsd,0).toFixed(2)}`:`—`})]},t.id)})})]})]}),(0,Y.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit,minmax(280px,1fr))`,gap:16,marginTop:16},children:[(0,Y.jsxs)(`div`,{style:$,children:[(0,Y.jsx)(`h3`,{children:`最近の利用`}),t.recentUses.map((e,t)=>(0,Y.jsxs)(`p`,{children:[e.solved?`解決`:`未解決`,` · +$`,e.amountUsd.toFixed(2),(0,Y.jsx)(`br`,{}),e.pages.map(e=>`[[${e}]]`).join(` `)]},t))]}),(0,Y.jsxs)(`div`,{style:$,children:[(0,Y.jsx)(`h3`,{children:`役に立ったページ`}),Object.entries(t.pageUses).map(([e,n])=>(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`p`,{children:[e,` · `,n,`回`]}),(0,Y.jsx)(`div`,{style:{height:6,background:s.border},children:(0,Y.jsx)(`div`,{style:{height:6,width:`${n/Math.max(1,...Object.values(t.pageUses))*100}%`,background:s.blue}})})]},e))]})]}),(0,Y.jsxs)(`div`,{style:{...$,marginTop:16},children:[(0,Y.jsx)(`h3`,{children:`内訳`}),(0,Y.jsxs)(`div`,{style:{display:`flex`,color:s.white},children:[(0,Y.jsx)(`div`,{style:{width:`90%`,padding:10,background:s.navy},children:`あなた 90%`}),(0,Y.jsx)(`div`,{style:{width:`10%`,padding:10,background:s.blue},children:`10%`})]})]})]})}function st(e){let t=0xffffffff;for(let n of e){t^=n;for(let e=0;e<8;e++)t=t>>>1^-(t&1)&0xedb88320}return(t^0xffffffff)>>>0}function ct(e,t){let n=new TextEncoder,r=`packs/${e.id}/`,i=new Set,a=fe(e,t).map(({path:t,markdown:a})=>{if(!t.startsWith(r))throw Error(`Invalid import path`);let o=t.slice(6),s=o.split(`/`);if(s.length!==2||s[0]!==e.id||s.some(e=>!e||e===`.`||e===`..`||e.includes(`\\`)||Array.from(e).some(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127)))throw Error(`Invalid import path`);let c=o.normalize(`NFC`).toLowerCase();if(i.has(c))throw Error(`Duplicate import path`);i.add(c);let l=n.encode(o),u=n.encode(a);if(l.length>65535||u.length>0xffffffff)throw Error(`Import file is too large for ZIP`);return{name:l,content:u,crc:st(u)}});if(a.length>65535)throw Error(`Too many import files for ZIP`);let o=0,s=0;for(let e of a)o+=30+e.name.length+e.content.length,s+=46+e.name.length;if(o>0xffffffff||s>0xffffffff||o+s+22>0xffffffff)throw Error(`Import is too large for ZIP`);let c=new Uint8Array(o+s+22),l=new DataView(c.buffer),u=(e,t)=>l.setUint16(e,t,!0),d=(e,t)=>l.setUint32(e,t,!0),f=0,p=o;for(let{name:e,content:t,crc:n}of a)d(f,67324752),u(f+4,20),u(f+6,2048),u(f+12,33),d(f+14,n),d(f+18,t.length),d(f+22,t.length),u(f+26,e.length),c.set(e,f+30),c.set(t,f+30+e.length),d(p,33639248),u(p+4,20),u(p+6,20),u(p+8,2048),u(p+14,33),d(p+16,n),d(p+20,t.length),d(p+24,t.length),u(p+28,e.length),d(p+42,f),c.set(e,p+46),f+=30+e.length+t.length,p+=46+e.length;return d(p,0x6054b50),u(p+8,a.length),u(p+10,a.length),d(p+12,s),d(p+16,o),c}function lt(){let[e,t]=(0,c.useState)(()=>K()),[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(`browser`),[o,s]=(0,c.useState)(``),[l,u]=(0,c.useState)(!1),[d,f]=(0,c.useState)(``),[p,m]=(0,c.useState)(null),[h,g]=(0,c.useState)(``);(0,c.useEffect)(()=>{g(crypto.randomUUID());try{let e=et(window.localStorage);t(e.store),r(!0),e.recovered&&f(`以前の保存データを退避し、初期状態から始めました。`)}catch{f(`保存データを読み込めませんでした。保存は停止しています。`)}return rt().then(a),nt(window,e=>{t(e.store),r(!0),e.recovered&&f(`以前の保存データを退避し、初期状態から始めました。`)},()=>{r(!1),f(`保存データを読み込めませんでした。保存は停止しています。`)})},[]);function _(r){if(!n)throw Error(`Store is unavailable`);tt(window.localStorage,r,e.rev),t(r)}function v(t,n){if(t){if(e.packs.some(e=>e.id===t.id))f(`同じ ID のパックが既にあります。別のパック名を指定してください。`);else try{_({...e,rev:e.rev+1,brain:{pages:n},packs:[...e.packs,t]}),f(`パックを出品しました。`)}catch{f(`保存に失敗しました。`)}}}function y(t){let n=M(e,t.id,h,t.score);if(!n.ok){f(`購入できませんでした: ${n.code}`);return}let r=ne(e,t.id,h,`web`,new Date().toISOString(),crypto.randomUUID(),e.rev,t.score);if(!r.ok)f(`購入できませんでした: ${r.code}`);else try{r.alreadyPurchased||_(r.store),f(r.alreadyPurchased?`${t.title} は購入済みです。`:`${t.title} を購入しました。`)}catch{f(`購入を保存できませんでした。再読み込みしてください。`)}}function b(t,n){let r=e.ledger.find(e=>e.packId===t),i=e.packs.find(e=>e.id===t);if(!r||!i||!j(e,t)){let e=`書き出すには購入が必要です。`;return f(e),{ok:!1,reason:e}}try{let a=re(e,t);if(!a.ok){let e=`パックを読み込めませんでした: ${a.code}`;return f(e),{ok:!1,reason:e}}let o=Uint8Array.from(n===`skill`?Le(i):ct(i,r.at)),s=URL.createObjectURL(new Blob([o.buffer],{type:`application/zip`}));try{let e=document.createElement(`a`);e.href=s,e.download=n===`skill`?`${t}.zip`:`${t}-gbrain.zip`,e.click()}finally{URL.revokeObjectURL(s)}return{ok:!0}}catch(e){let t=e instanceof Error?e.message:`書き出しに失敗しました。`;return f(t),{ok:!1,reason:t}}}function x(t,n){let r=N(e,t,n);if(!r.ok)f(`結果を保存できませんでした: ${r.code}`);else try{_(r.store),f(`利用結果を保存しました。`)}catch{f(`結果を保存できませんでした。`)}}function S(){try{return _({...K(),rev:e.rev+1}),m(e),f(`初期状態に戻しました。`),!0}catch{return f(`保存に失敗しました。`),!1}}function C(){if(p)try{_({...p,rev:e.rev+1}),m(null)}catch{f(`保存に失敗しました。`)}}return{store:e,ready:n,mode:i,query:o,setQuery:s,searched:l,setSearched:u,message:d,setMessage:f,previous:p,sessionId:h,results:l?Ne(o,e):[],publish:v,buy:y,download:b,markResult:x,reset:S,undo:C}}function ut(){return[{title:`GBrainX`}]}var dt=t(function(){let e=lt(),[t]=i(),n=Je(e.setMessage,a(t.toString())),[r,o]=(0,c.useState)(`factory`),[l,u]=(0,c.useState)(!1),d=e.store.packs.some(e=>e.author===`you`),f=e.store.ledger.some(e=>e.result===`solved`),p=l?4:f?3:d?2:+!!n.state.draft,m=[[`factory`,`ファクトリー`],[`agent`,`Claude Code`],[`earnings`,`収益`]],h=r===`factory`?n.state.unconfirmed?`要確認の段落を判断してください。`:n.state.stage===0?`GBrain を読み込んでください。`:n.state.draft?`パックを出品できます。`:`分類と各ゲートの結果を確認してください。`:r===`agent`?`Expert brain を検索し、購入して読み込めます。`:`利用と収益を確認できます。`;return(0,Y.jsxs)(`main`,{style:{minHeight:`100vh`,background:s.background,color:s.navy,lineHeight:1.6},children:[(0,Y.jsxs)(`header`,{style:{background:s.navy,color:s.white,padding:`12px 24px`,display:`flex`,alignItems:`center`,gap:20,flexWrap:`wrap`},children:[(0,Y.jsx)(`strong`,{children:`GbrainX`}),(0,Y.jsx)(`span`,{children:e.mode===`local`?`ローカル版`:`ブラウザ版`}),(0,Y.jsx)(`div`,{role:`tablist`,"aria-label":`画面`,style:{display:`flex`,padding:4,background:s.navyRaised,borderRadius:999},children:m.map(([t,n])=>(0,Y.jsx)(`button`,{type:`button`,role:`tab`,id:`tab-${t}`,"aria-controls":`panel-${t}`,"aria-selected":r===t,onClick:()=>{o(t),t===`earnings`&&e.store.ledger.length>0&&u(!0)},style:{border:0,borderRadius:999,padding:`7px 16px`,minHeight:36,cursor:`pointer`,background:r===t?s.white:`transparent`,color:r===t?s.navy:s.textOnNavy},children:n},t))}),(0,Y.jsx)(`div`,{style:{flex:`1 1 auto`}}),(0,Y.jsx)(`div`,{role:`img`,"aria-label":`進行状況`,style:{display:`flex`,gap:6},children:[`コンパイル`,`出品`,`解決`,`収益`].map((e,t)=>(0,Y.jsx)(`span`,{title:e,style:{width:t===p?24:6,height:6,borderRadius:999,background:t<p?s.mint:t===p?s.white:s.navyBorder}},e))}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>{e.reset()&&(n.reset(),o(`factory`),u(!1))},disabled:!e.ready,children:`初期状態に戻す`}),e.previous&&(0,Y.jsx)(`button`,{type:`button`,onClick:e.undo,children:`元に戻す`})]}),(0,Y.jsxs)(`div`,{"aria-live":`polite`,style:{background:`#EAF1FA`,padding:`12px 24px`,color:s.navy},children:[(0,Y.jsx)(`strong`,{children:m.find(([e])=>e===r)?.[1]}),` · `,h]}),e.message&&(0,Y.jsx)(`p`,{role:`status`,children:e.message}),(0,Y.jsx)(`div`,{role:`tabpanel`,id:`panel-factory`,"aria-labelledby":`tab-factory`,hidden:r!==`factory`,children:(0,Y.jsx)($e,{factory:n,ready:e.ready,publish:()=>e.publish(n.state.draft,n.state.pages)})}),(0,Y.jsx)(`div`,{role:`tabpanel`,id:`panel-agent`,"aria-labelledby":`tab-agent`,hidden:r!==`agent`,children:(0,Y.jsx)(at,{query:e.query,setQuery:e.setQuery,searched:e.searched,search:()=>e.setSearched(!0),results:e.results,store:e.store,ready:e.ready,sessionId:e.sessionId,buy:e.buy,download:e.download,markResult:e.markResult})}),(0,Y.jsx)(`div`,{role:`tabpanel`,id:`panel-earnings`,"aria-labelledby":`tab-earnings`,hidden:r!==`earnings`,children:(0,Y.jsx)(ot,{store:e.store})})]})});export{dt as default,ut as meta};
|
|
103
|
+
`)})})]}),(0,Y.jsxs)(`label`,{children:[`合言葉(カンマ区切り)`,(0,Y.jsx)(`input`,{"data-testid":`evaluation-keywords`,value:c.keywords.join(`, `),onChange:e=>l({keywords:e.target.value.split(`,`).map(e=>e.trim()).filter(Boolean)})})]}),(0,Y.jsxs)(`p`,{"data-testid":`evaluation-stage-0`,"data-status":c.static?.passed?`passed`:`pending`,children:[`静的検査 `,c.static?.passed?`✓`:`未完了`]}),(0,Y.jsxs)(`p`,{"data-testid":`evaluation-stage-1`,"data-status":c.keyword?.passed?`passed`:`pending`,children:[`合言葉 `,c.keyword?.passed?`✓`:`未完了`]})]})]})]})]})}var Q=me;function tt(e){let t=e.getItem(Q);if(t===null)return{store:K(),recovered:!1};try{return{store:Se(t),recovered:!1}}catch{let n=1;for(;e.getItem(`${Q}:backup:${n}`)!==null;)n++;e.setItem(`${Q}:backup:${n}`,t);let r=K();if(e.getItem(Q)!==t)throw Error(`Store changed during recovery`);return e.setItem(Q,Ce(r)),{store:r,recovered:!0}}}function nt(e,t,n){if(n!==void 0){let t=e.getItem(Q);if((t===null?0:Se(t).rev)!==n)throw Error(`Store revision conflict`)}e.setItem(Q,Ce(t))}function rt(e,t,n){let r=r=>{if(r.key!==Q&&r.key!==null)return;let i;try{if(r.storageArea!==e.localStorage)return;i=tt(e.localStorage)}catch(e){n(e);return}t(i)};return e.addEventListener(`storage`,r),()=>e.removeEventListener(`storage`,r)}async function it(){let e=new AbortController,t;try{let n=await Promise.race([fetch(`http://127.0.0.1:4747/api/health`,{signal:e.signal}),new Promise((n,r)=>{t=setTimeout(()=>{e.abort(),r(Error(`Health check timed out`))},500)})]);if(!n.ok)return`browser`;let r=await Promise.race([n.json(),new Promise((t,n)=>{e.signal.addEventListener(`abort`,()=>n(Error(`Health check timed out`)),{once:!0})})]);return typeof r==`object`&&r&&`ok`in r&&r.ok===!0?`local`:`browser`}catch{return`browser`}finally{clearTimeout(t),e.abort()}}function at(e){let t=new Set(e.packs.filter(e=>e.author===`you`).map(e=>e.id)),n=e.ledger.filter(e=>t.has(e.packId)),r=P(e),i=Math.round(r.authorUsd*100),a=[1,1,2,1,2,2,1,2,1,2,1,1,2,4,1,2,3,5,3,4,6,2,6,3,4,4,5,7,4,4];a[a.length-1]+=n.length;let o=[...n.map(e=>({amountUsd:e.authorUsd,solved:e.result===`solved`,pages:e.pagesUsed})),{amountUsd:.45,solved:!0,pages:[`stripe-webhook-signature`,`raw-body-parsing`]},{amountUsd:.72,solved:!0,pages:[`pg-add-column-safely`]},{amountUsd:.45,solved:!1,pages:[`stripe-webhook-signature`]}],s={"stripe-webhook-signature":41,"pg-add-column-safely":27,"raw-body-parsing":22,"stripe-idempotency":0,"webhook-dedupe":0};for(let e of n)for(let t of e.pagesUsed)s[t]=(s[t]??0)+1;return{balanceUsd:(1336+i)/100,earned30dUsd:(4788+i)/100,uses30d:86+r.uses,solved30d:78+r.solved,dailyUses30d:a,recentUses:o,pageUses:s}}var $={background:s.white,border:`1px solid ${s.border}`,borderRadius:14,padding:22};function ot({query:e,setQuery:t,searched:n,search:r,results:i,store:a,ready:l,sessionId:u,buy:d,download:f,markResult:p}){let[m,h]=(0,c.useState)(()=>new Set),[g,_]=(0,c.useState)(``);function v(e){let t=f(e,`brain`);if(!t.ok){_(t.reason);return}_(``);let n=a.ledger.find(t=>t.packId===e);n&&h(e=>new Set(e).add(n.id))}return(0,Y.jsxs)(`section`,{"aria-labelledby":`market`,style:{padding:`28px 24px 48px`,background:s.background,color:s.navy},children:[(0,Y.jsx)(`h2`,{id:`market`,children:`Claude Code`}),(0,Y.jsxs)(`div`,{style:{...$,background:s.navy,color:s.white,fontFamily:`ui-monospace, monospace`},children:[(0,Y.jsx)(`p`,{children:`● ● ● Claude Code`}),(0,Y.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),r()},children:[(0,Y.jsxs)(`label`,{children:[`検索 `,(0,Y.jsx)(`input`,{value:e,onChange:e=>t(e.target.value)})]}),` `,(0,Y.jsx)(`button`,{type:`submit`,children:`検索する`})]}),g&&(0,Y.jsx)(`p`,{role:`alert`,children:g}),n&&i.length===0&&(0,Y.jsx)(`p`,{children:`一致するパックはありません。`}),(0,Y.jsx)(`ul`,{children:i.map(e=>(0,Y.jsxs)(`li`,{children:[(0,Y.jsx)(`strong`,{children:e.title}),` · 一致度 `,Math.round(e.score*100),`% · $`,e.priceUsd.toFixed(2),` `,(0,Y.jsx)(`button`,{type:`button`,onClick:()=>d(e),disabled:!l||!u,children:`購入する`}),` `,(0,Y.jsx)(`button`,{type:`button`,disabled:!e.owned,onClick:()=>f(e.id,`skill`),children:`スキルを書き出す`}),` `,(0,Y.jsx)(`button`,{type:`button`,disabled:!e.owned||a.ledger.some(t=>t.packId===e.id&&m.has(t.id)),onClick:()=>v(e.id),children:a.ledger.some(t=>t.packId===e.id&&m.has(t.id))?o(`ja`).importDone:o(`ja`).importBtn}),a.ledger.filter(t=>t.packId===e.id).map(e=>(0,Y.jsxs)(`div`,{"data-testid":`transaction-result`,children:[`利用結果: `,e.result===`solved`?`解決`:e.result===`unsolved`?`未解決`:`実行中`,` `,(0,Y.jsx)(`button`,{type:`button`,disabled:!l,"aria-pressed":e.result===`solved`,onClick:()=>p(e.id,`solved`),children:`解決`}),` `,(0,Y.jsx)(`button`,{type:`button`,disabled:!l,"aria-pressed":e.result===`unsolved`,onClick:()=>p(e.id,`unsolved`),children:`未解決`})]},e.id))]},e.id))}),(0,Y.jsxs)(`p`,{children:[`ローカルでは `,(0,Y.jsx)(`code`,{children:`gbrainx import`}),` を使えます。同名ファイルがある場合は取り込みが止まります。内容を確認してから操作してください。`]})]})]})}function st({store:e}){let t=at(e);return(0,Y.jsxs)(`section`,{"aria-labelledby":`earnings`,style:{padding:`32px 24px 48px`,background:s.background,color:s.navy},children:[(0,Y.jsx)(`h2`,{id:`earnings`,children:`収益`}),(0,Y.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit,minmax(260px,1fr))`,gap:16},children:[(0,Y.jsxs)(`div`,{style:{...$,background:s.navy,color:s.white},children:[(0,Y.jsxs)(`div`,{"data-testid":`earnings-balance`,children:[`作者収益 `,(0,Y.jsxs)(`strong`,{style:{fontSize:38},children:[`$`,t.balanceUsd.toFixed(2)]})]}),(0,Y.jsxs)(`p`,{children:[`購入者残高 $`,e.wallet.buyerUsd.toFixed(2)]})]}),(0,Y.jsxs)(`div`,{style:$,children:[(0,Y.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Y.jsxs)(`div`,{children:[`利用回数`,(0,Y.jsx)(`h2`,{children:t.uses30d})]}),(0,Y.jsxs)(`div`,{children:[`解決率`,(0,Y.jsxs)(`h2`,{"data-testid":`earnings-solve-rate`,children:[Math.round(t.solved30d/t.uses30d*100),`%`]})]}),(0,Y.jsxs)(`div`,{children:[`30日間の収益`,(0,Y.jsxs)(`h2`,{children:[`$`,t.earned30dUsd.toFixed(2)]})]})]}),(0,Y.jsx)(`div`,{"aria-label":`30日間の利用回数`,style:{height:66,display:`flex`,alignItems:`end`,gap:3},children:t.dailyUses30d.map((e,n)=>(0,Y.jsx)(`div`,{title:`${e}回`,style:{flex:1,height:Math.max(3,e/Math.max(...t.dailyUses30d)*66),background:n===29?s.blue:s.border,borderRadius:3}},n))})]})]}),(0,Y.jsxs)(`div`,{style:{...$,marginTop:16,overflowX:`auto`},children:[(0,Y.jsx)(`h3`,{children:`出品中の Expert brain`}),(0,Y.jsxs)(`table`,{style:{width:`100%`,textAlign:`left`},children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:`パック`}),(0,Y.jsx)(`th`,{children:`価格`}),(0,Y.jsx)(`th`,{children:`利用`}),(0,Y.jsx)(`th`,{children:`解決`}),(0,Y.jsx)(`th`,{children:`収益`})]})}),(0,Y.jsx)(`tbody`,{children:e.packs.map(t=>{let n=e.ledger.filter(e=>e.packId===t.id&&t.author===`you`);return(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{children:t.title}),(0,Y.jsxs)(`td`,{children:[`$`,t.priceUsd.toFixed(2)]}),(0,Y.jsx)(`td`,{children:t.author===`you`?n.length:`—`}),(0,Y.jsx)(`td`,{children:t.author===`you`?n.filter(e=>e.result===`solved`).length:`—`}),(0,Y.jsx)(`td`,{children:t.author===`you`?`$${n.reduce((e,t)=>e+t.authorUsd,0).toFixed(2)}`:`—`})]},t.id)})})]})]}),(0,Y.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`repeat(auto-fit,minmax(280px,1fr))`,gap:16,marginTop:16},children:[(0,Y.jsxs)(`div`,{style:$,children:[(0,Y.jsx)(`h3`,{children:`最近の利用`}),t.recentUses.map((e,t)=>(0,Y.jsxs)(`p`,{children:[e.solved?`解決`:`未解決`,` · +$`,e.amountUsd.toFixed(2),(0,Y.jsx)(`br`,{}),e.pages.map(e=>`[[${e}]]`).join(` `)]},t))]}),(0,Y.jsxs)(`div`,{style:$,children:[(0,Y.jsx)(`h3`,{children:`役に立ったページ`}),Object.entries(t.pageUses).map(([e,n])=>(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`p`,{children:[e,` · `,n,`回`]}),(0,Y.jsx)(`div`,{style:{height:6,background:s.border},children:(0,Y.jsx)(`div`,{style:{height:6,width:`${n/Math.max(1,...Object.values(t.pageUses))*100}%`,background:s.blue}})})]},e))]})]}),(0,Y.jsxs)(`div`,{style:{...$,marginTop:16},children:[(0,Y.jsx)(`h3`,{children:`内訳`}),(0,Y.jsxs)(`div`,{style:{display:`flex`,color:s.white},children:[(0,Y.jsx)(`div`,{style:{width:`90%`,padding:10,background:s.navy},children:`あなた 90%`}),(0,Y.jsx)(`div`,{style:{width:`10%`,padding:10,background:s.blue},children:`10%`})]})]})]})}function ct(e){let t=0xffffffff;for(let n of e){t^=n;for(let e=0;e<8;e++)t=t>>>1^-(t&1)&0xedb88320}return(t^0xffffffff)>>>0}function lt(e,t){let n=new TextEncoder,r=`packs/${e.id}/`,i=new Set,a=pe(e,t).map(({path:t,markdown:a})=>{if(!t.startsWith(r))throw Error(`Invalid import path`);let o=t.slice(6),s=o.split(`/`);if(s.length!==2||s[0]!==e.id||s.some(e=>!e||e===`.`||e===`..`||e.includes(`\\`)||Array.from(e).some(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127)))throw Error(`Invalid import path`);let c=o.normalize(`NFC`).toLowerCase();if(i.has(c))throw Error(`Duplicate import path`);i.add(c);let l=n.encode(o),u=n.encode(a);if(l.length>65535||u.length>0xffffffff)throw Error(`Import file is too large for ZIP`);return{name:l,content:u,crc:ct(u)}});if(a.length>65535)throw Error(`Too many import files for ZIP`);let o=0,s=0;for(let e of a)o+=30+e.name.length+e.content.length,s+=46+e.name.length;if(o>0xffffffff||s>0xffffffff||o+s+22>0xffffffff)throw Error(`Import is too large for ZIP`);let c=new Uint8Array(o+s+22),l=new DataView(c.buffer),u=(e,t)=>l.setUint16(e,t,!0),d=(e,t)=>l.setUint32(e,t,!0),f=0,p=o;for(let{name:e,content:t,crc:n}of a)d(f,67324752),u(f+4,20),u(f+6,2048),u(f+12,33),d(f+14,n),d(f+18,t.length),d(f+22,t.length),u(f+26,e.length),c.set(e,f+30),c.set(t,f+30+e.length),d(p,33639248),u(p+4,20),u(p+6,20),u(p+8,2048),u(p+14,33),d(p+16,n),d(p+20,t.length),d(p+24,t.length),u(p+28,e.length),d(p+42,f),c.set(e,p+46),f+=30+e.length+t.length,p+=46+e.length;return d(p,0x6054b50),u(p+8,a.length),u(p+10,a.length),d(p+12,s),d(p+16,o),c}function ut(){let[e,t]=(0,c.useState)(()=>K()),[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(`browser`),[o,s]=(0,c.useState)(``),[l,u]=(0,c.useState)(!1),[d,f]=(0,c.useState)(``),[p,m]=(0,c.useState)(null),[h,g]=(0,c.useState)(``);(0,c.useEffect)(()=>{g(crypto.randomUUID());try{let e=tt(window.localStorage);t(e.store),r(!0),e.recovered&&f(`以前の保存データを退避し、初期状態から始めました。`)}catch{f(`保存データを読み込めませんでした。保存は停止しています。`)}return it().then(a),rt(window,e=>{t(e.store),r(!0),e.recovered&&f(`以前の保存データを退避し、初期状態から始めました。`)},()=>{r(!1),f(`保存データを読み込めませんでした。保存は停止しています。`)})},[]);function _(r){if(!n)throw Error(`Store is unavailable`);nt(window.localStorage,r,e.rev),t(r)}function v(t,n){if(t){if(e.packs.some(e=>e.id===t.id))f(`同じ ID のパックが既にあります。別のパック名を指定してください。`);else try{_({...e,rev:e.rev+1,brain:{pages:n},packs:[...e.packs,t]}),f(`パックを出品しました。`)}catch{f(`保存に失敗しました。`)}}}function y(t){let n=M(e,t.id,h,t.score);if(!n.ok){f(`購入できませんでした: ${n.code}`);return}let r=ne(e,t.id,h,`web`,new Date().toISOString(),crypto.randomUUID(),e.rev,t.score);if(!r.ok)f(`購入できませんでした: ${r.code}`);else try{r.alreadyPurchased||_(r.store),f(r.alreadyPurchased?`${t.title} は購入済みです。`:`${t.title} を購入しました。`)}catch{f(`購入を保存できませんでした。再読み込みしてください。`)}}function b(t,n){let r=e.ledger.find(e=>e.packId===t),i=e.packs.find(e=>e.id===t);if(!r||!i||!j(e,t)){let e=`書き出すには購入が必要です。`;return f(e),{ok:!1,reason:e}}try{let a=re(e,t);if(!a.ok){let e=`パックを読み込めませんでした: ${a.code}`;return f(e),{ok:!1,reason:e}}let o=Uint8Array.from(n===`skill`?Re(i):lt(i,r.at)),s=URL.createObjectURL(new Blob([o.buffer],{type:`application/zip`}));try{let e=document.createElement(`a`);e.href=s,e.download=n===`skill`?`${t}.zip`:`${t}-gbrain.zip`,e.click()}finally{URL.revokeObjectURL(s)}return{ok:!0}}catch(e){let t=e instanceof Error?e.message:`書き出しに失敗しました。`;return f(t),{ok:!1,reason:t}}}function x(t,n){let r=N(e,t,n);if(!r.ok)f(`結果を保存できませんでした: ${r.code}`);else try{_(r.store),f(`利用結果を保存しました。`)}catch{f(`結果を保存できませんでした。`)}}function S(){try{return _({...K(),rev:e.rev+1}),m(e),f(`初期状態に戻しました。`),!0}catch{return f(`保存に失敗しました。`),!1}}function C(){if(p)try{_({...p,rev:e.rev+1}),m(null)}catch{f(`保存に失敗しました。`)}}return{store:e,ready:n,mode:i,query:o,setQuery:s,searched:l,setSearched:u,message:d,setMessage:f,previous:p,sessionId:h,results:l?Pe(o,e):[],publish:v,buy:y,download:b,markResult:x,reset:S,undo:C}}function dt(){return[{title:`GBrainX`}]}var ft=t(function(){let e=ut(),[t]=i(),n=Ye(e.setMessage,a(t.toString())),[r,o]=(0,c.useState)(`factory`),[l,u]=(0,c.useState)(!1),d=e.store.packs.some(e=>e.author===`you`),f=e.store.ledger.some(e=>e.result===`solved`),p=l?4:f?3:d?2:+!!n.state.draft,m=[[`factory`,`ファクトリー`],[`agent`,`Claude Code`],[`earnings`,`収益`]],h=r===`factory`?n.state.unconfirmed?`要確認の段落を判断してください。`:n.state.stage===0?`GBrain を読み込んでください。`:n.state.draft?`パックを出品できます。`:`分類と各ゲートの結果を確認してください。`:r===`agent`?`Expert brain を検索し、購入して読み込めます。`:`利用と収益を確認できます。`;return(0,Y.jsxs)(`main`,{style:{minHeight:`100vh`,background:s.background,color:s.navy,lineHeight:1.6},children:[(0,Y.jsxs)(`header`,{style:{background:s.navy,color:s.white,padding:`12px 24px`,display:`flex`,alignItems:`center`,gap:20,flexWrap:`wrap`},children:[(0,Y.jsx)(`strong`,{children:`GbrainX`}),(0,Y.jsx)(`span`,{children:e.mode===`local`?`ローカル版`:`ブラウザ版`}),(0,Y.jsx)(`div`,{role:`tablist`,"aria-label":`画面`,style:{display:`flex`,padding:4,background:s.navyRaised,borderRadius:999},children:m.map(([t,n])=>(0,Y.jsx)(`button`,{type:`button`,role:`tab`,id:`tab-${t}`,"aria-controls":`panel-${t}`,"aria-selected":r===t,onClick:()=>{o(t),t===`earnings`&&e.store.ledger.length>0&&u(!0)},style:{border:0,borderRadius:999,padding:`7px 16px`,minHeight:36,cursor:`pointer`,background:r===t?s.white:`transparent`,color:r===t?s.navy:s.textOnNavy},children:n},t))}),(0,Y.jsx)(`div`,{style:{flex:`1 1 auto`}}),(0,Y.jsx)(`div`,{role:`img`,"aria-label":`進行状況`,style:{display:`flex`,gap:6},children:[`コンパイル`,`出品`,`解決`,`収益`].map((e,t)=>(0,Y.jsx)(`span`,{title:e,style:{width:t===p?24:6,height:6,borderRadius:999,background:t<p?s.mint:t===p?s.white:s.navyBorder}},e))}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>{e.reset()&&(n.reset(),o(`factory`),u(!1))},disabled:!e.ready,children:`初期状態に戻す`}),e.previous&&(0,Y.jsx)(`button`,{type:`button`,onClick:e.undo,children:`元に戻す`})]}),(0,Y.jsxs)(`div`,{"aria-live":`polite`,style:{background:`#EAF1FA`,padding:`12px 24px`,color:s.navy},children:[(0,Y.jsx)(`strong`,{children:m.find(([e])=>e===r)?.[1]}),` · `,h]}),e.message&&(0,Y.jsx)(`p`,{role:`status`,children:e.message}),(0,Y.jsx)(`div`,{role:`tabpanel`,id:`panel-factory`,"aria-labelledby":`tab-factory`,hidden:r!==`factory`,children:(0,Y.jsx)(et,{factory:n,ready:e.ready,publish:()=>e.publish(n.state.draft,n.state.pages)})}),(0,Y.jsx)(`div`,{role:`tabpanel`,id:`panel-agent`,"aria-labelledby":`tab-agent`,hidden:r!==`agent`,children:(0,Y.jsx)(ot,{query:e.query,setQuery:e.setQuery,searched:e.searched,search:()=>e.setSearched(!0),results:e.results,store:e.store,ready:e.ready,sessionId:e.sessionId,buy:e.buy,download:e.download,markResult:e.markResult})}),(0,Y.jsx)(`div`,{role:`tabpanel`,id:`panel-earnings`,"aria-labelledby":`tab-earnings`,hidden:r!==`earnings`,children:(0,Y.jsx)(st,{store:e.store})})]})});export{ft as default,dt as meta};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
window.__reactRouterManifest={"entry":{"module":"/assets/entry.client-BMJZABtH.js","imports":["/assets/jsx-runtime-C8YK_IxR.js"],"css":[]},"routes":{"root":{"id":"root","path":"","hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":true,"module":"/assets/root-C-cLqVHP.js","imports":["/assets/jsx-runtime-C8YK_IxR.js","/assets/lib-C32AnKSP.js","/assets/root-i18n-_0Yddpt_.js"],"css":["/assets/root-D4kqIC2S.css"]},"routes/home":{"id":"routes/home","parentId":"root","index":true,"hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":false,"module":"/assets/home-DSGr2mzJ.js","imports":["/assets/jsx-runtime-C8YK_IxR.js","/assets/use-lp-language-ij45BzB4.js","/assets/lib-C32AnKSP.js"],"css":[]},"routes/demo":{"id":"routes/demo","parentId":"root","path":"demo","hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":false,"module":"/assets/demo-G0WCPBHC.js","imports":["/assets/jsx-runtime-C8YK_IxR.js","/assets/lib-C32AnKSP.js","/assets/i18n-CbBRRmtS.js","/assets/root-i18n-_0Yddpt_.js"],"css":[]},"routes/gbrainx":{"id":"routes/gbrainx","parentId":"root","path":"app","hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":false,"module":"/assets/gbrainx-
|
|
1
|
+
window.__reactRouterManifest={"entry":{"module":"/assets/entry.client-BMJZABtH.js","imports":["/assets/jsx-runtime-C8YK_IxR.js"],"css":[]},"routes":{"root":{"id":"root","path":"","hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":true,"module":"/assets/root-C-cLqVHP.js","imports":["/assets/jsx-runtime-C8YK_IxR.js","/assets/lib-C32AnKSP.js","/assets/root-i18n-_0Yddpt_.js"],"css":["/assets/root-D4kqIC2S.css"]},"routes/home":{"id":"routes/home","parentId":"root","index":true,"hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":false,"module":"/assets/home-DSGr2mzJ.js","imports":["/assets/jsx-runtime-C8YK_IxR.js","/assets/use-lp-language-ij45BzB4.js","/assets/lib-C32AnKSP.js"],"css":[]},"routes/demo":{"id":"routes/demo","parentId":"root","path":"demo","hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":false,"module":"/assets/demo-G0WCPBHC.js","imports":["/assets/jsx-runtime-C8YK_IxR.js","/assets/lib-C32AnKSP.js","/assets/i18n-CbBRRmtS.js","/assets/root-i18n-_0Yddpt_.js"],"css":[]},"routes/gbrainx":{"id":"routes/gbrainx","parentId":"root","path":"app","hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":false,"module":"/assets/gbrainx-DHJfi3id.js","imports":["/assets/jsx-runtime-C8YK_IxR.js","/assets/lib-C32AnKSP.js","/assets/root-i18n-_0Yddpt_.js","/assets/i18n-CbBRRmtS.js"],"css":[]},"routes/sell":{"id":"routes/sell","parentId":"root","path":"sell","hasAction":false,"hasLoader":false,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":true,"hasErrorBoundary":false,"module":"/assets/sell-DbbNBdAa.js","imports":["/assets/jsx-runtime-C8YK_IxR.js","/assets/use-lp-language-ij45BzB4.js","/assets/lib-C32AnKSP.js"],"css":["/assets/sell-CxnwvqXu.css"]},"routes/health":{"id":"routes/health","parentId":"root","path":"health","hasAction":false,"hasLoader":true,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":false,"hasErrorBoundary":false,"module":"/assets/health-BvRk9kiK.js","imports":[],"css":[]},"routes/api":{"id":"routes/api","parentId":"root","path":"api/*","hasAction":true,"hasLoader":true,"hasClientAction":false,"hasClientLoader":false,"hasClientMiddleware":false,"hasDefaultExport":false,"hasErrorBoundary":false,"module":"/assets/api-BvRk9kiK.js","imports":[],"css":[]}},"url":"/assets/manifest-df2f285a.js","version":"df2f285a"};
|
|
@@ -18074,6 +18074,50 @@ function evaluateKeywords(markdown, keywords) {
|
|
|
18074
18074
|
missing
|
|
18075
18075
|
};
|
|
18076
18076
|
}
|
|
18077
|
+
// packages/core/src/double-charge-seed.ts
|
|
18078
|
+
var doubleChargeSeed = {
|
|
18079
|
+
"id": "stripe-double-charge-prevention",
|
|
18080
|
+
"title": "Stripe Double-Charge Prevention",
|
|
18081
|
+
"version": "v1",
|
|
18082
|
+
"domain": "payments",
|
|
18083
|
+
"errorSignatures": [
|
|
18084
|
+
"double charge",
|
|
18085
|
+
"charged twice",
|
|
18086
|
+
"idempotency",
|
|
18087
|
+
"orderKey",
|
|
18088
|
+
"stripe double charge on retry"
|
|
18089
|
+
],
|
|
18090
|
+
"nodes": [
|
|
18091
|
+
"stripe-idempotency",
|
|
18092
|
+
"payment-retries",
|
|
18093
|
+
"webhook-dedupe"
|
|
18094
|
+
],
|
|
18095
|
+
"markdown": "## [[stripe-idempotency]]\n\n# Stripe idempotency\n\nImport `orderKey` from `./pay-client.mjs` and use `payClient.charge(order, { orderKey: orderKey(order) })`. The key is derived from `order.merchantId`, `order.id`, and `order.revision`. Retry the same operation with the same values. A new revision represents a new operation. The client does not use `Idempotency-Key` for deduplication.\n\nSee [[payment-retries]] for retry handling and [[webhook-dedupe]] for duplicate events.\n\n\n## [[payment-retries]]\n\n# Payment retries\n\nRetry the same checkout operation with the same `order.merchantId`, `order.id`, and `order.revision`. Import `orderKey` from `./pay-client.mjs` and pass `orderKey(order)` as the `orderKey` option to `payClient.charge`. Generating a new key for each attempt can create a duplicate charge.\n\nSee [[stripe-idempotency]] and [[webhook-dedupe]] for the charge and event boundaries.\n\n\n## [[webhook-dedupe]]\n\n# Webhook deduplication\n\nUse the webhook event ID to detect duplicate deliveries before applying the event's effects. Record the ID only when processing succeeds, so a failed delivery can be retried.\n\nSee [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.\n\n\n## Sources\n\n- [[stripe-idempotency]]\n- [[payment-retries]]\n- [[webhook-dedupe]]",
|
|
18096
|
+
"summary": "## symptom\n\nRetries can produce a duplicate charge. [payment-retries#2]\n\n## cause\n\nA new key on each attempt creates separate operations. [payment-retries#2]\n\n## fix\n\nImport orderKey from ./pay-client.mjs and pass orderKey(order) as the orderKey option to payClient.charge. [stripe-idempotency#2]\n\n## avoid\n\nDo not generate a new key for retries. [payment-retries#2]\n\n## verify\n\nDeduplicate webhook deliveries using the event ID after successful processing. [webhook-dedupe#2]",
|
|
18097
|
+
"pages": [
|
|
18098
|
+
{
|
|
18099
|
+
"id": "stripe-idempotency",
|
|
18100
|
+
"markdown": "# Stripe idempotency\n\nImport `orderKey` from `./pay-client.mjs` and use `payClient.charge(order, { orderKey: orderKey(order) })`. The key is derived from `order.merchantId`, `order.id`, and `order.revision`. Retry the same operation with the same values. A new revision represents a new operation. The client does not use `Idempotency-Key` for deduplication.\n\nSee [[payment-retries]] for retry handling and [[webhook-dedupe]] for duplicate events.\n"
|
|
18101
|
+
},
|
|
18102
|
+
{
|
|
18103
|
+
"id": "payment-retries",
|
|
18104
|
+
"markdown": "# Payment retries\n\nRetry the same checkout operation with the same `order.merchantId`, `order.id`, and `order.revision`. Import `orderKey` from `./pay-client.mjs` and pass `orderKey(order)` as the `orderKey` option to `payClient.charge`. Generating a new key for each attempt can create a duplicate charge.\n\nSee [[stripe-idempotency]] and [[webhook-dedupe]] for the charge and event boundaries.\n"
|
|
18105
|
+
},
|
|
18106
|
+
{
|
|
18107
|
+
"id": "webhook-dedupe",
|
|
18108
|
+
"markdown": "# Webhook deduplication\n\nUse the webhook event ID to detect duplicate deliveries before applying the event's effects. Record the ID only when processing succeeds, so a failed delivery can be retried.\n\nSee [[stripe-idempotency]] for checkout keys and [[payment-retries]] for retries.\n"
|
|
18109
|
+
}
|
|
18110
|
+
],
|
|
18111
|
+
"scrubbed": [],
|
|
18112
|
+
"eval": {
|
|
18113
|
+
"without": "Not recorded",
|
|
18114
|
+
"with": "Not recorded",
|
|
18115
|
+
"recorded": true
|
|
18116
|
+
},
|
|
18117
|
+
"priceUsd": .5,
|
|
18118
|
+
"author": "seed",
|
|
18119
|
+
"createdAt": "2026-01-01T00:00:00.000Z"
|
|
18120
|
+
};
|
|
18077
18121
|
// packages/core/src/import-files.ts
|
|
18078
18122
|
function safeSegment(value) {
|
|
18079
18123
|
return typeof value === "string" && value.length > 0 && value !== "." && value !== ".." && !Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 || "<>:\"/\\|?*[]".includes(char)) && !/[. ]$/.test(value) && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value);
|
|
@@ -18552,40 +18596,44 @@ function createInitialStore() {
|
|
|
18552
18596
|
},
|
|
18553
18597
|
ledger: [],
|
|
18554
18598
|
sessions: [],
|
|
18555
|
-
packs: [
|
|
18556
|
-
|
|
18557
|
-
|
|
18558
|
-
|
|
18559
|
-
|
|
18560
|
-
|
|
18561
|
-
|
|
18562
|
-
|
|
18563
|
-
|
|
18564
|
-
|
|
18565
|
-
|
|
18566
|
-
|
|
18567
|
-
|
|
18568
|
-
|
|
18569
|
-
|
|
18570
|
-
|
|
18571
|
-
|
|
18572
|
-
|
|
18573
|
-
|
|
18574
|
-
|
|
18575
|
-
|
|
18576
|
-
|
|
18577
|
-
|
|
18578
|
-
|
|
18579
|
-
|
|
18580
|
-
|
|
18581
|
-
|
|
18582
|
-
|
|
18583
|
-
|
|
18584
|
-
|
|
18585
|
-
|
|
18586
|
-
|
|
18587
|
-
|
|
18588
|
-
|
|
18599
|
+
packs: [
|
|
18600
|
+
{
|
|
18601
|
+
...common,
|
|
18602
|
+
id: "stripe-webhook-signature-errors",
|
|
18603
|
+
title: "Stripe Webhook Signature Errors",
|
|
18604
|
+
version: "v3",
|
|
18605
|
+
domain: "payments",
|
|
18606
|
+
errorSignatures: ["webhook signature verification failed", "raw body parsing"],
|
|
18607
|
+
nodes: ["stripe-webhook-signature", "raw-body-parsing"],
|
|
18608
|
+
markdown: "Verify the webhook signature against the raw request body.",
|
|
18609
|
+
summary: "Verify the webhook signature against the raw request body.",
|
|
18610
|
+
pages: [{
|
|
18611
|
+
id: "stripe-webhook-signature",
|
|
18612
|
+
markdown: "Verify the webhook signature against the raw request body."
|
|
18613
|
+
}, {
|
|
18614
|
+
id: "raw-body-parsing",
|
|
18615
|
+
markdown: "Keep the raw request body for verification."
|
|
18616
|
+
}],
|
|
18617
|
+
priceUsd: .5
|
|
18618
|
+
},
|
|
18619
|
+
{
|
|
18620
|
+
...common,
|
|
18621
|
+
id: "postgres-zero-downtime-migrations",
|
|
18622
|
+
title: "Postgres Zero-Downtime Migrations",
|
|
18623
|
+
version: "v2",
|
|
18624
|
+
domain: "data",
|
|
18625
|
+
errorSignatures: ["database migration downtime", "add column safely"],
|
|
18626
|
+
nodes: ["pg-add-column-safely"],
|
|
18627
|
+
markdown: "Add columns in stages and migrate data before enforcing constraints.",
|
|
18628
|
+
summary: "Add columns in stages and migrate data before enforcing constraints.",
|
|
18629
|
+
pages: [{
|
|
18630
|
+
id: "pg-add-column-safely",
|
|
18631
|
+
markdown: "Add columns in stages and migrate data before enforcing constraints."
|
|
18632
|
+
}],
|
|
18633
|
+
priceUsd: .8
|
|
18634
|
+
},
|
|
18635
|
+
structuredClone(doubleChargeSeed)
|
|
18636
|
+
]
|
|
18589
18637
|
};
|
|
18590
18638
|
}
|
|
18591
18639
|
function createSkillMarkdown(pack) {
|
|
@@ -22677,7 +22725,7 @@ var server_manifest_default = {
|
|
|
22677
22725
|
"hasClientMiddleware": false,
|
|
22678
22726
|
"hasDefaultExport": true,
|
|
22679
22727
|
"hasErrorBoundary": false,
|
|
22680
|
-
"module": "/assets/gbrainx-
|
|
22728
|
+
"module": "/assets/gbrainx-DHJfi3id.js",
|
|
22681
22729
|
"imports": [
|
|
22682
22730
|
"/assets/jsx-runtime-C8YK_IxR.js",
|
|
22683
22731
|
"/assets/lib-C32AnKSP.js",
|
|
@@ -22758,8 +22806,8 @@ var server_manifest_default = {
|
|
|
22758
22806
|
"hydrateFallbackModule": void 0
|
|
22759
22807
|
}
|
|
22760
22808
|
},
|
|
22761
|
-
"url": "/assets/manifest-
|
|
22762
|
-
"version": "
|
|
22809
|
+
"url": "/assets/manifest-df2f285a.js",
|
|
22810
|
+
"version": "df2f285a",
|
|
22763
22811
|
"sri": void 0
|
|
22764
22812
|
};
|
|
22765
22813
|
// \0virtual:react-router/server-build
|
|
@@ -22842,4 +22890,4 @@ var routes = {
|
|
|
22842
22890
|
var allowedActionOrigins = false;
|
|
22843
22891
|
export { allowedActionOrigins, server_manifest_default as assets, assetsBuildDirectory, basename, entry, future, isSpaMode, prerender, publicPath, routeDiscovery, routes, ssr, unstable_apiOnly, unstable_apiServerOrigin };
|
|
22844
22892
|
|
|
22845
|
-
//# sourceMappingURL=server-build-
|
|
22893
|
+
//# sourceMappingURL=server-build-BVJ_AFpB.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@takeokunn/gbrainx",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Local app and CLI for GBrain: serves the four compile gates (secret scrubbing, pruning, distillation and evaluation) that turn exported pages into knowledge packs, and imports purchased packs into a GBrain folder.",
|
|
5
5
|
"keywords": ["gbrain", "knowledge-pack", "memory", "secret-scrubbing", "claude-code", "mcp", "cli"],
|
|
6
6
|
"homepage": "https://github.com/takeokunn/gbrainx#readme",
|