Offline-First DSL & Templating

FreakQuery Guide & Reference

FreakQuery is an embedded query DSL and reactive templating engine built directly into Freaklog. Analyze consumption patterns, compute tolerance gaps, monitor binge durations, and embed live self-tracking analytics inside your Discord webhooks—100% locally on your device with zero cloud tracking.

Overview: Why FreakQuery?

Self-tracking journals are only as good as the insights you can extract from them. Freaklog includes FreakQuery to give you direct, expressive access to your personal journal history without exporting data to external cloud services or writing complex SQL queries.

🔒 Fully Offline & Private

FreakQuery runs entirely within Freaklog's Android runtime on your local Room database. No analytics payloads, queries, or logs ever touch a proprietary server.

⚡ Composable Unix-Style Pipe DSL

Queries are built from chainable tags separated by the | pipe character. Compose filters, groups, selectors, and metrics into readable single-line statements.

📢 Discord Webhook Templating

Embed dynamic {{tag}} expressions directly into your Discord webhook message templates to automatically broadcast pacing reminders and daily sums on log creation.

⚖️ Smart Units & Normalization

Automatic dose conversion into milligrams (mg) across micrograms, milligrams, grams, and custom units. Built-in alias resolution for common substance nicknames and routes.

Core Concepts: The Tag Pipeline

Every FreakQuery query or template expression follows a structured 5-stage transformation pipeline. When you execute a query, raw ingestion rows pass sequentially through each stage:

Stage 1
Filter

Time windows & attributes (e.g. today, substance=LSD)

|
Stage 2
Group

Cluster rows into episodes (binges, streaks)

|
Stage 3
Selector

Select target event or group (last, first, largest)

|
Stage 4
Metric

Compute aggregate or extract value (sum_dose, since)

|
Stage 5
Format

Render output format (json, compact, sep)

The pipeline syntax is permissive: tags can be provided in any order, and FreakQuery's internal query planner normalizes and arranges them into their canonical execution order. If you write sum_dose|today|substance=Ketamine, it automatically runs as today|substance=Ketamine|sum_dose.

Type Pipeline Rule: Filters narrow log rows; groups assemble rows into clusters; selectors choose specific items from rows or groups; metrics produce numbers, time strings, or summary tables; formatters shape the final presentation.

Reference: Time & Attribute Filters

Filters constrain which ingestion events from your journal are considered for subsequent calculations.

Time Filters

Time filters check the timestamp of each ingestion against the current local calendar date and time on your device.

Tag Description Example
today (or day) Restricts to ingestions logged today (since 00:00 local time). today|sum_dose
week Restricts to ingestions in the current calendar week (Monday to Sunday). week|count
month Restricts to ingestions in the current calendar month. month|top_substances
year Restricts to ingestions in the current calendar year. year|substance_totals

Attribute Filters

Attribute filters match specific properties of an ingestion event. Exact matches and canonical aliases are automatically resolved.

Filter Syntax Type Description Example
substance=<name> String Filters by canonical substance name or registered alias (e.g. weed → Cannabis). substance=MDMA|last|since
route=<route> Route Filters by administration route (oral, insufflated, sublingual, smoked, rectal, intramuscular, intravenous). route=oral|count
limit=<n> or top=<n> Integer Limits the number of output items or ranked records to n. top_substances|limit=3
reverse Flag Reverses the chronological sorting order of the results. today|reverse|timeline
<field>=<value> Key=Value Matches any arbitrary ingestion attribute, such as site=<location> or experienceTitle=<title>. site=left_deltoid|count

Reference: Groups & Selectors

Grouping Operators

Grouping operators partition individual log rows into meaningful behavioral episodes.

Group Tag Type Output Clustering Logic Example
binges group_rows Clusters consecutive ingestions separated by less than the binge threshold (default: 6 hours). Useful for tracking re-dosing sessions and binge duration. binges|last|group_duration
streaks group_rows Groups consecutive calendar days with at least one logged ingestion into unbroken daily streaks. streaks|longest|count

Selectors

Selectors extract a specific target event from log rows, or a target session from grouped rows.

Selector Tag Applies To Selection Logic Example
last Log rows or Groups Selects the most recent ingestion event, or the most recent binge/streak group. substance=Ketamine|last|since
first Log rows or Groups Selects the earliest ingestion event, or the very first recorded binge/streak. today|first|dose
random Log rows or Groups Selects a uniformly random item from the filtered set. month|random|substance
largest Groups only Picks the group with the highest cumulative dose (converted to mg). binges|largest|group_sum
longest Groups only Picks the group with the longest time span (duration between first and last dose). binges|longest|group_duration

Reference: Metrics

Metrics compute numerical totals, analyze patterns, extract individual fields, or generate rankings from the selected data.

Metric Tag Output Format Description Example
count Integer Total count of matching ingestions or items in the selected group. month|substance=Cannabis|count
dose String Dose and unit of the selected event (e.g. 20 mg, 1.5 tabs). last|dose
substance String Canonical substance name of the selected event. last|substance
since Duration Human-readable elapsed time since the event (e.g. 2h 15m, 3d 4h). substance=LSD|last|since
sum_dose Number (mg) Total cumulative dose converted into milligrams across all matching rows. today|sum_dose
top_substances Table Substances ranked in descending order by frequency of consumption. month|top_substances|limit=5
top_routes Table Administration routes ranked by count. year|top_routes
sites Table Injection or application sites ranked by usage frequency. month|sites
substance_totals Table Aggregates per-substance total doses (in mg) alongside event counts. month|substance_totals
timeline Lines Chronological listing of events including timestamps, doses, and routes. today|timeline|time
sequence Chain Transitions between substances in order (e.g. Caffeine -> Amphetamine -> Alcohol). Supports sequence=dose, sequence=time, and sequence=patterns. today|sequence
ratio=<field> Percentage Percentage and count breakdown for any field (e.g. ratio=route, ratio=substance). month|ratio=route
group_sum Number (mg) Total cumulative mg dose of all ingestions inside a selected binge or streak. binges|last|group_sum
group_duration Duration Total time span of a selected binge or streak (from first to last ingestion). binges|last|group_duration
group_count Integer Number of distinct ingestions logged within a selected group. binges|last|group_count
main_substance String The most frequently consumed substance within a selected group session. binges|last|main_substance

Reference: Display & Formatting Options

Control the text structure, serialization format, and delimiter behavior of query outputs.

Modifier Tag Type Description Example
json Format Serializes the result as raw structured JSON instead of plain formatted text. Ideal for scripts or advanced integrations. today|top_substances|json
compact Layout Produces a single-line delimited summary rather than multi-line output. today|top_substances|compact
sep=<delimiter> Delimiter Overrides the default delimiter (default is , ) for lists and compact representations. top_substances|compact|sep= •
labels Toggle Toggles field labels on or off (e.g. substance names in value-count outputs). top_substances|labels=false
parens Toggle Toggles wrapping count values in parentheses (e.g. Cannabis (5) vs Cannabis 5). top_substances|parens=false
time Toggle / String Displays timestamps alongside entries in timelines (e.g. 14:30 or full date). today|timeline|time

Webhook Templating Guide

Freaklog lets you configure Discord-compatible webhooks to automatically notify a private channel or bot when an ingestion is logged. FreakQuery tags can be embedded anywhere in your template using {{...}} delimiters.

Standard Variables vs. FreakQuery Tags

Freaklog message templates support two layers of interpolation:

  • Event Variables: Instant values for the current ingestion, including {user}, {substance}, {dose}, {units}, {route}, {site}, and {note}. Optional blocks can be wrapped in brackets [...] so they vanish if empty.
  • FreakQuery Expressions: Wrapped in double braces {{tag|pipeline}}. FreakQuery executes the tag against your entire local journal history and substitutes the dynamic answer into the message before sending.

Real-World Webhook Template Examples

Example 1: Harm Reduction & Running Daily Dose Alert

Displays the current log, along with the user's running cumulative dose for that substance today and total sessions logged.

{user}: [{dose} {units} ]{substance} via {route}[ at {site}][\n> Note: {note}]
> 📊 **Today's Total ({substance}):** {{today|substance={substance}|sum_dose}} mg ({{today|substance={substance}|count}} doses)
> ⏱️ **Previous dose was:** {{substance={substance}|last|since}} ago

Example 2: Tolerance & Spacing Monitor

Especially helpful for substances requiring significant breaks (e.g. psychedelics, empathogens, or dissociatives).

🚨 **{substance} Logged by {user}**
> Dose: {dose} {units} ({route})
> Last intake was: {{substance={substance}|last|since}} ago
> Total past 30 days: {{month|substance={substance}|count}} sessions

Example 3: Active Binge / Session Tracker

Monitors how long the current clustered dosing session has lasted and how many re-doses have occurred.

{user} re-dosed {substance} ({dose} {units})
> ⏳ Current Session Length: {{binges|last|group_duration}}
> 🔁 Session Dose Count: {{binges|last|group_count}} doses (total {{binges|last|group_sum}} mg)

Practical Recipes & Shell Queries

A reference collection of useful query patterns for ad-hoc insights, journal audits, and automated notifications.

Quick Daily Dose Summary

Daily Pacing

Sums all substance doses taken today into milligrams to quickly verify if intake is within personal harm-reduction limits.

today | sum_dose
Sample Output: 125 (total mg)

Tolerance & Break Check

Harm Reduction

Computes the exact time elapsed since the last time a specific substance was logged.

substance=LSD | last | since
Sample Output: 14d 6h

Monthly Top Substances

Habit Analysis

Lists your most frequently used substances for the current month, limited to the top 3 with counts.

month | top_substances | limit=3
Sample Output:
Cannabis (24)
Caffeine (18)
Amphetamine (6)

Polysubstance Transition Sequence

Pattern Detection

Traces the sequence of substances ingested throughout the day to detect compounding combinations or unintended patterns.

today | sequence
Sample Output: Caffeine -> Modafinil -> Cannabis -> Melatonin

Active Binge Duration

Session Monitoring

Calculates the time span between the first dose and the latest dose of the currently active binge cluster.

binges | last | group_duration
Sample Output: 8h 42m

Route of Administration Distribution

Safer Use

Provides a percentage and count breakdown of all administration routes used over the past month.

month | ratio=route
Sample Output:
oral 65% 13
insufflated 25% 5
smoked 10% 2

Structured JSON Export for Custom Scripts

Integration

Outputs all per-substance mg totals and counts for today in valid JSON for external processing.

today | substance_totals | json
Sample Output: [{"substance":"Amphetamine","total_mg":30.0,"count":2}]